Fix sysvinit bug #29758
[sysvinit.git] / src / init.c
CommitLineData
a74aeac6
PR
1/*
2 * Init A System-V Init Clone.
3 *
4 * Usage: /sbin/init
5 * init [0123456SsQqAaBbCc]
6 * telinit [0123456SsQqAaBbCc]
7 *
8 * Version: @(#)init.c 2.86 30-Jul-2004 miquels@cistron.nl
9 */
c6fb5841 10#define VERSION "2.89"
23d97522 11#define DATE "26-Mar-2010"
a74aeac6
PR
12/*
13 * This file is part of the sysvinit suite,
14 * Copyright (C) 1991-2004 Miquel van Smoorenburg.
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 *
30 */
31
32#include <sys/types.h>
33#include <sys/stat.h>
34#include <sys/ioctl.h>
35#include <sys/wait.h>
36#ifdef __linux__
37#include <sys/kd.h>
38#endif
39#include <sys/resource.h>
40#include <stdlib.h>
41#include <unistd.h>
42#include <errno.h>
43#include <stdio.h>
44#include <time.h>
45#include <fcntl.h>
46#include <string.h>
47#include <signal.h>
48#include <termios.h>
49#include <utmp.h>
50#include <ctype.h>
51#include <stdarg.h>
52#include <sys/syslog.h>
53#include <sys/time.h>
54
55#ifdef WITH_SELINUX
55f242bf
DWF
56# include <selinux/selinux.h>
57# include <sys/mount.h>
a42284e9
PR
58# ifndef MNT_DETACH /* present in glibc 2.10, missing in 2.7 */
59# define MNT_DETACH 2
60# endif
a74aeac6
PR
61#endif
62
a74aeac6 63#ifdef __i386__
5f959b29 64# ifdef __GLIBC__
a74aeac6
PR
65 /* GNU libc 2.x */
66# define STACK_DEBUG 1
67# if (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
68 /* Only glibc 2.0 needs this */
69# include <sigcontext.h>
5f959b29
DWF
70# elif ( __GLIBC__ > 2) && ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))
71# include <bits/sigcontext.h>
a74aeac6
PR
72# endif
73# endif
74#endif
75
76#include "init.h"
77#include "initreq.h"
78#include "paths.h"
79#include "reboot.h"
80#include "set.h"
81
82#ifndef SIGPWR
83# define SIGPWR SIGUSR2
84#endif
85
86#ifndef CBAUD
87# define CBAUD 0
88#endif
89#ifndef CBAUDEX
90# define CBAUDEX 0
91#endif
92
93/* Set a signal handler. */
94#define SETSIG(sa, sig, fun, flags) \
95 do { \
96 sa.sa_handler = fun; \
97 sa.sa_flags = flags; \
98 sigemptyset(&sa.sa_mask); \
99 sigaction(sig, &sa, NULL); \
100 } while(0)
101
102/* Version information */
103char *Version = "@(#) init " VERSION " " DATE " miquels@cistron.nl";
104char *bootmsg = "version " VERSION " %s";
105#define E_VERSION "INIT_VERSION=sysvinit-" VERSION
106
107CHILD *family = NULL; /* The linked list of all entries */
108CHILD *newFamily = NULL; /* The list after inittab re-read */
109
110CHILD ch_emerg = { /* Emergency shell */
111 WAITING, 0, 0, 0, 0,
112 "~~",
113 "S",
114 3,
115 "/sbin/sulogin",
116 NULL,
117 NULL
118};
119
120char runlevel = 'S'; /* The current run level */
121char thislevel = 'S'; /* The current runlevel */
122char prevlevel = 'N'; /* Previous runlevel */
123int dfl_level = 0; /* Default runlevel */
124sig_atomic_t got_cont = 0; /* Set if we received the SIGCONT signal */
125sig_atomic_t got_signals; /* Set if we received a signal. */
126int emerg_shell = 0; /* Start emergency shell? */
127int wrote_wtmp_reboot = 1; /* Set when we wrote the reboot record */
128int wrote_utmp_reboot = 1; /* Set when we wrote the reboot record */
63a2c981
DWF
129int wrote_wtmp_rlevel = 1; /* Set when we wrote the runlevel record */
130int wrote_utmp_rlevel = 1; /* Set when we wrote the runlevel record */
a74aeac6
PR
131int sltime = 5; /* Sleep time between TERM and KILL */
132char *argv0; /* First arguments; show up in ps listing */
133int maxproclen; /* Maximal length of argv[0] with \0 */
134struct utmp utproto; /* Only used for sizeof(utproto.ut_id) */
a74aeac6
PR
135char *console_dev; /* Console device. */
136int pipe_fd = -1; /* /dev/initctl */
137int did_boot = 0; /* Did we already do BOOT* stuff? */
138int main(int, char **);
139
140/* Used by re-exec part */
141int reload = 0; /* Should we do initialization stuff? */
142char *myname="/sbin/init"; /* What should we exec */
143int oops_error; /* Used by some of the re-exec code. */
144const char *Signature = "12567362"; /* Signature for re-exec fd */
145
146/* Macro to see if this is a special action */
147#define ISPOWER(i) ((i) == POWERWAIT || (i) == POWERFAIL || \
148 (i) == POWEROKWAIT || (i) == POWERFAILNOW || \
149 (i) == CTRLALTDEL)
150
151/* ascii values for the `action' field. */
152struct actions {
153 char *name;
154 int act;
155} actions[] = {
156 { "respawn", RESPAWN },
157 { "wait", WAIT },
158 { "once", ONCE },
159 { "boot", BOOT },
160 { "bootwait", BOOTWAIT },
161 { "powerfail", POWERFAIL },
162 { "powerfailnow",POWERFAILNOW },
163 { "powerwait", POWERWAIT },
164 { "powerokwait", POWEROKWAIT },
165 { "ctrlaltdel", CTRLALTDEL },
166 { "off", OFF },
167 { "ondemand", ONDEMAND },
168 { "initdefault", INITDEFAULT },
169 { "sysinit", SYSINIT },
170 { "kbrequest", KBREQUEST },
171 { NULL, 0 },
172};
173
174/*
175 * State parser token table (see receive_state)
176 */
177struct {
178 char name[4];
179 int cmd;
180} cmds[] = {
181 { "VER", C_VER },
182 { "END", C_END },
183 { "REC", C_REC },
184 { "EOR", C_EOR },
185 { "LEV", C_LEV },
186 { "FL ", C_FLAG },
187 { "AC ", C_ACTION },
188 { "CMD", C_PROCESS },
189 { "PID", C_PID },
190 { "EXS", C_EXS },
191 { "-RL", D_RUNLEVEL },
192 { "-TL", D_THISLEVEL },
193 { "-PL", D_PREVLEVEL },
194 { "-SI", D_GOTSIGN },
195 { "-WR", D_WROTE_WTMP_REBOOT},
196 { "-WU", D_WROTE_UTMP_REBOOT},
197 { "-ST", D_SLTIME },
198 { "-DB", D_DIDBOOT },
63a2c981
DWF
199 { "-LW", D_WROTE_WTMP_RLEVEL},
200 { "-LU", D_WROTE_UTMP_RLEVEL},
a74aeac6
PR
201 { "", 0 }
202};
203struct {
204 char *name;
205 int mask;
206} flags[]={
207 {"RU",RUNNING},
208 {"DE",DEMAND},
209 {"XD",XECUTED},
210 {"WT",WAITING},
211 {NULL,0}
212};
213
214#define NR_EXTRA_ENV 16
215char *extra_env[NR_EXTRA_ENV];
216
217
218/*
219 * Sleep a number of seconds.
220 *
221 * This only works correctly because the linux select updates
222 * the elapsed time in the struct timeval passed to select!
223 */
5f959b29 224static
a74aeac6
PR
225void do_sleep(int sec)
226{
227 struct timeval tv;
228
229 tv.tv_sec = sec;
230 tv.tv_usec = 0;
231
232 while(select(0, NULL, NULL, NULL, &tv) < 0 && errno == EINTR)
233 ;
234}
235
236
237/*
238 * Non-failing allocation routines (init cannot fail).
239 */
5f959b29 240static
a74aeac6
PR
241void *imalloc(size_t size)
242{
243 void *m;
244
245 while ((m = malloc(size)) == NULL) {
246 initlog(L_VB, "out of memory");
247 do_sleep(5);
248 }
249 memset(m, 0, size);
250 return m;
251}
252
5f959b29 253static
a74aeac6
PR
254char *istrdup(char *s)
255{
256 char *m;
257 int l;
258
259 l = strlen(s) + 1;
260 m = imalloc(l);
261 memcpy(m, s, l);
262 return m;
263}
264
265
266/*
267 * Send the state info of the previous running init to
268 * the new one, in a version-independant way.
269 */
5f959b29 270static
a74aeac6
PR
271void send_state(int fd)
272{
273 FILE *fp;
274 CHILD *p;
275 int i,val;
276
277 fp = fdopen(fd,"w");
278
279 fprintf(fp, "VER%s\n", Version);
280 fprintf(fp, "-RL%c\n", runlevel);
281 fprintf(fp, "-TL%c\n", thislevel);
282 fprintf(fp, "-PL%c\n", prevlevel);
283 fprintf(fp, "-SI%u\n", got_signals);
284 fprintf(fp, "-WR%d\n", wrote_wtmp_reboot);
285 fprintf(fp, "-WU%d\n", wrote_utmp_reboot);
286 fprintf(fp, "-ST%d\n", sltime);
287 fprintf(fp, "-DB%d\n", did_boot);
288
289 for (p = family; p; p = p->next) {
290 fprintf(fp, "REC%s\n", p->id);
291 fprintf(fp, "LEV%s\n", p->rlevel);
292 for (i = 0, val = p->flags; flags[i].mask; i++)
293 if (val & flags[i].mask) {
294 val &= ~flags[i].mask;
295 fprintf(fp, "FL %s\n",flags[i].name);
296 }
297 fprintf(fp, "PID%d\n",p->pid);
298 fprintf(fp, "EXS%u\n",p->exstat);
299 for(i = 0; actions[i].act; i++)
300 if (actions[i].act == p->action) {
301 fprintf(fp, "AC %s\n", actions[i].name);
302 break;
303 }
304 fprintf(fp, "CMD%s\n", p->process);
305 fprintf(fp, "EOR\n");
306 }
307 fprintf(fp, "END\n");
308 fclose(fp);
309}
310
311/*
312 * Read a string from a file descriptor.
313 * FIXME: why not use fgets() ?
314 */
315static int get_string(char *p, int size, FILE *f)
316{
317 int c;
318
319 while ((c = getc(f)) != EOF && c != '\n') {
320 if (--size > 0)
321 *p++ = c;
322 }
323 *p = '\0';
324 return (c != EOF) && (size > 0);
325}
326
327/*
328 * Read trailing data from the state pipe until we see a newline.
329 */
330static int get_void(FILE *f)
331{
332 int c;
333
334 while ((c = getc(f)) != EOF && c != '\n')
335 ;
336
337 return (c != EOF);
338}
339
340/*
341 * Read the next "command" from the state pipe.
342 */
343static int get_cmd(FILE *f)
344{
345 char cmd[4] = " ";
346 int i;
347
348 if (fread(cmd, 1, sizeof(cmd) - 1, f) != sizeof(cmd) - 1)
349 return C_EOF;
350
351 for(i = 0; cmds[i].cmd && strcmp(cmds[i].name, cmd) != 0; i++)
352 ;
353 return cmds[i].cmd;
354}
355
356/*
357 * Read a CHILD * from the state pipe.
358 */
359static CHILD *get_record(FILE *f)
360{
361 int cmd;
362 char s[32];
363 int i;
364 CHILD *p;
365
366 do {
367 switch (cmd = get_cmd(f)) {
368 case C_END:
369 get_void(f);
370 return NULL;
371 case 0:
372 get_void(f);
373 break;
374 case C_REC:
375 break;
376 case D_RUNLEVEL:
377 fscanf(f, "%c\n", &runlevel);
378 break;
379 case D_THISLEVEL:
380 fscanf(f, "%c\n", &thislevel);
381 break;
382 case D_PREVLEVEL:
383 fscanf(f, "%c\n", &prevlevel);
384 break;
385 case D_GOTSIGN:
386 fscanf(f, "%u\n", &got_signals);
387 break;
388 case D_WROTE_WTMP_REBOOT:
389 fscanf(f, "%d\n", &wrote_wtmp_reboot);
390 break;
391 case D_WROTE_UTMP_REBOOT:
392 fscanf(f, "%d\n", &wrote_utmp_reboot);
393 break;
394 case D_SLTIME:
395 fscanf(f, "%d\n", &sltime);
396 break;
397 case D_DIDBOOT:
398 fscanf(f, "%d\n", &did_boot);
399 break;
63a2c981
DWF
400 case D_WROTE_WTMP_RLEVEL:
401 fscanf(f, "%d\n", &wrote_wtmp_rlevel);
402 break;
403 case D_WROTE_UTMP_RLEVEL:
404 fscanf(f, "%d\n", &wrote_utmp_rlevel);
405 break;
a74aeac6
PR
406 default:
407 if (cmd > 0 || cmd == C_EOF) {
408 oops_error = -1;
409 return NULL;
410 }
411 }
412 } while (cmd != C_REC);
413
414 p = imalloc(sizeof(CHILD));
415 get_string(p->id, sizeof(p->id), f);
416
417 do switch(cmd = get_cmd(f)) {
418 case 0:
419 case C_EOR:
420 get_void(f);
421 break;
422 case C_PID:
423 fscanf(f, "%d\n", &(p->pid));
424 break;
425 case C_EXS:
426 fscanf(f, "%u\n", &(p->exstat));
427 break;
428 case C_LEV:
429 get_string(p->rlevel, sizeof(p->rlevel), f);
430 break;
431 case C_PROCESS:
432 get_string(p->process, sizeof(p->process), f);
433 break;
434 case C_FLAG:
435 get_string(s, sizeof(s), f);
436 for(i = 0; flags[i].name; i++) {
437 if (strcmp(flags[i].name,s) == 0)
438 break;
439 }
440 p->flags |= flags[i].mask;
441 break;
442 case C_ACTION:
443 get_string(s, sizeof(s), f);
444 for(i = 0; actions[i].name; i++) {
445 if (strcmp(actions[i].name, s) == 0)
446 break;
447 }
448 p->action = actions[i].act ? actions[i].act : OFF;
449 break;
450 default:
451 free(p);
452 oops_error = -1;
453 return NULL;
454 } while( cmd != C_EOR);
455
456 return p;
457}
458
459/*
460 * Read the complete state info from the state pipe.
461 * Returns 0 on success
462 */
5f959b29 463static
a74aeac6
PR
464int receive_state(int fd)
465{
466 FILE *f;
467 char old_version[256];
468 CHILD **pp;
469
470 f = fdopen(fd, "r");
471
472 if (get_cmd(f) != C_VER)
473 return -1;
474 get_string(old_version, sizeof(old_version), f);
475 oops_error = 0;
476 for (pp = &family; (*pp = get_record(f)) != NULL; pp = &((*pp)->next))
477 ;
478 fclose(f);
479 return oops_error;
480}
481
482/*
483 * Set the process title.
484 */
485#ifdef __GNUC__
486__attribute__ ((format (printf, 1, 2)))
487#endif
488static int setproctitle(char *fmt, ...)
489{
490 va_list ap;
491 int len;
492 char buf[256];
493
494 buf[0] = 0;
495
496 va_start(ap, fmt);
497 len = vsnprintf(buf, sizeof(buf), fmt, ap);
498 va_end(ap);
499
500 if (maxproclen > 1) {
501 memset(argv0, 0, maxproclen);
502 strncpy(argv0, buf, maxproclen - 1);
503 }
504
505 return len;
506}
507
508/*
509 * Set console_dev to a working console.
510 */
5f959b29 511static
a74aeac6
PR
512void console_init(void)
513{
514 int fd;
515 int tried_devcons = 0;
516 int tried_vtmaster = 0;
517 char *s;
518
a33820c3 519 if ((s = getenv("CONSOLE")) != NULL)
a74aeac6
PR
520 console_dev = s;
521 else {
522 console_dev = CONSOLE;
523 tried_devcons++;
524 }
525
526 while ((fd = open(console_dev, O_RDONLY|O_NONBLOCK)) < 0) {
527 if (!tried_devcons) {
528 tried_devcons++;
529 console_dev = CONSOLE;
530 continue;
531 }
532 if (!tried_vtmaster) {
533 tried_vtmaster++;
534 console_dev = VT_MASTER;
535 continue;
536 }
537 break;
538 }
539 if (fd < 0)
540 console_dev = "/dev/null";
541 else
542 close(fd);
543}
544
545
546/*
547 * Open the console with retries.
548 */
5f959b29 549static
a74aeac6
PR
550int console_open(int mode)
551{
552 int f, fd = -1;
553 int m;
554
555 /*
556 * Open device in nonblocking mode.
557 */
558 m = mode | O_NONBLOCK;
559
560 /*
561 * Retry the open five times.
562 */
563 for(f = 0; f < 5; f++) {
564 if ((fd = open(console_dev, m)) >= 0) break;
23d97522 565 usleep(10000);
a74aeac6
PR
566 }
567
568 if (fd < 0) return fd;
569
570 /*
571 * Set original flags.
572 */
573 if (m != mode)
574 fcntl(fd, F_SETFL, mode);
575 return fd;
576}
577
578/*
579 * We got a signal (HUP PWR WINCH ALRM INT)
580 */
5f959b29 581static
a74aeac6
PR
582void signal_handler(int sig)
583{
584 ADDSET(got_signals, sig);
585}
586
587/*
588 * SIGCHLD: one of our children has died.
589 */
5f959b29
DWF
590static
591# ifdef __GNUC__
592void chld_handler(int sig __attribute__((unused)))
593# else
594void chld_handler(int sig)
595# endif
a74aeac6
PR
596{
597 CHILD *ch;
598 int pid, st;
599 int saved_errno = errno;
600
601 /*
602 * Find out which process(es) this was (were)
603 */
604 while((pid = waitpid(-1, &st, WNOHANG)) != 0) {
605 if (errno == ECHILD) break;
606 for( ch = family; ch; ch = ch->next )
607 if ( ch->pid == pid && (ch->flags & RUNNING) ) {
608 INITDBG(L_VB,
609 "chld_handler: marked %d as zombie",
610 ch->pid);
611 ADDSET(got_signals, SIGCHLD);
612 ch->exstat = st;
613 ch->flags |= ZOMBIE;
614 if (ch->new) {
615 ch->new->exstat = st;
616 ch->new->flags |= ZOMBIE;
617 }
618 break;
619 }
620 if (ch == NULL) {
621 INITDBG(L_VB, "chld_handler: unknown child %d exited.",
622 pid);
623 }
624 }
625 errno = saved_errno;
626}
627
628/*
629 * Linux ignores all signals sent to init when the
630 * SIG_DFL handler is installed. Therefore we must catch SIGTSTP
631 * and SIGCONT, or else they won't work....
632 *
633 * The SIGCONT handler
634 */
5f959b29
DWF
635static
636# ifdef __GNUC__
637void cont_handler(int sig __attribute__((unused)))
638# else
639void cont_handler(int sig)
640# endif
a74aeac6
PR
641{
642 got_cont = 1;
643}
644
645/*
646 * Fork and dump core in /.
647 */
5f959b29 648static
a74aeac6
PR
649void coredump(void)
650{
651 static int dumped = 0;
652 struct rlimit rlim;
653 sigset_t mask;
654
655 if (dumped) return;
656 dumped = 1;
657
658 if (fork() != 0) return;
659
660 sigfillset(&mask);
661 sigprocmask(SIG_SETMASK, &mask, NULL);
662
663 rlim.rlim_cur = RLIM_INFINITY;
664 rlim.rlim_max = RLIM_INFINITY;
665 setrlimit(RLIMIT_CORE, &rlim);
666 chdir("/");
667
668 signal(SIGSEGV, SIG_DFL);
669 raise(SIGSEGV);
670 sigdelset(&mask, SIGSEGV);
671 sigprocmask(SIG_SETMASK, &mask, NULL);
672
673 do_sleep(5);
674 exit(0);
675}
676
677/*
678 * OOPS: segmentation violation!
679 * If we have the info, print where it occured.
680 * Then sleep 30 seconds and try to continue.
681 */
5f959b29 682static
a74aeac6 683#if defined(STACK_DEBUG) && defined(__linux__)
5f959b29
DWF
684# ifdef __GNUC__
685void segv_handler(int sig __attribute__((unused)), struct sigcontext ctx)
686# else
a74aeac6 687void segv_handler(int sig, struct sigcontext ctx)
5f959b29 688# endif
a74aeac6
PR
689{
690 char *p = "";
691 int saved_errno = errno;
692
693 if ((void *)ctx.eip >= (void *)do_sleep &&
694 (void *)ctx.eip < (void *)main)
695 p = " (code)";
696 initlog(L_VB, "PANIC: segmentation violation at %p%s! "
697 "sleeping for 30 seconds.", (void *)ctx.eip, p);
698 coredump();
699 do_sleep(30);
700 errno = saved_errno;
701}
702#else
5f959b29
DWF
703# ifdef __GNUC__
704void segv_handler(int sig __attribute__((unused)))
705# else
706void segv_handler(int sig)
707# endif
a74aeac6
PR
708{
709 int saved_errno = errno;
710
711 initlog(L_VB,
712 "PANIC: segmentation violation! sleeping for 30 seconds.");
713 coredump();
714 do_sleep(30);
715 errno = saved_errno;
716}
717#endif
718
719/*
720 * The SIGSTOP & SIGTSTP handler
721 */
5f959b29
DWF
722static
723# ifdef __GNUC__
724void stop_handler(int sig __attribute__((unused)))
725# else
726void stop_handler(int sig)
727# endif
a74aeac6
PR
728{
729 int saved_errno = errno;
730
731 got_cont = 0;
732 while(!got_cont) pause();
733 got_cont = 0;
734 errno = saved_errno;
735}
736
737/*
738 * Set terminal settings to reasonable defaults
739 */
5f959b29 740static
a74aeac6
PR
741void console_stty(void)
742{
743 struct termios tty;
744 int fd;
745
746 if ((fd = console_open(O_RDWR|O_NOCTTY)) < 0) {
747 initlog(L_VB, "can't open %s", console_dev);
748 return;
749 }
750
55f242bf
DWF
751#ifdef __FreeBSD_kernel__
752 /*
753 * The kernel of FreeBSD expects userland to set TERM. Usually, we want
754 * "cons25". Later, gettys might disagree on this (i.e. we're not using
755 * syscons) but some boot scripts, like /etc/init.d/xserver-xorg, still
756 * need a non-dumb terminal.
757 */
758 putenv ("TERM=cons25");
759#endif
760
a74aeac6
PR
761 (void) tcgetattr(fd, &tty);
762
763 tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
764 tty.c_cflag |= HUPCL|CLOCAL|CREAD;
765
5f959b29
DWF
766 tty.c_cc[VINTR] = CINTR;
767 tty.c_cc[VQUIT] = CQUIT;
768 tty.c_cc[VERASE] = CERASE; /* ASCII DEL (0177) */
769 tty.c_cc[VKILL] = CKILL;
770 tty.c_cc[VEOF] = CEOF;
771 tty.c_cc[VTIME] = 0;
772 tty.c_cc[VMIN] = 1;
fc3def35 773#ifdef VSWTC /* not defined on FreeBSD */
5f959b29 774 tty.c_cc[VSWTC] = _POSIX_VDISABLE;
fc3def35 775#endif /* VSWTC */
5f959b29
DWF
776 tty.c_cc[VSTART] = CSTART;
777 tty.c_cc[VSTOP] = CSTOP;
778 tty.c_cc[VSUSP] = CSUSP;
779 tty.c_cc[VEOL] = _POSIX_VDISABLE;
780 tty.c_cc[VREPRINT] = CREPRINT;
781 tty.c_cc[VDISCARD] = CDISCARD;
782 tty.c_cc[VWERASE] = CWERASE;
783 tty.c_cc[VLNEXT] = CLNEXT;
784 tty.c_cc[VEOL2] = _POSIX_VDISABLE;
a74aeac6
PR
785
786 /*
787 * Set pre and post processing
788 */
33dca826
DWF
789 tty.c_iflag = IGNPAR|ICRNL|IXON|IXANY
790#ifdef IUTF8 /* Not defined on FreeBSD */
791 | (tty.c_iflag & IUTF8)
334256b0 792#endif /* IUTF8 */
33dca826 793 ;
a74aeac6
PR
794 tty.c_oflag = OPOST|ONLCR;
795 tty.c_lflag = ISIG|ICANON|ECHO|ECHOCTL|ECHOPRT|ECHOKE;
796
5f959b29
DWF
797#if defined(SANE_TIO) && (SANE_TIO == 1)
798 /*
799 * Disable flow control (-ixon), ignore break (ignbrk),
800 * and make nl/cr more usable (sane).
801 */
802 tty.c_iflag |= IGNBRK;
803 tty.c_iflag &= ~(BRKINT|INLCR|IGNCR|IXON);
804 tty.c_oflag &= ~(OCRNL|ONLRET);
805#endif
a74aeac6
PR
806 /*
807 * Now set the terminal line.
808 * We don't care about non-transmitted output data
809 * and non-read input data.
810 */
811 (void) tcsetattr(fd, TCSANOW, &tty);
812 (void) tcflush(fd, TCIOFLUSH);
813 (void) close(fd);
814}
815
816/*
817 * Print to the system console
818 */
819void print(char *s)
820{
821 int fd;
822
823 if ((fd = console_open(O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
824 write(fd, s, strlen(s));
825 close(fd);
826 }
827}
828
829/*
830 * Log something to a logfile and the console.
831 */
832#ifdef __GNUC__
833__attribute__ ((format (printf, 2, 3)))
834#endif
835void initlog(int loglevel, char *s, ...)
836{
837 va_list va_alist;
838 char buf[256];
839 sigset_t nmask, omask;
840
841 va_start(va_alist, s);
842 vsnprintf(buf, sizeof(buf), s, va_alist);
843 va_end(va_alist);
844
845 if (loglevel & L_SY) {
846 /*
847 * Re-establish connection with syslogd every time.
848 * Block signals while talking to syslog.
849 */
850 sigfillset(&nmask);
851 sigprocmask(SIG_BLOCK, &nmask, &omask);
852 openlog("init", 0, LOG_DAEMON);
853 syslog(LOG_INFO, "%s", buf);
854 closelog();
855 sigprocmask(SIG_SETMASK, &omask, NULL);
856 }
857
858 /*
859 * And log to the console.
860 */
861 if (loglevel & L_CO) {
862 print("\rINIT: ");
863 print(buf);
864 print("\r\n");
865 }
866}
867
868
869/*
870 * Build a new environment for execve().
871 */
872char **init_buildenv(int child)
873{
874 char i_lvl[] = "RUNLEVEL=x";
875 char i_prev[] = "PREVLEVEL=x";
876 char i_cons[32];
5f959b29 877 char i_shell[] = "SHELL=" SHELL;
a74aeac6
PR
878 char **e;
879 int n, i;
880
881 for (n = 0; environ[n]; n++)
882 ;
23d97522 883 n += NR_EXTRA_ENV;
fd6f5c50 884 if (child)
23d97522 885 n += 8;
a74aeac6
PR
886 e = calloc(n, sizeof(char *));
887
888 for (n = 0; environ[n]; n++)
889 e[n] = istrdup(environ[n]);
890
23d97522 891 for (i = 0; i < NR_EXTRA_ENV; i++) {
a74aeac6
PR
892 if (extra_env[i])
893 e[n++] = istrdup(extra_env[i]);
23d97522 894 }
a74aeac6
PR
895
896 if (child) {
897 snprintf(i_cons, sizeof(i_cons), "CONSOLE=%s", console_dev);
898 i_lvl[9] = thislevel;
899 i_prev[10] = prevlevel;
5f959b29 900 e[n++] = istrdup(i_shell);
a74aeac6
PR
901 e[n++] = istrdup(i_lvl);
902 e[n++] = istrdup(i_prev);
903 e[n++] = istrdup(i_cons);
904 e[n++] = istrdup(E_VERSION);
905 }
906
907 e[n++] = NULL;
908
909 return e;
910}
911
912
913void init_freeenv(char **e)
914{
915 int n;
916
917 for (n = 0; e[n]; n++)
918 free(e[n]);
919 free(e);
920}
921
922
923/*
924 * Fork and execute.
925 *
926 * This function is too long and indents too deep.
927 *
928 */
5f959b29 929static
23d97522 930pid_t spawn(CHILD *ch, int *res)
a74aeac6
PR
931{
932 char *args[16]; /* Argv array */
933 char buf[136]; /* Line buffer */
23d97522 934 int f, st; /* Scratch variables */
a74aeac6
PR
935 char *ptr; /* Ditto */
936 time_t t; /* System time */
937 int oldAlarm; /* Previous alarm value */
938 char *proc = ch->process; /* Command line */
939 pid_t pid, pgrp; /* child, console process group. */
940 sigset_t nmask, omask; /* For blocking SIGCHLD */
941 struct sigaction sa;
942
943 *res = -1;
944 buf[sizeof(buf) - 1] = 0;
945
946 /* Skip '+' if it's there */
947 if (proc[0] == '+') proc++;
948
949 ch->flags |= XECUTED;
950
951 if (ch->action == RESPAWN || ch->action == ONDEMAND) {
952 /* Is the date stamp from less than 2 minutes ago? */
953 time(&t);
954 if (ch->tm + TESTTIME > t) {
955 ch->count++;
956 } else {
957 ch->count = 0;
958 ch->tm = t;
959 }
960
961 /* Do we try to respawn too fast? */
962 if (ch->count >= MAXSPAWN) {
963
964 initlog(L_VB,
965 "Id \"%s\" respawning too fast: disabled for %d minutes",
966 ch->id, SLEEPTIME / 60);
967 ch->flags &= ~RUNNING;
968 ch->flags |= FAILING;
969
970 /* Remember the time we stopped */
971 ch->tm = t;
972
973 /* Try again in 5 minutes */
974 oldAlarm = alarm(0);
975 if (oldAlarm > SLEEPTIME || oldAlarm <= 0) oldAlarm = SLEEPTIME;
976 alarm(oldAlarm);
977 return(-1);
978 }
979 }
980
981 /* See if there is an "initscript" (except in single user mode). */
982 if (access(INITSCRIPT, R_OK) == 0 && runlevel != 'S') {
983 /* Build command line using "initscript" */
984 args[1] = SHELL;
985 args[2] = INITSCRIPT;
986 args[3] = ch->id;
987 args[4] = ch->rlevel;
988 args[5] = "unknown";
989 for(f = 0; actions[f].name; f++) {
990 if (ch->action == actions[f].act) {
991 args[5] = actions[f].name;
992 break;
993 }
994 }
995 args[6] = proc;
996 args[7] = NULL;
997 } else if (strpbrk(proc, "~`!$^&*()=|\\{}[];\"'<>?")) {
998 /* See if we need to fire off a shell for this command */
999 /* Give command line to shell */
1000 args[1] = SHELL;
1001 args[2] = "-c";
1002 strcpy(buf, "exec ");
1003 strncat(buf, proc, sizeof(buf) - strlen(buf) - 1);
1004 args[3] = buf;
1005 args[4] = NULL;
1006 } else {
1007 /* Split up command line arguments */
1008 buf[0] = 0;
1009 strncat(buf, proc, sizeof(buf) - 1);
1010 ptr = buf;
1011 for(f = 1; f < 15; f++) {
1012 /* Skip white space */
1013 while(*ptr == ' ' || *ptr == '\t') ptr++;
1014 args[f] = ptr;
1015
1016 /* May be trailing space.. */
1017 if (*ptr == 0) break;
1018
1019 /* Skip this `word' */
1020 while(*ptr && *ptr != ' ' && *ptr != '\t' && *ptr != '#')
1021 ptr++;
1022
1023 /* If end-of-line, break */
1024 if (*ptr == '#' || *ptr == 0) {
1025 f++;
1026 *ptr = 0;
1027 break;
1028 }
1029 /* End word with \0 and continue */
1030 *ptr++ = 0;
1031 }
1032 args[f] = NULL;
1033 }
1034 args[0] = args[1];
1035 while(1) {
1036 /*
1037 * Block sigchild while forking.
1038 */
1039 sigemptyset(&nmask);
1040 sigaddset(&nmask, SIGCHLD);
1041 sigprocmask(SIG_BLOCK, &nmask, &omask);
1042
1043 if ((pid = fork()) == 0) {
fd6f5c50 1044
a74aeac6
PR
1045 close(0);
1046 close(1);
1047 close(2);
1048 if (pipe_fd >= 0) close(pipe_fd);
1049
1050 sigprocmask(SIG_SETMASK, &omask, NULL);
1051
1052 /*
1053 * In sysinit, boot, bootwait or single user mode:
1054 * for any wait-type subprocess we _force_ the console
1055 * to be its controlling tty.
1056 */
1057 if (strchr("*#sS", runlevel) && ch->flags & WAITING) {
1058 /*
1059 * We fork once extra. This is so that we can
1060 * wait and change the process group and session
1061 * of the console after exit of the leader.
1062 */
1063 setsid();
1064 if ((f = console_open(O_RDWR|O_NOCTTY)) >= 0) {
1065 /* Take over controlling tty by force */
1066 (void)ioctl(f, TIOCSCTTY, 1);
1067 dup(f);
1068 dup(f);
1069 }
63a2c981
DWF
1070
1071 /*
1072 * 4 Sep 2001, Andrea Arcangeli:
1073 * Fix a race in spawn() that is used to deadlock init in a
1074 * waitpid() loop: must set the childhandler as default before forking
1075 * off the child or the chld_handler could run before the waitpid loop
1076 * has a chance to find its zombie-child.
1077 */
a74aeac6
PR
1078 SETSIG(sa, SIGCHLD, SIG_DFL, SA_RESTART);
1079 if ((pid = fork()) < 0) {
1080 initlog(L_VB, "cannot fork: %s",
1081 strerror(errno));
1082 exit(1);
1083 }
1084 if (pid > 0) {
23d97522 1085 pid_t rc;
a74aeac6
PR
1086 /*
1087 * Ignore keyboard signals etc.
1088 * Then wait for child to exit.
1089 */
1090 SETSIG(sa, SIGINT, SIG_IGN, SA_RESTART);
1091 SETSIG(sa, SIGTSTP, SIG_IGN, SA_RESTART);
1092 SETSIG(sa, SIGQUIT, SIG_IGN, SA_RESTART);
1093
1094 while ((rc = waitpid(pid, &st, 0)) != pid)
1095 if (rc < 0 && errno == ECHILD)
1096 break;
1097
1098 /*
1099 * Small optimization. See if stealing
1100 * controlling tty back is needed.
1101 */
1102 pgrp = tcgetpgrp(f);
1103 if (pgrp != getpid())
1104 exit(0);
1105
1106 /*
1107 * Steal controlling tty away. We do
1108 * this with a temporary process.
1109 */
1110 if ((pid = fork()) < 0) {
1111 initlog(L_VB, "cannot fork: %s",
1112 strerror(errno));
1113 exit(1);
1114 }
1115 if (pid == 0) {
1116 setsid();
1117 (void)ioctl(f, TIOCSCTTY, 1);
1118 exit(0);
1119 }
1120 while((rc = waitpid(pid, &st, 0)) != pid)
1121 if (rc < 0 && errno == ECHILD)
1122 break;
1123 exit(0);
1124 }
1125
1126 /* Set ioctl settings to default ones */
1127 console_stty();
1128
1129 } else {
1130 setsid();
1131 if ((f = console_open(O_RDWR|O_NOCTTY)) < 0) {
1132 initlog(L_VB, "open(%s): %s", console_dev,
1133 strerror(errno));
1134 f = open("/dev/null", O_RDWR);
1135 }
1136 dup(f);
1137 dup(f);
1138 }
1139
23d97522
DWF
1140 /*
1141 * Update utmp/wtmp file prior to starting
1142 * any child. This MUST be done right here in
1143 * the child process in order to prevent a race
1144 * condition that occurs when the child
1145 * process' time slice executes before the
1146 * parent (can and does happen in a uniprocessor
1147 * environment). If the child is a getty and
1148 * the race condition happens, then init's utmp
1149 * update will happen AFTER the getty runs
1150 * and expects utmp to be updated already!
1151 *
1152 * Do NOT log if process field starts with '+'
1153 * FIXME: that's for compatibility with *very*
1154 * old getties - probably it can be taken out.
1155 */
1156 if (ch->process[0] != '+')
1157 write_utmp_wtmp("", ch->id, getpid(), INIT_PROCESS, "");
1158
a74aeac6
PR
1159 /* Reset all the signals, set up environment */
1160 for(f = 1; f < NSIG; f++) SETSIG(sa, f, SIG_DFL, SA_RESTART);
1161 environ = init_buildenv(1);
1162
1163 /*
1164 * Execute prog. In case of ENOEXEC try again
1165 * as a shell script.
1166 */
1167 execvp(args[1], args + 1);
1168 if (errno == ENOEXEC) {
1169 args[1] = SHELL;
1170 args[2] = "-c";
1171 strcpy(buf, "exec ");
1172 strncat(buf, proc, sizeof(buf) - strlen(buf) - 1);
1173 args[3] = buf;
1174 args[4] = NULL;
1175 execvp(args[1], args + 1);
1176 }
1177 initlog(L_VB, "cannot execute \"%s\"", args[1]);
23d97522
DWF
1178
1179 if (ch->process[0] != '+')
1180 write_utmp_wtmp("", ch->id, getpid(), DEAD_PROCESS, NULL);
a74aeac6
PR
1181 exit(1);
1182 }
1183 *res = pid;
1184 sigprocmask(SIG_SETMASK, &omask, NULL);
1185
1186 INITDBG(L_VB, "Started id %s (pid %d)", ch->id, pid);
1187
1188 if (pid == -1) {
1189 initlog(L_VB, "cannot fork, retry..");
1190 do_sleep(5);
1191 continue;
1192 }
1193 return(pid);
1194 }
1195}
1196
1197/*
1198 * Start a child running!
1199 */
5f959b29 1200static
a74aeac6
PR
1201void startup(CHILD *ch)
1202{
1203 /*
1204 * See if it's disabled
1205 */
1206 if (ch->flags & FAILING) return;
1207
1208 switch(ch->action) {
1209
1210 case SYSINIT:
1211 case BOOTWAIT:
1212 case WAIT:
1213 case POWERWAIT:
1214 case POWERFAILNOW:
1215 case POWEROKWAIT:
1216 case CTRLALTDEL:
1217 if (!(ch->flags & XECUTED)) ch->flags |= WAITING;
1218 case KBREQUEST:
1219 case BOOT:
1220 case POWERFAIL:
1221 case ONCE:
1222 if (ch->flags & XECUTED) break;
1223 case ONDEMAND:
1224 case RESPAWN:
1225 ch->flags |= RUNNING;
90c78fcc 1226 (void)spawn(ch, &(ch->pid));
a74aeac6
PR
1227 break;
1228 }
1229}
1230
1231
1232/*
1233 * Read the inittab file.
1234 */
5f959b29 1235static
a74aeac6
PR
1236void read_inittab(void)
1237{
1238 FILE *fp; /* The INITTAB file */
1239 CHILD *ch, *old, *i; /* Pointers to CHILD structure */
1240 CHILD *head = NULL; /* Head of linked list */
1241#ifdef INITLVL
1242 struct stat st; /* To stat INITLVL */
1243#endif
1244 sigset_t nmask, omask; /* For blocking SIGCHLD. */
1245 char buf[256]; /* Line buffer */
1246 char err[64]; /* Error message. */
1247 char *id, *rlevel,
1248 *action, *process; /* Fields of a line */
1249 char *p;
1250 int lineNo = 0; /* Line number in INITTAB file */
1251 int actionNo; /* Decoded action field */
1252 int f; /* Counter */
1253 int round; /* round 0 for SIGTERM, 1 for SIGKILL */
1254 int foundOne = 0; /* No killing no sleep */
1255 int talk; /* Talk to the user */
1256 int done = 0; /* Ready yet? */
1257
1258#if DEBUG
1259 if (newFamily != NULL) {
1260 INITDBG(L_VB, "PANIC newFamily != NULL");
1261 exit(1);
1262 }
1263 INITDBG(L_VB, "Reading inittab");
1264#endif
1265
1266 /*
1267 * Open INITTAB and real line by line.
1268 */
1269 if ((fp = fopen(INITTAB, "r")) == NULL)
1270 initlog(L_VB, "No inittab file found");
1271
1272 while(!done) {
1273 /*
1274 * Add single user shell entry at the end.
1275 */
1276 if (fp == NULL || fgets(buf, sizeof(buf), fp) == NULL) {
1277 done = 1;
1278 /*
1279 * See if we have a single user entry.
1280 */
1281 for(old = newFamily; old; old = old->next)
1282 if (strpbrk(old->rlevel, "S")) break;
1283 if (old == NULL)
1284 snprintf(buf, sizeof(buf), "~~:S:wait:%s\n", SULOGIN);
1285 else
1286 continue;
1287 }
1288 lineNo++;
1289 /*
1290 * Skip comments and empty lines
1291 */
1292 for(p = buf; *p == ' ' || *p == '\t'; p++)
1293 ;
1294 if (*p == '#' || *p == '\n') continue;
1295
1296 /*
1297 * Decode the fields
1298 */
1299 id = strsep(&p, ":");
1300 rlevel = strsep(&p, ":");
1301 action = strsep(&p, ":");
1302 process = strsep(&p, "\n");
1303
1304 /*
1305 * Check if syntax is OK. Be very verbose here, to
1306 * avoid newbie postings on comp.os.linux.setup :)
1307 */
1308 err[0] = 0;
1309 if (!id || !*id) strcpy(err, "missing id field");
1310 if (!rlevel) strcpy(err, "missing runlevel field");
1311 if (!process) strcpy(err, "missing process field");
1312 if (!action || !*action)
1313 strcpy(err, "missing action field");
1314 if (id && strlen(id) > sizeof(utproto.ut_id))
1315 sprintf(err, "id field too long (max %d characters)",
1316 (int)sizeof(utproto.ut_id));
1317 if (rlevel && strlen(rlevel) > 11)
1318 strcpy(err, "rlevel field too long (max 11 characters)");
1319 if (process && strlen(process) > 127)
1320 strcpy(err, "process field too long");
1321 if (action && strlen(action) > 32)
1322 strcpy(err, "action field too long");
1323 if (err[0] != 0) {
1324 initlog(L_VB, "%s[%d]: %s", INITTAB, lineNo, err);
1325 INITDBG(L_VB, "%s:%s:%s:%s", id, rlevel, action, process);
1326 continue;
1327 }
1328
1329 /*
1330 * Decode the "action" field
1331 */
1332 actionNo = -1;
1333 for(f = 0; actions[f].name; f++)
1334 if (strcasecmp(action, actions[f].name) == 0) {
1335 actionNo = actions[f].act;
1336 break;
1337 }
1338 if (actionNo == -1) {
1339 initlog(L_VB, "%s[%d]: %s: unknown action field",
1340 INITTAB, lineNo, action);
1341 continue;
1342 }
1343
1344 /*
1345 * See if the id field is unique
1346 */
1347 for(old = newFamily; old; old = old->next) {
1348 if(strcmp(old->id, id) == 0 && strcmp(id, "~~")) {
1349 initlog(L_VB, "%s[%d]: duplicate ID field \"%s\"",
1350 INITTAB, lineNo, id);
1351 break;
1352 }
1353 }
1354 if (old) continue;
1355
1356 /*
1357 * Allocate a CHILD structure
1358 */
1359 ch = imalloc(sizeof(CHILD));
1360
1361 /*
1362 * And fill it in.
1363 */
1364 ch->action = actionNo;
1365 strncpy(ch->id, id, sizeof(utproto.ut_id) + 1); /* Hack for different libs. */
1366 strncpy(ch->process, process, sizeof(ch->process) - 1);
1367 if (rlevel[0]) {
192c4567 1368 for(f = 0; f < (int)sizeof(rlevel) - 1 && rlevel[f]; f++) {
a74aeac6
PR
1369 ch->rlevel[f] = rlevel[f];
1370 if (ch->rlevel[f] == 's') ch->rlevel[f] = 'S';
1371 }
1372 strncpy(ch->rlevel, rlevel, sizeof(ch->rlevel) - 1);
1373 } else {
1374 strcpy(ch->rlevel, "0123456789");
1375 if (ISPOWER(ch->action))
1376 strcpy(ch->rlevel, "S0123456789");
1377 }
1378 /*
1379 * We have the fake runlevel '#' for SYSINIT and
1380 * '*' for BOOT and BOOTWAIT.
1381 */
1382 if (ch->action == SYSINIT) strcpy(ch->rlevel, "#");
1383 if (ch->action == BOOT || ch->action == BOOTWAIT)
1384 strcpy(ch->rlevel, "*");
1385
1386 /*
1387 * Now add it to the linked list. Special for powerfail.
1388 */
1389 if (ISPOWER(ch->action)) {
1390
1391 /*
1392 * Disable by default
1393 */
1394 ch->flags |= XECUTED;
1395
1396 /*
1397 * Tricky: insert at the front of the list..
1398 */
1399 old = NULL;
1400 for(i = newFamily; i; i = i->next) {
1401 if (!ISPOWER(i->action)) break;
1402 old = i;
1403 }
1404 /*
1405 * Now add after entry "old"
1406 */
1407 if (old) {
1408 ch->next = i;
1409 old->next = ch;
1410 if (i == NULL) head = ch;
1411 } else {
1412 ch->next = newFamily;
1413 newFamily = ch;
1414 if (ch->next == NULL) head = ch;
1415 }
1416 } else {
1417 /*
1418 * Just add at end of the list
1419 */
1420 if (ch->action == KBREQUEST) ch->flags |= XECUTED;
1421 ch->next = NULL;
1422 if (head)
1423 head->next = ch;
1424 else
1425 newFamily = ch;
1426 head = ch;
1427 }
1428
1429 /*
1430 * Walk through the old list comparing id fields
1431 */
1432 for(old = family; old; old = old->next)
1433 if (strcmp(old->id, ch->id) == 0) {
1434 old->new = ch;
1435 break;
1436 }
1437 }
1438 /*
1439 * We're done.
1440 */
1441 if (fp) fclose(fp);
1442
1443 /*
1444 * Loop through the list of children, and see if they need to
1445 * be killed.
1446 */
1447
1448 INITDBG(L_VB, "Checking for children to kill");
1449 for(round = 0; round < 2; round++) {
1450 talk = 1;
1451 for(ch = family; ch; ch = ch->next) {
1452 ch->flags &= ~KILLME;
1453
1454 /*
1455 * Is this line deleted?
1456 */
1457 if (ch->new == NULL) ch->flags |= KILLME;
1458
1459 /*
1460 * If the entry has changed, kill it anyway. Note that
1461 * we do not check ch->process, only the "action" field.
1462 * This way, you can turn an entry "off" immediately, but
1463 * changes in the command line will only become effective
1464 * after the running version has exited.
1465 */
1466 if (ch->new && ch->action != ch->new->action) ch->flags |= KILLME;
1467
1468 /*
1469 * Only BOOT processes may live in all levels
1470 */
1471 if (ch->action != BOOT &&
1472 strchr(ch->rlevel, runlevel) == NULL) {
1473 /*
1474 * Ondemand procedures live always,
1475 * except in single user
1476 */
1477 if (runlevel == 'S' || !(ch->flags & DEMAND))
1478 ch->flags |= KILLME;
1479 }
1480
1481 /*
1482 * Now, if this process may live note so in the new list
1483 */
1484 if ((ch->flags & KILLME) == 0) {
1485 ch->new->flags = ch->flags;
1486 ch->new->pid = ch->pid;
1487 ch->new->exstat = ch->exstat;
1488 continue;
1489 }
1490
1491
1492 /*
1493 * Is this process still around?
1494 */
1495 if ((ch->flags & RUNNING) == 0) {
1496 ch->flags &= ~KILLME;
1497 continue;
1498 }
1499 INITDBG(L_VB, "Killing \"%s\"", ch->process);
1500 switch(round) {
1501 case 0: /* Send TERM signal */
1502 if (talk)
1503 initlog(L_CO,
1504 "Sending processes the TERM signal");
1505 kill(-(ch->pid), SIGTERM);
1506 foundOne = 1;
1507 break;
1508 case 1: /* Send KILL signal and collect status */
1509 if (talk)
1510 initlog(L_CO,
1511 "Sending processes the KILL signal");
1512 kill(-(ch->pid), SIGKILL);
1513 break;
1514 }
1515 talk = 0;
1516
1517 }
1518 /*
1519 * See if we have to wait 5 seconds
1520 */
1521 if (foundOne && round == 0) {
1522 /*
1523 * Yup, but check every second if we still have children.
1524 */
1525 for(f = 0; f < sltime; f++) {
1526 for(ch = family; ch; ch = ch->next) {
1527 if (!(ch->flags & KILLME)) continue;
1528 if ((ch->flags & RUNNING) && !(ch->flags & ZOMBIE))
1529 break;
1530 }
1531 if (ch == NULL) {
1532 /*
1533 * No running children, skip SIGKILL
1534 */
1535 round = 1;
1536 foundOne = 0; /* Skip the sleep below. */
1537 break;
1538 }
1539 do_sleep(1);
1540 }
1541 }
1542 }
1543
1544 /*
1545 * Now give all processes the chance to die and collect exit statuses.
1546 */
1547 if (foundOne) do_sleep(1);
1548 for(ch = family; ch; ch = ch->next)
1549 if (ch->flags & KILLME) {
1550 if (!(ch->flags & ZOMBIE))
1551 initlog(L_CO, "Pid %d [id %s] seems to hang", ch->pid,
1552 ch->id);
1553 else {
1554 INITDBG(L_VB, "Updating utmp for pid %d [id %s]",
1555 ch->pid, ch->id);
1556 ch->flags &= ~RUNNING;
1557 if (ch->process[0] != '+')
1558 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
1559 }
1560 }
1561
1562 /*
1563 * Both rounds done; clean up the list.
1564 */
1565 sigemptyset(&nmask);
1566 sigaddset(&nmask, SIGCHLD);
1567 sigprocmask(SIG_BLOCK, &nmask, &omask);
1568 for(ch = family; ch; ch = old) {
1569 old = ch->next;
1570 free(ch);
1571 }
1572 family = newFamily;
1573 for(ch = family; ch; ch = ch->next) ch->new = NULL;
1574 newFamily = NULL;
1575 sigprocmask(SIG_SETMASK, &omask, NULL);
1576
1577#ifdef INITLVL
1578 /*
1579 * Dispose of INITLVL file.
1580 */
1581 if (lstat(INITLVL, &st) >= 0 && S_ISLNK(st.st_mode)) {
1582 /*
1583 * INITLVL is a symbolic link, so just truncate the file.
1584 */
1585 close(open(INITLVL, O_WRONLY|O_TRUNC));
1586 } else {
1587 /*
1588 * Delete INITLVL file.
1589 */
1590 unlink(INITLVL);
1591 }
1592#endif
1593#ifdef INITLVL2
1594 /*
1595 * Dispose of INITLVL2 file.
1596 */
1597 if (lstat(INITLVL2, &st) >= 0 && S_ISLNK(st.st_mode)) {
1598 /*
1599 * INITLVL2 is a symbolic link, so just truncate the file.
1600 */
1601 close(open(INITLVL2, O_WRONLY|O_TRUNC));
1602 } else {
1603 /*
1604 * Delete INITLVL2 file.
1605 */
1606 unlink(INITLVL2);
1607 }
1608#endif
1609}
1610
1611/*
1612 * Walk through the family list and start up children.
1613 * The entries that do not belong here at all are removed
1614 * from the list.
1615 */
5f959b29 1616static
a74aeac6
PR
1617void start_if_needed(void)
1618{
1619 CHILD *ch; /* Pointer to child */
1620 int delete; /* Delete this entry from list? */
1621
1622 INITDBG(L_VB, "Checking for children to start");
1623
1624 for(ch = family; ch; ch = ch->next) {
1625
1626#if DEBUG
1627 if (ch->rlevel[0] == 'C') {
1628 INITDBG(L_VB, "%s: flags %d", ch->process, ch->flags);
1629 }
1630#endif
1631
1632 /* Are we waiting for this process? Then quit here. */
1633 if (ch->flags & WAITING) break;
1634
1635 /* Already running? OK, don't touch it */
1636 if (ch->flags & RUNNING) continue;
1637
1638 /* See if we have to start it up */
1639 delete = 1;
1640 if (strchr(ch->rlevel, runlevel) ||
1641 ((ch->flags & DEMAND) && !strchr("#*Ss", runlevel))) {
1642 startup(ch);
1643 delete = 0;
1644 }
1645
1646 if (delete) {
1647 /* FIXME: is this OK? */
1648 ch->flags &= ~(RUNNING|WAITING);
1649 if (!ISPOWER(ch->action) && ch->action != KBREQUEST)
1650 ch->flags &= ~XECUTED;
1651 ch->pid = 0;
1652 } else
1653 /* Do we have to wait for this process? */
1654 if (ch->flags & WAITING) break;
1655 }
1656 /* Done. */
1657}
1658
1659/*
1660 * Ask the user on the console for a runlevel
1661 */
5f959b29 1662static
a74aeac6
PR
1663int ask_runlevel(void)
1664{
1665 const char prompt[] = "\nEnter runlevel: ";
1666 char buf[8];
1667 int lvl = -1;
1668 int fd;
1669
1670 console_stty();
1671 fd = console_open(O_RDWR|O_NOCTTY);
1672
1673 if (fd < 0) return('S');
1674
1675 while(!strchr("0123456789S", lvl)) {
1676 write(fd, prompt, sizeof(prompt) - 1);
1677 buf[0] = 0;
1678 read(fd, buf, sizeof(buf));
1679 if (buf[0] != 0 && (buf[1] == '\r' || buf[1] == '\n'))
1680 lvl = buf[0];
1681 if (islower(lvl)) lvl = toupper(lvl);
1682 }
1683 close(fd);
1684 return lvl;
1685}
1686
1687/*
1688 * Search the INITTAB file for the 'initdefault' field, with the default
1689 * runlevel. If this fails, ask the user to supply a runlevel.
1690 */
5f959b29 1691static
a74aeac6
PR
1692int get_init_default(void)
1693{
1694 CHILD *ch;
1695 int lvl = -1;
1696 char *p;
1697
1698 /*
1699 * Look for initdefault.
1700 */
1701 for(ch = family; ch; ch = ch->next)
1702 if (ch->action == INITDEFAULT) {
1703 p = ch->rlevel;
1704 while(*p) {
1705 if (*p > lvl) lvl = *p;
1706 p++;
1707 }
1708 break;
1709 }
1710 /*
1711 * See if level is valid
1712 */
1713 if (lvl > 0) {
1714 if (islower(lvl)) lvl = toupper(lvl);
1715 if (strchr("0123456789S", lvl) == NULL) {
1716 initlog(L_VB,
1717 "Initdefault level '%c' is invalid", lvl);
1718 lvl = 0;
1719 }
1720 }
1721 /*
1722 * Ask for runlevel on console if needed.
1723 */
1724 if (lvl <= 0) lvl = ask_runlevel();
1725
1726 /*
1727 * Log the fact that we have a runlevel now.
1728 */
1729 return lvl;
1730}
1731
1732
1733/*
1734 * We got signaled.
1735 *
1736 * Do actions for the new level. If we are compatible with
1737 * the "old" INITLVL and arg == 0, try to read the new
1738 * runlevel from that file first.
1739 */
5f959b29 1740static
a74aeac6
PR
1741int read_level(int arg)
1742{
1743 CHILD *ch; /* Walk through list */
1744 unsigned char foo = 'X'; /* Contents of INITLVL */
1745 int ok = 1;
1746#ifdef INITLVL
1747 FILE *fp;
1748 struct stat stt;
1749 int st;
1750#endif
1751
1752 if (arg) foo = arg;
1753
1754#ifdef INITLVL
1755 ok = 0;
1756
1757 if (arg == 0) {
1758 fp = NULL;
1759 if (stat(INITLVL, &stt) != 0 || stt.st_size != 0L)
1760 fp = fopen(INITLVL, "r");
1761#ifdef INITLVL2
1762 if (fp == NULL &&
1763 (stat(INITLVL2, &stt) != 0 || stt.st_size != 0L))
1764 fp = fopen(INITLVL2, "r");
1765#endif
1766 if (fp == NULL) {
1767 /* INITLVL file empty or not there - act as 'init q' */
1768 initlog(L_SY, "Re-reading inittab");
1769 return(runlevel);
1770 }
1771 ok = fscanf(fp, "%c %d", &foo, &st);
1772 fclose(fp);
1773 } else {
1774 /* We go to the new runlevel passed as an argument. */
1775 foo = arg;
1776 ok = 1;
1777 }
1778 if (ok == 2) sltime = st;
1779
1780#endif /* INITLVL */
1781
1782 if (islower(foo)) foo = toupper(foo);
1783 if (ok < 1 || ok > 2 || strchr("QS0123456789ABCU", foo) == NULL) {
1784 initlog(L_VB, "bad runlevel: %c", foo);
1785 return runlevel;
1786 }
1787
1788 /* Log this action */
1789 switch(foo) {
1790 case 'S':
1791 initlog(L_VB, "Going single user");
1792 break;
1793 case 'Q':
1794 initlog(L_SY, "Re-reading inittab");
1795 break;
1796 case 'A':
1797 case 'B':
1798 case 'C':
1799 initlog(L_SY,
1800 "Activating demand-procedures for '%c'", foo);
1801 break;
1802 case 'U':
1803 initlog(L_SY, "Trying to re-exec init");
1804 return 'U';
1805 default:
1806 initlog(L_VB, "Switching to runlevel: %c", foo);
1807 }
1808
5f959b29
DWF
1809 if (foo == 'Q') {
1810#if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1811 /* Re-enable signal from keyboard */
1812 struct sigaction sa;
1813 SETSIG(sa, SIGINT, signal_handler, 0);
1814#endif
1815 return runlevel;
1816 }
a74aeac6
PR
1817
1818 /* Check if this is a runlevel a, b or c */
1819 if (strchr("ABC", foo)) {
1820 if (runlevel == 'S') return(runlevel);
1821
1822 /* Read inittab again first! */
1823 read_inittab();
1824
1825 /* Mark those special tasks */
1826 for(ch = family; ch; ch = ch->next)
1827 if (strchr(ch->rlevel, foo) != NULL ||
1828 strchr(ch->rlevel, tolower(foo)) != NULL) {
1829 ch->flags |= DEMAND;
1830 ch->flags &= ~XECUTED;
1831 INITDBG(L_VB,
1832 "Marking (%s) as ondemand, flags %d",
1833 ch->id, ch->flags);
1834 }
1835 return runlevel;
1836 }
1837
1838 /* Store both the old and the new runlevel. */
63a2c981
DWF
1839 wrote_utmp_rlevel = 0;
1840 wrote_wtmp_rlevel = 0;
a74aeac6
PR
1841 write_utmp_wtmp("runlevel", "~~", foo + 256*runlevel, RUN_LVL, "~");
1842 thislevel = foo;
1843 prevlevel = runlevel;
1844 return foo;
1845}
1846
1847
1848/*
1849 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1850 *
1851 * Only clear the 'failing' flag if the process is sleeping
1852 * longer than 5 minutes, or inittab was read again due
1853 * to user interaction.
1854 */
5f959b29 1855static
a74aeac6
PR
1856void fail_check(void)
1857{
1858 CHILD *ch; /* Pointer to child structure */
1859 time_t t; /* System time */
1860 time_t next_alarm = 0; /* When to set next alarm */
1861
1862 time(&t);
1863
1864 for(ch = family; ch; ch = ch->next) {
1865
1866 if (ch->flags & FAILING) {
1867 /* Can we free this sucker? */
1868 if (ch->tm + SLEEPTIME < t) {
1869 ch->flags &= ~FAILING;
1870 ch->count = 0;
1871 ch->tm = 0;
1872 } else {
1873 /* No, we'll look again later */
1874 if (next_alarm == 0 ||
1875 ch->tm + SLEEPTIME > next_alarm)
1876 next_alarm = ch->tm + SLEEPTIME;
1877 }
1878 }
1879 }
1880 if (next_alarm) {
1881 next_alarm -= t;
1882 if (next_alarm < 1) next_alarm = 1;
1883 alarm(next_alarm);
1884 }
1885}
1886
1887/* Set all 'Fail' timers to 0 */
5f959b29 1888static
a74aeac6
PR
1889void fail_cancel(void)
1890{
1891 CHILD *ch;
1892
1893 for(ch = family; ch; ch = ch->next) {
1894 ch->count = 0;
1895 ch->tm = 0;
1896 ch->flags &= ~FAILING;
1897 }
1898}
1899
1900/*
1901 * Start up powerfail entries.
1902 */
5f959b29 1903static
a74aeac6
PR
1904void do_power_fail(int pwrstat)
1905{
1906 CHILD *ch;
1907
1908 /*
1909 * Tell powerwait & powerfail entries to start up
1910 */
1911 for (ch = family; ch; ch = ch->next) {
1912 if (pwrstat == 'O') {
1913 /*
1914 * The power is OK again.
1915 */
1916 if (ch->action == POWEROKWAIT)
1917 ch->flags &= ~XECUTED;
1918 } else if (pwrstat == 'L') {
1919 /*
1920 * Low battery, shut down now.
1921 */
1922 if (ch->action == POWERFAILNOW)
1923 ch->flags &= ~XECUTED;
1924 } else {
1925 /*
1926 * Power is failing, shutdown imminent
1927 */
1928 if (ch->action == POWERFAIL || ch->action == POWERWAIT)
1929 ch->flags &= ~XECUTED;
1930 }
1931 }
1932}
1933
1934/*
1935 * Check for state-pipe presence
1936 */
5f959b29 1937static
a74aeac6
PR
1938int check_pipe(int fd)
1939{
1940 struct timeval t;
1941 fd_set s;
1942 char signature[8];
1943
1944 FD_ZERO(&s);
1945 FD_SET(fd, &s);
1946 t.tv_sec = t.tv_usec = 0;
1947
1948 if (select(fd+1, &s, NULL, NULL, &t) != 1)
1949 return 0;
1950 if (read(fd, signature, 8) != 8)
1951 return 0;
1952 return strncmp(Signature, signature, 8) == 0;
1953}
1954
1955/*
1956 * Make a state-pipe.
1957 */
5f959b29 1958static
a74aeac6
PR
1959int make_pipe(int fd)
1960{
1961 int fds[2];
1962
1963 pipe(fds);
1964 dup2(fds[0], fd);
1965 close(fds[0]);
1966 fcntl(fds[1], F_SETFD, 1);
1967 fcntl(fd, F_SETFD, 0);
1968 write(fds[1], Signature, 8);
1969
1970 return fds[1];
1971}
1972
1973/*
1974 * Attempt to re-exec.
1975 */
5f959b29 1976static
a74aeac6
PR
1977void re_exec(void)
1978{
1979 CHILD *ch;
1980 sigset_t mask, oldset;
1981 pid_t pid;
1982 char **env;
1983 int fd;
1984
1985 if (strchr("S0123456",runlevel) == NULL)
1986 return;
1987
1988 /*
1989 * Reset the alarm, and block all signals.
1990 */
1991 alarm(0);
1992 sigfillset(&mask);
1993 sigprocmask(SIG_BLOCK, &mask, &oldset);
1994
1995 /*
1996 * construct a pipe fd --> STATE_PIPE and write a signature
1997 */
1998 fd = make_pipe(STATE_PIPE);
1999
2000 /*
2001 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
2002 * does have it's advantages...
2003 */
2004 fail_cancel();
2005 close(pipe_fd);
2006 pipe_fd = -1;
2007 DELSET(got_signals, SIGCHLD);
2008 DELSET(got_signals, SIGHUP);
2009 DELSET(got_signals, SIGUSR1);
2010
2011 /*
2012 * That should be cleaned.
2013 */
2014 for(ch = family; ch; ch = ch->next)
2015 if (ch->flags & ZOMBIE) {
2016 INITDBG(L_VB, "Child died, PID= %d", ch->pid);
2017 ch->flags &= ~(RUNNING|ZOMBIE|WAITING);
2018 if (ch->process[0] != '+')
2019 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
2020 }
2021
2022 if ((pid = fork()) == 0) {
2023 /*
2024 * Child sends state information to the parent.
2025 */
2026 send_state(fd);
2027 exit(0);
2028 }
2029
2030 /*
2031 * The existing init process execs a new init binary.
2032 */
2033 env = init_buildenv(0);
2034 execle(myname, myname, "--init", NULL, env);
2035
2036 /*
2037 * We shouldn't be here, something failed.
2038 * Bitch, close the state pipe, unblock signals and return.
2039 */
2040 close(fd);
2041 close(STATE_PIPE);
2042 sigprocmask(SIG_SETMASK, &oldset, NULL);
2043 init_freeenv(env);
2044 initlog(L_CO, "Attempt to re-exec failed");
2045}
2046
63a2c981
DWF
2047/*
2048 * Redo utmp/wtmp entries if required or requested
2049 * Check for written records and size of utmp
2050 */
2051static
2052void redo_utmp_wtmp(void)
2053{
2054 struct stat ustat;
2055 const int ret = stat(UTMP_FILE, &ustat);
2056
2057 if ((ret < 0) || (ustat.st_size == 0))
2058 wrote_utmp_rlevel = wrote_utmp_reboot = 0;
2059
2060 if ((wrote_wtmp_reboot == 0) || (wrote_utmp_reboot == 0))
2061 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME, "~");
2062
2063 if ((wrote_wtmp_rlevel == 0) || (wrote_wtmp_rlevel == 0))
2064 write_utmp_wtmp("runlevel", "~~", thislevel + 256 * prevlevel, RUN_LVL, "~");
2065}
a74aeac6
PR
2066
2067/*
2068 * We got a change runlevel request through the
2069 * init.fifo. Process it.
2070 */
5f959b29 2071static
a74aeac6
PR
2072void fifo_new_level(int level)
2073{
2074#if CHANGE_WAIT
2075 CHILD *ch;
2076#endif
2077 int oldlevel;
2078
2079 if (level == runlevel) return;
2080
2081#if CHANGE_WAIT
2082 /* Are we waiting for a child? */
2083 for(ch = family; ch; ch = ch->next)
2084 if (ch->flags & WAITING) break;
2085 if (ch == NULL)
2086#endif
2087 {
2088 /* We need to go into a new runlevel */
2089 oldlevel = runlevel;
2090 runlevel = read_level(level);
2091 if (runlevel == 'U') {
2092 runlevel = oldlevel;
2093 re_exec();
2094 } else {
2095 if (oldlevel != 'S' && runlevel == 'S') console_stty();
2096 if (runlevel == '6' || runlevel == '0' ||
2097 runlevel == '1') console_stty();
63a2c981 2098 if (runlevel > '1' && runlevel < '6') redo_utmp_wtmp();
a74aeac6
PR
2099 read_inittab();
2100 fail_cancel();
5f959b29 2101 setproctitle("init [%c]", (int)runlevel);
a74aeac6
PR
2102 }
2103 }
2104}
2105
2106
2107/*
2108 * Set/unset environment variables. The variables are
2109 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2110 * setenv, without it means unsetenv.
2111 */
5f959b29 2112static
a74aeac6
PR
2113void initcmd_setenv(char *data, int size)
2114{
2115 char *env, *p, *e, *eq;
2116 int i, sz;
2117
2118 e = data + size;
2119
2120 while (*data && data < e) {
2121 eq = NULL;
2122 for (p = data; *p && p < e; p++)
2123 if (*p == '=') eq = p;
2124 if (*p) break;
2125 env = data;
2126 data = ++p;
2127
2128 sz = eq ? (eq - env) : (p - env);
2129
2130 /*initlog(L_SY, "init_setenv: %s, %s, %d", env, eq, sz);*/
2131
2132 /*
2133 * We only allow INIT_* to be set.
2134 */
2135 if (strncmp(env, "INIT_", 5) != 0)
2136 continue;
2137
2138 /* Free existing vars. */
2139 for (i = 0; i < NR_EXTRA_ENV; i++) {
2140 if (extra_env[i] == NULL) continue;
2141 if (!strncmp(extra_env[i], env, sz) &&
2142 extra_env[i][sz] == '=') {
2143 free(extra_env[i]);
2144 extra_env[i] = NULL;
2145 }
2146 }
2147
2148 /* Set new vars if needed. */
2149 if (eq == NULL) continue;
2150 for (i = 0; i < NR_EXTRA_ENV; i++) {
2151 if (extra_env[i] == NULL) {
2152 extra_env[i] = istrdup(env);
2153 break;
2154 }
2155 }
2156 }
2157}
2158
2159
2160/*
2161 * Read from the init FIFO. Processes like telnetd and rlogind can
2162 * ask us to create login processes on their behalf.
2163 *
2164 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2165 * to add the telnetd/rlogind stuff so people can start using it.
2166 * Maybe move to using an AF_UNIX socket so we can use
2167 * the 2.2 kernel credential stuff to see who we're talking to.
2168 *
2169 */
5f959b29 2170static
a74aeac6
PR
2171void check_init_fifo(void)
2172{
2173 struct init_request request;
2174 struct timeval tv;
2175 struct stat st, st2;
2176 fd_set fds;
2177 int n;
2178 int quit = 0;
2179
2180 /*
2181 * First, try to create /dev/initctl if not present.
2182 */
2183 if (stat(INIT_FIFO, &st2) < 0 && errno == ENOENT)
2184 (void)mkfifo(INIT_FIFO, 0600);
2185
2186 /*
2187 * If /dev/initctl is open, stat the file to see if it
2188 * is still the _same_ inode.
2189 */
2190 if (pipe_fd >= 0) {
2191 fstat(pipe_fd, &st);
2192 if (stat(INIT_FIFO, &st2) < 0 ||
2193 st.st_dev != st2.st_dev ||
2194 st.st_ino != st2.st_ino) {
2195 close(pipe_fd);
2196 pipe_fd = -1;
2197 }
2198 }
2199
2200 /*
2201 * Now finally try to open /dev/initctl
2202 */
2203 if (pipe_fd < 0) {
2204 if ((pipe_fd = open(INIT_FIFO, O_RDWR|O_NONBLOCK)) >= 0) {
2205 fstat(pipe_fd, &st);
2206 if (!S_ISFIFO(st.st_mode)) {
2207 initlog(L_VB, "%s is not a fifo", INIT_FIFO);
2208 close(pipe_fd);
2209 pipe_fd = -1;
2210 }
2211 }
2212 if (pipe_fd >= 0) {
2213 /*
2214 * Don't use fd's 0, 1 or 2.
2215 */
2216 (void) dup2(pipe_fd, PIPE_FD);
2217 close(pipe_fd);
2218 pipe_fd = PIPE_FD;
2219
2220 /*
2221 * Return to caller - we'll be back later.
2222 */
2223 }
2224 }
2225
2226 /* Wait for data to appear, _if_ the pipe was opened. */
2227 if (pipe_fd >= 0) while(!quit) {
2228
2229 /* Do select, return on EINTR. */
2230 FD_ZERO(&fds);
2231 FD_SET(pipe_fd, &fds);
2232 tv.tv_sec = 5;
2233 tv.tv_usec = 0;
2234 n = select(pipe_fd + 1, &fds, NULL, NULL, &tv);
2235 if (n <= 0) {
2236 if (n == 0 || errno == EINTR) return;
2237 continue;
2238 }
2239
2240 /* Read the data, return on EINTR. */
2241 n = read(pipe_fd, &request, sizeof(request));
2242 if (n == 0) {
2243 /*
2244 * End of file. This can't happen under Linux (because
2245 * the pipe is opened O_RDWR - see select() in the
2246 * kernel) but you never know...
2247 */
2248 close(pipe_fd);
2249 pipe_fd = -1;
2250 return;
2251 }
2252 if (n <= 0) {
2253 if (errno == EINTR) return;
2254 initlog(L_VB, "error reading initrequest");
2255 continue;
2256 }
2257
2258 /*
2259 * This is a convenient point to also try to
2260 * find the console device or check if it changed.
2261 */
2262 console_init();
2263
2264 /*
2265 * Process request.
2266 */
2267 if (request.magic != INIT_MAGIC || n != sizeof(request)) {
2268 initlog(L_VB, "got bogus initrequest");
2269 continue;
2270 }
2271 switch(request.cmd) {
2272 case INIT_CMD_RUNLVL:
2273 sltime = request.sleeptime;
2274 fifo_new_level(request.runlevel);
2275 quit = 1;
2276 break;
2277 case INIT_CMD_POWERFAIL:
2278 sltime = request.sleeptime;
2279 do_power_fail('F');
2280 quit = 1;
2281 break;
2282 case INIT_CMD_POWERFAILNOW:
2283 sltime = request.sleeptime;
2284 do_power_fail('L');
2285 quit = 1;
2286 break;
2287 case INIT_CMD_POWEROK:
2288 sltime = request.sleeptime;
2289 do_power_fail('O');
2290 quit = 1;
2291 break;
2292 case INIT_CMD_SETENV:
2293 initcmd_setenv(request.i.data, sizeof(request.i.data));
2294 break;
a74aeac6
PR
2295 default:
2296 initlog(L_VB, "got unimplemented initrequest.");
2297 break;
2298 }
2299 }
2300
2301 /*
2302 * We come here if the pipe couldn't be opened.
2303 */
2304 if (pipe_fd < 0) pause();
2305
2306}
2307
2308
2309/*
2310 * This function is used in the transition
2311 * sysinit (-> single user) boot -> multi-user.
2312 */
5f959b29 2313static
a74aeac6
PR
2314void boot_transitions()
2315{
2316 CHILD *ch;
2317 static int newlevel = 0;
2318 static int warn = 1;
2319 int loglevel;
2320 int oldlevel;
2321
2322 /* Check if there is something to wait for! */
2323 for( ch = family; ch; ch = ch->next )
2324 if ((ch->flags & RUNNING) && ch->action != BOOT) break;
2325
2326 if (ch == NULL) {
2327 /* No processes left in this level, proceed to next level. */
2328 loglevel = -1;
2329 oldlevel = 'N';
2330 switch(runlevel) {
2331 case '#': /* SYSINIT -> BOOT */
2332 INITDBG(L_VB, "SYSINIT -> BOOT");
2333
2334 /* Write a boot record. */
2335 wrote_utmp_reboot = 0;
2336 wrote_wtmp_reboot = 0;
2337 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME, "~");
2338
2339 /* Get our run level */
2340 newlevel = dfl_level ? dfl_level : get_init_default();
2341 if (newlevel == 'S') {
2342 runlevel = newlevel;
2343 /* Not really 'S' but show anyway. */
2344 setproctitle("init [S]");
2345 } else
2346 runlevel = '*';
2347 break;
2348 case '*': /* BOOT -> NORMAL */
2349 INITDBG(L_VB, "BOOT -> NORMAL");
2350 if (runlevel != newlevel)
2351 loglevel = newlevel;
2352 runlevel = newlevel;
2353 did_boot = 1;
2354 warn = 1;
2355 break;
2356 case 'S': /* Ended SU mode */
2357 case 's':
2358 INITDBG(L_VB, "END SU MODE");
2359 newlevel = get_init_default();
2360 if (!did_boot && newlevel != 'S')
2361 runlevel = '*';
2362 else {
2363 if (runlevel != newlevel)
2364 loglevel = newlevel;
2365 runlevel = newlevel;
2366 oldlevel = 'S';
2367 }
2368 warn = 1;
2369 for(ch = family; ch; ch = ch->next)
2370 if (strcmp(ch->rlevel, "S") == 0)
2371 ch->flags &= ~(FAILING|WAITING|XECUTED);
2372 break;
2373 default:
2374 if (warn)
2375 initlog(L_VB,
2376 "no more processes left in this runlevel");
2377 warn = 0;
2378 loglevel = -1;
2379 if (got_signals == 0)
2380 check_init_fifo();
2381 break;
2382 }
2383 if (loglevel > 0) {
2384 initlog(L_VB, "Entering runlevel: %c", runlevel);
63a2c981
DWF
2385 wrote_utmp_rlevel = 0;
2386 wrote_wtmp_rlevel = 0;
a74aeac6
PR
2387 write_utmp_wtmp("runlevel", "~~", runlevel + 256 * oldlevel, RUN_LVL, "~");
2388 thislevel = runlevel;
2389 prevlevel = oldlevel;
5f959b29 2390 setproctitle("init [%c]", (int)runlevel);
a74aeac6
PR
2391 }
2392 }
2393}
2394
2395/*
2396 * Init got hit by a signal. See which signal it is,
2397 * and act accordingly.
2398 */
5f959b29 2399static
a74aeac6
PR
2400void process_signals()
2401{
2402 CHILD *ch;
2403 int pwrstat;
2404 int oldlevel;
2405 int fd;
2406 char c;
2407
2408 if (ISMEMBER(got_signals, SIGPWR)) {
2409 INITDBG(L_VB, "got SIGPWR");
2410 /* See _what_ kind of SIGPWR this is. */
2411 pwrstat = 0;
2412 if ((fd = open(PWRSTAT, O_RDONLY)) >= 0) {
2413 c = 0;
2414 read(fd, &c, 1);
2415 pwrstat = c;
2416 close(fd);
2417 unlink(PWRSTAT);
364b4b0b
PR
2418 } else if ((fd = open(PWRSTAT_OLD, O_RDONLY)) >= 0) {
2419 /* Path changed 2010-03-20. Look for the old path for a while. */
2420 initlog(L_VB, "warning: found obsolete path %s, use %s instead",
2421 PWRSTAT_OLD, PWRSTAT);
2422 c = 0;
2423 read(fd, &c, 1);
2424 pwrstat = c;
2425 close(fd);
2426 unlink(PWRSTAT_OLD);
2427 }
a74aeac6
PR
2428 do_power_fail(pwrstat);
2429 DELSET(got_signals, SIGPWR);
2430 }
2431
2432 if (ISMEMBER(got_signals, SIGINT)) {
5f959b29
DWF
2433#if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2434 /* Ignore any further signal from keyboard */
2435 struct sigaction sa;
2436 SETSIG(sa, SIGINT, SIG_IGN, SA_RESTART);
2437#endif
a74aeac6
PR
2438 INITDBG(L_VB, "got SIGINT");
2439 /* Tell ctrlaltdel entry to start up */
2440 for(ch = family; ch; ch = ch->next)
2441 if (ch->action == CTRLALTDEL)
2442 ch->flags &= ~XECUTED;
2443 DELSET(got_signals, SIGINT);
2444 }
2445
2446 if (ISMEMBER(got_signals, SIGWINCH)) {
2447 INITDBG(L_VB, "got SIGWINCH");
2448 /* Tell kbrequest entry to start up */
2449 for(ch = family; ch; ch = ch->next)
2450 if (ch->action == KBREQUEST)
2451 ch->flags &= ~XECUTED;
2452 DELSET(got_signals, SIGWINCH);
2453 }
2454
2455 if (ISMEMBER(got_signals, SIGALRM)) {
2456 INITDBG(L_VB, "got SIGALRM");
2457 /* The timer went off: check it out */
2458 DELSET(got_signals, SIGALRM);
2459 }
2460
2461 if (ISMEMBER(got_signals, SIGCHLD)) {
2462 INITDBG(L_VB, "got SIGCHLD");
2463 /* First set flag to 0 */
2464 DELSET(got_signals, SIGCHLD);
2465
2466 /* See which child this was */
2467 for(ch = family; ch; ch = ch->next)
2468 if (ch->flags & ZOMBIE) {
2469 INITDBG(L_VB, "Child died, PID= %d", ch->pid);
2470 ch->flags &= ~(RUNNING|ZOMBIE|WAITING);
2471 if (ch->process[0] != '+')
2472 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
2473 }
2474
2475 }
2476
2477 if (ISMEMBER(got_signals, SIGHUP)) {
2478 INITDBG(L_VB, "got SIGHUP");
2479#if CHANGE_WAIT
2480 /* Are we waiting for a child? */
2481 for(ch = family; ch; ch = ch->next)
2482 if (ch->flags & WAITING) break;
2483 if (ch == NULL)
2484#endif
2485 {
2486 /* We need to go into a new runlevel */
2487 oldlevel = runlevel;
2488#ifdef INITLVL
2489 runlevel = read_level(0);
2490#endif
2491 if (runlevel == 'U') {
2492 runlevel = oldlevel;
2493 re_exec();
2494 } else {
2495 if (oldlevel != 'S' && runlevel == 'S') console_stty();
2496 if (runlevel == '6' || runlevel == '0' ||
2497 runlevel == '1') console_stty();
2498 read_inittab();
2499 fail_cancel();
5f959b29 2500 setproctitle("init [%c]", (int)runlevel);
a74aeac6
PR
2501 DELSET(got_signals, SIGHUP);
2502 }
2503 }
2504 }
2505 if (ISMEMBER(got_signals, SIGUSR1)) {
2506 /*
2507 * SIGUSR1 means close and reopen /dev/initctl
2508 */
2509 INITDBG(L_VB, "got SIGUSR1");
2510 close(pipe_fd);
2511 pipe_fd = -1;
2512 DELSET(got_signals, SIGUSR1);
2513 }
2514}
2515
2516/*
2517 * The main loop
2518 */
5f959b29
DWF
2519static
2520void init_main(void)
a74aeac6
PR
2521{
2522 CHILD *ch;
2523 struct sigaction sa;
2524 sigset_t sgt;
a74aeac6
PR
2525 int f, st;
2526
2527 if (!reload) {
2528
2529#if INITDEBUG
2530 /*
2531 * Fork so we can debug the init process.
2532 */
2533 if ((f = fork()) > 0) {
2534 static const char killmsg[] = "PRNT: init killed.\r\n";
2535 pid_t rc;
2536
2537 while((rc = wait(&st)) != f)
2538 if (rc < 0 && errno == ECHILD)
2539 break;
2540 write(1, killmsg, sizeof(killmsg) - 1);
2541 while(1) pause();
2542 }
2543#endif
2544
2545#ifdef __linux__
2546 /*
2547 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2548 * is pressed, and that we want to handle keyboard signals.
2549 */
2550 init_reboot(BMAGIC_SOFT);
2551 if ((f = open(VT_MASTER, O_RDWR | O_NOCTTY)) >= 0) {
2552 (void) ioctl(f, KDSIGACCEPT, SIGWINCH);
2553 close(f);
2554 } else
2555 (void) ioctl(0, KDSIGACCEPT, SIGWINCH);
2556#endif
2557
2558 /*
2559 * Ignore all signals.
2560 */
2561 for(f = 1; f <= NSIG; f++)
2562 SETSIG(sa, f, SIG_IGN, SA_RESTART);
2563 }
2564
2565 SETSIG(sa, SIGALRM, signal_handler, 0);
2566 SETSIG(sa, SIGHUP, signal_handler, 0);
2567 SETSIG(sa, SIGINT, signal_handler, 0);
2568 SETSIG(sa, SIGCHLD, chld_handler, SA_RESTART);
2569 SETSIG(sa, SIGPWR, signal_handler, 0);
2570 SETSIG(sa, SIGWINCH, signal_handler, 0);
2571 SETSIG(sa, SIGUSR1, signal_handler, 0);
2572 SETSIG(sa, SIGSTOP, stop_handler, SA_RESTART);
2573 SETSIG(sa, SIGTSTP, stop_handler, SA_RESTART);
2574 SETSIG(sa, SIGCONT, cont_handler, SA_RESTART);
2575 SETSIG(sa, SIGSEGV, (void (*)(int))segv_handler, SA_RESTART);
2576
2577 console_init();
2578
2579 if (!reload) {
63a2c981 2580 int fd;
a74aeac6
PR
2581
2582 /* Close whatever files are open, and reset the console. */
2583 close(0);
2584 close(1);
2585 close(2);
2586 console_stty();
2587 setsid();
2588
2589 /*
2590 * Set default PATH variable.
2591 */
2592 setenv("PATH", PATH_DEFAULT, 1 /* Overwrite */);
2593
2594 /*
2595 * Initialize /var/run/utmp (only works if /var is on
2596 * root and mounted rw)
2597 */
63a2c981
DWF
2598 if ((fd = open(UTMP_FILE, O_WRONLY|O_CREAT|O_TRUNC, 0644)) >= 0)
2599 close(fd);
a74aeac6
PR
2600
2601 /*
2602 * Say hello to the world
2603 */
2604 initlog(L_CO, bootmsg, "booting");
2605
2606 /*
2607 * See if we have to start an emergency shell.
2608 */
2609 if (emerg_shell) {
23d97522 2610 pid_t rc;
a74aeac6
PR
2611 SETSIG(sa, SIGCHLD, SIG_DFL, SA_RESTART);
2612 if (spawn(&ch_emerg, &f) > 0) {
2613 while((rc = wait(&st)) != f)
2614 if (rc < 0 && errno == ECHILD)
2615 break;
2616 }
2617 SETSIG(sa, SIGCHLD, chld_handler, SA_RESTART);
2618 }
2619
2620 /*
2621 * Start normal boot procedure.
2622 */
2623 runlevel = '#';
2624 read_inittab();
2625
2626 } else {
2627 /*
2628 * Restart: unblock signals and let the show go on
2629 */
2630 initlog(L_CO, bootmsg, "reloading");
2631 sigfillset(&sgt);
2632 sigprocmask(SIG_UNBLOCK, &sgt, NULL);
2633
2634 /*
2635 * Set default PATH variable.
2636 */
2637 setenv("PATH", PATH_DEFAULT, 0 /* Don't overwrite */);
2638 }
2639 start_if_needed();
2640
2641 while(1) {
2642
2643 /* See if we need to make the boot transitions. */
2644 boot_transitions();
2645 INITDBG(L_VB, "init_main: waiting..");
2646
2647 /* Check if there are processes to be waited on. */
2648 for(ch = family; ch; ch = ch->next)
2649 if ((ch->flags & RUNNING) && ch->action != BOOT) break;
2650
2651#if CHANGE_WAIT
2652 /* Wait until we get hit by some signal. */
2653 while (ch != NULL && got_signals == 0) {
2654 if (ISMEMBER(got_signals, SIGHUP)) {
2655 /* See if there are processes to be waited on. */
2656 for(ch = family; ch; ch = ch->next)
2657 if (ch->flags & WAITING) break;
2658 }
2659 if (ch != NULL) check_init_fifo();
2660 }
2661#else /* CHANGE_WAIT */
2662 if (ch != NULL && got_signals == 0) check_init_fifo();
2663#endif /* CHANGE_WAIT */
2664
2665 /* Check the 'failing' flags */
2666 fail_check();
2667
2668 /* Process any signals. */
2669 process_signals();
2670
2671 /* See what we need to start up (again) */
2672 start_if_needed();
2673 }
2674 /*NOTREACHED*/
2675}
2676
2677/*
2678 * Tell the user about the syntax we expect.
2679 */
5f959b29 2680static
a74aeac6
PR
2681void usage(char *s)
2682{
2683 fprintf(stderr, "Usage: %s {-e VAR[=VAL] | [-t SECONDS] {0|1|2|3|4|5|6|S|s|Q|q|A|a|B|b|C|c|U|u}}\n", s);
2684 exit(1);
2685}
2686
5f959b29 2687static
a74aeac6
PR
2688int telinit(char *progname, int argc, char **argv)
2689{
2690#ifdef TELINIT_USES_INITLVL
2691 FILE *fp;
2692#endif
2693 struct init_request request;
2694 struct sigaction sa;
2695 int f, fd, l;
2696 char *env = NULL;
2697
2698 memset(&request, 0, sizeof(request));
2699 request.magic = INIT_MAGIC;
2700
2701 while ((f = getopt(argc, argv, "t:e:")) != EOF) switch(f) {
2702 case 't':
2703 sltime = atoi(optarg);
2704 break;
2705 case 'e':
2706 if (env == NULL)
2707 env = request.i.data;
2708 l = strlen(optarg);
2709 if (env + l + 2 > request.i.data + sizeof(request.i.data)) {
2710 fprintf(stderr, "%s: -e option data "
2711 "too large\n", progname);
2712 exit(1);
2713 }
2714 memcpy(env, optarg, l);
2715 env += l;
2716 *env++ = 0;
2717 break;
2718 default:
2719 usage(progname);
2720 break;
2721 }
2722
2723 if (env) *env++ = 0;
2724
2725 if (env) {
2726 if (argc != optind)
2727 usage(progname);
2728 request.cmd = INIT_CMD_SETENV;
2729 } else {
2730 if (argc - optind != 1 || strlen(argv[optind]) != 1)
2731 usage(progname);
2732 if (!strchr("0123456789SsQqAaBbCcUu", argv[optind][0]))
2733 usage(progname);
2734 request.cmd = INIT_CMD_RUNLVL;
2735 request.runlevel = env ? 0 : argv[optind][0];
2736 request.sleeptime = sltime;
2737 }
2738
5f959b29
DWF
2739 /* Change to the root directory. */
2740 chdir("/");
2741
a74aeac6
PR
2742 /* Open the fifo and write a command. */
2743 /* Make sure we don't hang on opening /dev/initctl */
2744 SETSIG(sa, SIGALRM, signal_handler, 0);
2745 alarm(3);
5f959b29
DWF
2746 if ((fd = open(INIT_FIFO, O_WRONLY)) >= 0) {
2747 ssize_t p = 0;
2748 size_t s = sizeof(request);
2749 void *ptr = &request;
2750
2751 while (s > 0) {
2752 p = write(fd, ptr, s);
2753 if (p < 0) {
2754 if (errno == EINTR || errno == EAGAIN)
2755 continue;
2756 break;
2757 }
2758 ptr += p;
2759 s -= p;
2760 }
a74aeac6
PR
2761 close(fd);
2762 alarm(0);
2763 return 0;
2764 }
2765
2766#ifdef TELINIT_USES_INITLVL
2767 if (request.cmd == INIT_CMD_RUNLVL) {
2768 /* Fallthrough to the old method. */
2769
2770 /* Now write the new runlevel. */
2771 if ((fp = fopen(INITLVL, "w")) == NULL) {
2772 fprintf(stderr, "%s: cannot create %s\n",
2773 progname, INITLVL);
2774 exit(1);
2775 }
2776 fprintf(fp, "%s %d", argv[optind], sltime);
2777 fclose(fp);
2778
2779 /* And tell init about the pending runlevel change. */
2780 if (kill(INITPID, SIGHUP) < 0) perror(progname);
2781
2782 return 0;
2783 }
2784#endif
2785
2786 fprintf(stderr, "%s: ", progname);
2787 if (ISMEMBER(got_signals, SIGALRM)) {
2788 fprintf(stderr, "timeout opening/writing control channel %s\n",
2789 INIT_FIFO);
2790 } else {
2791 perror(INIT_FIFO);
2792 }
2793 return 1;
2794}
2795
2796/*
2797 * Main entry for init and telinit.
2798 */
2799int main(int argc, char **argv)
2800{
2801 char *p;
2802 int f;
2803 int isinit;
e481cba6 2804#ifdef WITH_SELINUX
a74aeac6 2805 int enforce = 0;
e481cba6 2806#endif
a74aeac6
PR
2807
2808 /* Get my own name */
2809 if ((p = strrchr(argv[0], '/')) != NULL)
2810 p++;
2811 else
2812 p = argv[0];
5f959b29
DWF
2813
2814 /* Common umask */
a74aeac6
PR
2815 umask(022);
2816
2817 /* Quick check */
2818 if (geteuid() != 0) {
2819 fprintf(stderr, "%s: must be superuser.\n", p);
2820 exit(1);
2821 }
2822
2823 /*
2824 * Is this telinit or init ?
2825 */
2826 isinit = (getpid() == 1);
2827 for (f = 1; f < argc; f++) {
54cb4b75 2828 if (!strcmp(argv[f], "-i") || !strcmp(argv[f], "--init")) {
a74aeac6
PR
2829 isinit = 1;
2830 break;
54cb4b75 2831 }
a74aeac6
PR
2832 }
2833 if (!isinit) exit(telinit(p, argc, argv));
2834
2835 /*
2836 * Check for re-exec
2837 */
2838 if (check_pipe(STATE_PIPE)) {
2839
2840 receive_state(STATE_PIPE);
2841
2842 myname = istrdup(argv[0]);
2843 argv0 = argv[0];
2844 maxproclen = 0;
2845 for (f = 0; f < argc; f++)
2846 maxproclen += strlen(argv[f]) + 1;
2847 reload = 1;
5f959b29 2848 setproctitle("init [%c]", (int)runlevel);
a74aeac6
PR
2849
2850 init_main();
2851 }
2852
2853 /* Check command line arguments */
2854 maxproclen = strlen(argv[0]) + 1;
2855 for(f = 1; f < argc; f++) {
2856 if (!strcmp(argv[f], "single") || !strcmp(argv[f], "-s"))
2857 dfl_level = 'S';
2858 else if (!strcmp(argv[f], "-a") || !strcmp(argv[f], "auto"))
2859 putenv("AUTOBOOT=YES");
2860 else if (!strcmp(argv[f], "-b") || !strcmp(argv[f],"emergency"))
2861 emerg_shell = 1;
2862 else if (!strcmp(argv[f], "-z")) {
2863 /* Ignore -z xxx */
2864 if (argv[f + 1]) f++;
2865 } else if (strchr("0123456789sS", argv[f][0])
2866 && strlen(argv[f]) == 1)
2867 dfl_level = argv[f][0];
2868 /* "init u" in the very beginning makes no sense */
2869 if (dfl_level == 's') dfl_level = 'S';
2870 maxproclen += strlen(argv[f]) + 1;
2871 }
2872
2873#ifdef WITH_SELINUX
9af2d863
DWF
2874 if (getenv("SELINUX_INIT") == NULL) {
2875 const int rc = mount("proc", "/proc", "proc", 0, 0);
2876 if (is_selinux_enabled() > 0) {
2877 putenv("SELINUX_INIT=YES");
2878 if (rc == 0) umount2("/proc", MNT_DETACH);
2879 if (selinux_init_load_policy(&enforce) == 0) {
2880 execv(myname, argv);
2881 } else {
2882 if (enforce > 0) {
2883 /* SELinux in enforcing mode but load_policy failed */
2884 /* At this point, we probably can't open /dev/console, so log() won't work */
2885 fprintf(stderr,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2886 exit(1);
2887 }
a74aeac6
PR
2888 }
2889 }
9af2d863 2890 if (rc == 0) umount2("/proc", MNT_DETACH);
a74aeac6
PR
2891 }
2892#endif
2893 /* Start booting. */
2894 argv0 = argv[0];
2895 argv[1] = NULL;
2896 setproctitle("init boot");
5f959b29 2897 init_main();
a74aeac6
PR
2898
2899 /*NOTREACHED*/
2900 return 0;
2901}