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