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