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