*: shrink: use Vladimir's "o+" specifier instead of xatou(opt_param)
[oweals/busybox.git] / init / init.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini init implementation for busybox
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7  * Adjusted by so many folks, it's impossible to keep track.
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  */
11
12 #include "libbb.h"
13 #include <syslog.h>
14 #include <paths.h>
15 #include <sys/reboot.h>
16
17 #define COMMAND_SIZE 256
18 #define CONSOLE_NAME_SIZE 32
19 #define MAXENV  16              /* Number of env. vars */
20
21 /*
22  * When a file named CORE_ENABLE_FLAG_FILE exists, setrlimit is called
23  * before processes are spawned to set core file size as unlimited.
24  * This is for debugging only.  Don't use this is production, unless
25  * you want core dumps lying about....
26  */
27 #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
28 #include <sys/resource.h>
29
30 #define INITTAB      "/etc/inittab"     /* inittab file location */
31 #ifndef INIT_SCRIPT
32 #define INIT_SCRIPT  "/etc/init.d/rcS"  /* Default sysinit script. */
33 #endif
34
35 /* Allowed init action types */
36 #define SYSINIT     0x001
37 #define RESPAWN     0x002
38 #define ASKFIRST    0x004
39 #define WAIT        0x008
40 #define ONCE        0x010
41 #define CTRLALTDEL  0x020
42 #define SHUTDOWN    0x040
43 #define RESTART     0x080
44
45 #define STR_SYSINIT     "\x01"
46 #define STR_RESPAWN     "\x02"
47 #define STR_ASKFIRST    "\x04"
48 #define STR_WAIT        "\x08"
49 #define STR_ONCE        "\x10"
50 #define STR_CTRLALTDEL  "\x20"
51 #define STR_SHUTDOWN    "\x40"
52 #define STR_RESTART     "\x80"
53
54 /* Set up a linked list of init_actions, to be read from inittab */
55 struct init_action {
56         struct init_action *next;
57         pid_t pid;
58         uint8_t action_type;
59         char terminal[CONSOLE_NAME_SIZE];
60         char command[COMMAND_SIZE];
61 };
62
63 /* Static variables */
64 static struct init_action *init_action_list = NULL;
65
66 static const char *log_console = VC_5;
67 static sig_atomic_t got_cont = 0;
68
69 enum {
70         L_LOG = 0x1,
71         L_CONSOLE = 0x2,
72
73 #if ENABLE_FEATURE_EXTRA_QUIET
74         MAYBE_CONSOLE = 0x0,
75 #else
76         MAYBE_CONSOLE = L_CONSOLE,
77 #endif
78
79 #ifndef RB_HALT_SYSTEM
80         RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
81         RB_ENABLE_CAD = 0x89abcdef,
82         RB_DISABLE_CAD = 0,
83         RB_POWER_OFF = 0x4321fedc,
84         RB_AUTOBOOT = 0x01234567,
85 #endif
86 };
87
88 static const char *const environment[] = {
89         "HOME=/",
90         bb_PATH_root_path,
91         "SHELL=/bin/sh",
92         "USER=root",
93         NULL
94 };
95
96 /* Function prototypes */
97 static void delete_init_action(struct init_action *a);
98 static void halt_reboot_pwoff(int sig) ATTRIBUTE_NORETURN;
99
100 static void waitfor(pid_t pid)
101 {
102         /* waitfor(run(x)): protect against failed fork inside run() */
103         if (pid <= 0)
104                 return;
105
106         /* Wait for any child (prevent zombies from exiting orphaned processes)
107          * but exit the loop only when specified one has exited. */
108         while (wait(NULL) != pid)
109                 continue;
110 }
111
112 static void loop_forever(void) ATTRIBUTE_NORETURN;
113 static void loop_forever(void)
114 {
115         while (1)
116                 sleep(1);
117 }
118
119 /* Print a message to the specified device.
120  * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
121  * NB: careful, we can be called after vfork!
122  */
123 #define messageD(...) do { if (ENABLE_DEBUG_INIT) message(__VA_ARGS__); } while (0)
124 static void message(int where, const char *fmt, ...)
125         __attribute__ ((format(printf, 2, 3)));
126 static void message(int where, const char *fmt, ...)
127 {
128         static int log_fd = -1;
129         va_list arguments;
130         int l;
131         char msg[128];
132
133         msg[0] = '\r';
134         va_start(arguments, fmt);
135         vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
136         va_end(arguments);
137         msg[sizeof(msg) - 2] = '\0';
138         l = strlen(msg);
139
140         if (ENABLE_FEATURE_INIT_SYSLOG) {
141                 /* Log the message to syslogd */
142                 if (where & L_LOG) {
143                         /* don't out "\r" */
144                         openlog(applet_name, 0, LOG_DAEMON);
145                         syslog(LOG_INFO, "init: %s", msg + 1);
146                         closelog();
147                 }
148                 msg[l++] = '\n';
149                 msg[l] = '\0';
150         } else {
151                 msg[l++] = '\n';
152                 msg[l] = '\0';
153                 /* Take full control of the log tty, and never close it.
154                  * It's mine, all mine!  Muhahahaha! */
155                 if (log_fd < 0) {
156                         if (!log_console) {
157                                 log_fd = 2;
158                         } else {
159                                 log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
160                                 if (log_fd < 0) {
161                                         bb_error_msg("can't log to %s", log_console);
162                                         where = L_CONSOLE;
163                                 } else {
164                                         close_on_exec_on(log_fd);
165                                 }
166                         }
167                 }
168                 if (where & L_LOG) {
169                         full_write(log_fd, msg, l);
170                         if (log_fd == 2)
171                                 return; /* don't print dup messages */
172                 }
173         }
174
175         if (where & L_CONSOLE) {
176                 /* Send console messages to console so people will see them. */
177                 full_write(2, msg, l);
178         }
179 }
180
181 /* From <linux/serial.h> */
182 struct serial_struct {
183         int     type;
184         int     line;
185         unsigned int    port;
186         int     irq;
187         int     flags;
188         int     xmit_fifo_size;
189         int     custom_divisor;
190         int     baud_base;
191         unsigned short  close_delay;
192         char    io_type;
193         char    reserved_char[1];
194         int     hub6;
195         unsigned short  closing_wait; /* time to wait before closing */
196         unsigned short  closing_wait2; /* no longer used... */
197         unsigned char   *iomem_base;
198         unsigned short  iomem_reg_shift;
199         unsigned int    port_high;
200         unsigned long   iomap_base;     /* cookie passed into ioremap */
201         int     reserved[1];
202         /* Paranoia (imagine 64bit kernel overwriting 32bit userspace stack) */
203         uint32_t bbox_reserved[16];
204 };
205 static void console_init(void)
206 {
207         struct serial_struct sr;
208         char *s;
209
210         s = getenv("CONSOLE");
211         if (!s) s = getenv("console");
212         if (s) {
213                 int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
214                 if (fd >= 0) {
215                         dup2(fd, 0);
216                         dup2(fd, 1);
217                         dup2(fd, 2);
218                         while (fd > 2) close(fd--);
219                 }
220                 messageD(L_LOG, "console='%s'", s);
221         } else {
222                 /* Make sure fd 0,1,2 are not closed */
223                 bb_sanitize_stdio();
224         }
225
226         s = getenv("TERM");
227         if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
228                 /* Force the TERM setting to vt102 for serial console
229                  * if TERM is set to linux (the default) */
230                 if (!s || strcmp(s, "linux") == 0)
231                         putenv((char*)"TERM=vt102");
232                 if (!ENABLE_FEATURE_INIT_SYSLOG)
233                         log_console = NULL;
234         } else if (!s)
235                 putenv((char*)"TERM=linux");
236 }
237
238 /* Set terminal settings to reasonable defaults.
239  * NB: careful, we can be called after vfork! */
240 static void set_sane_term(void)
241 {
242         struct termios tty;
243
244         tcgetattr(STDIN_FILENO, &tty);
245
246         /* set control chars */
247         tty.c_cc[VINTR] = 3;    /* C-c */
248         tty.c_cc[VQUIT] = 28;   /* C-\ */
249         tty.c_cc[VERASE] = 127; /* C-? */
250         tty.c_cc[VKILL] = 21;   /* C-u */
251         tty.c_cc[VEOF] = 4;     /* C-d */
252         tty.c_cc[VSTART] = 17;  /* C-q */
253         tty.c_cc[VSTOP] = 19;   /* C-s */
254         tty.c_cc[VSUSP] = 26;   /* C-z */
255
256         /* use line dicipline 0 */
257         tty.c_line = 0;
258
259         /* Make it be sane */
260         tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
261         tty.c_cflag |= CREAD | HUPCL | CLOCAL;
262
263         /* input modes */
264         tty.c_iflag = ICRNL | IXON | IXOFF;
265
266         /* output modes */
267         tty.c_oflag = OPOST | ONLCR;
268
269         /* local modes */
270         tty.c_lflag =
271                 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
272
273         tcsetattr(STDIN_FILENO, TCSANOW, &tty);
274 }
275
276 /* Open the new terminal device.
277  * NB: careful, we can be called after vfork! */
278 static void open_stdio_to_tty(const char* tty_name, int exit_on_failure)
279 {
280         /* empty tty_name means "use init's tty", else... */
281         if (tty_name[0]) {
282                 int fd;
283                 close(0);
284                 /* fd can be only < 0 or 0: */
285                 fd = device_open(tty_name, O_RDWR);
286                 if (fd) {
287                         message(L_LOG | L_CONSOLE, "Can't open %s: %s",
288                                 tty_name, strerror(errno));
289                         if (exit_on_failure)
290                                 _exit(1);
291                         if (ENABLE_DEBUG_INIT)
292                                 _exit(2);
293                 /* NB: we don't reach this if we were called after vfork.
294                  * Thus halt_reboot_pwoff() itself need not be vfork-safe. */
295                         halt_reboot_pwoff(SIGUSR1); /* halt the system */
296                 }
297                 dup2(0, 1);
298                 dup2(0, 2);
299         }
300         set_sane_term();
301 }
302
303 /* Wrapper around exec:
304  * Takes string (max COMMAND_SIZE chars).
305  * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
306  * Otherwise splits words on whitespace, deals with leading dash,
307  * and uses plain exec().
308  * NB: careful, we can be called after vfork!
309  */
310 static void init_exec(const char *command)
311 {
312         char *cmd[COMMAND_SIZE / 2];
313         char buf[COMMAND_SIZE + 6];  /* COMMAND_SIZE+strlen("exec ")+1 */
314         int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
315
316         /* See if any special /bin/sh requiring characters are present */
317         if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
318                 strcpy(buf, "exec ");
319                 strcpy(buf + 5, command + dash); /* excluding "-" */
320                 /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
321                 cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
322                 cmd[1] = (char*)"-c";
323                 cmd[2] = buf;
324                 cmd[3] = NULL;
325         } else {
326                 /* Convert command (char*) into cmd (char**, one word per string) */
327                 char *word, *next;
328                 int i = 0;
329                 next = strcpy(buf, command); /* including "-" */
330                 while ((word = strsep(&next, " \t")) != NULL) {
331                         if (*word != '\0') { /* not two spaces/tabs together? */
332                                 cmd[i] = word;
333                                 i++;
334                         }
335                 }
336                 cmd[i] = NULL;
337         }
338         /* If we saw leading "-", it is interactive shell.
339          * Try harder to give it a controlling tty.
340          * And skip "-" in actual exec call. */
341         if (dash) {
342                 /* _Attempt_ to make stdin a controlling tty. */
343                 if (ENABLE_FEATURE_INIT_SCTTY)
344                         ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
345         }
346         BB_EXECVP(cmd[0] + dash, cmd);
347         message(L_LOG | L_CONSOLE, "Cannot run '%s': %s",
348                         cmd[0], strerror(errno));
349         /* returns if execvp fails */
350 }
351
352 /* Used only by run_actions */
353 static pid_t run(const struct init_action *a)
354 {
355         pid_t pid;
356         sigset_t nmask, omask;
357
358         /* Block sigchild while forking (why?) */
359         sigemptyset(&nmask);
360         sigaddset(&nmask, SIGCHLD);
361         sigprocmask(SIG_BLOCK, &nmask, &omask);
362         pid = vfork();
363         sigprocmask(SIG_SETMASK, &omask, NULL);
364
365         if (pid < 0)
366                 message(L_LOG | L_CONSOLE, "Can't fork");
367         if (pid)
368                 return pid;
369
370         /* Child */
371
372         /* Reset signal handlers that were set by the parent process */
373         bb_signals(0
374                 + (1 << SIGUSR1)
375                 + (1 << SIGUSR2)
376                 + (1 << SIGINT)
377                 + (1 << SIGTERM)
378                 + (1 << SIGHUP)
379                 + (1 << SIGQUIT)
380                 + (1 << SIGCONT)
381                 + (1 << SIGSTOP)
382                 + (1 << SIGTSTP)
383                 , SIG_DFL);
384
385         /* Create a new session and make ourself the process
386          * group leader */
387         setsid();
388
389         /* Open the new terminal device */
390         open_stdio_to_tty(a->terminal, 1 /* - exit if open fails */);
391
392 // NB: do not enable unless you change vfork to fork above
393 #ifdef BUT_RUN_ACTIONS_ALREADY_DOES_WAITING
394         /* If the init Action requires us to wait, then force the
395          * supplied terminal to be the controlling tty. */
396         if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
397                 /* Now fork off another process to just hang around */
398                 pid = fork();
399                 if (pid < 0) {
400                         message(L_LOG | L_CONSOLE, "Can't fork");
401                         _exit(1);
402                 }
403
404                 if (pid > 0) {
405                         /* Parent - wait till the child is done */
406                         bb_signals(0
407                                 + (1 << SIGINT)
408                                 + (1 << SIGTSTP)
409                                 + (1 << SIGQUIT)
410                                 , SIG_IGN);
411                         signal(SIGCHLD, SIG_DFL);
412
413                         waitfor(pid);
414                         /* See if stealing the controlling tty back is necessary */
415                         if (tcgetpgrp(0) != getpid())
416                                 _exit(0);
417
418                         /* Use a temporary process to steal the controlling tty. */
419                         pid = fork();
420                         if (pid < 0) {
421                                 message(L_LOG | L_CONSOLE, "Can't fork");
422                                 _exit(1);
423                         }
424                         if (pid == 0) {
425                                 setsid();
426                                 ioctl(0, TIOCSCTTY, 1);
427                                 _exit(0);
428                         }
429                         waitfor(pid);
430                         _exit(0);
431                 }
432
433                 /* Child - fall though to actually execute things */
434         }
435 #endif
436
437         /* NB: on NOMMU we can't wait for input in child */
438         if (BB_MMU && (a->action_type & ASKFIRST)) {
439                 static const char press_enter[] ALIGN1 =
440 #ifdef CUSTOMIZED_BANNER
441 #include CUSTOMIZED_BANNER
442 #endif
443                         "\nPlease press Enter to activate this console. ";
444                 char c;
445                 /*
446                  * Save memory by not exec-ing anything large (like a shell)
447                  * before the user wants it. This is critical if swap is not
448                  * enabled and the system has low memory. Generally this will
449                  * be run on the second virtual console, and the first will
450                  * be allowed to start a shell or whatever an init script
451                  * specifies.
452                  */
453                 messageD(L_LOG, "waiting for enter to start '%s'"
454                                         "(pid %d, tty '%s')\n",
455                                 a->command, getpid(), a->terminal);
456                 full_write(1, press_enter, sizeof(press_enter) - 1);
457                 while (safe_read(0, &c, 1) == 1 && c != '\n')
458                         continue;
459         }
460
461         if (ENABLE_FEATURE_INIT_COREDUMPS) {
462                 struct stat sb;
463                 if (stat(CORE_ENABLE_FLAG_FILE, &sb) == 0) {
464                         struct rlimit limit;
465                         limit.rlim_cur = RLIM_INFINITY;
466                         limit.rlim_max = RLIM_INFINITY;
467                         setrlimit(RLIMIT_CORE, &limit);
468                 }
469         }
470
471         /* Log the process name and args */
472         message(L_LOG, "starting pid %d, tty '%s': '%s'",
473                           getpid(), a->terminal, a->command);
474
475         /* Now run it.  The new program will take over this PID,
476          * so nothing further in init.c should be run. */
477         init_exec(a->command);
478         /* We're still here?  Some error happened. */
479         _exit(-1);
480 }
481
482 /* Run all commands of a particular type */
483 static void run_actions(int action_type)
484 {
485         struct init_action *a, *tmp;
486
487         for (a = init_action_list; a; a = tmp) {
488                 tmp = a->next;
489                 if (a->action_type == action_type) {
490                         // Pointless: run() will error out if open of device fails.
491                         ///* a->terminal of "" means "init's console" */
492                         //if (a->terminal[0] && access(a->terminal, R_OK | W_OK)) {
493                         //      //message(L_LOG | L_CONSOLE, "Device %s cannot be opened in RW mode", a->terminal /*, strerror(errno)*/);
494                         //      delete_init_action(a);
495                         //} else
496                         if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
497                                 waitfor(run(a));
498                                 delete_init_action(a);
499                         } else if (a->action_type & ONCE) {
500                                 run(a);
501                                 delete_init_action(a);
502                         } else if (a->action_type & (RESPAWN | ASKFIRST)) {
503                                 /* Only run stuff with pid==0.  If they have
504                                  * a pid, that means it is still running */
505                                 if (a->pid == 0) {
506                                         a->pid = run(a);
507                                 }
508                         }
509                 }
510         }
511 }
512
513 static void init_reboot(unsigned long magic)
514 {
515         pid_t pid;
516         /* We have to fork here, since the kernel calls do_exit(0) in
517          * linux/kernel/sys.c, which can cause the machine to panic when
518          * the init process is killed.... */
519         pid = vfork();
520         if (pid == 0) { /* child */
521                 reboot(magic);
522                 _exit(0);
523         }
524         waitfor(pid);
525 }
526
527 static void kill_all_processes(void)
528 {
529         /* run everything to be run at "shutdown".  This is done _prior_
530          * to killing everything, in case people wish to use scripts to
531          * shut things down gracefully... */
532         run_actions(SHUTDOWN);
533
534         /* first disable all our signals */
535         sigprocmask_allsigs(SIG_BLOCK);
536
537         message(L_CONSOLE | L_LOG, "The system is going down NOW!");
538
539         /* Allow Ctrl-Alt-Del to reboot system. */
540         init_reboot(RB_ENABLE_CAD);
541
542         /* Send signals to every process _except_ pid 1 */
543         message(L_CONSOLE | L_LOG, "Sending SIG%s to all processes", "TERM");
544         kill(-1, SIGTERM);
545         sync();
546         sleep(1);
547
548         message(L_CONSOLE | L_LOG, "Sending SIG%s to all processes", "KILL");
549         kill(-1, SIGKILL);
550         sync();
551         sleep(1);
552 }
553
554 static void halt_reboot_pwoff(int sig)
555 {
556         const char *m;
557         int rb;
558
559         kill_all_processes();
560
561         m = "halt";
562         rb = RB_HALT_SYSTEM;
563         if (sig == SIGTERM) {
564                 m = "reboot";
565                 rb = RB_AUTOBOOT;
566         } else if (sig == SIGUSR2) {
567                 m = "poweroff";
568                 rb = RB_POWER_OFF;
569         }
570         message(L_CONSOLE | L_LOG, "Requesting system %s", m);
571         /* allow time for last message to reach serial console */
572         sleep(2);
573         init_reboot(rb);
574         loop_forever();
575 }
576
577 /* Handler for QUIT - exec "restart" action,
578  * else (no such action defined) do nothing */
579 static void exec_restart_action(int sig ATTRIBUTE_UNUSED)
580 {
581         struct init_action *a;
582
583         for (a = init_action_list; a; a = a->next) {
584                 if (a->action_type & RESTART) {
585                         kill_all_processes();
586
587                         /* unblock all signals (blocked in kill_all_processes()) */
588                         sigprocmask_allsigs(SIG_UNBLOCK);
589
590                         /* Open the new terminal device */
591                         open_stdio_to_tty(a->terminal, 0 /* - halt if open fails */);
592
593                         messageD(L_CONSOLE | L_LOG, "Trying to re-exec %s", a->command);
594                         init_exec(a->command);
595                         sleep(2);
596                         init_reboot(RB_HALT_SYSTEM);
597                         loop_forever();
598                 }
599         }
600 }
601
602 static void ctrlaltdel_signal(int sig ATTRIBUTE_UNUSED)
603 {
604         run_actions(CTRLALTDEL);
605 }
606
607 /* The SIGSTOP & SIGTSTP handler */
608 static void stop_handler(int sig ATTRIBUTE_UNUSED)
609 {
610         int saved_errno = errno;
611
612         got_cont = 0;
613         while (!got_cont)
614                 pause();
615
616         errno = saved_errno;
617 }
618
619 /* The SIGCONT handler */
620 static void cont_handler(int sig ATTRIBUTE_UNUSED)
621 {
622         got_cont = 1;
623 }
624
625 static void new_init_action(uint8_t action_type, const char *command, const char *cons)
626 {
627         struct init_action *a, *last;
628
629 // Why?
630 //      if (strcmp(cons, bb_dev_null) == 0 && (action & ASKFIRST))
631 //              return;
632
633         /* Append to the end of the list */
634         for (a = last = init_action_list; a; a = a->next) {
635                 /* don't enter action if it's already in the list,
636                  * but do overwrite existing actions */
637                 if ((strcmp(a->command, command) == 0)
638                  && (strcmp(a->terminal, cons) == 0)
639                 ) {
640                         a->action_type = action_type;
641                         return;
642                 }
643                 last = a;
644         }
645
646         a = xzalloc(sizeof(*a));
647         if (last) {
648                 last->next = a;
649         } else {
650                 init_action_list = a;
651         }
652         a->action_type = action_type;
653         safe_strncpy(a->command, command, sizeof(a->command));
654         safe_strncpy(a->terminal, cons, sizeof(a->terminal));
655         messageD(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
656                 a->command, a->action_type, a->terminal);
657 }
658
659 static void delete_init_action(struct init_action *action)
660 {
661         struct init_action *a, *b = NULL;
662
663         for (a = init_action_list; a; b = a, a = a->next) {
664                 if (a == action) {
665                         if (b == NULL) {
666                                 init_action_list = a->next;
667                         } else {
668                                 b->next = a->next;
669                         }
670                         free(a);
671                         break;
672                 }
673         }
674 }
675
676 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
677  * then parse_inittab() simply adds in some default
678  * actions(i.e., runs INIT_SCRIPT and then starts a pair
679  * of "askfirst" shells).  If CONFIG_FEATURE_USE_INITTAB
680  * _is_ defined, but /etc/inittab is missing, this
681  * results in the same set of default behaviors.
682  */
683 static void parse_inittab(void)
684 {
685         FILE *file;
686         char buf[COMMAND_SIZE];
687
688         if (ENABLE_FEATURE_USE_INITTAB)
689                 file = fopen(INITTAB, "r");
690         else
691                 file = NULL;
692
693         /* No inittab file -- set up some default behavior */
694         if (file == NULL) {
695                 /* Reboot on Ctrl-Alt-Del */
696                 new_init_action(CTRLALTDEL, "reboot", "");
697                 /* Umount all filesystems on halt/reboot */
698                 new_init_action(SHUTDOWN, "umount -a -r", "");
699                 /* Swapoff on halt/reboot */
700                 if (ENABLE_SWAPONOFF)
701                         new_init_action(SHUTDOWN, "swapoff -a", "");
702                 /* Prepare to restart init when a QUIT is received */
703                 new_init_action(RESTART, "init", "");
704                 /* Askfirst shell on tty1-4 */
705                 new_init_action(ASKFIRST, bb_default_login_shell, "");
706                 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
707                 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
708                 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
709                 /* sysinit */
710                 new_init_action(SYSINIT, INIT_SCRIPT, "");
711
712                 return;
713         }
714
715         while (fgets(buf, COMMAND_SIZE, file) != NULL) {
716                 static const char actions[] =
717                         STR_SYSINIT    "sysinit\0"
718                         STR_RESPAWN    "respawn\0"
719                         STR_ASKFIRST   "askfirst\0"
720                         STR_WAIT       "wait\0"
721                         STR_ONCE       "once\0"
722                         STR_CTRLALTDEL "ctrlaltdel\0"
723                         STR_SHUTDOWN   "shutdown\0"
724                         STR_RESTART    "restart\0"
725                 ;
726                 char tmpConsole[CONSOLE_NAME_SIZE];
727                 char *id, *runlev, *action, *command;
728                 const char *a;
729
730                 /* Skip leading spaces */
731                 id = skip_whitespace(buf);
732                 /* Trim the trailing '\n' */
733                 *strchrnul(id, '\n') = '\0';
734                 /* Skip the line if it is a comment */
735                 if (*id == '#' || *id == '\0')
736                         continue;
737
738                 /* Line is: "id:runlevel_ignored:action:command" */
739                 runlev = strchr(id, ':');
740                 if (runlev == NULL /*|| runlev[1] == '\0' - not needed */)
741                         goto bad_entry;
742                 action = strchr(runlev + 1, ':');
743                 if (action == NULL /*|| action[1] == '\0' - not needed */)
744                         goto bad_entry;
745                 command = strchr(action + 1, ':');
746                 if (command == NULL || command[1] == '\0')
747                         goto bad_entry;
748
749                 *command = '\0'; /* action => ":action\0" now */
750                 for (a = actions; a[0]; a += strlen(a) + 1) {
751                         if (strcmp(a + 1, action + 1) == 0) {
752                                 *runlev = '\0';
753                                 if (*id != '\0') {
754                                         if (strncmp(id, "/dev/", 5) == 0)
755                                                 id += 5;
756                                         strcpy(tmpConsole, "/dev/");
757                                         safe_strncpy(tmpConsole + 5, id,
758                                                 sizeof(tmpConsole) - 5);
759                                         id = tmpConsole;
760                                 }
761                                 new_init_action((uint8_t)a[0], command + 1, id);
762                                 goto next_line;
763                         }
764                 }
765                 *command = ':';
766                 /* Choke on an unknown action */
767  bad_entry:
768                 message(L_LOG | L_CONSOLE, "Bad inittab entry: %s", id);
769  next_line: ;
770         }
771         fclose(file);
772 }
773
774 static void reload_signal(int sig ATTRIBUTE_UNUSED)
775 {
776         struct init_action *a, *tmp;
777
778         message(L_LOG, "reloading /etc/inittab");
779
780         /* disable old entrys */
781         for (a = init_action_list; a; a = a->next) {
782                 a->action_type = ONCE;
783         }
784
785         parse_inittab();
786
787         if (ENABLE_FEATURE_KILL_REMOVED) {
788                 /* Be nice and send SIGTERM first */
789                 for (a = init_action_list; a; a = a->next) {
790                         pid_t pid = a->pid;
791                         if ((a->action_type & ONCE) && pid != 0) {
792                                 kill(pid, SIGTERM);
793                         }
794                 }
795 #if CONFIG_FEATURE_KILL_DELAY
796                 /* NB: parent will wait in NOMMU case */
797                 if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
798                         sleep(CONFIG_FEATURE_KILL_DELAY);
799                         for (a = init_action_list; a; a = a->next) {
800                                 pid_t pid = a->pid;
801                                 if ((a->action_type & ONCE) && pid != 0) {
802                                         kill(pid, SIGKILL);
803                                 }
804                         }
805                         _exit(0);
806                 }
807 #endif
808         }
809
810         /* remove unused entrys */
811         for (a = init_action_list; a; a = tmp) {
812                 tmp = a->next;
813                 if ((a->action_type & (ONCE | SYSINIT | WAIT)) && a->pid == 0) {
814                         delete_init_action(a);
815                 }
816         }
817         run_actions(RESPAWN);
818 }
819
820 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
821 int init_main(int argc ATTRIBUTE_UNUSED, char **argv)
822 {
823         struct init_action *a;
824         pid_t wpid;
825
826         die_sleep = 30 * 24*60*60; /* if xmalloc will ever die... */
827
828         if (argv[1] && !strcmp(argv[1], "-q")) {
829                 return kill(1, SIGHUP);
830         }
831
832         if (!ENABLE_DEBUG_INIT) {
833                 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
834                 if (getpid() != 1
835                  && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
836                 ) {
837                         bb_show_usage();
838                 }
839                 /* Set up sig handlers  -- be sure to
840                  * clear all of these in run() */
841                 signal(SIGQUIT, exec_restart_action);
842                 bb_signals(0
843                         + (1 << SIGUSR1)  /* halt */
844                         + (1 << SIGUSR2)  /* poweroff */
845                         + (1 << SIGTERM)  /* reboot */
846                         , halt_reboot_pwoff);
847                 signal(SIGINT, ctrlaltdel_signal);
848                 signal(SIGCONT, cont_handler);
849                 bb_signals(0
850                         + (1 << SIGSTOP)
851                         + (1 << SIGTSTP)
852                         , stop_handler);
853
854                 /* Turn off rebooting via CTL-ALT-DEL -- we get a
855                  * SIGINT on CAD so we can shut things down gracefully... */
856                 init_reboot(RB_DISABLE_CAD);
857         }
858
859         /* Figure out where the default console should be */
860         console_init();
861         set_sane_term();
862         chdir("/");
863         setsid();
864         {
865                 const char *const *e;
866                 /* Make sure environs is set to something sane */
867                 for (e = environment; *e; e++)
868                         putenv((char *) *e);
869         }
870
871         if (argv[1]) setenv("RUNLEVEL", argv[1], 1);
872
873         /* Hello world */
874         message(MAYBE_CONSOLE | L_LOG, "init started: %s", bb_banner);
875
876         /* Make sure there is enough memory to do something useful. */
877         if (ENABLE_SWAPONOFF) {
878                 struct sysinfo info;
879
880                 if (!sysinfo(&info) &&
881                         (info.mem_unit ? : 1) * (long long)info.totalram < 1024*1024)
882                 {
883                         message(L_CONSOLE, "Low memory, forcing swapon");
884                         /* swapon -a requires /proc typically */
885                         new_init_action(SYSINIT, "mount -t proc proc /proc", "");
886                         /* Try to turn on swap */
887                         new_init_action(SYSINIT, "swapon -a", "");
888                         run_actions(SYSINIT);   /* wait and removing */
889                 }
890         }
891
892         /* Check if we are supposed to be in single user mode */
893         if (argv[1]
894          && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
895         ) {
896                 /* Start a shell on console */
897                 new_init_action(RESPAWN, bb_default_login_shell, "");
898         } else {
899                 /* Not in single user mode -- see what inittab says */
900
901                 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
902                  * then parse_inittab() simply adds in some default
903                  * actions(i.e., runs INIT_SCRIPT and then starts a pair
904                  * of "askfirst" shells */
905                 parse_inittab();
906         }
907
908 #if ENABLE_SELINUX
909         if (getenv("SELINUX_INIT") == NULL) {
910                 int enforce = 0;
911
912                 putenv((char*)"SELINUX_INIT=YES");
913                 if (selinux_init_load_policy(&enforce) == 0) {
914                         BB_EXECVP(argv[0], argv);
915                 } else if (enforce > 0) {
916                         /* SELinux in enforcing mode but load_policy failed */
917                         message(L_CONSOLE, "Cannot load SELinux Policy. "
918                                 "Machine is in enforcing mode. Halting now.");
919                         exit(1);
920                 }
921         }
922 #endif /* CONFIG_SELINUX */
923
924         /* Make the command line just say "init"  - thats all, nothing else */
925         strncpy(argv[0], "init", strlen(argv[0]));
926         /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
927         while (*++argv)
928                 memset(*argv, 0, strlen(*argv));
929
930         /* Now run everything that needs to be run */
931
932         /* First run the sysinit command */
933         run_actions(SYSINIT);
934
935         /* Next run anything that wants to block */
936         run_actions(WAIT);
937
938         /* Next run anything to be run only once */
939         run_actions(ONCE);
940
941         /* Redefine SIGHUP to reread /etc/inittab */
942         if (ENABLE_FEATURE_USE_INITTAB)
943                 signal(SIGHUP, reload_signal);
944         else
945                 signal(SIGHUP, SIG_IGN);
946
947         /* Now run the looping stuff for the rest of forever */
948         while (1) {
949                 /* run the respawn stuff */
950                 run_actions(RESPAWN);
951
952                 /* run the askfirst stuff */
953                 run_actions(ASKFIRST);
954
955                 /* Don't consume all CPU time -- sleep a bit */
956                 sleep(1);
957
958                 /* Wait for any child process to exit */
959                 wpid = wait(NULL);
960                 while (wpid > 0) {
961                         /* Find out who died and clean up their corpse */
962                         for (a = init_action_list; a; a = a->next) {
963                                 if (a->pid == wpid) {
964                                         /* Set the pid to 0 so that the process gets
965                                          * restarted by run_actions() */
966                                         a->pid = 0;
967                                         message(L_LOG, "process '%s' (pid %d) exited. "
968                                                         "Scheduling for restart.",
969                                                         a->command, wpid);
970                                 }
971                         }
972                         /* see if anyone else is waiting to be reaped */
973                         wpid = wait_any_nohang(NULL);
974                 }
975         }
976 }