xref: /dragonfly/sbin/init/init.c (revision f0e61bb7995c1cccad2d39368522d1e4deeee668)
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  * 3. 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  * @(#) Copyright (c) 1991, 1993 The Regents of the University of California.  All rights reserved.
33  * @(#)init.c       8.1 (Berkeley) 7/15/93
34  * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
35  */
36 
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/mount.h>
40 #include <sys/sysctl.h>
41 #include <sys/wait.h>
42 #include <sys/stat.h>
43 
44 #include <db.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <libutil.h>
48 #include <utmpx.h>
49 #include <paths.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <time.h>
56 #include <ttyent.h>
57 #include <unistd.h>
58 #include <sys/reboot.h>
59 #include <err.h>
60 
61 #include <stdarg.h>
62 
63 #ifdef SECURE
64 #include <pwd.h>
65 #endif
66 
67 #ifdef LOGIN_CAP
68 #include <login_cap.h>
69 #endif
70 
71 #include "pathnames.h"
72 
73 /*
74  * Sleep times; used to prevent thrashing.
75  */
76 #define   GETTY_SPACING                  5        /* N secs minimum getty spacing */
77 #define   GETTY_SLEEP                   30        /* sleep N secs after spacing problem */
78 #define   GETTY_NSPACE                   3        /* max. spacing count to bring reaction */
79 #define   WINDOW_WAIT                    3        /* wait N secs after starting window */
80 #define   STALL_TIMEOUT                 30        /* wait N secs after warning */
81 #define   DEATH_WATCH                   10        /* wait N secs for procs to die */
82 #define   DEATH_SCRIPT                  120       /* wait for 2min for /etc/rc.shutdown */
83 
84 /*
85  * User-based resource limits.
86  */
87 #define RESOURCE_RC           "daemon"
88 #define RESOURCE_WINDOW                 "default"
89 #define RESOURCE_GETTY                  "default"
90 
91 #ifndef DEFAULT_STATE
92 #define DEFAULT_STATE                   runcom
93 #endif
94 
95 typedef enum {
96           invalid_state,
97           single_user,
98           runcom,
99           read_ttys,
100           multi_user,
101           clean_ttys,
102           catatonia,
103           death
104 } state_t;
105 typedef state_t (*state_func_t)(void);
106 
107 static state_t f_single_user(void);
108 static state_t f_runcom(void);
109 static state_t f_read_ttys(void);
110 static state_t f_multi_user(void);
111 static state_t f_clean_ttys(void);
112 static state_t f_catatonia(void);
113 static state_t f_death(void);
114 
115 static state_func_t state_funcs[] = {
116           NULL,
117           f_single_user,
118           f_runcom,
119           f_read_ttys,
120           f_multi_user,
121           f_clean_ttys,
122           f_catatonia,
123           f_death
124 };
125 
126 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
127 #define FALSE       0
128 #define TRUE        1
129 
130 static void transition(state_t);
131 static volatile sig_atomic_t requested_transition = DEFAULT_STATE;
132 
133 static void         setctty(const char *);
134 
135 typedef struct init_session {
136           int       se_index;           /* index of entry in ttys file */
137           pid_t     se_process;                   /* controlling process */
138           struct timeval      se_started;                   /* used to avoid thrashing */
139           int       se_flags;           /* status of session */
140 #define   SE_SHUTDOWN         0x1                 /* session won't be restarted */
141 #define   SE_PRESENT          0x2                 /* session is in /etc/ttys */
142           int     se_nspace;              /* spacing count */
143           char      *se_device;                   /* filename of port */
144           char      *se_getty;                    /* what to run on that port */
145           char    *se_getty_argv_space;   /* pre-parsed argument array space */
146           char      **se_getty_argv;    /* pre-parsed argument array */
147           char      *se_window;                   /* window system (started only once) */
148           char    *se_window_argv_space;  /* pre-parsed argument array space */
149           char      **se_window_argv;   /* pre-parsed argument array */
150           char    *se_type;               /* default terminal type */
151           struct    init_session *se_prev;
152           struct    init_session *se_next;
153 } session_t;
154 
155 static void          handle(sig_t, ...);
156 static void          delset(sigset_t *, ...);
157 
158 static void          stall(const char *, ...) __printflike(1, 2);
159 static void          warning(const char *, ...) __printflike(1, 2);
160 static void          emergency(const char *, ...) __printflike(1, 2);
161 static void          disaster(int);
162 static void          badsys(int);
163 static int           runshutdown(void);
164 static char         *strk(char *);
165 
166 #define   DEATH               'd'
167 #define   SINGLE_USER         's'
168 #define   RUNCOM              'r'
169 #define   READ_TTYS 't'
170 #define   MULTI_USER          'm'
171 #define   CLEAN_TTYS          'T'
172 #define   CATATONIA 'c'
173 
174 static void         free_session(session_t *);
175 static session_t *new_session(session_t *, int, struct ttyent *);
176 static void         adjttyent(struct ttyent *typ);
177 
178 static char         **construct_argv(char *);
179 static void         start_window_system(session_t *);
180 static void         collect_child(pid_t, int);
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 char         *get_chroot(void);
187 static int          setupargv(session_t *, struct ttyent *);
188 #ifdef LOGIN_CAP
189 static void         setprocresources(const char *);
190 #endif
191 
192 static void         clear_session_logs(session_t *, int);
193 
194 static int          start_session_db(void);
195 static void         add_session(session_t *);
196 static void         del_session(session_t *);
197 static session_t *find_session(pid_t);
198 
199 static struct timeval boot_time;
200 static state_t current_state = death;
201 static void session_utmpx(const session_t *, int);
202 static void make_utmpx(const char *, const char *, int, pid_t,
203     const struct timeval *, int);
204 static char get_runlevel(const state_t);
205 static void utmpx_set_runlevel(char, char);
206 
207 static int Reboot = FALSE;
208 static int howto = RB_AUTOBOOT;
209 
210 static DB *session_db;
211 static volatile sig_atomic_t clang;
212 static session_t *sessions;
213 
214 /*
215  * The mother of all processes.
216  */
217 int
main(int argc,char * argv[])218 main(int argc, char *argv[])
219 {
220           char *init_chroot;
221           int c;
222           struct sigaction sa;
223           sigset_t mask;
224           struct stat sts;
225 
226           (void)gettimeofday(&boot_time, NULL);
227 
228           /* Dispose of random users. */
229           if (getuid() != 0)
230                     errx(1, "%s", strerror(EPERM));
231 
232           /* System V users like to reexec init. */
233           if (getpid() != 1) {
234 #ifdef COMPAT_SYSV_INIT
235                     /* So give them what they want */
236                     if (argc > 1) {
237                               if (strlen(argv[1]) == 1) {
238                                         char runlevel = *argv[1];
239                                         int sig;
240 
241                                         switch (runlevel) {
242                                                   case '0': /* halt + poweroff */
243                                                             sig = SIGUSR2;
244                                                             break;
245                                                   case '1': /* single-user */
246                                                             sig = SIGTERM;
247                                                             break;
248                                                   case '6': /* reboot */
249                                                             sig = SIGINT;
250                                                             break;
251                                                   case 'c': /* block further logins */
252                                                             sig = SIGTSTP;
253                                                             break;
254                                                   case 'q': /* rescan /etc/ttys */
255                                                             sig = SIGHUP;
256                                                             break;
257                                                   default:
258                                                             goto invalid;
259                                         }
260                                         kill(1, sig);
261                                         _exit(0);
262                               } else
263 invalid:
264                                         errx(1, "invalid run-level ``%s''", argv[1]);
265                     } else
266 #endif
267                               errx(1, "already running");
268           }
269           /*
270            * Note that this does NOT open a file...
271            * Does 'init' deserve its own facility number?
272            */
273           openlog("init", LOG_CONS, LOG_AUTH);
274 
275           /*
276            * If chroot has been requested by the boot loader,
277            * do it now.  Try to be robust:  If the directory
278            * doesn't exist, continue anyway.
279            */
280           init_chroot = get_chroot();
281           if (init_chroot != NULL) {
282                     if (chdir(init_chroot) == -1 || chroot(".") == -1)
283                               warning("can't chroot to %s: %m", init_chroot);
284                     free(init_chroot);
285           }
286 
287           /*
288            * Create an initial session.
289            */
290           if (setsid() < 0)
291                     warning("initial setsid() failed: %m");
292 
293           /*
294            * Establish an initial user so that programs running
295            * single user do not freak out and die (like passwd).
296            */
297           if (setlogin("root") < 0)
298                     warning("setlogin() failed: %m");
299 
300           if (stat("/dev/null", &sts) < 0) {
301                     warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
302                     sleep(5);
303           }
304 
305           /*
306            * This code assumes that we always get arguments through flags,
307            * never through bits set in some random machine register.
308            */
309           while ((c = getopt(argc, argv, "dsf")) != -1)
310                     switch (c) {
311                     case 'd':
312                               /* We don't support DEVFS. */
313                               break;
314                     case 's':
315                               requested_transition = single_user;
316                               break;
317                     case 'f':
318                               runcom_mode = FASTBOOT;
319                               break;
320                     default:
321                               warning("unrecognized flag '-%c'", c);
322                               break;
323                     }
324 
325           if (optind != argc)
326                     warning("ignoring excess arguments");
327 
328           /*
329            * We catch or block signals rather than ignore them,
330            * so that they get reset on exec.
331            */
332           handle(badsys, SIGSYS, 0);
333           handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
334                  SIGBUS, SIGXCPU, SIGXFSZ, 0);
335           handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
336                     SIGUSR1, SIGUSR2, 0);
337           handle(alrm_handler, SIGALRM, 0);
338           sigfillset(&mask);
339           delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
340                     SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
341                     SIGUSR1, SIGUSR2, 0);
342           sigprocmask(SIG_SETMASK, &mask, NULL);
343           sigemptyset(&sa.sa_mask);
344           sa.sa_flags = 0;
345           sa.sa_handler = SIG_IGN;
346           sigaction(SIGTTIN, &sa, NULL);
347           sigaction(SIGTTOU, &sa, NULL);
348 
349           /*
350            * Paranoia.
351            */
352           close(0);
353           close(1);
354           close(2);
355 
356           /*
357            * Start the state machine.
358            */
359           transition(requested_transition);
360 
361           /*
362            * Should never reach here.
363            */
364           return 1;
365 }
366 
367 /*
368  * Associate a function with a signal handler.
369  */
370 static void
handle(sig_t handler,...)371 handle(sig_t handler, ...)
372 {
373           int sig;
374           struct sigaction sa;
375           sigset_t mask_everything;
376           va_list ap;
377 
378           va_start(ap, handler);
379 
380           sa.sa_handler = handler;
381           sigfillset(&mask_everything);
382 
383           while ((sig = va_arg(ap, int)) != 0) {
384                     sa.sa_mask = mask_everything;
385                     /* XXX SA_RESTART? */
386                     sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
387                     sigaction(sig, &sa, NULL);
388           }
389           va_end(ap);
390 }
391 
392 /*
393  * Delete a set of signals from a mask.
394  */
395 static void
delset(sigset_t * maskp,...)396 delset(sigset_t *maskp, ...)
397 {
398           int sig;
399           va_list ap;
400 
401           va_start(ap, maskp);
402 
403           while ((sig = va_arg(ap, int)) != 0)
404                     sigdelset(maskp, sig);
405           va_end(ap);
406 }
407 
408 /*
409  * Log a message and sleep for a while (to give someone an opportunity
410  * to read it and to save log or hardcopy output if the problem is chronic).
411  */
412 static void
stall(const char * message,...)413 stall(const char *message, ...)
414 {
415           va_list ap;
416 
417           va_start(ap, message);
418 
419           vsyslog(LOG_ALERT, message, ap);
420           va_end(ap);
421           sleep(STALL_TIMEOUT);
422 }
423 
424 /*
425  * Like stall(), but doesn't sleep.
426  * If cpp had variadic macros, the two functions could be #defines for another.
427  */
428 static void
warning(const char * message,...)429 warning(const char *message, ...)
430 {
431           va_list ap;
432 
433           va_start(ap, message);
434 
435           vsyslog(LOG_ALERT, message, ap);
436           va_end(ap);
437 }
438 
439 /*
440  * Log an emergency message.
441  */
442 static void
emergency(const char * message,...)443 emergency(const char *message, ...)
444 {
445           va_list ap;
446 
447           va_start(ap, message);
448 
449           vsyslog(LOG_EMERG, message, ap);
450           va_end(ap);
451 }
452 
453 /*
454  * Catch a SIGSYS signal.
455  *
456  * These may arise if a system does not support sysctl.
457  * We tolerate up to 25 of these, then throw in the towel.
458  */
459 static void
badsys(int sig)460 badsys(int sig)
461 {
462           static int badcount = 0;
463 
464           if (badcount++ < 25)
465                     return;
466           disaster(sig);
467 }
468 
469 /*
470  * Catch an unexpected signal.
471  */
472 static void
disaster(int sig)473 disaster(int sig)
474 {
475           emergency("fatal signal: %s",
476                     (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
477 
478           sleep(STALL_TIMEOUT);
479           _exit(sig);                   /* reboot */
480 }
481 
482 /*
483  * Get the security level of the kernel.
484  */
485 static int
getsecuritylevel(void)486 getsecuritylevel(void)
487 {
488 #ifdef KERN_SECURELVL
489           int name[2], curlevel;
490           size_t len;
491 
492           name[0] = CTL_KERN;
493           name[1] = KERN_SECURELVL;
494           len = sizeof curlevel;
495           if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
496                     emergency("cannot get kernel security level: %s",
497                         strerror(errno));
498                     return (-1);
499           }
500           return (curlevel);
501 #else
502           return (-1);
503 #endif
504 }
505 
506 /*
507  * Get the value of the "init_chroot" variable from the
508  * kernel environment (or NULL if not set).
509  */
510 
511 static char *
get_chroot(void)512 get_chroot(void)
513 {
514           static const char ichname[] = "init_chroot=";     /* includes '=' */
515           const int ichlen = strlen(ichname);
516           int real_oid[CTL_MAXNAME];
517           char sbuf[1024];
518           size_t oidlen, slen;
519           char *res;
520           int i;
521 
522           oidlen = NELEM(real_oid);
523           if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
524                     warning("cannot find kern.environment base sysctl OID");
525                     return NULL;
526           }
527           if (oidlen + 1 >= NELEM(real_oid)) {
528                     warning("kern.environment OID is too large!");
529                     return NULL;
530           }
531           res = NULL;
532           real_oid[oidlen] = 0;
533 
534           for (i = 0; ; i++) {
535                     real_oid[oidlen + 1] = i;
536                     slen = sizeof(sbuf);
537                     if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
538                               if (errno != ENOENT)
539                                         warning("sysctl kern.environment.%d: %m", i);
540                               break;
541                     }
542 
543                     /*
544                      * slen includes the terminating \0, but do a few sanity
545                      * checks anyway.
546                      */
547                     if (slen == 0)
548                               continue;
549                     sbuf[slen - 1] = 0;
550                     if (strncmp(sbuf, ichname, ichlen) != 0)
551                               continue;
552                     if (sbuf[ichlen])
553                               res = strdup(sbuf + ichlen);
554                     break;
555           }
556           return (res);
557 }
558 
559 /*
560  * Set the security level of the kernel.
561  */
562 static void
setsecuritylevel(int newlevel)563 setsecuritylevel(int newlevel)
564 {
565 #ifdef KERN_SECURELVL
566           int name[2], curlevel;
567 
568           curlevel = getsecuritylevel();
569           if (newlevel == curlevel)
570                     return;
571           name[0] = CTL_KERN;
572           name[1] = KERN_SECURELVL;
573           if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
574                     emergency(
575                         "cannot change kernel security level from %d to %d: %s",
576                         curlevel, newlevel, strerror(errno));
577                     return;
578           }
579 #ifdef SECURE
580           warning("kernel security level changed from %d to %d",
581               curlevel, newlevel);
582 #endif
583 #endif
584 }
585 
586 /*
587  * Change states in the finite state machine.
588  * The initial state is passed as an argument.
589  */
590 static void
transition(state_t s)591 transition(state_t s)
592 {
593           for (;;) {
594                     utmpx_set_runlevel(get_runlevel(current_state),
595                         get_runlevel(s));
596                     current_state = s;
597                     s = (*state_funcs[s])();
598           }
599 }
600 
601 /*
602  * Close out the accounting files for a login session.
603  */
604 static void
clear_session_logs(session_t * sp,int status)605 clear_session_logs(session_t *sp, int status)
606 {
607           char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
608 
609           if (logoutx(line, status, DEAD_PROCESS))
610                      logwtmpx(line, "", "", status, DEAD_PROCESS);
611 }
612 
613 /*
614  * Start a session and allocate a controlling terminal.
615  * Only called by children of init after forking.
616  */
617 static void
setctty(const char * name)618 setctty(const char *name)
619 {
620           int fd;
621 
622           revoke(name);
623           if ((fd = open(name, O_RDWR)) == -1) {
624                     stall("can't open %s: %m", name);
625                     _exit(1);
626           }
627           if (login_tty(fd) == -1) {
628                     stall("can't get %s for controlling terminal: %m", name);
629                     _exit(1);
630           }
631 }
632 
633 /*
634  * Bring the system up single user.
635  */
636 static state_t
f_single_user(void)637 f_single_user(void)
638 {
639           pid_t pid, wpid;
640           int status;
641           sigset_t mask;
642           const char *shell = _PATH_BSHELL;
643           const char *argv[2];
644 #ifdef SECURE
645           struct ttyent *typ;
646           struct passwd *pp;
647           static const char banner[] =
648                     "Enter root password, or ^D to go multi-user\n";
649           char *clear, *password;
650 #endif
651 #ifdef DEBUGSHELL
652           char altshell[128];
653 #endif
654 
655           if (Reboot) {
656                     /* Instead of going single user, let's reboot the machine */
657                     sync();
658                     alarm(2);
659                     pause();
660                     reboot(howto);
661                     _exit(0);
662           }
663 
664           if ((pid = fork()) == 0) {
665                     /*
666                      * Start the single user session.
667                      */
668                     setctty(_PATH_CONSOLE);
669 
670 #ifdef SECURE
671                     /*
672                      * Check the root password.
673                      * We don't care if the console is 'on' by default;
674                      * it's the only tty that can be 'off' and 'secure'.
675                      */
676                     typ = getttynam("console");
677                     pp = getpwnam("root");
678                     if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
679                         pp && *pp->pw_passwd) {
680                               write(2, banner, sizeof banner - 1);
681                               for (;;) {
682                                         clear = getpass("Password:");
683                                         if (clear == NULL || *clear == '\0')
684                                                   _exit(0);
685                                         password = crypt(clear, pp->pw_passwd);
686                                         bzero(clear, _PASSWORD_LEN);
687                                         if (password != NULL && strcmp(password, pp->pw_passwd) == 0)
688                                                   break;
689                                         warning("single-user login failed\n");
690                               }
691                     }
692                     endttyent();
693                     endpwent();
694 #endif /* SECURE */
695 
696 #ifdef DEBUGSHELL
697                     {
698                               char *cp = altshell;
699                               int num;
700 
701 #define   SHREQUEST \
702           "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
703                               write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
704                               while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
705                                   num != 0 && *cp != '\n' && cp < &altshell[127])
706                                                   cp++;
707                               *cp = '\0';
708                               if (altshell[0] != '\0')
709                                         shell = altshell;
710                     }
711 #endif /* DEBUGSHELL */
712 
713                     /*
714                      * Unblock signals.
715                      * We catch all the interesting ones,
716                      * and those are reset to SIG_DFL on exec.
717                      */
718                     sigemptyset(&mask);
719                     sigprocmask(SIG_SETMASK, &mask, NULL);
720 
721                     /*
722                      * Fire off a shell.
723                      * If the default one doesn't work, try the Bourne shell.
724                      */
725                     argv[0] = "-sh";
726                     argv[1] = NULL;
727                     execv(shell, __DECONST(char **, argv));
728                     emergency("can't exec %s for single user: %m", shell);
729                     execv(_PATH_BSHELL, __DECONST(char **, argv));
730                     emergency("can't exec %s for single user: %m", _PATH_BSHELL);
731                     sleep(STALL_TIMEOUT);
732                     _exit(1);
733           }
734 
735           if (pid == -1) {
736                     /*
737                      * We are seriously hosed.  Do our best.
738                      */
739                     emergency("can't fork single-user shell, trying again");
740                     while (waitpid(-1, NULL, WNOHANG) > 0)
741                               continue;
742                     return single_user;
743           }
744 
745           requested_transition = 0;
746           do {
747                     if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
748                               collect_child(wpid, status);
749                     if (wpid == -1) {
750                               if (errno == EINTR)
751                                         continue;
752                               warning("wait for single-user shell failed: %m; restarting");
753                               return single_user;
754                     }
755                     if (wpid == pid && WIFSTOPPED(status)) {
756                               warning("init: shell stopped, restarting\n");
757                               kill(pid, SIGCONT);
758                               wpid = -1;
759                     }
760           } while (wpid != pid && !requested_transition);
761 
762           if (requested_transition)
763                     return requested_transition;
764 
765           if (!WIFEXITED(status)) {
766                     if (WTERMSIG(status) == SIGKILL) {
767                               /*
768                                *  reboot(8) killed shell?
769                                */
770                               warning("single user shell terminated.");
771                               sleep(STALL_TIMEOUT);
772                               _exit(0);
773                     } else {
774                               warning("single user shell terminated, restarting");
775                               return single_user;
776                     }
777           }
778 
779           runcom_mode = FASTBOOT;
780           return runcom;
781 }
782 
783 /*
784  * Run the system startup script.
785  */
786 static state_t
f_runcom(void)787 f_runcom(void)
788 {
789           pid_t pid, wpid;
790           int status;
791           const char *argv[4];
792           struct sigaction sa;
793 
794           if ((pid = fork()) == 0) {
795                     sigemptyset(&sa.sa_mask);
796                     sa.sa_flags = 0;
797                     sa.sa_handler = SIG_IGN;
798                     sigaction(SIGTSTP, &sa, NULL);
799                     sigaction(SIGHUP, &sa, NULL);
800 
801                     setctty(_PATH_CONSOLE);
802 
803                     argv[0] = "sh";
804                     argv[1] = _PATH_RUNCOM;
805                     argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
806                     argv[3] = NULL;
807 
808                     sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
809 
810 #ifdef LOGIN_CAP
811                     setprocresources(RESOURCE_RC);
812 #endif
813                     execv(_PATH_BSHELL, __DECONST(char **, argv));
814                     stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
815                     _exit(1); /* force single user mode */
816           }
817 
818           if (pid == -1) {
819                     emergency("can't fork for %s on %s: %m",
820                               _PATH_BSHELL, _PATH_RUNCOM);
821                     while (waitpid(-1, NULL, WNOHANG) > 0)
822                               continue;
823                     sleep(STALL_TIMEOUT);
824                     return single_user;
825           }
826 
827           /*
828            * Copied from single_user().  This is a bit paranoid.
829            */
830           requested_transition = 0;
831           do {
832                     if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
833                               collect_child(wpid, status);
834                     if (wpid == -1) {
835                               if (requested_transition == death)
836                                         return death;
837                               if (errno == EINTR)
838                                         continue;
839                               warning("wait for %s on %s failed: %m; going to single user mode",
840                                         _PATH_BSHELL, _PATH_RUNCOM);
841                               return single_user;
842                     }
843                     if (wpid == pid && WIFSTOPPED(status)) {
844                               warning("init: %s on %s stopped, restarting\n",
845                                         _PATH_BSHELL, _PATH_RUNCOM);
846                               kill(pid, SIGCONT);
847                               wpid = -1;
848                     }
849           } while (wpid != pid);
850 
851           if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
852               requested_transition == catatonia) {
853                     /* /etc/rc executed /sbin/reboot; wait for the end quietly */
854                     sigset_t s;
855 
856                     sigfillset(&s);
857                     for (;;)
858                               sigsuspend(&s);
859           }
860 
861           if (!WIFEXITED(status)) {
862                     warning("%s on %s terminated abnormally, going to single user mode",
863                               _PATH_BSHELL, _PATH_RUNCOM);
864                     return single_user;
865           }
866 
867           if (WEXITSTATUS(status))
868                     return single_user;
869 
870           runcom_mode = AUTOBOOT;                 /* the default */
871           logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
872           return read_ttys;
873 }
874 
875 /*
876  * Open the session database.
877  *
878  * NB: We could pass in the size here; is it necessary?
879  */
880 static int
start_session_db(void)881 start_session_db(void)
882 {
883           if (session_db && (*session_db->close)(session_db))
884                     emergency("session database close: %s", strerror(errno));
885           if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
886                     emergency("session database open: %s", strerror(errno));
887                     return (1);
888           }
889           return (0);
890 
891 }
892 
893 /*
894  * Add a new login session.
895  */
896 static void
add_session(session_t * sp)897 add_session(session_t *sp)
898 {
899           DBT key;
900           DBT data;
901 
902           key.data = &sp->se_process;
903           key.size = sizeof sp->se_process;
904           data.data = &sp;
905           data.size = sizeof sp;
906 
907           if ((*session_db->put)(session_db, &key, &data, 0))
908                     emergency("insert %d: %s", sp->se_process, strerror(errno));
909           session_utmpx(sp, 1);
910 }
911 
912 /*
913  * Delete an old login session.
914  */
915 static void
del_session(session_t * sp)916 del_session(session_t *sp)
917 {
918           DBT key;
919 
920           key.data = &sp->se_process;
921           key.size = sizeof sp->se_process;
922 
923           if ((*session_db->del)(session_db, &key, 0))
924                     emergency("delete %d: %s", sp->se_process, strerror(errno));
925           session_utmpx(sp, 0);
926 }
927 
928 /*
929  * Look up a login session by pid.
930  */
931 static session_t *
find_session(pid_t pid)932 find_session(pid_t pid)
933 {
934           DBT key;
935           DBT data;
936           session_t *ret;
937 
938           key.data = &pid;
939           key.size = sizeof pid;
940           if ((*session_db->get)(session_db, &key, &data, 0) != 0)
941                     return 0;
942           bcopy(data.data, (char *)&ret, sizeof(ret));
943           return ret;
944 }
945 
946 /*
947  * Construct an argument vector from a command line.
948  */
949 static char **
construct_argv(char * command)950 construct_argv(char *command)
951 {
952           int argc = 0;
953           char **argv = malloc(((strlen(command) + 1) / 2 + 1)
954                                                             * sizeof (char *));
955 
956           if ((argv[argc++] = strk(command)) == NULL) {
957                     free(argv);
958                     return (NULL);
959           }
960           while ((argv[argc++] = strk(NULL)) != NULL)
961                     continue;
962           return argv;
963 }
964 
965 /*
966  * Deallocate a session descriptor.
967  */
968 static void
free_session(session_t * sp)969 free_session(session_t *sp)
970 {
971           free(sp->se_device);
972           if (sp->se_getty) {
973                     free(sp->se_getty);
974                     free(sp->se_getty_argv_space);
975                     free(sp->se_getty_argv);
976           }
977           if (sp->se_window) {
978                     free(sp->se_window);
979                     free(sp->se_window_argv_space);
980                     free(sp->se_window_argv);
981           }
982           if (sp->se_type)
983                     free(sp->se_type);
984           free(sp);
985 }
986 
987 static
988 void
adjttyent(struct ttyent * typ)989 adjttyent(struct ttyent *typ)
990 {
991           struct stat st;
992           uint32_t rdev;
993           char *devpath;
994           size_t rdev_size = sizeof(rdev);
995 
996           if (typ->ty_name == NULL)
997                     return;
998 
999           /*
1000            * IFEXISTS option forces tty off if it doesn't exist.
1001            */
1002           if (typ->ty_status & TTY_IFEXISTS) {
1003                     asprintf(&devpath, "%s%s", _PATH_DEV, typ->ty_name);
1004                     if (stat(devpath, &st) < 0)
1005                               typ->ty_status &= ~TTY_ON;
1006                     free(devpath);
1007           }
1008 
1009           /*
1010            * IFCONSOLE option forces tty off if not the console.
1011            */
1012           if (typ->ty_status & TTY_IFCONSOLE) {
1013                     asprintf(&devpath, "%s%s", _PATH_DEV, typ->ty_name);
1014                     if (stat(devpath, &st) < 0 ||
1015                         sysctlbyname("kern.console_rdev",
1016                                          &rdev, &rdev_size,
1017                                          NULL, 0) < 0) {
1018                               /* device does not exist or no sysctl, disable */
1019                               typ->ty_status &= ~TTY_ON;
1020                     } else if (rdev != st.st_rdev) {
1021                               typ->ty_status &= ~TTY_ON;
1022                     }
1023                     free(devpath);
1024           }
1025 }
1026 
1027 /*
1028  * Allocate a new session descriptor.
1029  * Mark it SE_PRESENT.
1030  */
1031 static session_t *
new_session(session_t * sprev,int session_index,struct ttyent * typ)1032 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1033 {
1034           session_t *sp;
1035           int fd;
1036 
1037           if (typ->ty_name == NULL || typ->ty_getty == NULL)
1038                     return 0;
1039 
1040           if ((typ->ty_status & TTY_ON) == 0)
1041                     return 0;
1042 
1043           sp = (session_t *) calloc(1, sizeof (session_t));
1044 
1045           asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1046           sp->se_index = session_index;
1047           sp->se_flags |= SE_PRESENT;
1048 
1049           /*
1050            * Attempt to open the device, if we get "device not configured"
1051            * then don't add the device to the session list.
1052            */
1053           if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1054                     if (errno == ENXIO) {
1055                               free_session(sp);
1056                               return (0);
1057                     }
1058           } else
1059                     close(fd);
1060 
1061           if (setupargv(sp, typ) == 0) {
1062                     free_session(sp);
1063                     return (0);
1064           }
1065 
1066           sp->se_next = NULL;
1067           if (sprev == NULL) {
1068                     sessions = sp;
1069                     sp->se_prev = NULL;
1070           } else {
1071                     sprev->se_next = sp;
1072                     sp->se_prev = sprev;
1073           }
1074 
1075           return sp;
1076 }
1077 
1078 /*
1079  * Calculate getty and if useful window argv vectors.
1080  */
1081 static int
setupargv(session_t * sp,struct ttyent * typ)1082 setupargv(session_t *sp, struct ttyent *typ)
1083 {
1084 
1085           if (sp->se_getty) {
1086                     free(sp->se_getty);
1087                     free(sp->se_getty_argv_space);
1088                     free(sp->se_getty_argv);
1089           }
1090           sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1091           sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1092           sp->se_getty_argv_space = strdup(sp->se_getty);
1093           sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1094           if (sp->se_getty_argv == NULL) {
1095                     warning("can't parse getty for port %s", sp->se_device);
1096                     free(sp->se_getty);
1097                     free(sp->se_getty_argv_space);
1098                     sp->se_getty = sp->se_getty_argv_space = NULL;
1099                     return (0);
1100           }
1101           if (sp->se_window) {
1102                     free(sp->se_window);
1103                     free(sp->se_window_argv_space);
1104                     free(sp->se_window_argv);
1105           }
1106           sp->se_window = sp->se_window_argv_space = NULL;
1107           sp->se_window_argv = NULL;
1108           if (typ->ty_window) {
1109                     sp->se_window = strdup(typ->ty_window);
1110                     sp->se_window_argv_space = strdup(sp->se_window);
1111                     sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1112                     if (sp->se_window_argv == NULL) {
1113                               warning("can't parse window for port %s",
1114                                         sp->se_device);
1115                               free(sp->se_window_argv_space);
1116                               free(sp->se_window);
1117                               sp->se_window = sp->se_window_argv_space = NULL;
1118                               return (0);
1119                     }
1120           }
1121           if (sp->se_type)
1122                     free(sp->se_type);
1123           sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1124           return (1);
1125 }
1126 
1127 /*
1128  * Walk the list of ttys and create sessions for each active line.
1129  */
1130 static state_t
f_read_ttys(void)1131 f_read_ttys(void)
1132 {
1133           int session_index = 0;
1134           session_t *sp, *snext;
1135           struct ttyent *typ;
1136 
1137           if (sessions == NULL) {
1138                     struct stat st;
1139 
1140                     make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1141 
1142                     /*
1143                      * If wtmpx is not empty, pick the down time from there
1144                      */
1145                     if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1146                               struct timeval down_time;
1147 
1148                               TIMESPEC_TO_TIMEVAL(&down_time,
1149                                   st.st_atime > st.st_mtime ?
1150                                   &st.st_atimespec : &st.st_mtimespec);
1151                               make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1152                     }
1153           }
1154           /*
1155            * Destroy any previous session state.
1156            * There shouldn't be any, but just in case...
1157            */
1158           for (sp = sessions; sp; sp = snext) {
1159                     if (sp->se_process)
1160                               clear_session_logs(sp, 0);
1161                     snext = sp->se_next;
1162                     free_session(sp);
1163           }
1164           sessions = NULL;
1165           if (start_session_db())
1166                     return single_user;
1167 
1168           /*
1169            * Allocate a session entry for each active port.
1170            * Note that sp starts at 0.
1171            */
1172           while ((typ = getttyent()) != NULL) {
1173                     adjttyent(typ);
1174                     if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1175                               sp = snext;
1176           }
1177 
1178           endttyent();
1179 
1180           return multi_user;
1181 }
1182 
1183 /*
1184  * Start a window system running.
1185  */
1186 static void
start_window_system(session_t * sp)1187 start_window_system(session_t *sp)
1188 {
1189           pid_t pid;
1190           sigset_t mask;
1191           char term[64], *env[2];
1192 
1193           if ((pid = fork()) == -1) {
1194                     emergency("can't fork for window system on port %s: %m",
1195                               sp->se_device);
1196                     /* hope that getty fails and we can try again */
1197                     return;
1198           }
1199 
1200           if (pid)
1201                     return;
1202 
1203           sigemptyset(&mask);
1204           sigprocmask(SIG_SETMASK, &mask, NULL);
1205 
1206           if (setsid() < 0)
1207                     emergency("setsid failed (window) %m");
1208 
1209 #ifdef LOGIN_CAP
1210           setprocresources(RESOURCE_WINDOW);
1211 #endif
1212           if (sp->se_type) {
1213                     /* Don't use malloc after fork */
1214                     strcpy(term, "TERM=");
1215                     strncat(term, sp->se_type, sizeof(term) - 6);
1216                     env[0] = term;
1217                     env[1] = NULL;
1218           }
1219           else
1220                     env[0] = NULL;
1221           execve(sp->se_window_argv[0], sp->se_window_argv, env);
1222           stall("can't exec window system '%s' for port %s: %m",
1223                     sp->se_window_argv[0], sp->se_device);
1224           _exit(1);
1225 }
1226 
1227 /*
1228  * Start a login session running.
1229  */
1230 static pid_t
start_getty(session_t * sp)1231 start_getty(session_t *sp)
1232 {
1233           pid_t pid;
1234           sigset_t mask;
1235           time_t current_time = time(NULL);
1236           int too_quick = 0;
1237           char term[64], *env[2];
1238 
1239           if (current_time >= sp->se_started.tv_sec &&
1240               current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1241                     if (++sp->se_nspace > GETTY_NSPACE) {
1242                               sp->se_nspace = 0;
1243                               too_quick = 1;
1244                     }
1245           } else
1246                     sp->se_nspace = 0;
1247 
1248           /*
1249            * fork(), not vfork() -- we can't afford to block.
1250            */
1251           if ((pid = fork()) == -1) {
1252                     emergency("can't fork for getty on port %s: %m", sp->se_device);
1253                     return -1;
1254           }
1255 
1256           if (pid)
1257                     return pid;
1258 
1259           if (too_quick) {
1260                     warning("getty repeating too quickly on port %s, sleeping %d secs",
1261                               sp->se_device, GETTY_SLEEP);
1262                     sleep((unsigned) GETTY_SLEEP);
1263           }
1264 
1265           if (sp->se_window) {
1266                     start_window_system(sp);
1267                     sleep(WINDOW_WAIT);
1268           }
1269 
1270           sigemptyset(&mask);
1271           sigprocmask(SIG_SETMASK, &mask, NULL);
1272 
1273 #ifdef LOGIN_CAP
1274           setprocresources(RESOURCE_GETTY);
1275 #endif
1276           if (sp->se_type) {
1277                     /* Don't use malloc after fork */
1278                     strcpy(term, "TERM=");
1279                     strncat(term, sp->se_type, sizeof(term) - 6);
1280                     env[0] = term;
1281                     env[1] = NULL;
1282           }
1283           else
1284                     env[0] = NULL;
1285           execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1286           stall("can't exec getty '%s' for port %s: %m",
1287                     sp->se_getty_argv[0], sp->se_device);
1288           _exit(1);
1289 }
1290 
1291 /*
1292  * Collect exit status for a child.
1293  * If an exiting login, start a new login running.
1294  */
1295 static void
collect_child(pid_t pid,int status)1296 collect_child(pid_t pid, int status)
1297 {
1298           session_t *sp, *sprev, *snext;
1299 
1300           if (! sessions)
1301                     return;
1302 
1303           if (! (sp = find_session(pid)))
1304                     return;
1305 
1306           clear_session_logs(sp, status);
1307           del_session(sp);
1308           sp->se_process = 0;
1309 
1310           if (sp->se_flags & SE_SHUTDOWN) {
1311                     if ((sprev = sp->se_prev) != NULL)
1312                               sprev->se_next = sp->se_next;
1313                     else
1314                               sessions = sp->se_next;
1315                     if ((snext = sp->se_next) != NULL)
1316                               snext->se_prev = sp->se_prev;
1317                     free_session(sp);
1318                     return;
1319           }
1320 
1321           if ((pid = start_getty(sp)) == -1) {
1322                     /* serious trouble */
1323                     requested_transition = clean_ttys;
1324                     return;
1325           }
1326 
1327           sp->se_process = pid;
1328           gettimeofday(&sp->se_started, NULL);
1329           add_session(sp);
1330 }
1331 
1332 /*
1333  * Catch a signal and request a state transition.
1334  */
1335 static void
transition_handler(int sig)1336 transition_handler(int sig)
1337 {
1338 
1339           switch (sig) {
1340           case SIGHUP:
1341                     requested_transition = clean_ttys;
1342                     break;
1343           case SIGUSR2:
1344                     howto = RB_POWEROFF;
1345                     /* FALLTHROUGH */
1346           case SIGUSR1:
1347                     howto |= RB_HALT;
1348                     /* FALLTHROUGH */
1349           case SIGINT:
1350                     Reboot = TRUE;
1351                     /* FALLTHROUGH */
1352           case SIGTERM:
1353                     requested_transition = death;
1354                     break;
1355           case SIGTSTP:
1356                     requested_transition = catatonia;
1357                     break;
1358           default:
1359                     requested_transition = 0;
1360                     break;
1361           }
1362 }
1363 
1364 /*
1365  * Take the system multiuser.
1366  */
1367 static state_t
f_multi_user(void)1368 f_multi_user(void)
1369 {
1370           pid_t pid;
1371           int status;
1372           session_t *sp;
1373 
1374           requested_transition = 0;
1375 
1376           /*
1377            * If the administrator has not set the security level to -1
1378            * to indicate that the kernel should not run multiuser in secure
1379            * mode, and the run script has not set a higher level of security
1380            * than level 1, then put the kernel into secure mode.
1381            */
1382           if (getsecuritylevel() == 0)
1383                     setsecuritylevel(1);
1384 
1385           for (sp = sessions; sp; sp = sp->se_next) {
1386                     if (sp->se_process)
1387                               continue;
1388                     if ((pid = start_getty(sp)) == -1) {
1389                               /* serious trouble */
1390                               requested_transition = clean_ttys;
1391                               break;
1392                     }
1393                     sp->se_process = pid;
1394                     gettimeofday(&sp->se_started, NULL);
1395                     add_session(sp);
1396           }
1397 
1398           while (!requested_transition)
1399                     if ((pid = waitpid(-1, &status, 0)) != -1)
1400                               collect_child(pid, status);
1401 
1402           return requested_transition;
1403 }
1404 
1405 /*
1406  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1407  */
1408 static state_t
f_clean_ttys(void)1409 f_clean_ttys(void)
1410 {
1411           session_t *sp, *sprev;
1412           struct ttyent *typ;
1413           int session_index = 0;
1414           int devlen;
1415           char *old_getty, *old_window, *old_type;
1416 
1417           if (! sessions)
1418                     return multi_user;
1419 
1420           /*
1421            * mark all sessions for death, (!SE_PRESENT)
1422            * as we find or create new ones they'll be marked as keepers,
1423            * we'll later nuke all the ones not found in /etc/ttys
1424            */
1425           for (sp = sessions; sp != NULL; sp = sp->se_next)
1426                     sp->se_flags &= ~SE_PRESENT;
1427 
1428           devlen = sizeof(_PATH_DEV) - 1;
1429           while ((typ = getttyent()) != NULL) {
1430                     ++session_index;
1431 
1432                     adjttyent(typ);
1433                     for (sprev = NULL, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1434                               if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1435                                         break;
1436 
1437                     if (sp) {
1438                               /* we want this one to live */
1439                               sp->se_flags |= SE_PRESENT;
1440                               if (sp->se_index != session_index) {
1441                                         warning("port %s changed utmpx index from %d to %d",
1442                                                sp->se_device, sp->se_index,
1443                                                session_index);
1444                                         sp->se_index = session_index;
1445                               }
1446                               if ((typ->ty_status & TTY_ON) == 0 ||
1447                                   typ->ty_getty == 0) {
1448                                         sp->se_flags |= SE_SHUTDOWN;
1449                                         kill(sp->se_process, SIGHUP);
1450                                         continue;
1451                               }
1452                               sp->se_flags &= ~SE_SHUTDOWN;
1453                               old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1454                               old_window = sp->se_window ? strdup(sp->se_window) : 0;
1455                               old_type = sp->se_type ? strdup(sp->se_type) : 0;
1456                               if (setupargv(sp, typ) == 0) {
1457                                         warning("can't parse getty for port %s",
1458                                                   sp->se_device);
1459                                         sp->se_flags |= SE_SHUTDOWN;
1460                                         kill(sp->se_process, SIGHUP);
1461                               }
1462                               else if (   !old_getty
1463                                          || (!old_type && sp->se_type)
1464                                          || (old_type && !sp->se_type)
1465                                          || (!old_window && sp->se_window)
1466                                          || (old_window && !sp->se_window)
1467                                          || (strcmp(old_getty, sp->se_getty) != 0)
1468                                          || (old_window && strcmp(old_window, sp->se_window) != 0)
1469                                          || (old_type && strcmp(old_type, sp->se_type) != 0)
1470                                         ) {
1471                                         /* Don't set SE_SHUTDOWN here */
1472                                         sp->se_nspace = 0;
1473                                         sp->se_started.tv_sec = sp->se_started.tv_usec = 0;
1474                                         kill(sp->se_process, SIGHUP);
1475                               }
1476                               if (old_getty)
1477                                         free(old_getty);
1478                               if (old_window)
1479                                         free(old_window);
1480                               if (old_type)
1481                                         free(old_type);
1482                               continue;
1483                     }
1484 
1485                     new_session(sprev, session_index, typ);
1486           }
1487 
1488           endttyent();
1489 
1490           /*
1491            * sweep through and kill all deleted sessions
1492            * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1493            */
1494           for (sp = sessions; sp != NULL; sp = sp->se_next) {
1495                     if ((sp->se_flags & SE_PRESENT) == 0) {
1496                               sp->se_flags |= SE_SHUTDOWN;
1497                               kill(sp->se_process, SIGHUP);
1498                     }
1499           }
1500 
1501           return multi_user;
1502 }
1503 
1504 /*
1505  * Block further logins.
1506  */
1507 static state_t
f_catatonia(void)1508 f_catatonia(void)
1509 {
1510           session_t *sp;
1511 
1512           for (sp = sessions; sp; sp = sp->se_next)
1513                     sp->se_flags |= SE_SHUTDOWN;
1514 
1515           return multi_user;
1516 }
1517 
1518 /*
1519  * Note SIGALRM.
1520  */
1521 static void
alrm_handler(int sig __unused)1522 alrm_handler(int sig __unused)
1523 {
1524           clang = 1;
1525 }
1526 
1527 /*
1528  * Bring the system down to single user.
1529  */
1530 static state_t
f_death(void)1531 f_death(void)
1532 {
1533           session_t *sp;
1534           int i;
1535           pid_t pid;
1536           int status;
1537           static const int death_sigs[2] = { SIGTERM, SIGKILL };
1538 
1539           logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1540 
1541           for (sp = sessions; sp; sp = sp->se_next) {
1542                     sp->se_flags |= SE_SHUTDOWN;
1543                     kill(sp->se_process, SIGHUP);
1544           }
1545 
1546           /* Try to run the rc.shutdown script within a period of time */
1547           runshutdown();
1548 
1549           for (i = 0; i < 2; ++i) {
1550                     if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1551                               return single_user;
1552 
1553                     clang = 0;
1554                     alarm(DEATH_WATCH);
1555                     do
1556                               if ((pid = waitpid(-1, &status, 0)) != -1)
1557                                         collect_child(pid, status);
1558                     while (clang == 0 && errno != ECHILD);
1559 
1560                     if (errno == ECHILD)
1561                               return single_user;
1562           }
1563 
1564           warning("some processes would not die; ps axl advised");
1565 
1566           return single_user;
1567 }
1568 
1569 /*
1570  * Run the system shutdown script.
1571  *
1572  * Exit codes:      XXX I should document more
1573  * -2       shutdown script terminated abnormally
1574  * -1       fatal error - can't run script
1575  * 0        good.
1576  * >0       some error (exit code)
1577  */
1578 static int
runshutdown(void)1579 runshutdown(void)
1580 {
1581           pid_t pid, wpid;
1582           int status;
1583           int shutdowntimeout;
1584           size_t len;
1585           const char *argv[4];
1586           struct sigaction sa;
1587           struct stat sb;
1588 
1589           /*
1590            * rc.shutdown is optional, so to prevent any unnecessary
1591            * complaints from the shell we simply don't run it if the
1592            * file does not exist. If the stat() here fails for other
1593            * reasons, we'll let the shell complain.
1594            */
1595           if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1596                     return 0;
1597 
1598           if ((pid = fork()) == 0) {
1599                     int       fd;
1600 
1601                     /* Assume that init already grab console as ctty before */
1602 
1603                     sigemptyset(&sa.sa_mask);
1604                     sa.sa_flags = 0;
1605                     sa.sa_handler = SIG_IGN;
1606                     sigaction(SIGTSTP, &sa, NULL);
1607                     sigaction(SIGHUP, &sa, NULL);
1608 
1609                     if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1610                         warning("can't open %s: %m", _PATH_CONSOLE);
1611                     else {
1612                         dup2(fd, 0);
1613                         dup2(fd, 1);
1614                         dup2(fd, 2);
1615                         if (fd > 2)
1616                               close(fd);
1617                     }
1618 
1619                     /*
1620                      * Run the shutdown script.
1621                      */
1622                     argv[0] = "sh";
1623                     argv[1] = _PATH_RUNDOWN;
1624                     if (Reboot)
1625                               argv[2] = "reboot";
1626                     else
1627                               argv[2] = "single";
1628                     argv[3] = NULL;
1629 
1630                     sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1631 
1632 #ifdef LOGIN_CAP
1633                     setprocresources(RESOURCE_RC);
1634 #endif
1635                     execv(_PATH_BSHELL, __DECONST(char **, argv));
1636                     warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1637                     _exit(1); /* force single user mode */
1638           }
1639 
1640           if (pid == -1) {
1641                     emergency("can't fork for %s on %s: %m",
1642                               _PATH_BSHELL, _PATH_RUNDOWN);
1643                     while (waitpid(-1, NULL, WNOHANG) > 0)
1644                               continue;
1645                     sleep(STALL_TIMEOUT);
1646                     return -1;
1647           }
1648 
1649           len = sizeof(shutdowntimeout);
1650           if (sysctlbyname("kern.init_shutdown_timeout",
1651                                &shutdowntimeout,
1652                                &len, NULL, 0) == -1 || shutdowntimeout < 2)
1653               shutdowntimeout = DEATH_SCRIPT;
1654           alarm(shutdowntimeout);
1655           clang = 0;
1656           /*
1657            * Copied from single_user().  This is a bit paranoid.
1658            * Use the same ALRM handler.
1659            */
1660           do {
1661                     if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1662                               collect_child(wpid, status);
1663                     if (clang == 1) {
1664                               /* we were waiting for the sub-shell */
1665                               kill(wpid, SIGTERM);
1666                               warning("timeout expired for %s on %s: %m; going to single user mode",
1667                                         _PATH_BSHELL, _PATH_RUNDOWN);
1668                               return -1;
1669                     }
1670                     if (wpid == -1) {
1671                               if (errno == EINTR)
1672                                         continue;
1673                               warning("wait for %s on %s failed: %m; going to single user mode",
1674                                         _PATH_BSHELL, _PATH_RUNDOWN);
1675                               return -1;
1676                     }
1677                     if (wpid == pid && WIFSTOPPED(status)) {
1678                               warning("init: %s on %s stopped, restarting\n",
1679                                         _PATH_BSHELL, _PATH_RUNDOWN);
1680                               kill(pid, SIGCONT);
1681                               wpid = -1;
1682                     }
1683           } while (wpid != pid && !clang);
1684 
1685           /* Turn off the alarm */
1686           alarm(0);
1687 
1688           if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1689               requested_transition == catatonia) {
1690                     /*
1691                      * /etc/rc.shutdown executed /sbin/reboot;
1692                      * wait for the end quietly
1693                      */
1694                     sigset_t s;
1695 
1696                     sigfillset(&s);
1697                     for (;;)
1698                               sigsuspend(&s);
1699           }
1700 
1701           if (!WIFEXITED(status)) {
1702                     warning("%s on %s terminated abnormally, going to single user mode",
1703                               _PATH_BSHELL, _PATH_RUNDOWN);
1704                     return -2;
1705           }
1706 
1707           if ((status = WEXITSTATUS(status)) != 0)
1708                     warning("%s returned status %d", _PATH_RUNDOWN, status);
1709 
1710           return status;
1711 }
1712 
1713 static char *
strk(char * p)1714 strk(char *p)
1715 {
1716     static char *t;
1717     char *q;
1718     int c;
1719 
1720     if (p)
1721           t = p;
1722     if (!t)
1723           return 0;
1724 
1725     c = *t;
1726     while (c == ' ' || c == '\t' )
1727           c = *++t;
1728     if (!c) {
1729           t = NULL;
1730           return 0;
1731     }
1732     q = t;
1733     if (c == '\'') {
1734           c = *++t;
1735           q = t;
1736           while (c && c != '\'')
1737               c = *++t;
1738           if (!c)  /* unterminated string */
1739               q = t = NULL;
1740           else
1741               *t++ = 0;
1742     } else {
1743           while (c && c != ' ' && c != '\t' )
1744               c = *++t;
1745           *t++ = 0;
1746           if (!c)
1747               t = NULL;
1748     }
1749     return q;
1750 }
1751 
1752 #ifdef LOGIN_CAP
1753 static void
setprocresources(const char * cname)1754 setprocresources(const char *cname)
1755 {
1756           login_cap_t *lc;
1757           if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1758                     setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1759                     login_close(lc);
1760           }
1761 }
1762 #endif
1763 
1764 static void
session_utmpx(const session_t * sp,int add)1765 session_utmpx(const session_t *sp, int add)
1766 {
1767           const char *name = sp->se_getty ? sp->se_getty :
1768               (sp->se_window ? sp->se_window : "");
1769           const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1770 
1771           make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1772               sp->se_process, &sp->se_started, sp->se_index);
1773 }
1774 
1775 static void
make_utmpx(const char * name,const char * line,int type,pid_t pid,const struct timeval * tv,int session)1776 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1777     const struct timeval *tv, int session)
1778 {
1779           struct utmpx ut;
1780           const char *eline;
1781 
1782           (void)memset(&ut, 0, sizeof(ut));
1783           (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1784           ut.ut_type = type;
1785           (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1786           ut.ut_pid = pid;
1787           if (tv)
1788                     ut.ut_tv = *tv;
1789           else
1790                     (void)gettimeofday(&ut.ut_tv, NULL);
1791           ut.ut_session = session;
1792 
1793           eline = line + strlen(line);
1794           if ((size_t)(eline - line) >= sizeof(ut.ut_id))
1795                     line = eline - sizeof(ut.ut_id);
1796           (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1797 
1798           if (pututxline(&ut) == NULL)
1799                     warning("can't add utmpx record for `%s': %m", ut.ut_line);
1800           endutxent();
1801 }
1802 
1803 static char
get_runlevel(const state_t s)1804 get_runlevel(const state_t s)
1805 {
1806           if (s == single_user)
1807                     return SINGLE_USER;
1808           if (s == runcom)
1809                     return RUNCOM;
1810           if (s == read_ttys)
1811                     return READ_TTYS;
1812           if (s == multi_user)
1813                     return MULTI_USER;
1814           if (s == clean_ttys)
1815                     return CLEAN_TTYS;
1816           if (s == catatonia)
1817                     return CATATONIA;
1818           return DEATH;
1819 }
1820 
1821 static void
utmpx_set_runlevel(char old,char new)1822 utmpx_set_runlevel(char old, char new)
1823 {
1824           struct utmpx ut;
1825 
1826           /*
1827            * Don't record any transitions until we did the first transition
1828            * to read ttys, which is when we are guaranteed to have a read-write
1829            * /var. Perhaps use a different variable for this?
1830            */
1831           if (sessions == NULL)
1832                     return;
1833 
1834           (void)memset(&ut, 0, sizeof(ut));
1835           (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1836           ut.ut_type = RUN_LVL;
1837           (void)gettimeofday(&ut.ut_tv, NULL);
1838           ut.ut_exit.e_exit = old;
1839           ut.ut_exit.e_termination = new;
1840           if (pututxline(&ut) == NULL)
1841                     warning("can't add utmpx record for `runlevel': %m");
1842           endutxent();
1843 }
1844