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