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