]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/init/init.c
Add UPDATING entries and bump version.
[FreeBSD/FreeBSD.git] / sbin / init / init.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Donn Seeley at Berkeley Software Design, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1991, 1993\n\
38         The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)init.c      8.1 (Berkeley) 7/15/93";
44 #endif
45 static const char rcsid[] =
46   "$FreeBSD$";
47 #endif /* not lint */
48
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
51 #include <sys/mman.h>
52 #include <sys/mount.h>
53 #include <sys/sysctl.h>
54 #include <sys/wait.h>
55 #include <sys/stat.h>
56 #include <sys/uio.h>
57
58 #include <db.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <kenv.h>
62 #include <libutil.h>
63 #include <paths.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <syslog.h>
69 #include <time.h>
70 #include <ttyent.h>
71 #include <unistd.h>
72 #include <sys/reboot.h>
73 #include <err.h>
74
75 #include <stdarg.h>
76
77 #ifdef SECURE
78 #include <pwd.h>
79 #endif
80
81 #ifdef LOGIN_CAP
82 #include <login_cap.h>
83 #endif
84
85 #include "mntopts.h"
86 #include "pathnames.h"
87
88 /*
89  * Sleep times; used to prevent thrashing.
90  */
91 #define GETTY_SPACING            5      /* N secs minimum getty spacing */
92 #define GETTY_SLEEP             30      /* sleep N secs after spacing problem */
93 #define GETTY_NSPACE             3      /* max. spacing count to bring reaction */
94 #define WINDOW_WAIT              3      /* wait N secs after starting window */
95 #define STALL_TIMEOUT           30      /* wait N secs after warning */
96 #define DEATH_WATCH             10      /* wait N secs for procs to die */
97 #define DEATH_SCRIPT            120     /* wait for 2min for /etc/rc.shutdown */
98 #define RESOURCE_RC             "daemon"
99 #define RESOURCE_WINDOW         "default"
100 #define RESOURCE_GETTY          "default"
101
102 static void handle(sig_t, ...);
103 static void delset(sigset_t *, ...);
104
105 static void stall(const char *, ...) __printflike(1, 2);
106 static void warning(const char *, ...) __printflike(1, 2);
107 static void emergency(const char *, ...) __printflike(1, 2);
108 static void disaster(int);
109 static void revoke_ttys(void);
110 static int  runshutdown(void);
111 static char *strk(char *);
112 static void runfinal(void);
113
114 /*
115  * We really need a recursive typedef...
116  * The following at least guarantees that the return type of (*state_t)()
117  * is sufficiently wide to hold a function pointer.
118  */
119 typedef long (*state_func_t)(void);
120 typedef state_func_t (*state_t)(void);
121
122 static state_func_t single_user(void);
123 static state_func_t runcom(void);
124 static state_func_t read_ttys(void);
125 static state_func_t multi_user(void);
126 static state_func_t clean_ttys(void);
127 static state_func_t catatonia(void);
128 static state_func_t death(void);
129 static state_func_t death_single(void);
130 static state_func_t reroot(void);
131 static state_func_t reroot_phase_two(void);
132
133 static state_func_t run_script(const char *);
134
135 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
136 #define FALSE   0
137 #define TRUE    1
138
139 static int Reboot = FALSE;
140 static int howto = RB_AUTOBOOT;
141
142 static int devfs;
143 static char *init_path_argv0;
144
145 static void transition(state_t);
146 static state_t requested_transition;
147 static state_t current_state = death_single;
148
149 static void execute_script(char *argv[]);
150 static void open_console(void);
151 static const char *get_shell(void);
152 static void replace_init(char *path);
153 static void write_stderr(const char *message);
154
155 typedef struct init_session {
156         pid_t   se_process;             /* controlling process */
157         time_t  se_started;             /* used to avoid thrashing */
158         int     se_flags;               /* status of session */
159 #define SE_SHUTDOWN     0x1             /* session won't be restarted */
160 #define SE_PRESENT      0x2             /* session is in /etc/ttys */
161 #define SE_IFEXISTS     0x4             /* session defined as "onifexists" */
162 #define SE_IFCONSOLE    0x8             /* session defined as "onifconsole" */
163         int     se_nspace;              /* spacing count */
164         char    *se_device;             /* filename of port */
165         char    *se_getty;              /* what to run on that port */
166         char    *se_getty_argv_space;   /* pre-parsed argument array space */
167         char    **se_getty_argv;        /* pre-parsed argument array */
168         char    *se_window;             /* window system (started only once) */
169         char    *se_window_argv_space;  /* pre-parsed argument array space */
170         char    **se_window_argv;       /* pre-parsed argument array */
171         char    *se_type;               /* default terminal type */
172         struct  init_session *se_prev;
173         struct  init_session *se_next;
174 } session_t;
175
176 static void free_session(session_t *);
177 static session_t *new_session(session_t *, struct ttyent *);
178 static session_t *sessions;
179
180 static char **construct_argv(char *);
181 static void start_window_system(session_t *);
182 static void collect_child(pid_t);
183 static pid_t start_getty(session_t *);
184 static void transition_handler(int);
185 static void alrm_handler(int);
186 static void setsecuritylevel(int);
187 static int getsecuritylevel(void);
188 static int setupargv(session_t *, struct ttyent *);
189 #ifdef LOGIN_CAP
190 static void setprocresources(const char *);
191 #endif
192 static int clang;
193
194 static int start_session_db(void);
195 static void add_session(session_t *);
196 static void del_session(session_t *);
197 static session_t *find_session(pid_t);
198 static DB *session_db;
199
200 /*
201  * The mother of all processes.
202  */
203 int
204 main(int argc, char *argv[])
205 {
206         state_t initial_transition = runcom;
207         char kenv_value[PATH_MAX];
208         int c, error;
209         struct sigaction sa;
210         sigset_t mask;
211
212         /* Dispose of random users. */
213         if (getuid() != 0)
214                 errx(1, "%s", strerror(EPERM));
215
216         /* System V users like to reexec init. */
217         if (getpid() != 1) {
218 #ifdef COMPAT_SYSV_INIT
219                 /* So give them what they want */
220                 if (argc > 1) {
221                         if (strlen(argv[1]) == 1) {
222                                 char runlevel = *argv[1];
223                                 int sig;
224
225                                 switch (runlevel) {
226                                 case '0': /* halt + poweroff */
227                                         sig = SIGUSR2;
228                                         break;
229                                 case '1': /* single-user */
230                                         sig = SIGTERM;
231                                         break;
232                                 case '6': /* reboot */
233                                         sig = SIGINT;
234                                         break;
235                                 case 'c': /* block further logins */
236                                         sig = SIGTSTP;
237                                         break;
238                                 case 'q': /* rescan /etc/ttys */
239                                         sig = SIGHUP;
240                                         break;
241                                 case 'r': /* remount root */
242                                         sig = SIGEMT;
243                                         break;
244                                 default:
245                                         goto invalid;
246                                 }
247                                 kill(1, sig);
248                                 _exit(0);
249                         } else
250 invalid:
251                                 errx(1, "invalid run-level ``%s''", argv[1]);
252                 } else
253 #endif
254                         errx(1, "already running");
255         }
256
257         init_path_argv0 = strdup(argv[0]);
258         if (init_path_argv0 == NULL)
259                 err(1, "strdup");
260
261         /*
262          * Note that this does NOT open a file...
263          * Does 'init' deserve its own facility number?
264          */
265         openlog("init", LOG_CONS, LOG_AUTH);
266
267         /*
268          * Create an initial session.
269          */
270         if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
271                 warning("initial setsid() failed: %m");
272
273         /*
274          * Establish an initial user so that programs running
275          * single user do not freak out and die (like passwd).
276          */
277         if (setlogin("root") < 0)
278                 warning("setlogin() failed: %m");
279
280         /*
281          * This code assumes that we always get arguments through flags,
282          * never through bits set in some random machine register.
283          */
284         while ((c = getopt(argc, argv, "dsfr")) != -1)
285                 switch (c) {
286                 case 'd':
287                         devfs = 1;
288                         break;
289                 case 's':
290                         initial_transition = single_user;
291                         break;
292                 case 'f':
293                         runcom_mode = FASTBOOT;
294                         break;
295                 case 'r':
296                         initial_transition = reroot_phase_two;
297                         break;
298                 default:
299                         warning("unrecognized flag '-%c'", c);
300                         break;
301                 }
302
303         if (optind != argc)
304                 warning("ignoring excess arguments");
305
306         /*
307          * We catch or block signals rather than ignore them,
308          * so that they get reset on exec.
309          */
310         handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
311             SIGXCPU, SIGXFSZ, 0);
312         handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
313             SIGUSR1, SIGUSR2, SIGWINCH, 0);
314         handle(alrm_handler, SIGALRM, 0);
315         sigfillset(&mask);
316         delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
317             SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
318             SIGALRM, SIGUSR1, SIGUSR2, SIGWINCH, 0);
319         sigprocmask(SIG_SETMASK, &mask, NULL);
320         sigemptyset(&sa.sa_mask);
321         sa.sa_flags = 0;
322         sa.sa_handler = SIG_IGN;
323         sigaction(SIGTTIN, &sa, NULL);
324         sigaction(SIGTTOU, &sa, NULL);
325
326         /*
327          * Paranoia.
328          */
329         close(0);
330         close(1);
331         close(2);
332
333         if (kenv(KENV_GET, "init_exec", kenv_value, sizeof(kenv_value)) > 0) {
334                 replace_init(kenv_value);
335                 _exit(0); /* reboot */
336         }
337
338         if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
339                 state_func_t next_transition;
340
341                 if ((next_transition = run_script(kenv_value)) != NULL)
342                         initial_transition = (state_t) next_transition;
343         }
344
345         if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
346                 if (chdir(kenv_value) != 0 || chroot(".") != 0)
347                         warning("Can't chroot to %s: %m", kenv_value);
348         }
349
350         /*
351          * Additional check if devfs needs to be mounted:
352          * If "/" and "/dev" have the same device number,
353          * then it hasn't been mounted yet.
354          */
355         if (!devfs) {
356                 struct stat stst;
357                 dev_t root_devno;
358
359                 stat("/", &stst);
360                 root_devno = stst.st_dev;
361                 if (stat("/dev", &stst) != 0)
362                         warning("Can't stat /dev: %m");
363                 else if (stst.st_dev == root_devno)
364                         devfs++;
365         }
366
367         if (devfs) {
368                 struct iovec iov[4];
369                 char *s;
370                 int i;
371
372                 char _fstype[]  = "fstype";
373                 char _devfs[]   = "devfs";
374                 char _fspath[]  = "fspath";
375                 char _path_dev[]= _PATH_DEV;
376
377                 iov[0].iov_base = _fstype;
378                 iov[0].iov_len = sizeof(_fstype);
379                 iov[1].iov_base = _devfs;
380                 iov[1].iov_len = sizeof(_devfs);
381                 iov[2].iov_base = _fspath;
382                 iov[2].iov_len = sizeof(_fspath);
383                 /*
384                  * Try to avoid the trailing slash in _PATH_DEV.
385                  * Be *very* defensive.
386                  */
387                 s = strdup(_PATH_DEV);
388                 if (s != NULL) {
389                         i = strlen(s);
390                         if (i > 0 && s[i - 1] == '/')
391                                 s[i - 1] = '\0';
392                         iov[3].iov_base = s;
393                         iov[3].iov_len = strlen(s) + 1;
394                 } else {
395                         iov[3].iov_base = _path_dev;
396                         iov[3].iov_len = sizeof(_path_dev);
397                 }
398                 nmount(iov, 4, 0);
399                 if (s != NULL)
400                         free(s);
401         }
402
403         if (initial_transition != reroot_phase_two) {
404                 /*
405                  * Unmount reroot leftovers.  This runs after init(8)
406                  * gets reexecuted after reroot_phase_two() is done.
407                  */
408                 error = unmount(_PATH_REROOT, MNT_FORCE);
409                 if (error != 0 && errno != EINVAL)
410                         warning("Cannot unmount %s: %m", _PATH_REROOT);
411         }
412
413         /*
414          * Start the state machine.
415          */
416         transition(initial_transition);
417
418         /*
419          * Should never reach here.
420          */
421         return 1;
422 }
423
424 /*
425  * Associate a function with a signal handler.
426  */
427 static void
428 handle(sig_t handler, ...)
429 {
430         int sig;
431         struct sigaction sa;
432         sigset_t mask_everything;
433         va_list ap;
434         va_start(ap, handler);
435
436         sa.sa_handler = handler;
437         sigfillset(&mask_everything);
438
439         while ((sig = va_arg(ap, int)) != 0) {
440                 sa.sa_mask = mask_everything;
441                 /* XXX SA_RESTART? */
442                 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
443                 sigaction(sig, &sa, NULL);
444         }
445         va_end(ap);
446 }
447
448 /*
449  * Delete a set of signals from a mask.
450  */
451 static void
452 delset(sigset_t *maskp, ...)
453 {
454         int sig;
455         va_list ap;
456         va_start(ap, maskp);
457
458         while ((sig = va_arg(ap, int)) != 0)
459                 sigdelset(maskp, sig);
460         va_end(ap);
461 }
462
463 /*
464  * Log a message and sleep for a while (to give someone an opportunity
465  * to read it and to save log or hardcopy output if the problem is chronic).
466  * NB: should send a message to the session logger to avoid blocking.
467  */
468 static void
469 stall(const char *message, ...)
470 {
471         va_list ap;
472         va_start(ap, message);
473
474         vsyslog(LOG_ALERT, message, ap);
475         va_end(ap);
476         sleep(STALL_TIMEOUT);
477 }
478
479 /*
480  * Like stall(), but doesn't sleep.
481  * If cpp had variadic macros, the two functions could be #defines for another.
482  * NB: should send a message to the session logger to avoid blocking.
483  */
484 static void
485 warning(const char *message, ...)
486 {
487         va_list ap;
488         va_start(ap, message);
489
490         vsyslog(LOG_ALERT, message, ap);
491         va_end(ap);
492 }
493
494 /*
495  * Log an emergency message.
496  * NB: should send a message to the session logger to avoid blocking.
497  */
498 static void
499 emergency(const char *message, ...)
500 {
501         va_list ap;
502         va_start(ap, message);
503
504         vsyslog(LOG_EMERG, message, ap);
505         va_end(ap);
506 }
507
508 /*
509  * Catch an unexpected signal.
510  */
511 static void
512 disaster(int sig)
513 {
514
515         emergency("fatal signal: %s",
516             (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
517
518         sleep(STALL_TIMEOUT);
519         _exit(sig);             /* reboot */
520 }
521
522 /*
523  * Get the security level of the kernel.
524  */
525 static int
526 getsecuritylevel(void)
527 {
528 #ifdef KERN_SECURELVL
529         int name[2], curlevel;
530         size_t len;
531
532         name[0] = CTL_KERN;
533         name[1] = KERN_SECURELVL;
534         len = sizeof curlevel;
535         if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
536                 emergency("cannot get kernel security level: %s",
537                     strerror(errno));
538                 return (-1);
539         }
540         return (curlevel);
541 #else
542         return (-1);
543 #endif
544 }
545
546 /*
547  * Set the security level of the kernel.
548  */
549 static void
550 setsecuritylevel(int newlevel)
551 {
552 #ifdef KERN_SECURELVL
553         int name[2], curlevel;
554
555         curlevel = getsecuritylevel();
556         if (newlevel == curlevel)
557                 return;
558         name[0] = CTL_KERN;
559         name[1] = KERN_SECURELVL;
560         if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
561                 emergency(
562                     "cannot change kernel security level from %d to %d: %s",
563                     curlevel, newlevel, strerror(errno));
564                 return;
565         }
566 #ifdef SECURE
567         warning("kernel security level changed from %d to %d",
568             curlevel, newlevel);
569 #endif
570 #endif
571 }
572
573 /*
574  * Change states in the finite state machine.
575  * The initial state is passed as an argument.
576  */
577 static void
578 transition(state_t s)
579 {
580
581         current_state = s;
582         for (;;)
583                 current_state = (state_t) (*current_state)();
584 }
585
586 /*
587  * Start a session and allocate a controlling terminal.
588  * Only called by children of init after forking.
589  */
590 static void
591 open_console(void)
592 {
593         int fd;
594
595         /*
596          * Try to open /dev/console.  Open the device with O_NONBLOCK to
597          * prevent potential blocking on a carrier.
598          */
599         revoke(_PATH_CONSOLE);
600         if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
601                 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
602                 if (login_tty(fd) == 0)
603                         return;
604                 close(fd);
605         }
606
607         /* No luck.  Log output to file if possible. */
608         if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
609                 stall("cannot open null device.");
610                 _exit(1);
611         }
612         if (fd != STDIN_FILENO) {
613                 dup2(fd, STDIN_FILENO);
614                 close(fd);
615         }
616         fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
617         if (fd == -1)
618                 dup2(STDIN_FILENO, STDOUT_FILENO);
619         else if (fd != STDOUT_FILENO) {
620                 dup2(fd, STDOUT_FILENO);
621                 close(fd);
622         }
623         dup2(STDOUT_FILENO, STDERR_FILENO);
624 }
625
626 static const char *
627 get_shell(void)
628 {
629         static char kenv_value[PATH_MAX];
630
631         if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
632                 return kenv_value;
633         else
634                 return _PATH_BSHELL;
635 }
636
637 static void
638 write_stderr(const char *message)
639 {
640
641         write(STDERR_FILENO, message, strlen(message));
642 }
643
644 static int
645 read_file(const char *path, void **bufp, size_t *bufsizep)
646 {
647         struct stat sb;
648         size_t bufsize;
649         void *buf;
650         ssize_t nbytes;
651         int error, fd;
652
653         fd = open(path, O_RDONLY);
654         if (fd < 0) {
655                 emergency("%s: %s", path, strerror(errno));
656                 return (-1);
657         }
658
659         error = fstat(fd, &sb);
660         if (error != 0) {
661                 emergency("fstat: %s", strerror(errno));
662                 close(fd);
663                 return (error);
664         }
665
666         bufsize = sb.st_size;
667         buf = malloc(bufsize);
668         if (buf == NULL) {
669                 emergency("malloc: %s", strerror(errno));
670                 close(fd);
671                 return (error);
672         }
673
674         nbytes = read(fd, buf, bufsize);
675         if (nbytes != (ssize_t)bufsize) {
676                 emergency("read: %s", strerror(errno));
677                 close(fd);
678                 free(buf);
679                 return (error);
680         }
681
682         error = close(fd);
683         if (error != 0) {
684                 emergency("close: %s", strerror(errno));
685                 free(buf);
686                 return (error);
687         }
688
689         *bufp = buf;
690         *bufsizep = bufsize;
691
692         return (0);
693 }
694
695 static int
696 create_file(const char *path, const void *buf, size_t bufsize)
697 {
698         ssize_t nbytes;
699         int error, fd;
700
701         fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
702         if (fd < 0) {
703                 emergency("%s: %s", path, strerror(errno));
704                 return (-1);
705         }
706
707         nbytes = write(fd, buf, bufsize);
708         if (nbytes != (ssize_t)bufsize) {
709                 emergency("write: %s", strerror(errno));
710                 close(fd);
711                 return (-1);
712         }
713
714         error = close(fd);
715         if (error != 0) {
716                 emergency("close: %s", strerror(errno));
717                 return (-1);
718         }
719
720         return (0);
721 }
722
723 static int
724 mount_tmpfs(const char *fspath)
725 {
726         struct iovec *iov;
727         char errmsg[255];
728         int error, iovlen;
729
730         iov = NULL;
731         iovlen = 0;
732         memset(errmsg, 0, sizeof(errmsg));
733         build_iovec(&iov, &iovlen, "fstype",
734             __DECONST(void *, "tmpfs"), (size_t)-1);
735         build_iovec(&iov, &iovlen, "fspath",
736             __DECONST(void *, fspath), (size_t)-1);
737         build_iovec(&iov, &iovlen, "errmsg",
738             errmsg, sizeof(errmsg));
739
740         error = nmount(iov, iovlen, 0);
741         if (error != 0) {
742                 if (*errmsg != '\0') {
743                         emergency("cannot mount tmpfs on %s: %s: %s",
744                             fspath, errmsg, strerror(errno));
745                 } else {
746                         emergency("cannot mount tmpfs on %s: %s",
747                             fspath, strerror(errno));
748                 }
749                 return (error);
750         }
751         return (0);
752 }
753
754 static state_func_t
755 reroot(void)
756 {
757         void *buf;
758         size_t bufsize;
759         int error;
760
761         buf = NULL;
762         bufsize = 0;
763
764         revoke_ttys();
765         runshutdown();
766
767         /*
768          * Make sure nobody can interfere with our scheme.
769          * Ignore ESRCH, which can apparently happen when
770          * there are no processes to kill.
771          */
772         error = kill(-1, SIGKILL);
773         if (error != 0 && errno != ESRCH) {
774                 emergency("kill(2) failed: %s", strerror(errno));
775                 goto out;
776         }
777
778         /*
779          * Copy the init binary into tmpfs, so that we can unmount
780          * the old rootfs without committing suicide.
781          */
782         error = read_file(init_path_argv0, &buf, &bufsize);
783         if (error != 0)
784                 goto out;
785         error = mount_tmpfs(_PATH_REROOT);
786         if (error != 0)
787                 goto out;
788         error = create_file(_PATH_REROOT_INIT, buf, bufsize);
789         if (error != 0)
790                 goto out;
791
792         /*
793          * Execute the temporary init.
794          */
795         execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
796         emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
797
798 out:
799         emergency("reroot failed; going to single user mode");
800         free(buf);
801         return (state_func_t) single_user;
802 }
803
804 static state_func_t
805 reroot_phase_two(void)
806 {
807         char init_path[PATH_MAX], *path, *path_component;
808         size_t init_path_len;
809         int nbytes, error;
810
811         /*
812          * Ask the kernel to mount the new rootfs.
813          */
814         error = reboot(RB_REROOT);
815         if (error != 0) {
816                 emergency("RB_REBOOT failed: %s", strerror(errno));
817                 goto out;
818         }
819
820         /*
821          * Figure out where the destination init(8) binary is.  Note that
822          * the path could be different than what we've started with.  Use
823          * the value from kenv, if set, or the one from sysctl otherwise.
824          * The latter defaults to a hardcoded value, but can be overridden
825          * by a build time option.
826          */
827         nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
828         if (nbytes <= 0) {
829                 init_path_len = sizeof(init_path);
830                 error = sysctlbyname("kern.init_path",
831                     init_path, &init_path_len, NULL, 0);
832                 if (error != 0) {
833                         emergency("failed to retrieve kern.init_path: %s",
834                             strerror(errno));
835                         goto out;
836                 }
837         }
838
839         /*
840          * Repeat the init search logic from sys/kern/init_path.c
841          */
842         path_component = init_path;
843         while ((path = strsep(&path_component, ":")) != NULL) {
844                 /*
845                  * Execute init(8) from the new rootfs.
846                  */
847                 execl(path, path, NULL);
848         }
849         emergency("cannot exec init from %s: %s", init_path, strerror(errno));
850
851 out:
852         emergency("reroot failed; going to single user mode");
853         return (state_func_t) single_user;
854 }
855
856 /*
857  * Bring the system up single user.
858  */
859 static state_func_t
860 single_user(void)
861 {
862         pid_t pid, wpid;
863         int status;
864         sigset_t mask;
865         const char *shell;
866         char *argv[2];
867         struct timeval tv, tn;
868 #ifdef SECURE
869         struct ttyent *typ;
870         struct passwd *pp;
871         static const char banner[] =
872                 "Enter root password, or ^D to go multi-user\n";
873         char *clear, *password;
874 #endif
875 #ifdef DEBUGSHELL
876         char altshell[128];
877 #endif
878
879         if (Reboot) {
880                 /* Instead of going single user, let's reboot the machine */
881                 sync();
882                 /* Run scripts after all processes have been terminated. */
883                 runfinal();
884                 if (reboot(howto) == -1) {
885                         emergency("reboot(%#x) failed, %s", howto,
886                             strerror(errno));
887                         _exit(1); /* panic and reboot */
888                 }
889                 warning("reboot(%#x) returned", howto);
890                 _exit(0); /* panic as well */
891         }
892
893         shell = get_shell();
894
895         if ((pid = fork()) == 0) {
896                 /*
897                  * Start the single user session.
898                  */
899                 open_console();
900
901 #ifdef SECURE
902                 /*
903                  * Check the root password.
904                  * We don't care if the console is 'on' by default;
905                  * it's the only tty that can be 'off' and 'secure'.
906                  */
907                 typ = getttynam("console");
908                 pp = getpwnam("root");
909                 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
910                     pp && *pp->pw_passwd) {
911                         write_stderr(banner);
912                         for (;;) {
913                                 clear = getpass("Password:");
914                                 if (clear == NULL || *clear == '\0')
915                                         _exit(0);
916                                 password = crypt(clear, pp->pw_passwd);
917                                 explicit_bzero(clear, _PASSWORD_LEN);
918                                 if (password != NULL &&
919                                     strcmp(password, pp->pw_passwd) == 0)
920                                         break;
921                                 warning("single-user login failed\n");
922                         }
923                 }
924                 endttyent();
925                 endpwent();
926 #endif /* SECURE */
927
928 #ifdef DEBUGSHELL
929                 {
930                         char *cp = altshell;
931                         int num;
932
933 #define SHREQUEST "Enter full pathname of shell or RETURN for "
934                         write_stderr(SHREQUEST);
935                         write_stderr(shell);
936                         write_stderr(": ");
937                         while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
938                             num != 0 && *cp != '\n' && cp < &altshell[127])
939                                 cp++;
940                         *cp = '\0';
941                         if (altshell[0] != '\0')
942                                 shell = altshell;
943                 }
944 #endif /* DEBUGSHELL */
945
946                 /*
947                  * Unblock signals.
948                  * We catch all the interesting ones,
949                  * and those are reset to SIG_DFL on exec.
950                  */
951                 sigemptyset(&mask);
952                 sigprocmask(SIG_SETMASK, &mask, NULL);
953
954                 /*
955                  * Fire off a shell.
956                  * If the default one doesn't work, try the Bourne shell.
957                  */
958
959                 char name[] = "-sh";
960
961                 argv[0] = name;
962                 argv[1] = NULL;
963                 execv(shell, argv);
964                 emergency("can't exec %s for single user: %m", shell);
965                 execv(_PATH_BSHELL, argv);
966                 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
967                 sleep(STALL_TIMEOUT);
968                 _exit(1);
969         }
970
971         if (pid == -1) {
972                 /*
973                  * We are seriously hosed.  Do our best.
974                  */
975                 emergency("can't fork single-user shell, trying again");
976                 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
977                         continue;
978                 return (state_func_t) single_user;
979         }
980
981         requested_transition = 0;
982         do {
983                 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
984                         collect_child(wpid);
985                 if (wpid == -1) {
986                         if (errno == EINTR)
987                                 continue;
988                         warning("wait for single-user shell failed: %m; restarting");
989                         return (state_func_t) single_user;
990                 }
991                 if (wpid == pid && WIFSTOPPED(status)) {
992                         warning("init: shell stopped, restarting\n");
993                         kill(pid, SIGCONT);
994                         wpid = -1;
995                 }
996         } while (wpid != pid && !requested_transition);
997
998         if (requested_transition)
999                 return (state_func_t) requested_transition;
1000
1001         if (!WIFEXITED(status)) {
1002                 if (WTERMSIG(status) == SIGKILL) {
1003                         /*
1004                          *  reboot(8) killed shell?
1005                          */
1006                         warning("single user shell terminated.");
1007                         gettimeofday(&tv, NULL);
1008                         tn = tv;
1009                         tv.tv_sec += STALL_TIMEOUT;
1010                         while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1011                             tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1012                                 sleep(1);
1013                                 gettimeofday(&tn, NULL);
1014                         }
1015                         _exit(0);
1016                 } else {
1017                         warning("single user shell terminated, restarting");
1018                         return (state_func_t) single_user;
1019                 }
1020         }
1021
1022         runcom_mode = FASTBOOT;
1023         return (state_func_t) runcom;
1024 }
1025
1026 /*
1027  * Run the system startup script.
1028  */
1029 static state_func_t
1030 runcom(void)
1031 {
1032         state_func_t next_transition;
1033
1034         if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1035                 return next_transition;
1036
1037         runcom_mode = AUTOBOOT;         /* the default */
1038         return (state_func_t) read_ttys;
1039 }
1040
1041 static void
1042 execute_script(char *argv[])
1043 {
1044         struct sigaction sa;
1045         const char *shell, *script;
1046         int error;
1047
1048         bzero(&sa, sizeof(sa));
1049         sigemptyset(&sa.sa_mask);
1050         sa.sa_handler = SIG_IGN;
1051         sigaction(SIGTSTP, &sa, NULL);
1052         sigaction(SIGHUP, &sa, NULL);
1053
1054         open_console();
1055
1056         sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1057 #ifdef LOGIN_CAP
1058         setprocresources(RESOURCE_RC);
1059 #endif
1060
1061         /*
1062          * Try to directly execute the script first.  If it
1063          * fails, try the old method of passing the script path
1064          * to sh(1).  Don't complain if it fails because of
1065          * the missing execute bit.
1066          */
1067         script = argv[1];
1068         error = access(script, X_OK);
1069         if (error == 0) {
1070                 execv(script, argv + 1);
1071                 warning("can't exec %s: %m", script);
1072         } else if (errno != EACCES) {
1073                 warning("can't access %s: %m", script);
1074         }
1075
1076         shell = get_shell();
1077         execv(shell, argv);
1078         stall("can't exec %s for %s: %m", shell, script);
1079 }
1080
1081 /*
1082  * Execute binary, replacing init(8) as PID 1.
1083  */
1084 static void
1085 replace_init(char *path)
1086 {
1087         char *argv[3];
1088         char sh[] = "sh";
1089
1090         argv[0] = sh;
1091         argv[1] = path;
1092         argv[2] = NULL;
1093
1094         execute_script(argv);
1095 }
1096
1097 /*
1098  * Run a shell script.
1099  * Returns 0 on success, otherwise the next transition to enter:
1100  *  - single_user if fork/execv/waitpid failed, or if the script
1101  *    terminated with a signal or exit code != 0.
1102  *  - death_single if a SIGTERM was delivered to init(8).
1103  */
1104 static state_func_t
1105 run_script(const char *script)
1106 {
1107         pid_t pid, wpid;
1108         int status;
1109         char *argv[4];
1110         const char *shell;
1111
1112         shell = get_shell();
1113
1114         if ((pid = fork()) == 0) {
1115
1116                 char _sh[]              = "sh";
1117                 char _autoboot[]        = "autoboot";
1118
1119                 argv[0] = _sh;
1120                 argv[1] = __DECONST(char *, script);
1121                 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1122                 argv[3] = NULL;
1123
1124                 execute_script(argv);
1125                 sleep(STALL_TIMEOUT);
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, NULL);
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, NULL);
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 SIGWINCH:
1618         case SIGUSR2:
1619                 howto = sig == SIGUSR2 ? RB_POWEROFF : RB_POWERCYCLE;
1620         case SIGUSR1:
1621                 howto |= RB_HALT;
1622         case SIGINT:
1623                 Reboot = TRUE;
1624         case SIGTERM:
1625                 if (current_state == read_ttys || current_state == multi_user ||
1626                     current_state == clean_ttys || current_state == catatonia)
1627                         requested_transition = death;
1628                 else
1629                         requested_transition = death_single;
1630                 break;
1631         case SIGTSTP:
1632                 if (current_state == runcom || current_state == read_ttys ||
1633                     current_state == clean_ttys ||
1634                     current_state == multi_user || current_state == catatonia)
1635                         requested_transition = catatonia;
1636                 break;
1637         case SIGEMT:
1638                 requested_transition = reroot;
1639                 break;
1640         default:
1641                 requested_transition = 0;
1642                 break;
1643         }
1644 }
1645
1646 /*
1647  * Take the system multiuser.
1648  */
1649 static state_func_t
1650 multi_user(void)
1651 {
1652         pid_t pid;
1653         session_t *sp;
1654
1655         requested_transition = 0;
1656
1657         /*
1658          * If the administrator has not set the security level to -1
1659          * to indicate that the kernel should not run multiuser in secure
1660          * mode, and the run script has not set a higher level of security
1661          * than level 1, then put the kernel into secure mode.
1662          */
1663         if (getsecuritylevel() == 0)
1664                 setsecuritylevel(1);
1665
1666         for (sp = sessions; sp; sp = sp->se_next) {
1667                 if (sp->se_process)
1668                         continue;
1669                 if (session_has_no_tty(sp))
1670                         continue;
1671                 if ((pid = start_getty(sp)) == -1) {
1672                         /* serious trouble */
1673                         requested_transition = clean_ttys;
1674                         break;
1675                 }
1676                 sp->se_process = pid;
1677                 sp->se_started = time((time_t *) 0);
1678                 add_session(sp);
1679         }
1680
1681         while (!requested_transition)
1682                 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1683                         collect_child(pid);
1684
1685         return (state_func_t) requested_transition;
1686 }
1687
1688 /*
1689  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1690  */
1691 static state_func_t
1692 clean_ttys(void)
1693 {
1694         session_t *sp, *sprev;
1695         struct ttyent *typ;
1696         int devlen;
1697         char *old_getty, *old_window, *old_type;
1698
1699         /*
1700          * mark all sessions for death, (!SE_PRESENT)
1701          * as we find or create new ones they'll be marked as keepers,
1702          * we'll later nuke all the ones not found in /etc/ttys
1703          */
1704         for (sp = sessions; sp != NULL; sp = sp->se_next)
1705                 sp->se_flags &= ~SE_PRESENT;
1706
1707         devlen = sizeof(_PATH_DEV) - 1;
1708         while ((typ = getttyent()) != NULL) {
1709                 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1710                         if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1711                                 break;
1712
1713                 if (sp) {
1714                         /* we want this one to live */
1715                         sp->se_flags |= SE_PRESENT;
1716                         if ((typ->ty_status & TTY_ON) == 0 ||
1717                             typ->ty_getty == 0) {
1718                                 sp->se_flags |= SE_SHUTDOWN;
1719                                 kill(sp->se_process, SIGHUP);
1720                                 continue;
1721                         }
1722                         sp->se_flags &= ~SE_SHUTDOWN;
1723                         old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1724                         old_window = sp->se_window ? strdup(sp->se_window) : 0;
1725                         old_type = sp->se_type ? strdup(sp->se_type) : 0;
1726                         if (setupargv(sp, typ) == 0) {
1727                                 warning("can't parse getty for port %s",
1728                                         sp->se_device);
1729                                 sp->se_flags |= SE_SHUTDOWN;
1730                                 kill(sp->se_process, SIGHUP);
1731                         }
1732                         else if (   !old_getty
1733                                  || (!old_type && sp->se_type)
1734                                  || (old_type && !sp->se_type)
1735                                  || (!old_window && sp->se_window)
1736                                  || (old_window && !sp->se_window)
1737                                  || (strcmp(old_getty, sp->se_getty) != 0)
1738                                  || (old_window && strcmp(old_window, sp->se_window) != 0)
1739                                  || (old_type && strcmp(old_type, sp->se_type) != 0)
1740                                 ) {
1741                                 /* Don't set SE_SHUTDOWN here */
1742                                 sp->se_nspace = 0;
1743                                 sp->se_started = 0;
1744                                 kill(sp->se_process, SIGHUP);
1745                         }
1746                         if (old_getty)
1747                                 free(old_getty);
1748                         if (old_window)
1749                                 free(old_window);
1750                         if (old_type)
1751                                 free(old_type);
1752                         continue;
1753                 }
1754
1755                 new_session(sprev, typ);
1756         }
1757
1758         endttyent();
1759
1760         /*
1761          * sweep through and kill all deleted sessions
1762          * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1763          */
1764         for (sp = sessions; sp != NULL; sp = sp->se_next) {
1765                 if ((sp->se_flags & SE_PRESENT) == 0) {
1766                         sp->se_flags |= SE_SHUTDOWN;
1767                         kill(sp->se_process, SIGHUP);
1768                 }
1769         }
1770
1771         return (state_func_t) multi_user;
1772 }
1773
1774 /*
1775  * Block further logins.
1776  */
1777 static state_func_t
1778 catatonia(void)
1779 {
1780         session_t *sp;
1781
1782         for (sp = sessions; sp; sp = sp->se_next)
1783                 sp->se_flags |= SE_SHUTDOWN;
1784
1785         return (state_func_t) multi_user;
1786 }
1787
1788 /*
1789  * Note SIGALRM.
1790  */
1791 static void
1792 alrm_handler(int sig)
1793 {
1794
1795         (void)sig;
1796         clang = 1;
1797 }
1798
1799 /*
1800  * Bring the system down to single user.
1801  */
1802 static state_func_t
1803 death(void)
1804 {
1805         int block, blocked;
1806         size_t len;
1807
1808         /* Temporarily block suspend. */
1809         len = sizeof(blocked);
1810         block = 1;
1811         if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1812             &block, sizeof(block)) == -1)
1813                 blocked = 0;
1814
1815         /*
1816          * Also revoke the TTY here.  Because runshutdown() may reopen
1817          * the TTY whose getty we're killing here, there is no guarantee
1818          * runshutdown() will perform the initial open() call, causing
1819          * the terminal attributes to be misconfigured.
1820          */
1821         revoke_ttys();
1822
1823         /* Try to run the rc.shutdown script within a period of time */
1824         runshutdown();
1825
1826         /* Unblock suspend if we blocked it. */
1827         if (!blocked)
1828                 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1829                     &blocked, sizeof(blocked));
1830
1831         return (state_func_t) death_single;
1832 }
1833
1834 /*
1835  * Do what is necessary to reinitialize single user mode or reboot
1836  * from an incomplete state.
1837  */
1838 static state_func_t
1839 death_single(void)
1840 {
1841         int i;
1842         pid_t pid;
1843         static const int death_sigs[2] = { SIGTERM, SIGKILL };
1844
1845         revoke(_PATH_CONSOLE);
1846
1847         for (i = 0; i < 2; ++i) {
1848                 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1849                         return (state_func_t) single_user;
1850
1851                 clang = 0;
1852                 alarm(DEATH_WATCH);
1853                 do
1854                         if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1855                                 collect_child(pid);
1856                 while (clang == 0 && errno != ECHILD);
1857
1858                 if (errno == ECHILD)
1859                         return (state_func_t) single_user;
1860         }
1861
1862         warning("some processes would not die; ps axl advised");
1863
1864         return (state_func_t) single_user;
1865 }
1866
1867 static void
1868 revoke_ttys(void)
1869 {
1870         session_t *sp;
1871
1872         for (sp = sessions; sp; sp = sp->se_next) {
1873                 sp->se_flags |= SE_SHUTDOWN;
1874                 kill(sp->se_process, SIGHUP);
1875                 revoke(sp->se_device);
1876         }
1877 }
1878
1879 /*
1880  * Run the system shutdown script.
1881  *
1882  * Exit codes:      XXX I should document more
1883  * -2       shutdown script terminated abnormally
1884  * -1       fatal error - can't run script
1885  * 0        good.
1886  * >0       some error (exit code)
1887  */
1888 static int
1889 runshutdown(void)
1890 {
1891         pid_t pid, wpid;
1892         int status;
1893         int shutdowntimeout;
1894         size_t len;
1895         char *argv[4];
1896         struct stat sb;
1897
1898         /*
1899          * rc.shutdown is optional, so to prevent any unnecessary
1900          * complaints from the shell we simply don't run it if the
1901          * file does not exist. If the stat() here fails for other
1902          * reasons, we'll let the shell complain.
1903          */
1904         if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1905                 return 0;
1906
1907         if ((pid = fork()) == 0) {
1908                 char _sh[]      = "sh";
1909                 char _reboot[]  = "reboot";
1910                 char _single[]  = "single";
1911                 char _path_rundown[] = _PATH_RUNDOWN;
1912
1913                 argv[0] = _sh;
1914                 argv[1] = _path_rundown;
1915                 argv[2] = Reboot ? _reboot : _single;
1916                 argv[3] = NULL;
1917                 
1918                 execute_script(argv);
1919                 _exit(1);       /* force single user mode */
1920         }
1921
1922         if (pid == -1) {
1923                 emergency("can't fork for %s: %m", _PATH_RUNDOWN);
1924                 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1925                         continue;
1926                 sleep(STALL_TIMEOUT);
1927                 return -1;
1928         }
1929
1930         len = sizeof(shutdowntimeout);
1931         if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1932             NULL, 0) == -1 || shutdowntimeout < 2)
1933                 shutdowntimeout = DEATH_SCRIPT;
1934         alarm(shutdowntimeout);
1935         clang = 0;
1936         /*
1937          * Copied from single_user().  This is a bit paranoid.
1938          * Use the same ALRM handler.
1939          */
1940         do {
1941                 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1942                         collect_child(wpid);
1943                 if (clang == 1) {
1944                         /* we were waiting for the sub-shell */
1945                         kill(wpid, SIGTERM);
1946                         warning("timeout expired for %s: %m; going to "
1947                             "single user mode", _PATH_RUNDOWN);
1948                         return -1;
1949                 }
1950                 if (wpid == -1) {
1951                         if (errno == EINTR)
1952                                 continue;
1953                         warning("wait for %s failed: %m; going to "
1954                             "single user mode", _PATH_RUNDOWN);
1955                         return -1;
1956                 }
1957                 if (wpid == pid && WIFSTOPPED(status)) {
1958                         warning("init: %s stopped, restarting\n",
1959                             _PATH_RUNDOWN);
1960                         kill(pid, SIGCONT);
1961                         wpid = -1;
1962                 }
1963         } while (wpid != pid && !clang);
1964
1965         /* Turn off the alarm */
1966         alarm(0);
1967
1968         if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1969             requested_transition == catatonia) {
1970                 /*
1971                  * /etc/rc.shutdown executed /sbin/reboot;
1972                  * wait for the end quietly
1973                  */
1974                 sigset_t s;
1975
1976                 sigfillset(&s);
1977                 for (;;)
1978                         sigsuspend(&s);
1979         }
1980
1981         if (!WIFEXITED(status)) {
1982                 warning("%s terminated abnormally, going to "
1983                     "single user mode", _PATH_RUNDOWN);
1984                 return -2;
1985         }
1986
1987         if ((status = WEXITSTATUS(status)) != 0)
1988                 warning("%s returned status %d", _PATH_RUNDOWN, status);
1989
1990         return status;
1991 }
1992
1993 static char *
1994 strk(char *p)
1995 {
1996         static char *t;
1997         char *q;
1998         int c;
1999
2000         if (p)
2001                 t = p;
2002         if (!t)
2003                 return 0;
2004
2005         c = *t;
2006         while (c == ' ' || c == '\t' )
2007                 c = *++t;
2008         if (!c) {
2009                 t = 0;
2010                 return 0;
2011         }
2012         q = t;
2013         if (c == '\'') {
2014                 c = *++t;
2015                 q = t;
2016                 while (c && c != '\'')
2017                         c = *++t;
2018                 if (!c)  /* unterminated string */
2019                         q = t = 0;
2020                 else
2021                         *t++ = 0;
2022         } else {
2023                 while (c && c != ' ' && c != '\t' )
2024                         c = *++t;
2025                 *t++ = 0;
2026                 if (!c)
2027                         t = 0;
2028         }
2029         return q;
2030 }
2031
2032 #ifdef LOGIN_CAP
2033 static void
2034 setprocresources(const char *cname)
2035 {
2036         login_cap_t *lc;
2037         if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2038                 setusercontext(lc, (struct passwd*)NULL, 0,
2039                     LOGIN_SETENV |
2040                     LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2041                     LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);
2042                 login_close(lc);
2043         }
2044 }
2045 #endif
2046
2047 /*
2048  * Run /etc/rc.final to execute scripts after all user processes have been
2049  * terminated.
2050  */
2051 static void
2052 runfinal(void)
2053 {
2054         struct stat sb;
2055         pid_t other_pid, pid;
2056         sigset_t mask;
2057
2058         /* Avoid any surprises. */
2059         alarm(0);
2060
2061         /* rc.final is optional. */
2062         if (stat(_PATH_RUNFINAL, &sb) == -1 && errno == ENOENT)
2063                 return;
2064         if (access(_PATH_RUNFINAL, X_OK) != 0) {
2065                 warning("%s exists, but not executable", _PATH_RUNFINAL);
2066                 return;
2067         }
2068
2069         pid = fork();
2070         if (pid == 0) {
2071                 /*
2072                  * Reopen stdin/stdout/stderr so that scripts can write to
2073                  * console.
2074                  */
2075                 close(0);
2076                 open(_PATH_DEVNULL, O_RDONLY);
2077                 close(1);
2078                 close(2);
2079                 open_console();
2080                 dup2(1, 2);
2081                 sigemptyset(&mask);
2082                 sigprocmask(SIG_SETMASK, &mask, NULL);
2083                 signal(SIGCHLD, SIG_DFL);
2084                 execl(_PATH_RUNFINAL, _PATH_RUNFINAL, NULL);
2085                 perror("execl(" _PATH_RUNFINAL ") failed");
2086                 exit(1);
2087         }
2088
2089         /* Wait for rc.final script to exit */
2090         while ((other_pid = waitpid(-1, NULL, 0)) != pid && other_pid > 0) {
2091                 continue;
2092         }
2093 }