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