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