Use narrowly scoped file descriptor for handling opened TTY in
[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 dup(ftty);
1115 dup(ftty);
1116 }
1117
1118 /*
1119 * 4 Sep 2001, Andrea Arcangeli:
1120 * Fix a race in spawn() that is used to deadlock init in a
1121 * waitpid() loop: must set the childhandler as default before forking
1122 * off the child or the chld_handler could run before the waitpid loop
1123 * has a chance to find its zombie-child.
1124 */
1125 SETSIG(sa, SIGCHLD, SIG_DFL, SA_RESTART);
1126 if ((pid = fork()) < 0) {
1127 initlog(L_VB, "cannot fork: %s",
1128 strerror(errno));
1129 exit(1);
1130 }
1131 if (pid > 0) {
1132 pid_t rc;
1133 /*
1134 * Ignore keyboard signals etc.
1135 * Then wait for child to exit.
1136 */
1137 SETSIG(sa, SIGINT, SIG_IGN, SA_RESTART);
1138 SETSIG(sa, SIGTSTP, SIG_IGN, SA_RESTART);
1139 SETSIG(sa, SIGQUIT, SIG_IGN, SA_RESTART);
1140
1141 while ((rc = waitpid(pid, &st, 0)) != pid)
1142 if (rc < 0 && errno == ECHILD)
1143 break;
1144
1145 /*
1146 * Small optimization. See if stealing
1147 * controlling tty back is needed.
1148 */
1149 pgrp = tcgetpgrp(ftty);
1150 if (pgrp != getpid())
1151 exit(0);
1152
1153 /*
1154 * Steal controlling tty away. We do
1155 * this with a temporary process.
1156 */
1157 if ((pid = fork()) < 0) {
1158 initlog(L_VB, "cannot fork: %s",
1159 strerror(errno));
1160 exit(1);
1161 }
1162 if (pid == 0) {
1163 setsid();
1164 (void)ioctl(ftty, TIOCSCTTY, 1);
1165 exit(0);
1166 }
1167 while((rc = waitpid(pid, &st, 0)) != pid)
1168 if (rc < 0 && errno == ECHILD)
1169 break;
1170 exit(0);
1171 }
1172
1173 /* Set ioctl settings to default ones */
1174 console_stty();
1175
1176 } else { /* parent */
1177 int fd;
1178 setsid();
1179 if ((fd = console_open(O_RDWR|O_NOCTTY)) < 0) {
1180 initlog(L_VB, "open(%s): %s", console_dev,
1181 strerror(errno));
1182 fd = open("/dev/null", O_RDWR);
1183 }
1184 dup(fd);
1185 dup(fd);
1186 }
1187
1188 /*
1189 * Update utmp/wtmp file prior to starting
1190 * any child. This MUST be done right here in
1191 * the child process in order to prevent a race
1192 * condition that occurs when the child
1193 * process' time slice executes before the
1194 * parent (can and does happen in a uniprocessor
1195 * environment). If the child is a getty and
1196 * the race condition happens, then init's utmp
1197 * update will happen AFTER the getty runs
1198 * and expects utmp to be updated already!
1199 *
1200 * Do NOT log if process field starts with '+'
1201 * FIXME: that's for compatibility with *very*
1202 * old getties - probably it can be taken out.
1203 */
1204 if (ch->process[0] != '+')
1205 write_utmp_wtmp("", ch->id, getpid(), INIT_PROCESS, "");
1206
1207 /* Reset all the signals, set up environment */
1208 for(f = 1; f < NSIG; f++) SETSIG(sa, f, SIG_DFL, SA_RESTART);
1209 environ = init_buildenv(1);
1210
1211 /*
1212 * Execute prog. In case of ENOEXEC try again
1213 * as a shell script.
1214 */
1215 execvp(args[1], args + 1);
1216 if (errno == ENOEXEC) {
1217 args[1] = SHELL;
1218 args[2] = "-c";
1219 strcpy(buf, "exec ");
1220 strncat(buf, proc, sizeof(buf) - strlen(buf) - 1);
1221 args[3] = buf;
1222 args[4] = NULL;
1223 execvp(args[1], args + 1);
1224 }
1225 initlog(L_VB, "cannot execute \"%s\"", args[1]);
1226
1227 if (ch->process[0] != '+')
1228 write_utmp_wtmp("", ch->id, getpid(), DEAD_PROCESS, NULL);
1229 exit(1);
1230 }
1231 *res = pid;
1232 sigprocmask(SIG_SETMASK, &omask, NULL);
1233
1234 INITDBG(L_VB, "Started id %s (pid %d)", ch->id, pid);
1235
1236 if (pid == -1) {
1237 initlog(L_VB, "cannot fork, retry..");
1238 do_sleep(5);
1239 continue;
1240 }
1241 return(pid);
1242 }
1243 }
1244
1245 /*
1246 * Start a child running!
1247 */
1248 static
1249 void startup(CHILD *ch)
1250 {
1251 /*
1252 * See if it's disabled
1253 */
1254 if (ch->flags & FAILING) return;
1255
1256 switch(ch->action) {
1257
1258 case SYSINIT:
1259 case BOOTWAIT:
1260 case WAIT:
1261 case POWERWAIT:
1262 case POWERFAILNOW:
1263 case POWEROKWAIT:
1264 case CTRLALTDEL:
1265 if (!(ch->flags & XECUTED)) ch->flags |= WAITING;
1266 /* Fall through */
1267 case KBREQUEST:
1268 case BOOT:
1269 case POWERFAIL:
1270 case ONCE:
1271 if (ch->flags & XECUTED) break;
1272 case ONDEMAND:
1273 case RESPAWN:
1274 ch->flags |= RUNNING;
1275 (void)spawn(ch, &(ch->pid));
1276 break;
1277 }
1278 }
1279
1280
1281 /*
1282 * Read the inittab file.
1283 */
1284 static
1285 void read_inittab(void)
1286 {
1287 FILE *fp; /* The INITTAB file */
1288 CHILD *ch, *old, *i; /* Pointers to CHILD structure */
1289 CHILD *head = NULL; /* Head of linked list */
1290 #ifdef INITLVL
1291 struct stat st; /* To stat INITLVL */
1292 #endif
1293 sigset_t nmask, omask; /* For blocking SIGCHLD. */
1294 char buf[256]; /* Line buffer */
1295 char err[64]; /* Error message. */
1296 char *id, *rlevel,
1297 *action, *process; /* Fields of a line */
1298 char *p;
1299 int lineNo = 0; /* Line number in INITTAB file */
1300 int actionNo; /* Decoded action field */
1301 int f; /* Counter */
1302 int round; /* round 0 for SIGTERM, 1 for SIGKILL */
1303 int foundOne = 0; /* No killing no sleep */
1304 int talk; /* Talk to the user */
1305 int done = 0; /* Ready yet? */
1306
1307 #if DEBUG
1308 if (newFamily != NULL) {
1309 INITDBG(L_VB, "PANIC newFamily != NULL");
1310 exit(1);
1311 }
1312 INITDBG(L_VB, "Reading inittab");
1313 #endif
1314
1315 /*
1316 * Open INITTAB and read line by line.
1317 */
1318 if ((fp = fopen(INITTAB, "r")) == NULL)
1319 initlog(L_VB, "No inittab file found");
1320
1321 while(!done) {
1322 /*
1323 * Add single user shell entry at the end.
1324 */
1325 if (fp == NULL || fgets(buf, sizeof(buf), fp) == NULL) {
1326 done = 1;
1327 /*
1328 * See if we have a single user entry.
1329 */
1330 for(old = newFamily; old; old = old->next)
1331 if (strpbrk(old->rlevel, "S")) break;
1332 if (old == NULL)
1333 snprintf(buf, sizeof(buf), "~~:S:wait:%s\n", SULOGIN);
1334 else
1335 continue;
1336 }
1337 lineNo++;
1338 /*
1339 * Skip comments and empty lines
1340 */
1341 for(p = buf; *p == ' ' || *p == '\t'; p++)
1342 ;
1343 if (*p == '#' || *p == '\n') continue;
1344
1345 /*
1346 * Decode the fields
1347 */
1348 id = strsep(&p, ":");
1349 rlevel = strsep(&p, ":");
1350 action = strsep(&p, ":");
1351 process = strsep(&p, "\n");
1352
1353 /*
1354 * Check if syntax is OK. Be very verbose here, to
1355 * avoid newbie postings on comp.os.linux.setup :)
1356 */
1357 err[0] = 0;
1358 if (!id || !*id) strcpy(err, "missing id field");
1359 if (!rlevel) strcpy(err, "missing runlevel field");
1360 if (!process) strcpy(err, "missing process field");
1361 if (!action || !*action)
1362 strcpy(err, "missing action field");
1363 if (id && strlen(id) > sizeof(utproto.ut_id))
1364 sprintf(err, "id field too long (max %d characters)",
1365 (int)sizeof(utproto.ut_id));
1366 if (rlevel && strlen(rlevel) > 11)
1367 strcpy(err, "rlevel field too long (max 11 characters)");
1368 if (process && strlen(process) > 127)
1369 strcpy(err, "process field too long (max 127 characters)");
1370 if (action && strlen(action) > 32)
1371 strcpy(err, "action field too long");
1372 if (err[0] != 0) {
1373 initlog(L_VB, "%s[%d]: %s", INITTAB, lineNo, err);
1374 INITDBG(L_VB, "%s:%s:%s:%s", id, rlevel, action, process);
1375 continue;
1376 }
1377
1378 /*
1379 * Decode the "action" field
1380 */
1381 actionNo = -1;
1382 for(f = 0; actions[f].name; f++)
1383 if (strcasecmp(action, actions[f].name) == 0) {
1384 actionNo = actions[f].act;
1385 break;
1386 }
1387 if (actionNo == -1) {
1388 initlog(L_VB, "%s[%d]: %s: unknown action field",
1389 INITTAB, lineNo, action);
1390 continue;
1391 }
1392
1393 /*
1394 * See if the id field is unique
1395 */
1396 for(old = newFamily; old; old = old->next) {
1397 if(strcmp(old->id, id) == 0 && strcmp(id, "~~")) {
1398 initlog(L_VB, "%s[%d]: duplicate ID field \"%s\"",
1399 INITTAB, lineNo, id);
1400 break;
1401 }
1402 }
1403 if (old) continue;
1404
1405 /*
1406 * Allocate a CHILD structure
1407 */
1408 ch = imalloc(sizeof(CHILD));
1409
1410 /*
1411 * And fill it in.
1412 */
1413 ch->action = actionNo;
1414 strncpy(ch->id, id, sizeof(utproto.ut_id) + 1); /* Hack for different libs. */
1415 strncpy(ch->process, process, sizeof(ch->process) - 1);
1416 if (rlevel[0]) {
1417 for(f = 0; f < (int)sizeof(rlevel) - 1 && rlevel[f]; f++) {
1418 ch->rlevel[f] = rlevel[f];
1419 if (ch->rlevel[f] == 's') ch->rlevel[f] = 'S';
1420 }
1421 strncpy(ch->rlevel, rlevel, sizeof(ch->rlevel) - 1);
1422 } else {
1423 strcpy(ch->rlevel, "0123456789");
1424 if (ISPOWER(ch->action))
1425 strcpy(ch->rlevel, "S0123456789");
1426 }
1427 /*
1428 * We have the fake runlevel '#' for SYSINIT and
1429 * '*' for BOOT and BOOTWAIT.
1430 */
1431 if (ch->action == SYSINIT) strcpy(ch->rlevel, "#");
1432 if (ch->action == BOOT || ch->action == BOOTWAIT)
1433 strcpy(ch->rlevel, "*");
1434
1435 /*
1436 * Now add it to the linked list. Special for powerfail.
1437 */
1438 if (ISPOWER(ch->action)) {
1439
1440 /*
1441 * Disable by default
1442 */
1443 ch->flags |= XECUTED;
1444
1445 /*
1446 * Tricky: insert at the front of the list..
1447 */
1448 old = NULL;
1449 for(i = newFamily; i; i = i->next) {
1450 if (!ISPOWER(i->action)) break;
1451 old = i;
1452 }
1453 /*
1454 * Now add after entry "old"
1455 */
1456 if (old) {
1457 ch->next = i;
1458 old->next = ch;
1459 if (i == NULL) head = ch;
1460 } else {
1461 ch->next = newFamily;
1462 newFamily = ch;
1463 if (ch->next == NULL) head = ch;
1464 }
1465 } else {
1466 /*
1467 * Just add at end of the list
1468 */
1469 if (ch->action == KBREQUEST) ch->flags |= XECUTED;
1470 ch->next = NULL;
1471 if (head)
1472 head->next = ch;
1473 else
1474 newFamily = ch;
1475 head = ch;
1476 }
1477
1478 /*
1479 * Walk through the old list comparing id fields
1480 */
1481 for(old = family; old; old = old->next)
1482 if (strcmp(old->id, ch->id) == 0) {
1483 old->new = ch;
1484 break;
1485 }
1486 }
1487 /*
1488 * We're done.
1489 */
1490 if (fp) fclose(fp);
1491
1492 /*
1493 * Loop through the list of children, and see if they need to
1494 * be killed.
1495 */
1496
1497 INITDBG(L_VB, "Checking for children to kill");
1498 for(round = 0; round < 2; round++) {
1499 talk = 1;
1500 for(ch = family; ch; ch = ch->next) {
1501 ch->flags &= ~KILLME;
1502
1503 /*
1504 * Is this line deleted?
1505 */
1506 if (ch->new == NULL) ch->flags |= KILLME;
1507
1508 /*
1509 * If the entry has changed, kill it anyway. Note that
1510 * we do not check ch->process, only the "action" field.
1511 * This way, you can turn an entry "off" immediately, but
1512 * changes in the command line will only become effective
1513 * after the running version has exited.
1514 */
1515 if (ch->new && ch->action != ch->new->action) ch->flags |= KILLME;
1516
1517 /*
1518 * Only BOOT processes may live in all levels
1519 */
1520 if (ch->action != BOOT &&
1521 strchr(ch->rlevel, runlevel) == NULL) {
1522 /*
1523 * Ondemand procedures live always,
1524 * except in single user
1525 */
1526 if (runlevel == 'S' || !(ch->flags & DEMAND))
1527 ch->flags |= KILLME;
1528 }
1529
1530 /*
1531 * Now, if this process may live note so in the new list
1532 */
1533 if ((ch->flags & KILLME) == 0) {
1534 ch->new->flags = ch->flags;
1535 ch->new->pid = ch->pid;
1536 ch->new->exstat = ch->exstat;
1537 continue;
1538 }
1539
1540
1541 /*
1542 * Is this process still around?
1543 */
1544 if ((ch->flags & RUNNING) == 0) {
1545 ch->flags &= ~KILLME;
1546 continue;
1547 }
1548 INITDBG(L_VB, "Killing \"%s\"", ch->process);
1549 switch(round) {
1550 case 0: /* Send TERM signal */
1551 if (talk)
1552 initlog(L_CO,
1553 "Sending processes configured via /etc/inittab the TERM signal");
1554 kill(-(ch->pid), SIGTERM);
1555 foundOne = 1;
1556 break;
1557 case 1: /* Send KILL signal and collect status */
1558 if (talk)
1559 initlog(L_CO,
1560 "Sending processes configured via /etc/inittab the KILL signal");
1561 kill(-(ch->pid), SIGKILL);
1562 break;
1563 }
1564 talk = 0;
1565
1566 }
1567 /*
1568 * See if we have to wait 5 seconds
1569 */
1570 if (foundOne && round == 0) {
1571 /*
1572 * Yup, but check every second if we still have children.
1573 */
1574 for(f = 0; f < sltime; f++) {
1575 for(ch = family; ch; ch = ch->next) {
1576 if (!(ch->flags & KILLME)) continue;
1577 if ((ch->flags & RUNNING) && !(ch->flags & ZOMBIE))
1578 break;
1579 }
1580 if (ch == NULL) {
1581 /*
1582 * No running children, skip SIGKILL
1583 */
1584 round = 1;
1585 foundOne = 0; /* Skip the sleep below. */
1586 break;
1587 }
1588 do_sleep(1);
1589 }
1590 }
1591 }
1592
1593 /*
1594 * Now give all processes the chance to die and collect exit statuses.
1595 */
1596 if (foundOne) do_sleep(1);
1597 for(ch = family; ch; ch = ch->next)
1598 if (ch->flags & KILLME) {
1599 if (!(ch->flags & ZOMBIE))
1600 initlog(L_CO, "Pid %d [id %s] seems to hang", ch->pid,
1601 ch->id);
1602 else {
1603 INITDBG(L_VB, "Updating utmp for pid %d [id %s]",
1604 ch->pid, ch->id);
1605 ch->flags &= ~RUNNING;
1606 if (ch->process[0] != '+')
1607 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
1608 }
1609 }
1610
1611 /*
1612 * Both rounds done; clean up the list.
1613 */
1614 sigemptyset(&nmask);
1615 sigaddset(&nmask, SIGCHLD);
1616 sigprocmask(SIG_BLOCK, &nmask, &omask);
1617 for(ch = family; ch; ch = old) {
1618 old = ch->next;
1619 free(ch);
1620 }
1621 family = newFamily;
1622 for(ch = family; ch; ch = ch->next) ch->new = NULL;
1623 newFamily = NULL;
1624 sigprocmask(SIG_SETMASK, &omask, NULL);
1625
1626 #ifdef INITLVL
1627 /*
1628 * Dispose of INITLVL file.
1629 */
1630 if (lstat(INITLVL, &st) >= 0 && S_ISLNK(st.st_mode)) {
1631 /*
1632 * INITLVL is a symbolic link, so just truncate the file.
1633 */
1634 close(open(INITLVL, O_WRONLY|O_TRUNC));
1635 } else {
1636 /*
1637 * Delete INITLVL file.
1638 */
1639 unlink(INITLVL);
1640 }
1641 #endif
1642 #ifdef INITLVL2
1643 /*
1644 * Dispose of INITLVL2 file.
1645 */
1646 if (lstat(INITLVL2, &st) >= 0 && S_ISLNK(st.st_mode)) {
1647 /*
1648 * INITLVL2 is a symbolic link, so just truncate the file.
1649 */
1650 close(open(INITLVL2, O_WRONLY|O_TRUNC));
1651 } else {
1652 /*
1653 * Delete INITLVL2 file.
1654 */
1655 unlink(INITLVL2);
1656 }
1657 #endif
1658 }
1659
1660 /*
1661 * Walk through the family list and start up children.
1662 * The entries that do not belong here at all are removed
1663 * from the list.
1664 */
1665 static
1666 void start_if_needed(void)
1667 {
1668 CHILD *ch; /* Pointer to child */
1669 int delete; /* Delete this entry from list? */
1670
1671 INITDBG(L_VB, "Checking for children to start");
1672
1673 for(ch = family; ch; ch = ch->next) {
1674
1675 #if DEBUG
1676 if (ch->rlevel[0] == 'C') {
1677 INITDBG(L_VB, "%s: flags %d", ch->process, ch->flags);
1678 }
1679 #endif
1680
1681 /* Are we waiting for this process? Then quit here. */
1682 if (ch->flags & WAITING) break;
1683
1684 /* Already running? OK, don't touch it */
1685 if (ch->flags & RUNNING) continue;
1686
1687 /* See if we have to start it up */
1688 delete = 1;
1689 if (strchr(ch->rlevel, runlevel) ||
1690 ((ch->flags & DEMAND) && !strchr("#*Ss", runlevel))) {
1691 startup(ch);
1692 delete = 0;
1693 }
1694
1695 if (delete) {
1696 /* FIXME: is this OK? */
1697 ch->flags &= ~(RUNNING|WAITING);
1698 if (!ISPOWER(ch->action) && ch->action != KBREQUEST)
1699 ch->flags &= ~XECUTED;
1700 ch->pid = 0;
1701 } else
1702 /* Do we have to wait for this process? */
1703 if (ch->flags & WAITING) break;
1704 }
1705 /* Done. */
1706 }
1707
1708 /*
1709 * Ask the user on the console for a runlevel
1710 */
1711 static
1712 int ask_runlevel(void)
1713 {
1714 const char prompt[] = "\nEnter runlevel: ";
1715 char buf[8];
1716 int lvl = -1;
1717 int fd;
1718
1719 console_stty();
1720 fd = console_open(O_RDWR|O_NOCTTY);
1721
1722 if (fd < 0) return('S');
1723
1724 while(!strchr("0123456789S", lvl)) {
1725 safe_write(fd, prompt, sizeof(prompt) - 1);
1726 if (read(fd, buf, sizeof(buf)) <= 0)
1727 buf[0] = 0;
1728 if (buf[0] != 0 && (buf[1] == '\r' || buf[1] == '\n'))
1729 lvl = buf[0];
1730 if (islower(lvl)) lvl = toupper(lvl);
1731 }
1732 close(fd);
1733 return lvl;
1734 }
1735
1736 /*
1737 * Search the INITTAB file for the 'initdefault' field, with the default
1738 * runlevel. If this fails, ask the user to supply a runlevel.
1739 */
1740 static
1741 int get_init_default(void)
1742 {
1743 CHILD *ch;
1744 int lvl = -1;
1745 char *p;
1746
1747 /*
1748 * Look for initdefault.
1749 */
1750 for(ch = family; ch; ch = ch->next)
1751 if (ch->action == INITDEFAULT) {
1752 p = ch->rlevel;
1753 while(*p) {
1754 if (*p > lvl) lvl = *p;
1755 p++;
1756 }
1757 break;
1758 }
1759 /*
1760 * See if level is valid
1761 */
1762 if (lvl > 0) {
1763 if (islower(lvl)) lvl = toupper(lvl);
1764 if (strchr("0123456789S", lvl) == NULL) {
1765 initlog(L_VB,
1766 "Initdefault level '%c' is invalid", lvl);
1767 lvl = 0;
1768 }
1769 }
1770 /*
1771 * Ask for runlevel on console if needed.
1772 */
1773 if (lvl <= 0) lvl = ask_runlevel();
1774
1775 /*
1776 * Log the fact that we have a runlevel now.
1777 */
1778 return lvl;
1779 }
1780
1781
1782 /*
1783 * We got signaled.
1784 *
1785 * Do actions for the new level. If we are compatible with
1786 * the "old" INITLVL and arg == 0, try to read the new
1787 * runlevel from that file first.
1788 */
1789 static
1790 int read_level(int arg)
1791 {
1792 CHILD *ch; /* Walk through list */
1793 unsigned char foo = 'X'; /* Contents of INITLVL */
1794 int ok = 1;
1795 #ifdef INITLVL
1796 FILE *fp;
1797 struct stat stt;
1798 int st;
1799 #endif
1800
1801 if (arg) foo = arg;
1802
1803 #ifdef INITLVL
1804 ok = 0;
1805
1806 if (arg == 0) {
1807 fp = NULL;
1808 if (stat(INITLVL, &stt) != 0 || stt.st_size != 0L)
1809 fp = fopen(INITLVL, "r");
1810 #ifdef INITLVL2
1811 if (fp == NULL &&
1812 (stat(INITLVL2, &stt) != 0 || stt.st_size != 0L))
1813 fp = fopen(INITLVL2, "r");
1814 #endif
1815 if (fp == NULL) {
1816 /* INITLVL file empty or not there - act as 'init q' */
1817 initlog(L_SY, "Re-reading inittab");
1818 return(runlevel);
1819 }
1820 ok = fscanf(fp, "%c %d", &foo, &st);
1821 fclose(fp);
1822 } else {
1823 /* We go to the new runlevel passed as an argument. */
1824 foo = arg;
1825 ok = 1;
1826 }
1827 if (ok == 2) sltime = st;
1828
1829 #endif /* INITLVL */
1830
1831 if (islower(foo)) foo = toupper(foo);
1832 if (ok < 1 || ok > 2 || strchr("QS0123456789ABCU", foo) == NULL) {
1833 initlog(L_VB, "bad runlevel: %c", foo);
1834 return runlevel;
1835 }
1836
1837 /* Log this action */
1838 switch(foo) {
1839 case 'S':
1840 initlog(L_VB, "Going single user");
1841 break;
1842 case 'Q':
1843 initlog(L_SY, "Re-reading inittab");
1844 break;
1845 case 'A':
1846 case 'B':
1847 case 'C':
1848 initlog(L_SY,
1849 "Activating demand-procedures for '%c'", foo);
1850 break;
1851 case 'U':
1852 initlog(L_SY, "Trying to re-exec init");
1853 return 'U';
1854 default:
1855 initlog(L_VB, "Switching to runlevel: %c", foo);
1856 }
1857
1858 if (foo == 'Q') {
1859 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
1860 /* Re-enable signal from keyboard */
1861 struct sigaction sa;
1862 SETSIG(sa, SIGINT, signal_handler, 0);
1863 #endif
1864 return runlevel;
1865 }
1866
1867 /* Check if this is a runlevel a, b or c */
1868 if (strchr("ABC", foo)) {
1869 if (runlevel == 'S') return(runlevel);
1870
1871 /* Read inittab again first! */
1872 read_inittab();
1873
1874 /* Mark those special tasks */
1875 for(ch = family; ch; ch = ch->next)
1876 if (strchr(ch->rlevel, foo) != NULL ||
1877 strchr(ch->rlevel, tolower(foo)) != NULL) {
1878 ch->flags |= DEMAND;
1879 ch->flags &= ~XECUTED;
1880 INITDBG(L_VB,
1881 "Marking (%s) as ondemand, flags %d",
1882 ch->id, ch->flags);
1883 }
1884 return runlevel;
1885 }
1886
1887 /* Store both the old and the new runlevel. */
1888 wrote_utmp_rlevel = 0;
1889 wrote_wtmp_rlevel = 0;
1890 write_utmp_wtmp("runlevel", "~~", foo + 256*runlevel, RUN_LVL, "~");
1891 thislevel = foo;
1892 prevlevel = runlevel;
1893 return foo;
1894 }
1895
1896
1897 /*
1898 * This procedure is called after every signal (SIGHUP, SIGALRM..)
1899 *
1900 * Only clear the 'failing' flag if the process is sleeping
1901 * longer than 5 minutes, or inittab was read again due
1902 * to user interaction.
1903 */
1904 static
1905 void fail_check(void)
1906 {
1907 CHILD *ch; /* Pointer to child structure */
1908 time_t t; /* System time */
1909 time_t next_alarm = 0; /* When to set next alarm */
1910
1911 time(&t);
1912
1913 for(ch = family; ch; ch = ch->next) {
1914
1915 if (ch->flags & FAILING) {
1916 /* Can we free this sucker? */
1917 if (ch->tm + SLEEPTIME < t) {
1918 ch->flags &= ~FAILING;
1919 ch->count = 0;
1920 ch->tm = 0;
1921 } else {
1922 /* No, we'll look again later */
1923 if (next_alarm == 0 ||
1924 ch->tm + SLEEPTIME > next_alarm)
1925 next_alarm = ch->tm + SLEEPTIME;
1926 }
1927 }
1928 }
1929 if (next_alarm) {
1930 next_alarm -= t;
1931 if (next_alarm < 1) next_alarm = 1;
1932 alarm(next_alarm);
1933 }
1934 }
1935
1936 /* Set all 'Fail' timers to 0 */
1937 static
1938 void fail_cancel(void)
1939 {
1940 CHILD *ch;
1941
1942 for(ch = family; ch; ch = ch->next) {
1943 ch->count = 0;
1944 ch->tm = 0;
1945 ch->flags &= ~FAILING;
1946 }
1947 }
1948
1949 /*
1950 * Start up powerfail entries.
1951 */
1952 static
1953 void do_power_fail(int pwrstat)
1954 {
1955 CHILD *ch;
1956
1957 /*
1958 * Tell powerwait & powerfail entries to start up
1959 */
1960 for (ch = family; ch; ch = ch->next) {
1961 if (pwrstat == 'O') {
1962 /*
1963 * The power is OK again.
1964 */
1965 if (ch->action == POWEROKWAIT)
1966 ch->flags &= ~XECUTED;
1967 } else if (pwrstat == 'L') {
1968 /*
1969 * Low battery, shut down now.
1970 */
1971 if (ch->action == POWERFAILNOW)
1972 ch->flags &= ~XECUTED;
1973 } else {
1974 /*
1975 * Power is failing, shutdown imminent
1976 */
1977 if (ch->action == POWERFAIL || ch->action == POWERWAIT)
1978 ch->flags &= ~XECUTED;
1979 }
1980 }
1981 }
1982
1983 /*
1984 * Check for state-pipe presence
1985 */
1986 static
1987 int check_pipe(int fd)
1988 {
1989 struct timeval t;
1990 fd_set s;
1991 char signature[8];
1992
1993 FD_ZERO(&s);
1994 FD_SET(fd, &s);
1995 t.tv_sec = t.tv_usec = 0;
1996
1997 if (select(fd+1, &s, NULL, NULL, &t) != 1)
1998 return 0;
1999 if (read(fd, signature, 8) != 8)
2000 return 0;
2001 return strncmp(Signature, signature, 8) == 0;
2002 }
2003
2004 /*
2005 * Make a state-pipe.
2006 */
2007 static
2008 int make_pipe(int fd)
2009 {
2010 int fds[2];
2011
2012 if (pipe(fds)) {
2013 initlog(L_VB, "pipe: %m");
2014 return -1;
2015 }
2016 dup2(fds[0], fd);
2017 close(fds[0]);
2018 fcntl(fds[1], F_SETFD, 1);
2019 fcntl(fd, F_SETFD, 0);
2020 safe_write(fds[1], Signature, 8);
2021
2022 return fds[1];
2023 }
2024
2025 /*
2026 * Attempt to re-exec.
2027 */
2028 static
2029 void re_exec(void)
2030 {
2031 CHILD *ch;
2032 sigset_t mask, oldset;
2033 pid_t pid;
2034 char **env;
2035 int fd;
2036
2037 if (strchr("S0123456",runlevel) == NULL)
2038 return;
2039
2040 /*
2041 * Reset the alarm, and block all signals.
2042 */
2043 alarm(0);
2044 sigfillset(&mask);
2045 sigprocmask(SIG_BLOCK, &mask, &oldset);
2046
2047 /*
2048 * construct a pipe fd --> STATE_PIPE and write a signature
2049 */
2050 if ((fd = make_pipe(STATE_PIPE)) < 0) {
2051 sigprocmask(SIG_SETMASK, &oldset, NULL);
2052 initlog(L_CO, "Attempt to re-exec failed");
2053 }
2054
2055 /*
2056 * It's a backup day today, so I'm pissed off. Being a BOFH, however,
2057 * does have it's advantages...
2058 */
2059 fail_cancel();
2060 close(pipe_fd);
2061 pipe_fd = -1;
2062 DELSET(got_signals, SIGCHLD);
2063 DELSET(got_signals, SIGHUP);
2064 DELSET(got_signals, SIGUSR1);
2065
2066 /*
2067 * That should be cleaned.
2068 */
2069 for(ch = family; ch; ch = ch->next)
2070 if (ch->flags & ZOMBIE) {
2071 INITDBG(L_VB, "Child died, PID= %d", ch->pid);
2072 ch->flags &= ~(RUNNING|ZOMBIE|WAITING);
2073 if (ch->process[0] != '+')
2074 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
2075 }
2076
2077 if ((pid = fork()) == 0) {
2078 /*
2079 * Child sends state information to the parent.
2080 */
2081 send_state(fd);
2082 exit(0);
2083 }
2084
2085 /*
2086 * The existing init process execs a new init binary.
2087 */
2088 env = init_buildenv(0);
2089 execle(myname, myname, "--init", NULL, env);
2090
2091 /*
2092 * We shouldn't be here, something failed.
2093 * Bitch, close the state pipe, unblock signals and return.
2094 */
2095 init_freeenv(env);
2096 close(fd);
2097 close(STATE_PIPE);
2098 sigprocmask(SIG_SETMASK, &oldset, NULL);
2099 initlog(L_CO, "Attempt to re-exec failed");
2100 }
2101
2102 /*
2103 * Redo utmp/wtmp entries if required or requested
2104 * Check for written records and size of utmp
2105 */
2106 static
2107 void redo_utmp_wtmp(void)
2108 {
2109 struct stat ustat;
2110 const int ret = stat(UTMP_FILE, &ustat);
2111
2112 if ((ret < 0) || (ustat.st_size == 0))
2113 wrote_utmp_rlevel = wrote_utmp_reboot = 0;
2114
2115 if ((wrote_wtmp_reboot == 0) || (wrote_utmp_reboot == 0))
2116 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME, "~");
2117
2118 if ((wrote_wtmp_rlevel == 0) || (wrote_wtmp_rlevel == 0))
2119 write_utmp_wtmp("runlevel", "~~", thislevel + 256 * prevlevel, RUN_LVL, "~");
2120 }
2121
2122 /*
2123 * We got a change runlevel request through the
2124 * init.fifo. Process it.
2125 */
2126 static
2127 void fifo_new_level(int level)
2128 {
2129 #if CHANGE_WAIT
2130 CHILD *ch;
2131 #endif
2132 int oldlevel;
2133
2134 if (level == runlevel) return;
2135
2136 #if CHANGE_WAIT
2137 /* Are we waiting for a child? */
2138 for(ch = family; ch; ch = ch->next)
2139 if (ch->flags & WAITING) break;
2140 if (ch == NULL)
2141 #endif
2142 {
2143 /* We need to go into a new runlevel */
2144 oldlevel = runlevel;
2145 runlevel = read_level(level);
2146 if (runlevel == 'U') {
2147 runlevel = oldlevel;
2148 re_exec();
2149 } else {
2150 if (oldlevel != 'S' && runlevel == 'S') console_stty();
2151 if (runlevel == '6' || runlevel == '0' ||
2152 runlevel == '1') console_stty();
2153 if (runlevel > '1' && runlevel < '6') redo_utmp_wtmp();
2154 read_inittab();
2155 fail_cancel();
2156 setproctitle("init [%c]", (int)runlevel);
2157 }
2158 }
2159 }
2160
2161
2162 /*
2163 * Set/unset environment variables. The variables are
2164 * encoded as KEY=VAL\0KEY=VAL\0\0. With "=VAL" it means
2165 * setenv, without it means unsetenv.
2166 */
2167 static
2168 void initcmd_setenv(char *data, int size)
2169 {
2170 char *env, *p, *e;
2171 size_t sz;
2172 int i, eq;
2173
2174 e = data + size;
2175
2176 while (*data && data < e) {
2177 for (p = data; *p && p < e; p++)
2178 ;
2179 if (*p) break;
2180 env = data;
2181 data = ++p;
2182
2183 /*
2184 * We only allow INIT_* to be set.
2185 */
2186 if (strncmp(env, "INIT_", 5) != 0)
2187 continue;
2188
2189 sz = strcspn(env, "=");
2190 eq = (env[sz] == '=');
2191
2192 /*initlog(L_SY, "init_setenv: %s, %d, %d", env, eq, sz);*/
2193
2194 /* Free existing vars. */
2195 for (i = 0; i < NR_EXTRA_ENV; i++) {
2196 if (extra_env[i] == NULL)
2197 continue;
2198 if (sz != strcspn(extra_env[i], "="))
2199 continue;
2200 if (strncmp(extra_env[i], env, sz) == 0) {
2201 free(extra_env[i]);
2202 extra_env[i] = NULL;
2203 }
2204 }
2205
2206 if (eq == 0)
2207 continue;
2208
2209 /* Set new vars if needed. */
2210 for (i = 0; i < NR_EXTRA_ENV; i++) {
2211 if (extra_env[i] == NULL) {
2212 extra_env[i] = istrdup(env);
2213 break;
2214 }
2215 }
2216 }
2217 }
2218
2219
2220 /*
2221 * Read from the init FIFO. Processes like telnetd and rlogind can
2222 * ask us to create login processes on their behalf.
2223 *
2224 * FIXME: this needs to be finished. NOT that it is buggy, but we need
2225 * to add the telnetd/rlogind stuff so people can start using it.
2226 * Maybe move to using an AF_UNIX socket so we can use
2227 * the 2.2 kernel credential stuff to see who we're talking to.
2228 *
2229 */
2230 static
2231 void check_init_fifo(void)
2232 {
2233 struct init_request request;
2234 struct timeval tv;
2235 struct stat st, st2;
2236 fd_set fds;
2237 int n;
2238 int quit = 0;
2239
2240 /*
2241 * First, try to create /dev/initctl if not present.
2242 */
2243 if (stat(INIT_FIFO, &st2) < 0 && errno == ENOENT)
2244 (void)mkfifo(INIT_FIFO, 0600);
2245
2246 /*
2247 * If /dev/initctl is open, stat the file to see if it
2248 * is still the _same_ inode.
2249 */
2250 if (pipe_fd >= 0) {
2251 fstat(pipe_fd, &st);
2252 if (stat(INIT_FIFO, &st2) < 0 ||
2253 st.st_dev != st2.st_dev ||
2254 st.st_ino != st2.st_ino) {
2255 close(pipe_fd);
2256 pipe_fd = -1;
2257 }
2258 }
2259
2260 /*
2261 * Now finally try to open /dev/initctl
2262 */
2263 if (pipe_fd < 0) {
2264 if ((pipe_fd = open(INIT_FIFO, O_RDWR|O_NONBLOCK)) >= 0) {
2265 fstat(pipe_fd, &st);
2266 if (!S_ISFIFO(st.st_mode)) {
2267 initlog(L_VB, "%s is not a fifo", INIT_FIFO);
2268 close(pipe_fd);
2269 pipe_fd = -1;
2270 }
2271 }
2272 if (pipe_fd >= 0) {
2273 /*
2274 * Don't use fd's 0, 1 or 2.
2275 */
2276 (void) dup2(pipe_fd, PIPE_FD);
2277 close(pipe_fd);
2278 pipe_fd = PIPE_FD;
2279
2280 /*
2281 * Return to caller - we'll be back later.
2282 */
2283 }
2284 }
2285
2286 /* Wait for data to appear, _if_ the pipe was opened. */
2287 if (pipe_fd >= 0) while(!quit) {
2288
2289 /* Do select, return on EINTR. */
2290 FD_ZERO(&fds);
2291 FD_SET(pipe_fd, &fds);
2292 tv.tv_sec = 5;
2293 tv.tv_usec = 0;
2294 n = select(pipe_fd + 1, &fds, NULL, NULL, &tv);
2295 if (n <= 0) {
2296 if (n == 0 || errno == EINTR) return;
2297 continue;
2298 }
2299
2300 /* Read the data, return on EINTR. */
2301 n = read(pipe_fd, &request, sizeof(request));
2302 if (n == 0) {
2303 /*
2304 * End of file. This can't happen under Linux (because
2305 * the pipe is opened O_RDWR - see select() in the
2306 * kernel) but you never know...
2307 */
2308 close(pipe_fd);
2309 pipe_fd = -1;
2310 return;
2311 }
2312 if (n <= 0) {
2313 if (errno == EINTR) return;
2314 initlog(L_VB, "error reading initrequest");
2315 continue;
2316 }
2317
2318 /*
2319 * This is a convenient point to also try to
2320 * find the console device or check if it changed.
2321 */
2322 console_init();
2323
2324 /*
2325 * Process request.
2326 */
2327 if (request.magic != INIT_MAGIC || n != sizeof(request)) {
2328 initlog(L_VB, "got bogus initrequest");
2329 continue;
2330 }
2331 switch(request.cmd) {
2332 case INIT_CMD_RUNLVL:
2333 sltime = request.sleeptime;
2334 fifo_new_level(request.runlevel);
2335 quit = 1;
2336 break;
2337 case INIT_CMD_POWERFAIL:
2338 sltime = request.sleeptime;
2339 do_power_fail('F');
2340 quit = 1;
2341 break;
2342 case INIT_CMD_POWERFAILNOW:
2343 sltime = request.sleeptime;
2344 do_power_fail('L');
2345 quit = 1;
2346 break;
2347 case INIT_CMD_POWEROK:
2348 sltime = request.sleeptime;
2349 do_power_fail('O');
2350 quit = 1;
2351 break;
2352 case INIT_CMD_SETENV:
2353 initcmd_setenv(request.i.data, sizeof(request.i.data));
2354 break;
2355 default:
2356 initlog(L_VB, "got unimplemented initrequest.");
2357 break;
2358 }
2359 }
2360
2361 /*
2362 * We come here if the pipe couldn't be opened.
2363 */
2364 if (pipe_fd < 0) pause();
2365
2366 }
2367
2368
2369 /*
2370 * This function is used in the transition
2371 * sysinit (-> single user) boot -> multi-user.
2372 */
2373 static
2374 void boot_transitions()
2375 {
2376 CHILD *ch;
2377 static int newlevel = 0;
2378 static int warn = 1;
2379 int loglevel;
2380 int oldlevel;
2381
2382 /* Check if there is something to wait for! */
2383 for( ch = family; ch; ch = ch->next )
2384 if ((ch->flags & RUNNING) && ch->action != BOOT) break;
2385
2386 if (ch == NULL) {
2387 /* No processes left in this level, proceed to next level. */
2388 loglevel = -1;
2389 oldlevel = 'N';
2390 switch(runlevel) {
2391 case '#': /* SYSINIT -> BOOT */
2392 INITDBG(L_VB, "SYSINIT -> BOOT");
2393
2394 /* Write a boot record. */
2395 wrote_utmp_reboot = 0;
2396 wrote_wtmp_reboot = 0;
2397 write_utmp_wtmp("reboot", "~~", 0, BOOT_TIME, "~");
2398
2399 /* Get our run level */
2400 newlevel = dfl_level ? dfl_level : get_init_default();
2401 if (newlevel == 'S') {
2402 runlevel = newlevel;
2403 /* Not really 'S' but show anyway. */
2404 setproctitle("init [S]");
2405 } else
2406 runlevel = '*';
2407 break;
2408 case '*': /* BOOT -> NORMAL */
2409 INITDBG(L_VB, "BOOT -> NORMAL");
2410 if (runlevel != newlevel)
2411 loglevel = newlevel;
2412 runlevel = newlevel;
2413 did_boot = 1;
2414 warn = 1;
2415 break;
2416 case 'S': /* Ended SU mode */
2417 case 's':
2418 INITDBG(L_VB, "END SU MODE");
2419 newlevel = get_init_default();
2420 if (!did_boot && newlevel != 'S')
2421 runlevel = '*';
2422 else {
2423 if (runlevel != newlevel)
2424 loglevel = newlevel;
2425 runlevel = newlevel;
2426 oldlevel = 'S';
2427 }
2428 warn = 1;
2429 for(ch = family; ch; ch = ch->next)
2430 if (strcmp(ch->rlevel, "S") == 0)
2431 ch->flags &= ~(FAILING|WAITING|XECUTED);
2432 break;
2433 default:
2434 if (warn)
2435 initlog(L_VB,
2436 "no more processes left in this runlevel");
2437 warn = 0;
2438 loglevel = -1;
2439 if (got_signals == 0)
2440 check_init_fifo();
2441 break;
2442 }
2443 if (loglevel > 0) {
2444 initlog(L_VB, "Entering runlevel: %c", runlevel);
2445 wrote_utmp_rlevel = 0;
2446 wrote_wtmp_rlevel = 0;
2447 write_utmp_wtmp("runlevel", "~~", runlevel + 256 * oldlevel, RUN_LVL, "~");
2448 thislevel = runlevel;
2449 prevlevel = oldlevel;
2450 setproctitle("init [%c]", (int)runlevel);
2451 }
2452 }
2453 }
2454
2455 /*
2456 * Init got hit by a signal. See which signal it is,
2457 * and act accordingly.
2458 */
2459 static
2460 void process_signals()
2461 {
2462 CHILD *ch;
2463 int pwrstat;
2464 int oldlevel;
2465 int fd;
2466 char c;
2467
2468 if (ISMEMBER(got_signals, SIGPWR)) {
2469 INITDBG(L_VB, "got SIGPWR");
2470 /* See _what_ kind of SIGPWR this is. */
2471 pwrstat = 0;
2472 if ((fd = open(PWRSTAT, O_RDONLY)) >= 0) {
2473 if (read(fd, &c, 1) != 1)
2474 c = 0;
2475 pwrstat = c;
2476 close(fd);
2477 unlink(PWRSTAT);
2478 } else if ((fd = open(PWRSTAT_OLD, O_RDONLY)) >= 0) {
2479 /* Path changed 2010-03-20. Look for the old path for a while. */
2480 initlog(L_VB, "warning: found obsolete path %s, use %s instead",
2481 PWRSTAT_OLD, PWRSTAT);
2482 if (read(fd, &c, 1) != 1)
2483 c = 0;
2484 pwrstat = c;
2485 close(fd);
2486 unlink(PWRSTAT_OLD);
2487 }
2488 do_power_fail(pwrstat);
2489 DELSET(got_signals, SIGPWR);
2490 }
2491
2492 if (ISMEMBER(got_signals, SIGINT)) {
2493 #if defined(SIGINT_ONLYONCE) && (SIGINT_ONLYONCE == 1)
2494 /* Ignore any further signal from keyboard */
2495 struct sigaction sa;
2496 SETSIG(sa, SIGINT, SIG_IGN, SA_RESTART);
2497 #endif
2498 INITDBG(L_VB, "got SIGINT");
2499 /* Tell ctrlaltdel entry to start up */
2500 for(ch = family; ch; ch = ch->next)
2501 if (ch->action == CTRLALTDEL)
2502 ch->flags &= ~XECUTED;
2503 DELSET(got_signals, SIGINT);
2504 }
2505
2506 if (ISMEMBER(got_signals, SIGWINCH)) {
2507 INITDBG(L_VB, "got SIGWINCH");
2508 /* Tell kbrequest entry to start up */
2509 for(ch = family; ch; ch = ch->next)
2510 if (ch->action == KBREQUEST)
2511 ch->flags &= ~XECUTED;
2512 DELSET(got_signals, SIGWINCH);
2513 }
2514
2515 if (ISMEMBER(got_signals, SIGALRM)) {
2516 INITDBG(L_VB, "got SIGALRM");
2517 /* The timer went off: check it out */
2518 DELSET(got_signals, SIGALRM);
2519 }
2520
2521 if (ISMEMBER(got_signals, SIGCHLD)) {
2522 INITDBG(L_VB, "got SIGCHLD");
2523 /* First set flag to 0 */
2524 DELSET(got_signals, SIGCHLD);
2525
2526 /* See which child this was */
2527 for(ch = family; ch; ch = ch->next)
2528 if (ch->flags & ZOMBIE) {
2529 INITDBG(L_VB, "Child died, PID= %d", ch->pid);
2530 ch->flags &= ~(RUNNING|ZOMBIE|WAITING);
2531 if (ch->process[0] != '+')
2532 write_utmp_wtmp("", ch->id, ch->pid, DEAD_PROCESS, NULL);
2533 }
2534
2535 }
2536
2537 if (ISMEMBER(got_signals, SIGHUP)) {
2538 INITDBG(L_VB, "got SIGHUP");
2539 #if CHANGE_WAIT
2540 /* Are we waiting for a child? */
2541 for(ch = family; ch; ch = ch->next)
2542 if (ch->flags & WAITING) break;
2543 if (ch == NULL)
2544 #endif
2545 {
2546 /* We need to go into a new runlevel */
2547 oldlevel = runlevel;
2548 #ifdef INITLVL
2549 runlevel = read_level(0);
2550 #endif
2551 if (runlevel == 'U') {
2552 runlevel = oldlevel;
2553 re_exec();
2554 } else {
2555 if (oldlevel != 'S' && runlevel == 'S') console_stty();
2556 if (runlevel == '6' || runlevel == '0' ||
2557 runlevel == '1') console_stty();
2558 read_inittab();
2559 fail_cancel();
2560 setproctitle("init [%c]", (int)runlevel);
2561 DELSET(got_signals, SIGHUP);
2562 }
2563 }
2564 }
2565 if (ISMEMBER(got_signals, SIGUSR1)) {
2566 /*
2567 * SIGUSR1 means close and reopen /dev/initctl
2568 */
2569 INITDBG(L_VB, "got SIGUSR1");
2570 close(pipe_fd);
2571 pipe_fd = -1;
2572 DELSET(got_signals, SIGUSR1);
2573 }
2574 }
2575
2576 /*
2577 * The main loop
2578 */
2579 static
2580 void init_main(void)
2581 {
2582 CHILD *ch;
2583 struct sigaction sa;
2584 sigset_t sgt;
2585 int f, st;
2586
2587 if (!reload) {
2588
2589 #if INITDEBUG
2590 /*
2591 * Fork so we can debug the init process.
2592 */
2593 if ((f = fork()) > 0) {
2594 static const char killmsg[] = "PRNT: init killed.\r\n";
2595 pid_t rc;
2596
2597 while((rc = wait(&st)) != f)
2598 if (rc < 0 && errno == ECHILD)
2599 break;
2600 safe_write(1, killmsg, sizeof(killmsg) - 1);
2601 while(1) pause();
2602 }
2603 #endif
2604
2605 #ifdef __linux__
2606 /*
2607 * Tell the kernel to send us SIGINT when CTRL-ALT-DEL
2608 * is pressed, and that we want to handle keyboard signals.
2609 */
2610 init_reboot(BMAGIC_SOFT);
2611 if ((f = open(VT_MASTER, O_RDWR | O_NOCTTY)) >= 0) {
2612 (void) ioctl(f, KDSIGACCEPT, SIGWINCH);
2613 close(f);
2614 } else
2615 (void) ioctl(0, KDSIGACCEPT, SIGWINCH);
2616 #endif
2617
2618 /*
2619 * Ignore all signals.
2620 */
2621 for(f = 1; f <= NSIG; f++)
2622 SETSIG(sa, f, SIG_IGN, SA_RESTART);
2623 }
2624
2625 SETSIG(sa, SIGALRM, signal_handler, 0);
2626 SETSIG(sa, SIGHUP, signal_handler, 0);
2627 SETSIG(sa, SIGINT, signal_handler, 0);
2628 SETSIG(sa, SIGCHLD, chld_handler, SA_RESTART);
2629 SETSIG(sa, SIGPWR, signal_handler, 0);
2630 SETSIG(sa, SIGWINCH, signal_handler, 0);
2631 SETSIG(sa, SIGUSR1, signal_handler, 0);
2632 SETSIG(sa, SIGSTOP, stop_handler, SA_RESTART);
2633 SETSIG(sa, SIGTSTP, stop_handler, SA_RESTART);
2634 SETSIG(sa, SIGCONT, cont_handler, SA_RESTART);
2635 SETSIG(sa, SIGSEGV, (void (*)(int))segv_handler, SA_RESTART);
2636
2637 console_init();
2638
2639 if (!reload) {
2640 int fd;
2641
2642 /* Close whatever files are open, and reset the console. */
2643 close(0);
2644 close(1);
2645 close(2);
2646 console_stty();
2647 setsid();
2648
2649 /*
2650 * Set default PATH variable.
2651 */
2652 setenv("PATH", PATH_DEFAULT, 1 /* Overwrite */);
2653
2654 /*
2655 * Initialize /var/run/utmp (only works if /var is on
2656 * root and mounted rw)
2657 */
2658 if ((fd = open(UTMP_FILE, O_WRONLY|O_CREAT|O_TRUNC, 0644)) >= 0)
2659 close(fd);
2660
2661 /*
2662 * Say hello to the world
2663 */
2664 initlog(L_CO, bootmsg, "booting");
2665
2666 /*
2667 * See if we have to start an emergency shell.
2668 */
2669 if (emerg_shell) {
2670 pid_t rc;
2671 SETSIG(sa, SIGCHLD, SIG_DFL, SA_RESTART);
2672 if (spawn(&ch_emerg, &f) > 0) {
2673 while((rc = wait(&st)) != f)
2674 if (rc < 0 && errno == ECHILD)
2675 break;
2676 }
2677 SETSIG(sa, SIGCHLD, chld_handler, SA_RESTART);
2678 }
2679
2680 /*
2681 * Start normal boot procedure.
2682 */
2683 runlevel = '#';
2684 read_inittab();
2685
2686 } else {
2687 /*
2688 * Restart: unblock signals and let the show go on
2689 */
2690 initlog(L_CO, bootmsg, "reloading");
2691 sigfillset(&sgt);
2692 sigprocmask(SIG_UNBLOCK, &sgt, NULL);
2693
2694 /*
2695 * Set default PATH variable.
2696 */
2697 setenv("PATH", PATH_DEFAULT, 0 /* Don't overwrite */);
2698 }
2699 start_if_needed();
2700
2701 while(1) {
2702
2703 /* See if we need to make the boot transitions. */
2704 boot_transitions();
2705 INITDBG(L_VB, "init_main: waiting..");
2706
2707 /* Check if there are processes to be waited on. */
2708 for(ch = family; ch; ch = ch->next)
2709 if ((ch->flags & RUNNING) && ch->action != BOOT) break;
2710
2711 #if CHANGE_WAIT
2712 /* Wait until we get hit by some signal. */
2713 while (ch != NULL && got_signals == 0) {
2714 if (ISMEMBER(got_signals, SIGHUP)) {
2715 /* See if there are processes to be waited on. */
2716 for(ch = family; ch; ch = ch->next)
2717 if (ch->flags & WAITING) break;
2718 }
2719 if (ch != NULL) check_init_fifo();
2720 }
2721 #else /* CHANGE_WAIT */
2722 if (ch != NULL && got_signals == 0) check_init_fifo();
2723 #endif /* CHANGE_WAIT */
2724
2725 /* Check the 'failing' flags */
2726 fail_check();
2727
2728 /* Process any signals. */
2729 process_signals();
2730
2731 /* See what we need to start up (again) */
2732 start_if_needed();
2733 }
2734 /*NOTREACHED*/
2735 }
2736
2737 /*
2738 * Tell the user about the syntax we expect.
2739 */
2740 static
2741 void usage(char *s)
2742 {
2743 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);
2744 exit(1);
2745 }
2746
2747 static
2748 int telinit(char *progname, int argc, char **argv)
2749 {
2750 #ifdef TELINIT_USES_INITLVL
2751 FILE *fp;
2752 #endif
2753 struct init_request request;
2754 struct sigaction sa;
2755 int f, fd, l;
2756 char *env = NULL;
2757
2758 memset(&request, 0, sizeof(request));
2759 request.magic = INIT_MAGIC;
2760
2761 while ((f = getopt(argc, argv, "t:e:")) != EOF) switch(f) {
2762 case 't':
2763 sltime = atoi(optarg);
2764 break;
2765 case 'e':
2766 if (env == NULL)
2767 env = request.i.data;
2768 l = strlen(optarg);
2769 if (env + l + 2 > request.i.data + sizeof(request.i.data)) {
2770 fprintf(stderr, "%s: -e option data "
2771 "too large\n", progname);
2772 exit(1);
2773 }
2774 memcpy(env, optarg, l);
2775 env += l;
2776 *env++ = 0;
2777 break;
2778 default:
2779 usage(progname);
2780 break;
2781 }
2782
2783 if (env) *env++ = 0;
2784
2785 if (env) {
2786 if (argc != optind)
2787 usage(progname);
2788 request.cmd = INIT_CMD_SETENV;
2789 } else {
2790 if (argc - optind != 1 || strlen(argv[optind]) != 1)
2791 usage(progname);
2792 if (!strchr("0123456789SsQqAaBbCcUu", argv[optind][0]))
2793 usage(progname);
2794 request.cmd = INIT_CMD_RUNLVL;
2795 request.runlevel = argv[optind][0];
2796 request.sleeptime = sltime;
2797 }
2798
2799 /* Change to the root directory. */
2800 if (0 != chdir("/"))
2801 initlog(L_VB, "unable to chdir to /: %s",
2802 strerror(errno));
2803
2804 /* Open the fifo and write a command. */
2805 /* Make sure we don't hang on opening /dev/initctl */
2806 SETSIG(sa, SIGALRM, signal_handler, 0);
2807 alarm(3);
2808 if ((fd = open(INIT_FIFO, O_WRONLY)) >= 0) {
2809 ssize_t p = 0;
2810 size_t s = sizeof(request);
2811 void *ptr = &request;
2812
2813 while (s > 0) {
2814 p = write(fd, ptr, s);
2815 if (p < 0) {
2816 if (errno == EINTR || errno == EAGAIN)
2817 continue;
2818 break;
2819 }
2820 ptr += p;
2821 s -= p;
2822 }
2823 close(fd);
2824 alarm(0);
2825 return 0;
2826 }
2827
2828 #ifdef TELINIT_USES_INITLVL
2829 if (request.cmd == INIT_CMD_RUNLVL) {
2830 /* Fallthrough to the old method. */
2831
2832 /* Now write the new runlevel. */
2833 if ((fp = fopen(INITLVL, "w")) == NULL) {
2834 fprintf(stderr, "%s: cannot create %s\n",
2835 progname, INITLVL);
2836 exit(1);
2837 }
2838 fprintf(fp, "%s %d", argv[optind], sltime);
2839 fclose(fp);
2840
2841 /* And tell init about the pending runlevel change. */
2842 if (kill(INITPID, SIGHUP) < 0) perror(progname);
2843
2844 return 0;
2845 }
2846 #endif
2847
2848 fprintf(stderr, "%s: ", progname);
2849 if (ISMEMBER(got_signals, SIGALRM)) {
2850 fprintf(stderr, "timeout opening/writing control channel %s\n",
2851 INIT_FIFO);
2852 } else {
2853 perror(INIT_FIFO);
2854 }
2855 return 1;
2856 }
2857
2858 /*
2859 * Main entry for init and telinit.
2860 */
2861 int main(int argc, char **argv)
2862 {
2863 char *p;
2864 int f;
2865 int isinit;
2866 #ifdef WITH_SELINUX
2867 int enforce = 0;
2868 #endif
2869
2870 /* Get my own name */
2871 if ((p = strrchr(argv[0], '/')) != NULL)
2872 p++;
2873 else
2874 p = argv[0];
2875
2876 /* Common umask */
2877 umask(umask(077) | 022);
2878
2879 /* Quick check */
2880 if (geteuid() != 0) {
2881 fprintf(stderr, "%s: must be superuser.\n", p);
2882 exit(1);
2883 }
2884
2885 /*
2886 * Is this telinit or init ?
2887 */
2888 isinit = (getpid() == 1);
2889 for (f = 1; f < argc; f++) {
2890 if (!strcmp(argv[f], "-i") || !strcmp(argv[f], "--init")) {
2891 isinit = 1;
2892 break;
2893 }
2894 }
2895 if (!isinit) exit(telinit(p, argc, argv));
2896
2897 /*
2898 * Check for re-exec
2899 */
2900 if (check_pipe(STATE_PIPE)) {
2901
2902 receive_state(STATE_PIPE);
2903
2904 myname = istrdup(argv[0]);
2905 argv0 = argv[0];
2906 maxproclen = 0;
2907 for (f = 0; f < argc; f++)
2908 maxproclen += strlen(argv[f]) + 1;
2909 reload = 1;
2910 setproctitle("init [%c]", (int)runlevel);
2911
2912 init_main();
2913 }
2914
2915 /* Check command line arguments */
2916 maxproclen = strlen(argv[0]) + 1;
2917 for(f = 1; f < argc; f++) {
2918 if (!strcmp(argv[f], "single") || !strcmp(argv[f], "-s"))
2919 dfl_level = 'S';
2920 else if (!strcmp(argv[f], "-a") || !strcmp(argv[f], "auto"))
2921 putenv("AUTOBOOT=YES");
2922 else if (!strcmp(argv[f], "-b") || !strcmp(argv[f],"emergency"))
2923 emerg_shell = 1;
2924 else if (!strcmp(argv[f], "-z")) {
2925 /* Ignore -z xxx */
2926 if (argv[f + 1]) f++;
2927 } else if (strchr("0123456789sS", argv[f][0])
2928 && strlen(argv[f]) == 1)
2929 dfl_level = argv[f][0];
2930 /* "init u" in the very beginning makes no sense */
2931 if (dfl_level == 's') dfl_level = 'S';
2932 maxproclen += strlen(argv[f]) + 1;
2933 }
2934
2935 #ifdef WITH_SELINUX
2936 if (getenv("SELINUX_INIT") == NULL) {
2937 if (is_selinux_enabled() != 1) {
2938 if (selinux_init_load_policy(&enforce) == 0) {
2939 putenv("SELINUX_INIT=YES");
2940 execv(myname, argv);
2941 } else {
2942 if (enforce > 0) {
2943 /* SELinux in enforcing mode but load_policy failed */
2944 /* At this point, we probably can't open /dev/console, so log() won't work */
2945 fprintf(stderr,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.\n");
2946 exit(1);
2947 }
2948 }
2949 }
2950 }
2951 #endif
2952 /* Start booting. */
2953 argv0 = argv[0];
2954 argv[1] = NULL;
2955 setproctitle("init boot");
2956 init_main();
2957
2958 /*NOTREACHED*/
2959 return 0;
2960 }