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