init: fix logically inverted FEATURE_EXTRA_QUIET check
[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 #include <sys/resource.h>
17 #include <linux/vt.h>
18
19
20 /* Was a CONFIG_xxx option. A lot of people were building
21  * not fully functional init by switching it on! */
22 #define DEBUG_INIT 0
23
24 #define COMMAND_SIZE      256
25 #define CONSOLE_NAME_SIZE 32
26
27 /* Default sysinit script. */
28 #ifndef INIT_SCRIPT
29 #define INIT_SCRIPT  "/etc/init.d/rcS"
30 #endif
31
32 /* Each type of actions can appear many times. They will be
33  * handled in order. RESTART is an exception, only 1st is used.
34  */
35 /* Start these actions first and wait for completion */
36 #define SYSINIT     0x01
37 /* Start these after SYSINIT and wait for completion */
38 #define WAIT        0x02
39 /* Start these after WAIT and *dont* wait for completion */
40 #define ONCE        0x04
41 /*
42  * NB: while SYSINIT/WAIT/ONCE are being processed,
43  * SIGHUP ("reread /etc/inittab") will be processed only after
44  * each group of actions. If new inittab adds, say, a SYSINIT action,
45  * it will not be run, since init is already "past SYSINIT stage".
46  */
47 /* Start these after ONCE are started, restart on exit */
48 #define RESPAWN     0x08
49 /* Like RESPAWN, but wait for <Enter> to be pressed on tty */
50 #define ASKFIRST    0x10
51 /*
52  * Start these on SIGINT, and wait for completion.
53  * Then go back to respawning RESPAWN and ASKFIRST actions.
54  * NB: kernel sends SIGINT to us if Ctrl-Alt-Del was pressed.
55  */
56 #define CTRLALTDEL  0x20
57 /*
58  * Start these before killing all processes in preparation for
59  * running RESTART actions or doing low-level halt/reboot/poweroff
60  * (initiated by SIGUSR1/SIGTERM/SIGUSR2).
61  * Wait for completion before proceeding.
62  */
63 #define SHUTDOWN    0x40
64 /*
65  * exec() on SIGQUIT. SHUTDOWN actions are started and waited for,
66  * then all processes are killed, then init exec's 1st RESTART action,
67  * replacing itself by it. If no RESTART action specified,
68  * SIGQUIT has no effect.
69  */
70 #define RESTART     0x80
71
72
73 /* A linked list of init_actions, to be read from inittab */
74 struct init_action {
75         struct init_action *next;
76         pid_t pid;
77         uint8_t action_type;
78         char terminal[CONSOLE_NAME_SIZE];
79         char command[COMMAND_SIZE];
80 };
81
82 static struct init_action *init_action_list = NULL;
83
84 static const char *log_console = VC_5;
85
86 enum {
87         L_LOG = 0x1,
88         L_CONSOLE = 0x2,
89 #ifndef RB_HALT_SYSTEM
90         RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
91         RB_ENABLE_CAD = 0x89abcdef,
92         RB_DISABLE_CAD = 0,
93         RB_POWER_OFF = 0x4321fedc,
94         RB_AUTOBOOT = 0x01234567,
95 #endif
96 };
97
98 /* Print a message to the specified device.
99  * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
100  * NB: careful, we can be called after vfork!
101  */
102 #define dbg_message(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
103 static void message(int where, const char *fmt, ...)
104         __attribute__ ((format(printf, 2, 3)));
105 static void message(int where, const char *fmt, ...)
106 {
107         va_list arguments;
108         unsigned l;
109         char msg[128];
110
111         msg[0] = '\r';
112         va_start(arguments, fmt);
113         l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
114         if (l > sizeof(msg) - 1)
115                 l = sizeof(msg) - 1;
116         va_end(arguments);
117
118 #if ENABLE_FEATURE_INIT_SYSLOG
119         msg[l] = '\0';
120         if (where & L_LOG) {
121                 /* Log the message to syslogd */
122                 openlog(applet_name, 0, LOG_DAEMON);
123                 /* don't print "\r" */
124                 syslog(LOG_INFO, "%s", msg + 1);
125                 closelog();
126         }
127         msg[l++] = '\n';
128         msg[l] = '\0';
129 #else
130         {
131                 static int log_fd = -1;
132
133                 msg[l++] = '\n';
134                 msg[l] = '\0';
135                 /* Take full control of the log tty, and never close it.
136                  * It's mine, all mine!  Muhahahaha! */
137                 if (log_fd < 0) {
138                         if (!log_console) {
139                                 log_fd = STDERR_FILENO;
140                         } else {
141                                 log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
142                                 if (log_fd < 0) {
143                                         bb_error_msg("can't log to %s", log_console);
144                                         where = L_CONSOLE;
145                                 } else {
146                                         close_on_exec_on(log_fd);
147                                 }
148                         }
149                 }
150                 if (where & L_LOG) {
151                         full_write(log_fd, msg, l);
152                         if (log_fd == STDERR_FILENO)
153                                 return; /* don't print dup messages */
154                 }
155         }
156 #endif
157
158         if (where & L_CONSOLE) {
159                 /* Send console messages to console so people will see them. */
160                 full_write(STDERR_FILENO, msg, l);
161         }
162 }
163
164 static void console_init(void)
165 {
166         int vtno;
167         char *s;
168
169         s = getenv("CONSOLE");
170         if (!s)
171                 s = getenv("console");
172         if (s) {
173                 int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
174                 if (fd >= 0) {
175                         dup2(fd, STDIN_FILENO);
176                         dup2(fd, STDOUT_FILENO);
177                         xmove_fd(fd, STDERR_FILENO);
178                 }
179                 dbg_message(L_LOG, "console='%s'", s);
180         } else {
181                 /* Make sure fd 0,1,2 are not closed
182                  * (so that they won't be used by future opens) */
183                 bb_sanitize_stdio();
184 // Users report problems
185 //              /* Make sure init can't be blocked by writing to stderr */
186 //              fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
187         }
188
189         s = getenv("TERM");
190         if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
191                 /* Not a linux terminal, probably serial console.
192                  * Force the TERM setting to vt102
193                  * if TERM is set to linux (the default) */
194                 if (!s || strcmp(s, "linux") == 0)
195                         putenv((char*)"TERM=vt102");
196                 if (!ENABLE_FEATURE_INIT_SYSLOG)
197                         log_console = NULL;
198         } else if (!s)
199                 putenv((char*)"TERM=linux");
200 }
201
202 /* Set terminal settings to reasonable defaults.
203  * NB: careful, we can be called after vfork! */
204 static void set_sane_term(void)
205 {
206         struct termios tty;
207
208         tcgetattr(STDIN_FILENO, &tty);
209
210         /* set control chars */
211         tty.c_cc[VINTR] = 3;    /* C-c */
212         tty.c_cc[VQUIT] = 28;   /* C-\ */
213         tty.c_cc[VERASE] = 127; /* C-? */
214         tty.c_cc[VKILL] = 21;   /* C-u */
215         tty.c_cc[VEOF] = 4;     /* C-d */
216         tty.c_cc[VSTART] = 17;  /* C-q */
217         tty.c_cc[VSTOP] = 19;   /* C-s */
218         tty.c_cc[VSUSP] = 26;   /* C-z */
219
220         /* use line discipline 0 */
221         tty.c_line = 0;
222
223         /* Make it be sane */
224         tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
225         tty.c_cflag |= CREAD | HUPCL | CLOCAL;
226
227         /* input modes */
228         tty.c_iflag = ICRNL | IXON | IXOFF;
229
230         /* output modes */
231         tty.c_oflag = OPOST | ONLCR;
232
233         /* local modes */
234         tty.c_lflag =
235                 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
236
237         tcsetattr_stdin_TCSANOW(&tty);
238 }
239
240 /* Open the new terminal device.
241  * NB: careful, we can be called after vfork! */
242 static int open_stdio_to_tty(const char* tty_name)
243 {
244         /* empty tty_name means "use init's tty", else... */
245         if (tty_name[0]) {
246                 int fd;
247
248                 close(STDIN_FILENO);
249                 /* fd can be only < 0 or 0: */
250                 fd = device_open(tty_name, O_RDWR);
251                 if (fd) {
252                         message(L_LOG | L_CONSOLE, "can't open %s: %s",
253                                 tty_name, strerror(errno));
254                         return 0; /* failure */
255                 }
256                 dup2(STDIN_FILENO, STDOUT_FILENO);
257                 dup2(STDIN_FILENO, STDERR_FILENO);
258         }
259         set_sane_term();
260         return 1; /* success */
261 }
262
263 static void reset_sighandlers_and_unblock_sigs(void)
264 {
265         bb_signals(0
266                 + (1 << SIGUSR1)
267                 + (1 << SIGUSR2)
268                 + (1 << SIGTERM)
269                 + (1 << SIGQUIT)
270                 + (1 << SIGINT)
271                 + (1 << SIGHUP)
272                 + (1 << SIGTSTP)
273                 + (1 << SIGSTOP)
274                 , SIG_DFL);
275         sigprocmask_allsigs(SIG_UNBLOCK);
276 }
277
278 /* Wrapper around exec:
279  * Takes string (max COMMAND_SIZE chars).
280  * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
281  * Otherwise splits words on whitespace, deals with leading dash,
282  * and uses plain exec().
283  * NB: careful, we can be called after vfork!
284  */
285 static void init_exec(const char *command)
286 {
287         char *cmd[COMMAND_SIZE / 2];
288         char buf[COMMAND_SIZE + 6];  /* COMMAND_SIZE+strlen("exec ")+1 */
289         int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
290
291         /* See if any special /bin/sh requiring characters are present */
292         if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
293                 strcpy(buf, "exec ");
294                 strcpy(buf + 5, command + dash); /* excluding "-" */
295                 /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
296                 cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
297                 cmd[1] = (char*)"-c";
298                 cmd[2] = buf;
299                 cmd[3] = NULL;
300         } else {
301                 /* Convert command (char*) into cmd (char**, one word per string) */
302                 char *word, *next;
303                 int i = 0;
304                 next = strcpy(buf, command); /* including "-" */
305                 while ((word = strsep(&next, " \t")) != NULL) {
306                         if (*word != '\0') { /* not two spaces/tabs together? */
307                                 cmd[i] = word;
308                                 i++;
309                         }
310                 }
311                 cmd[i] = NULL;
312         }
313         /* If we saw leading "-", it is interactive shell.
314          * Try harder to give it a controlling tty.
315          * And skip "-" in actual exec call. */
316         if (dash) {
317                 /* _Attempt_ to make stdin a controlling tty. */
318                 if (ENABLE_FEATURE_INIT_SCTTY)
319                         ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
320         }
321         BB_EXECVP(cmd[0] + dash, cmd);
322         message(L_LOG | L_CONSOLE, "can't run '%s': %s", cmd[0], strerror(errno));
323         /* returns if execvp fails */
324 }
325
326 /* Used only by run_actions */
327 static pid_t run(const struct init_action *a)
328 {
329         pid_t pid;
330
331         /* Careful: don't be affected by a signal in vforked child */
332         sigprocmask_allsigs(SIG_BLOCK);
333         if (BB_MMU && (a->action_type & ASKFIRST))
334                 pid = fork();
335         else
336                 pid = vfork();
337         if (pid < 0)
338                 message(L_LOG | L_CONSOLE, "can't fork");
339         if (pid) {
340                 sigprocmask_allsigs(SIG_UNBLOCK);
341                 return pid; /* Parent or error */
342         }
343
344         /* Child */
345
346         /* Reset signal handlers that were set by the parent process */
347         reset_sighandlers_and_unblock_sigs();
348
349         /* Create a new session and make ourself the process group leader */
350         setsid();
351
352         /* Open the new terminal device */
353         if (!open_stdio_to_tty(a->terminal))
354                 _exit(EXIT_FAILURE);
355
356         /* NB: on NOMMU we can't wait for input in child, so
357          * "askfirst" will work the same as "respawn". */
358         if (BB_MMU && (a->action_type & ASKFIRST)) {
359                 static const char press_enter[] ALIGN1 =
360 #ifdef CUSTOMIZED_BANNER
361 #include CUSTOMIZED_BANNER
362 #endif
363                         "\nPlease press Enter to activate this console. ";
364                 char c;
365                 /*
366                  * Save memory by not exec-ing anything large (like a shell)
367                  * before the user wants it. This is critical if swap is not
368                  * enabled and the system has low memory. Generally this will
369                  * be run on the second virtual console, and the first will
370                  * be allowed to start a shell or whatever an init script
371                  * specifies.
372                  */
373                 dbg_message(L_LOG, "waiting for enter to start '%s'"
374                                         "(pid %d, tty '%s')\n",
375                                 a->command, getpid(), a->terminal);
376                 full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
377                 while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
378                         continue;
379         }
380
381         /*
382          * When a file named /.init_enable_core exists, setrlimit is called
383          * before processes are spawned to set core file size as unlimited.
384          * This is for debugging only.  Don't use this is production, unless
385          * you want core dumps lying about....
386          */
387         if (ENABLE_FEATURE_INIT_COREDUMPS) {
388                 if (access("/.init_enable_core", F_OK) == 0) {
389                         struct rlimit limit;
390                         limit.rlim_cur = RLIM_INFINITY;
391                         limit.rlim_max = RLIM_INFINITY;
392                         setrlimit(RLIMIT_CORE, &limit);
393                 }
394         }
395
396         /* Log the process name and args */
397         message(L_LOG, "starting pid %d, tty '%s': '%s'",
398                           getpid(), a->terminal, a->command);
399
400         /* Now run it.  The new program will take over this PID,
401          * so nothing further in init.c should be run. */
402         init_exec(a->command);
403         /* We're still here?  Some error happened. */
404         _exit(-1);
405 }
406
407 static struct init_action *mark_terminated(pid_t pid)
408 {
409         struct init_action *a;
410
411         if (pid > 0) {
412                 for (a = init_action_list; a; a = a->next) {
413                         if (a->pid == pid) {
414                                 a->pid = 0;
415                                 return a;
416                         }
417                 }
418         }
419         return NULL;
420 }
421
422 static void waitfor(pid_t pid)
423 {
424         /* waitfor(run(x)): protect against failed fork inside run() */
425         if (pid <= 0)
426                 return;
427
428         /* Wait for any child (prevent zombies from exiting orphaned processes)
429          * but exit the loop only when specified one has exited. */
430         while (1) {
431                 pid_t wpid = wait(NULL);
432                 mark_terminated(wpid);
433                 /* Unsafe. SIGTSTP handler might have wait'ed it already */
434                 /*if (wpid == pid) break;*/
435                 /* More reliable: */
436                 if (kill(pid, 0))
437                         break;
438         }
439 }
440
441 /* Run all commands of a particular type */
442 static void run_actions(int action_type)
443 {
444         struct init_action *a;
445
446         for (a = init_action_list; a; a = a->next) {
447                 if (!(a->action_type & action_type))
448                         continue;
449
450                 if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
451                         pid_t pid = run(a);
452                         if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
453                                 waitfor(pid);
454                 }
455                 if (a->action_type & (RESPAWN | ASKFIRST)) {
456                         /* Only run stuff with pid == 0. If pid != 0,
457                          * it is already running
458                          */
459                         if (a->pid == 0)
460                                 a->pid = run(a);
461                 }
462         }
463 }
464
465 static void new_init_action(uint8_t action_type, const char *command, const char *cons)
466 {
467         struct init_action *a, **nextp;
468
469         /* Scenario:
470          * old inittab:
471          * ::shutdown:umount -a -r
472          * ::shutdown:swapoff -a
473          * new inittab:
474          * ::shutdown:swapoff -a
475          * ::shutdown:umount -a -r
476          * On reload, we must ensure entries end up in correct order.
477          * To achieve that, if we find a matching entry, we move it
478          * to the end.
479          */
480         nextp = &init_action_list;
481         while ((a = *nextp) != NULL) {
482                 /* Don't enter action if it's already in the list,
483                  * This prevents losing running RESPAWNs.
484                  */
485                 if (strcmp(a->command, command) == 0
486                  && strcmp(a->terminal, cons) == 0
487                 ) {
488                         /* Remove from list */
489                         *nextp = a->next;
490                         /* Find the end of the list */
491                         while (*nextp != NULL)
492                                 nextp = &(*nextp)->next;
493                         a->next = NULL;
494                         break;
495                 }
496                 nextp = &a->next;
497         }
498
499         if (!a)
500                 a = xzalloc(sizeof(*a));
501         /* Append to the end of the list */
502         *nextp = a;
503         a->action_type = action_type;
504         safe_strncpy(a->command, command, sizeof(a->command));
505         safe_strncpy(a->terminal, cons, sizeof(a->terminal));
506         dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
507                 a->command, a->action_type, a->terminal);
508 }
509
510 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
511  * then parse_inittab() simply adds in some default
512  * actions(i.e., runs INIT_SCRIPT and then starts a pair
513  * of "askfirst" shells).  If CONFIG_FEATURE_USE_INITTAB
514  * _is_ defined, but /etc/inittab is missing, this
515  * results in the same set of default behaviors.
516  */
517 static void parse_inittab(void)
518 {
519 #if ENABLE_FEATURE_USE_INITTAB
520         char *token[4];
521         parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
522
523         if (parser == NULL)
524 #endif
525         {
526                 /* No inittab file - set up some default behavior */
527                 /* Reboot on Ctrl-Alt-Del */
528                 new_init_action(CTRLALTDEL, "reboot", "");
529                 /* Umount all filesystems on halt/reboot */
530                 new_init_action(SHUTDOWN, "umount -a -r", "");
531                 /* Swapoff on halt/reboot */
532                 if (ENABLE_SWAPONOFF)
533                         new_init_action(SHUTDOWN, "swapoff -a", "");
534                 /* Prepare to restart init when a QUIT is received */
535                 new_init_action(RESTART, "init", "");
536                 /* Askfirst shell on tty1-4 */
537                 new_init_action(ASKFIRST, bb_default_login_shell, "");
538 //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
539                 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
540                 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
541                 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
542                 /* sysinit */
543                 new_init_action(SYSINIT, INIT_SCRIPT, "");
544                 return;
545         }
546
547 #if ENABLE_FEATURE_USE_INITTAB
548         /* optional_tty:ignored_runlevel:action:command
549          * Delims are not to be collapsed and need exactly 4 tokens
550          */
551         while (config_read(parser, token, 4, 0, "#:",
552                                 PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
553                 /* order must correspond to SYSINIT..RESTART constants */
554                 static const char actions[] ALIGN1 =
555                         "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
556                         "ctrlaltdel\0""shutdown\0""restart\0";
557                 int action;
558                 char *tty = token[0];
559
560                 if (!token[3]) /* less than 4 tokens */
561                         goto bad_entry;
562                 action = index_in_strings(actions, token[2]);
563                 if (action < 0 || !token[3][0]) /* token[3]: command */
564                         goto bad_entry;
565                 /* turn .*TTY -> /dev/TTY */
566                 if (tty[0]) {
567                         if (strncmp(tty, "/dev/", 5) == 0)
568                                 tty += 5;
569                         tty = concat_path_file("/dev/", tty);
570                 }
571                 new_init_action(1 << action, token[3], tty);
572                 if (tty[0])
573                         free(tty);
574                 continue;
575  bad_entry:
576                 message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
577                                 parser->lineno);
578         }
579         config_close(parser);
580 #endif
581 }
582
583 static void pause_and_low_level_reboot(unsigned magic) NORETURN;
584 static void pause_and_low_level_reboot(unsigned magic)
585 {
586         pid_t pid;
587
588         /* Allow time for last message to reach serial console, etc */
589         sleep(1);
590
591         /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
592          * in linux/kernel/sys.c, which can cause the machine to panic when
593          * the init process exits... */
594         pid = vfork();
595         if (pid == 0) { /* child */
596                 reboot(magic);
597                 _exit(EXIT_SUCCESS);
598         }
599         while (1)
600                 sleep(1);
601 }
602
603 static void run_shutdown_and_kill_processes(void)
604 {
605         /* Run everything to be run at "shutdown".  This is done _prior_
606          * to killing everything, in case people wish to use scripts to
607          * shut things down gracefully... */
608         run_actions(SHUTDOWN);
609
610         message(L_CONSOLE | L_LOG, "The system is going down NOW!");
611
612         /* Send signals to every process _except_ pid 1 */
613         kill(-1, SIGTERM);
614         message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
615         sync();
616         sleep(1);
617
618         kill(-1, SIGKILL);
619         message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
620         sync();
621         /*sleep(1); - callers take care about making a pause */
622 }
623
624 /* Signal handling by init:
625  *
626  * For process with PID==1, on entry kernel sets all signals to SIG_DFL
627  * and unmasks all signals. However, for process with PID==1,
628  * default action (SIG_DFL) on any signal is to ignore it,
629  * even for special signals SIGKILL and SIGCONT.
630  * Also, any signal can be caught or blocked.
631  * (but SIGSTOP is still handled specially, at least in 2.6.20)
632  *
633  * We install two kinds of handlers, "immediate" and "delayed".
634  *
635  * Immediate handlers execute at any time, even while, say, sysinit
636  * is running.
637  *
638  * Delayed handlers just set a flag variable. The variable is checked
639  * in the main loop and acted upon.
640  *
641  * halt/poweroff/reboot and restart have immediate handlers.
642  * They only traverse linked list of struct action's, never modify it,
643  * this should be safe to do even in signal handler. Also they
644  * never return.
645  *
646  * SIGSTOP and SIGTSTP have immediate handlers. They just wait
647  * for SIGCONT to happen.
648  *
649  * SIGHUP has a delayed handler, because modifying linked list
650  * of struct action's from a signal handler while it is manipulated
651  * by the program may be disastrous.
652  *
653  * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
654  * it to happen even somewhere inside "sysinit" would be a bit awkward.
655  *
656  * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
657  * and only one will be remembered and acted upon.
658  */
659
660 /* The SIGUSR[12]/SIGTERM handler */
661 static void halt_reboot_pwoff(int sig) NORETURN;
662 static void halt_reboot_pwoff(int sig)
663 {
664         const char *m;
665         unsigned rb;
666
667         /* We may call run() and it unmasks signals,
668          * including the one masked inside this signal handler.
669          * Testcase which would start multiple reboot scripts:
670          *  while true; do reboot; done
671          * Preventing it:
672          */
673         reset_sighandlers_and_unblock_sigs();
674
675         run_shutdown_and_kill_processes();
676
677         m = "halt";
678         rb = RB_HALT_SYSTEM;
679         if (sig == SIGTERM) {
680                 m = "reboot";
681                 rb = RB_AUTOBOOT;
682         } else if (sig == SIGUSR2) {
683                 m = "poweroff";
684                 rb = RB_POWER_OFF;
685         }
686         message(L_CONSOLE, "Requesting system %s", m);
687         pause_and_low_level_reboot(rb);
688         /* not reached */
689 }
690
691 /* Handler for QUIT - exec "restart" action,
692  * else (no such action defined) do nothing */
693 static void restart_handler(int sig UNUSED_PARAM)
694 {
695         struct init_action *a;
696
697         for (a = init_action_list; a; a = a->next) {
698                 if (!(a->action_type & RESTART))
699                         continue;
700
701                 /* Starting from here, we won't return.
702                  * Thus don't need to worry about preserving errno
703                  * and such.
704                  */
705
706                 reset_sighandlers_and_unblock_sigs();
707
708                 run_shutdown_and_kill_processes();
709
710                 /* Allow Ctrl-Alt-Del to reboot the system.
711                  * This is how kernel sets it up for init, we follow suit.
712                  */
713                 reboot(RB_ENABLE_CAD); /* misnomer */
714
715                 if (open_stdio_to_tty(a->terminal)) {
716                         dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
717                         /* Theoretically should be safe.
718                          * But in practice, kernel bugs may leave
719                          * unkillable processes, and wait() may block forever.
720                          * Oh well. Hoping "new" init won't be too surprised
721                          * by having children it didn't create.
722                          */
723                         //while (wait(NULL) > 0)
724                         //      continue;
725                         init_exec(a->command);
726                 }
727                 /* Open or exec failed */
728                 pause_and_low_level_reboot(RB_HALT_SYSTEM);
729                 /* not reached */
730         }
731 }
732
733 /* The SIGSTOP/SIGTSTP handler
734  * NB: inside it, all signals except SIGCONT are masked
735  * via appropriate setup in sigaction().
736  */
737 static void stop_handler(int sig UNUSED_PARAM)
738 {
739         smallint saved_bb_got_signal;
740         int saved_errno;
741
742         saved_bb_got_signal = bb_got_signal;
743         saved_errno = errno;
744         signal(SIGCONT, record_signo);
745
746         while (1) {
747                 pid_t wpid;
748
749                 if (bb_got_signal == SIGCONT)
750                         break;
751                 /* NB: this can accidentally wait() for a process
752                  * which we waitfor() elsewhere! waitfor() must have
753                  * code which is resilient against this.
754                  */
755                 wpid = wait_any_nohang(NULL);
756                 mark_terminated(wpid);
757                 sleep(1);
758         }
759
760         signal(SIGCONT, SIG_DFL);
761         errno = saved_errno;
762         bb_got_signal = saved_bb_got_signal;
763 }
764
765 #if ENABLE_FEATURE_USE_INITTAB
766 static void reload_inittab(void)
767 {
768         struct init_action *a, **nextp;
769
770         message(L_LOG, "reloading /etc/inittab");
771
772         /* Disable old entries */
773         for (a = init_action_list; a; a = a->next)
774                 a->action_type = 0;
775
776         /* Append new entries, or modify existing entries
777          * (incl. setting a->action_type) if cmd and device name
778          * match new ones. End result: only entries with
779          * a->action_type == 0 are stale.
780          */
781         parse_inittab();
782
783 #if ENABLE_FEATURE_KILL_REMOVED
784         /* Kill stale entries */
785         /* Be nice and send SIGTERM first */
786         for (a = init_action_list; a; a = a->next)
787                 if (a->action_type == 0 && a->pid != 0)
788                         kill(a->pid, SIGTERM);
789         if (CONFIG_FEATURE_KILL_DELAY) {
790                 /* NB: parent will wait in NOMMU case */
791                 if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
792                         sleep(CONFIG_FEATURE_KILL_DELAY);
793                         for (a = init_action_list; a; a = a->next)
794                                 if (a->action_type == 0 && a->pid != 0)
795                                         kill(a->pid, SIGKILL);
796                         _exit(EXIT_SUCCESS);
797                 }
798         }
799 #endif
800
801         /* Remove stale entries and SYSINIT entries.
802          * We never rerun SYSINIT entries anyway,
803          * removing them too saves a few bytes */
804         nextp = &init_action_list;
805         while ((a = *nextp) != NULL) {
806                 if ((a->action_type & ~SYSINIT) == 0) {
807                         *nextp = a->next;
808                         free(a);
809                 } else {
810                         nextp = &a->next;
811                 }
812         }
813
814         /* Not needed: */
815         /* run_actions(RESPAWN | ASKFIRST); */
816         /* - we return to main loop, which does this automagically */
817 }
818 #endif
819
820 static int check_delayed_sigs(void)
821 {
822         int sigs_seen = 0;
823
824         while (1) {
825                 smallint sig = bb_got_signal;
826
827                 if (!sig)
828                         return sigs_seen;
829                 bb_got_signal = 0;
830                 sigs_seen = 1;
831 #if ENABLE_FEATURE_USE_INITTAB
832                 if (sig == SIGHUP)
833                         reload_inittab();
834 #endif
835                 if (sig == SIGINT)
836                         run_actions(CTRLALTDEL);
837         }
838 }
839
840 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
841 int init_main(int argc UNUSED_PARAM, char **argv)
842 {
843         die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
844
845         if (argv[1] && strcmp(argv[1], "-q") == 0) {
846                 return kill(1, SIGHUP);
847         }
848
849         if (!DEBUG_INIT) {
850                 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
851                 if (getpid() != 1
852                  && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
853                 ) {
854                         bb_show_usage();
855                 }
856                 /* Turn off rebooting via CTL-ALT-DEL - we get a
857                  * SIGINT on CAD so we can shut things down gracefully... */
858                 reboot(RB_DISABLE_CAD); /* misnomer */
859         }
860
861         /* Figure out where the default console should be */
862         console_init();
863         set_sane_term();
864         xchdir("/");
865         setsid();
866
867         /* Make sure environs is set to something sane */
868         putenv((char *) "HOME=/");
869         putenv((char *) bb_PATH_root_path);
870         putenv((char *) "SHELL=/bin/sh");
871         putenv((char *) "USER=root"); /* needed? why? */
872
873         if (argv[1])
874                 xsetenv("RUNLEVEL", argv[1]);
875
876 #if !ENABLE_FEATURE_EXTRA_QUIET
877         /* Hello world */
878         message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
879 #endif
880
881         /* Make sure there is enough memory to do something useful. */
882         if (ENABLE_SWAPONOFF) {
883                 struct sysinfo info;
884
885                 if (sysinfo(&info) == 0
886                  && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
887                 ) {
888                         message(L_CONSOLE, "Low memory, forcing swapon");
889                         /* swapon -a requires /proc typically */
890                         new_init_action(SYSINIT, "mount -t proc proc /proc", "");
891                         /* Try to turn on swap */
892                         new_init_action(SYSINIT, "swapon -a", "");
893                         run_actions(SYSINIT);   /* wait and removing */
894                 }
895         }
896
897         /* Check if we are supposed to be in single user mode */
898         if (argv[1]
899          && (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "-s") == 0 || LONE_CHAR(argv[1], '1'))
900         ) {
901                 /* ??? shouldn't we set RUNLEVEL="b" here? */
902                 /* Start a shell on console */
903                 new_init_action(RESPAWN, bb_default_login_shell, "");
904         } else {
905                 /* Not in single user mode - see what inittab says */
906
907                 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
908                  * then parse_inittab() simply adds in some default
909                  * actions(i.e., INIT_SCRIPT and a pair
910                  * of "askfirst" shells */
911                 parse_inittab();
912         }
913
914 #if ENABLE_SELINUX
915         if (getenv("SELINUX_INIT") == NULL) {
916                 int enforce = 0;
917
918                 putenv((char*)"SELINUX_INIT=YES");
919                 if (selinux_init_load_policy(&enforce) == 0) {
920                         BB_EXECVP(argv[0], argv);
921                 } else if (enforce > 0) {
922                         /* SELinux in enforcing mode but load_policy failed */
923                         message(L_CONSOLE, "can't load SELinux Policy. "
924                                 "Machine is in enforcing mode. Halting now.");
925                         exit(EXIT_FAILURE);
926                 }
927         }
928 #endif
929
930         /* Make the command line just say "init"  - thats all, nothing else */
931         strncpy(argv[0], "init", strlen(argv[0]));
932         /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
933         while (*++argv)
934                 memset(*argv, 0, strlen(*argv));
935
936         /* Set up signal handlers */
937         if (!DEBUG_INIT) {
938                 struct sigaction sa;
939
940                 bb_signals(0
941                         + (1 << SIGUSR1) /* halt */
942                         + (1 << SIGTERM) /* reboot */
943                         + (1 << SIGUSR2) /* poweroff */
944                         , halt_reboot_pwoff);
945                 signal(SIGQUIT, restart_handler); /* re-exec another init */
946
947                 /* Stop handler must allow only SIGCONT inside itself */
948                 memset(&sa, 0, sizeof(sa));
949                 sigfillset(&sa.sa_mask);
950                 sigdelset(&sa.sa_mask, SIGCONT);
951                 sa.sa_handler = stop_handler;
952                 /* NB: sa_flags doesn't have SA_RESTART.
953                  * It must be able to interrupt wait().
954                  */
955                 sigaction_set(SIGTSTP, &sa); /* pause */
956                 /* Does not work as intended, at least in 2.6.20.
957                  * SIGSTOP is simply ignored by init:
958                  */
959                 sigaction_set(SIGSTOP, &sa); /* pause */
960
961                 /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),
962                  * setting handler without SA_RESTART flag.
963                  */
964                 bb_signals_recursive_norestart((1 << SIGINT), record_signo);
965         }
966
967         /* Set up "reread /etc/inittab" handler.
968          * Handler is set up without SA_RESTART, it will interrupt syscalls.
969          */
970         if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
971                 bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
972
973         /* Now run everything that needs to be run */
974         /* First run the sysinit command */
975         run_actions(SYSINIT);
976         check_delayed_sigs();
977         /* Next run anything that wants to block */
978         run_actions(WAIT);
979         check_delayed_sigs();
980         /* Next run anything to be run only once */
981         run_actions(ONCE);
982
983         /* Now run the looping stuff for the rest of forever.
984          */
985         while (1) {
986                 int maybe_WNOHANG;
987
988                 maybe_WNOHANG = check_delayed_sigs();
989
990                 /* (Re)run the respawn/askfirst stuff */
991                 run_actions(RESPAWN | ASKFIRST);
992                 maybe_WNOHANG |= check_delayed_sigs();
993
994                 /* Don't consume all CPU time - sleep a bit */
995                 sleep(1);
996                 maybe_WNOHANG |= check_delayed_sigs();
997
998                 /* Wait for any child process(es) to exit.
999                  *
1000                  * If check_delayed_sigs above reported that a signal
1001                  * was caught, wait will be nonblocking. This ensures
1002                  * that if SIGHUP has reloaded inittab, respawn and askfirst
1003                  * actions will not be delayed until next child death.
1004                  */
1005                 if (maybe_WNOHANG)
1006                         maybe_WNOHANG = WNOHANG;
1007                 while (1) {
1008                         pid_t wpid;
1009                         struct init_action *a;
1010
1011                         /* If signals happen _in_ the wait, they interrupt it,
1012                          * bb_signals_recursive_norestart set them up that way
1013                          */
1014                         wpid = waitpid(-1, NULL, maybe_WNOHANG);
1015                         if (wpid <= 0)
1016                                 break;
1017
1018                         a = mark_terminated(wpid);
1019                         if (a) {
1020                                 message(L_LOG, "process '%s' (pid %d) exited. "
1021                                                 "Scheduling for restart.",
1022                                                 a->command, wpid);
1023                         }
1024                         /* See if anyone else is waiting to be reaped */
1025                         maybe_WNOHANG = WNOHANG;
1026                 }
1027         } /* while (1) */
1028 }