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