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