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