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