init: fix "while true; do reboot; done" bug. +15 bytes. Closes bug 781
[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("init", 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                 , SIG_DFL);
274         sigprocmask_allsigs(SIG_UNBLOCK);
275 }
276
277 /* Wrapper around exec:
278  * Takes string (max COMMAND_SIZE chars).
279  * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
280  * Otherwise splits words on whitespace, deals with leading dash,
281  * and uses plain exec().
282  * NB: careful, we can be called after vfork!
283  */
284 static void init_exec(const char *command)
285 {
286         char *cmd[COMMAND_SIZE / 2];
287         char buf[COMMAND_SIZE + 6];  /* COMMAND_SIZE+strlen("exec ")+1 */
288         int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
289
290         /* See if any special /bin/sh requiring characters are present */
291         if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
292                 strcpy(buf, "exec ");
293                 strcpy(buf + 5, command + dash); /* excluding "-" */
294                 /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
295                 cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
296                 cmd[1] = (char*)"-c";
297                 cmd[2] = buf;
298                 cmd[3] = NULL;
299         } else {
300                 /* Convert command (char*) into cmd (char**, one word per string) */
301                 char *word, *next;
302                 int i = 0;
303                 next = strcpy(buf, command); /* including "-" */
304                 while ((word = strsep(&next, " \t")) != NULL) {
305                         if (*word != '\0') { /* not two spaces/tabs together? */
306                                 cmd[i] = word;
307                                 i++;
308                         }
309                 }
310                 cmd[i] = NULL;
311         }
312         /* If we saw leading "-", it is interactive shell.
313          * Try harder to give it a controlling tty.
314          * And skip "-" in actual exec call. */
315         if (dash) {
316                 /* _Attempt_ to make stdin a controlling tty. */
317                 if (ENABLE_FEATURE_INIT_SCTTY)
318                         ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
319         }
320         BB_EXECVP(cmd[0] + dash, cmd);
321         message(L_LOG | L_CONSOLE, "can't run '%s': %s", cmd[0], strerror(errno));
322         /* returns if execvp fails */
323 }
324
325 /* Used only by run_actions */
326 static pid_t run(const struct init_action *a)
327 {
328         pid_t pid;
329
330         /* Careful: don't be affected by a signal in vforked child */
331         sigprocmask_allsigs(SIG_BLOCK);
332         if (BB_MMU && (a->action_type & ASKFIRST))
333                 pid = fork();
334         else
335                 pid = vfork();
336         if (pid < 0)
337                 message(L_LOG | L_CONSOLE, "can't fork");
338         if (pid) {
339                 sigprocmask_allsigs(SIG_UNBLOCK);
340                 return pid; /* Parent or error */
341         }
342
343         /* Child */
344
345         /* Reset signal handlers that were set by the parent process */
346         reset_sighandlers_and_unblock_sigs();
347
348         /* Create a new session and make ourself the process group leader */
349         setsid();
350
351         /* Open the new terminal device */
352         if (!open_stdio_to_tty(a->terminal))
353                 _exit(EXIT_FAILURE);
354
355         /* NB: on NOMMU we can't wait for input in child, so
356          * "askfirst" will work the same as "respawn". */
357         if (BB_MMU && (a->action_type & ASKFIRST)) {
358                 static const char press_enter[] ALIGN1 =
359 #ifdef CUSTOMIZED_BANNER
360 #include CUSTOMIZED_BANNER
361 #endif
362                         "\nPlease press Enter to activate this console. ";
363                 char c;
364                 /*
365                  * Save memory by not exec-ing anything large (like a shell)
366                  * before the user wants it. This is critical if swap is not
367                  * enabled and the system has low memory. Generally this will
368                  * be run on the second virtual console, and the first will
369                  * be allowed to start a shell or whatever an init script
370                  * specifies.
371                  */
372                 dbg_message(L_LOG, "waiting for enter to start '%s'"
373                                         "(pid %d, tty '%s')\n",
374                                 a->command, getpid(), a->terminal);
375                 full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
376                 while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
377                         continue;
378         }
379
380         /*
381          * When a file named /.init_enable_core exists, setrlimit is called
382          * before processes are spawned to set core file size as unlimited.
383          * This is for debugging only.  Don't use this is production, unless
384          * you want core dumps lying about....
385          */
386         if (ENABLE_FEATURE_INIT_COREDUMPS) {
387                 if (access("/.init_enable_core", F_OK) == 0) {
388                         struct rlimit limit;
389                         limit.rlim_cur = RLIM_INFINITY;
390                         limit.rlim_max = RLIM_INFINITY;
391                         setrlimit(RLIMIT_CORE, &limit);
392                 }
393         }
394
395         /* Log the process name and args */
396         message(L_LOG, "starting pid %d, tty '%s': '%s'",
397                           getpid(), a->terminal, a->command);
398
399         /* Now run it.  The new program will take over this PID,
400          * so nothing further in init.c should be run. */
401         init_exec(a->command);
402         /* We're still here?  Some error happened. */
403         _exit(-1);
404 }
405
406 static struct init_action *mark_terminated(pid_t pid)
407 {
408         struct init_action *a;
409
410         if (pid > 0) {
411                 for (a = init_action_list; a; a = a->next) {
412                         if (a->pid == pid) {
413                                 a->pid = 0;
414                                 return a;
415                         }
416                 }
417         }
418         return NULL;
419 }
420
421 static void waitfor(pid_t pid)
422 {
423         /* waitfor(run(x)): protect against failed fork inside run() */
424         if (pid <= 0)
425                 return;
426
427         /* Wait for any child (prevent zombies from exiting orphaned processes)
428          * but exit the loop only when specified one has exited. */
429         while (1) {
430                 pid_t wpid = wait(NULL);
431                 mark_terminated(wpid);
432                 /* Unsafe. SIGTSTP handler might have wait'ed it already */
433                 /*if (wpid == pid) break;*/
434                 /* More reliable: */
435                 if (kill(pid, 0))
436                         break;
437         }
438 }
439
440 /* Run all commands of a particular type */
441 static void run_actions(int action_type)
442 {
443         struct init_action *a;
444
445         for (a = init_action_list; a; a = a->next) {
446                 if (!(a->action_type & action_type))
447                         continue;
448
449                 if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
450                         pid_t pid = run(a);
451                         if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
452                                 waitfor(pid);
453                 }
454                 if (a->action_type & (RESPAWN | ASKFIRST)) {
455                         /* Only run stuff with pid == 0. If pid != 0,
456                          * it is already running
457                          */
458                         if (a->pid == 0)
459                                 a->pid = run(a);
460                 }
461         }
462 }
463
464 static void new_init_action(uint8_t action_type, const char *command, const char *cons)
465 {
466         struct init_action *a, **nextp;
467
468         /* Scenario:
469          * old inittab:
470          * ::shutdown:umount -a -r
471          * ::shutdown:swapoff -a
472          * new inittab:
473          * ::shutdown:swapoff -a
474          * ::shutdown:umount -a -r
475          * On reload, we must ensure entries end up in correct order.
476          * To achieve that, if we find a matching entry, we move it
477          * to the end.
478          */
479         nextp = &init_action_list;
480         while ((a = *nextp) != NULL) {
481                 /* Don't enter action if it's already in the list,
482                  * This prevents losing running RESPAWNs.
483                  */
484                 if ((strcmp(a->command, command) == 0)
485                  && (strcmp(a->terminal, cons) == 0)
486                 ) {
487                         /* Remove from list */
488                         *nextp = a->next;
489                         /* Find the end of the list */
490                         while (*nextp != NULL)
491                                 nextp = &(*nextp)->next;
492                         a->next = NULL;
493                         break;
494                 }
495                 nextp = &a->next;
496         }
497
498         if (!a)
499                 a = xzalloc(sizeof(*a));
500         /* Append to the end of the list */
501         *nextp = a;
502         a->action_type = action_type;
503         safe_strncpy(a->command, command, sizeof(a->command));
504         safe_strncpy(a->terminal, cons, sizeof(a->terminal));
505         dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
506                 a->command, a->action_type, a->terminal);
507 }
508
509 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
510  * then parse_inittab() simply adds in some default
511  * actions(i.e., runs INIT_SCRIPT and then starts a pair
512  * of "askfirst" shells).  If CONFIG_FEATURE_USE_INITTAB
513  * _is_ defined, but /etc/inittab is missing, this
514  * results in the same set of default behaviors.
515  */
516 static void parse_inittab(void)
517 {
518 #if ENABLE_FEATURE_USE_INITTAB
519         char *token[4];
520         parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
521
522         if (parser == NULL)
523 #endif
524         {
525                 /* No inittab file - set up some default behavior */
526                 /* Reboot on Ctrl-Alt-Del */
527                 new_init_action(CTRLALTDEL, "reboot", "");
528                 /* Umount all filesystems on halt/reboot */
529                 new_init_action(SHUTDOWN, "umount -a -r", "");
530                 /* Swapoff on halt/reboot */
531                 if (ENABLE_SWAPONOFF)
532                         new_init_action(SHUTDOWN, "swapoff -a", "");
533                 /* Prepare to restart init when a QUIT is received */
534                 new_init_action(RESTART, "init", "");
535                 /* Askfirst shell on tty1-4 */
536                 new_init_action(ASKFIRST, bb_default_login_shell, "");
537 //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
538                 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
539                 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
540                 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
541                 /* sysinit */
542                 new_init_action(SYSINIT, INIT_SCRIPT, "");
543                 return;
544         }
545
546 #if ENABLE_FEATURE_USE_INITTAB
547         /* optional_tty:ignored_runlevel:action:command
548          * Delims are not to be collapsed and need exactly 4 tokens
549          */
550         while (config_read(parser, token, 4, 0, "#:",
551                                 PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
552                 /* order must correspond to SYSINIT..RESTART constants */
553                 static const char actions[] ALIGN1 =
554                         "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
555                         "ctrlaltdel\0""shutdown\0""restart\0";
556                 int action;
557                 char *tty = token[0];
558
559                 if (!token[3]) /* less than 4 tokens */
560                         goto bad_entry;
561                 action = index_in_strings(actions, token[2]);
562                 if (action < 0 || !token[3][0]) /* token[3]: command */
563                         goto bad_entry;
564                 /* turn .*TTY -> /dev/TTY */
565                 if (tty[0]) {
566                         if (strncmp(tty, "/dev/", 5) == 0)
567                                 tty += 5;
568                         tty = concat_path_file("/dev/", tty);
569                 }
570                 new_init_action(1 << action, token[3], tty);
571                 if (tty[0])
572                         free(tty);
573                 continue;
574  bad_entry:
575                 message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
576                                 parser->lineno);
577         }
578         config_close(parser);
579 #endif
580 }
581
582 static void pause_and_low_level_reboot(unsigned magic) NORETURN;
583 static void pause_and_low_level_reboot(unsigned magic)
584 {
585         pid_t pid;
586
587         /* Allow time for last message to reach serial console, etc */
588         sleep(1);
589
590         /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
591          * in linux/kernel/sys.c, which can cause the machine to panic when
592          * the init process exits... */
593         pid = vfork();
594         if (pid == 0) { /* child */
595                 reboot(magic);
596                 _exit(EXIT_SUCCESS);
597         }
598         while (1)
599                 sleep(1);
600 }
601
602 static void run_shutdown_and_kill_processes(void)
603 {
604         /* Run everything to be run at "shutdown".  This is done _prior_
605          * to killing everything, in case people wish to use scripts to
606          * shut things down gracefully... */
607         run_actions(SHUTDOWN);
608
609         message(L_CONSOLE | L_LOG, "The system is going down NOW!");
610
611         /* Send signals to every process _except_ pid 1 */
612         kill(-1, SIGTERM);
613         message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
614         sync();
615         sleep(1);
616
617         kill(-1, SIGKILL);
618         message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
619         sync();
620         /*sleep(1); - callers take care about making a pause */
621 }
622
623 /* Signal handling by init:
624  *
625  * For process with PID==1, on entry kernel sets all signals to SIG_DFL
626  * and unmasks all signals. However, for process with PID==1,
627  * default action (SIG_DFL) on any signal is to ignore it,
628  * even for special signals SIGKILL and SIGCONT.
629  * Also, any signal can be caught or blocked.
630  * (but SIGSTOP is still handled specially, at least in 2.6.20)
631  *
632  * We install two kinds of handlers, "immediate" and "delayed".
633  *
634  * Immediate handlers execute at any time, even while, say, sysinit
635  * is running.
636  *
637  * Delayed handlers just set a flag variable. The variable is checked
638  * in the main loop and acted upon.
639  *
640  * halt/poweroff/reboot and restart have immediate handlers.
641  * They only traverse linked list of struct action's, never modify it,
642  * this should be safe to do even in signal handler. Also they
643  * never return.
644  *
645  * SIGSTOP and SIGTSTP have immediate handlers. They just wait
646  * for SIGCONT to happen.
647  *
648  * SIGHUP has a delayed handler, because modifying linked list
649  * of struct action's from a signal handler while it is manipulated
650  * by the program may be disastrous.
651  *
652  * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
653  * it to happen even somewhere inside "sysinit" would be a bit awkward.
654  *
655  * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
656  * and only one will be remembered and acted upon.
657  */
658
659 /* The SIGUSR[12]/SIGTERM handler */
660 static void halt_reboot_pwoff(int sig) NORETURN;
661 static void halt_reboot_pwoff(int sig)
662 {
663         const char *m;
664         unsigned rb;
665
666         /* We may call run() and it unmasks signals,
667          * including the one masked inside this signal handler.
668          * Testcase which would start multiple reboot scripts:
669          *  while true; do reboot; done
670          * Preventing it:
671          */
672         reset_sighandlers_and_unblock_sigs();
673
674         run_shutdown_and_kill_processes();
675
676         m = "halt";
677         rb = RB_HALT_SYSTEM;
678         if (sig == SIGTERM) {
679                 m = "reboot";
680                 rb = RB_AUTOBOOT;
681         } else if (sig == SIGUSR2) {
682                 m = "poweroff";
683                 rb = RB_POWER_OFF;
684         }
685         message(L_CONSOLE, "Requesting system %s", m);
686         pause_and_low_level_reboot(rb);
687         /* not reached */
688 }
689
690 /* Handler for QUIT - exec "restart" action,
691  * else (no such action defined) do nothing */
692 static void restart_handler(int sig UNUSED_PARAM)
693 {
694         struct init_action *a;
695
696         for (a = init_action_list; a; a = a->next) {
697                 if (!(a->action_type & RESTART))
698                         continue;
699
700                 /* Starting from here, we won't return.
701                  * Thus don't need to worry about preserving errno
702                  * and such.
703                  */
704
705                 reset_sighandlers_and_unblock_sigs();
706
707                 run_shutdown_and_kill_processes();
708
709                 /* Allow Ctrl-Alt-Del to reboot the system.
710                  * This is how kernel sets it up for init, we follow suit.
711                  */
712                 reboot(RB_ENABLE_CAD); /* misnomer */
713
714                 if (open_stdio_to_tty(a->terminal)) {
715                         dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
716                         /* Theoretically should be safe.
717                          * But in practice, kernel bugs may leave
718                          * unkillable processes, and wait() may block forever.
719                          * Oh well. Hoping "new" init won't be too surprised
720                          * by having children it didn't create.
721                          */
722                         //while (wait(NULL) > 0)
723                         //      continue;
724                         init_exec(a->command);
725                 }
726                 /* Open or exec failed */
727                 pause_and_low_level_reboot(RB_HALT_SYSTEM);
728                 /* not reached */
729         }
730 }
731
732 /* The SIGSTOP/SIGTSTP handler
733  * NB: inside it, all signals except SIGCONT are masked
734  * via appropriate setup in sigaction().
735  */
736 static void stop_handler(int sig UNUSED_PARAM)
737 {
738         smallint saved_bb_got_signal;
739         int saved_errno;
740
741         saved_bb_got_signal = bb_got_signal;
742         saved_errno = errno;
743         signal(SIGCONT, record_signo);
744
745         while (1) {
746                 pid_t wpid;
747
748                 if (bb_got_signal == SIGCONT)
749                         break;
750                 /* NB: this can accidentally wait() for a process
751                  * which we waitfor() elsewhere! waitfor() must have
752                  * code which is resilient against this.
753                  */
754                 wpid = wait_any_nohang(NULL);
755                 mark_terminated(wpid);
756                 sleep(1);
757         }
758
759         signal(SIGCONT, SIG_DFL);
760         errno = saved_errno;
761         bb_got_signal = saved_bb_got_signal;
762 }
763
764 #if ENABLE_FEATURE_USE_INITTAB
765 static void reload_inittab(void)
766 {
767         struct init_action *a, **nextp;
768
769         message(L_LOG, "reloading /etc/inittab");
770
771         /* Disable old entries */
772         for (a = init_action_list; a; a = a->next)
773                 a->action_type = 0;
774
775         /* Append new entries, or modify existing entries
776          * (incl. setting a->action_type) if cmd and device name
777          * match new ones. End result: only entries with
778          * a->action_type == 0 are stale.
779          */
780         parse_inittab();
781
782 #if ENABLE_FEATURE_KILL_REMOVED
783         /* Kill stale entries */
784         /* Be nice and send SIGTERM first */
785         for (a = init_action_list; a; a = a->next)
786                 if (a->action_type == 0 && a->pid != 0)
787                         kill(a->pid, SIGTERM);
788         if (CONFIG_FEATURE_KILL_DELAY) {
789                 /* NB: parent will wait in NOMMU case */
790                 if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
791                         sleep(CONFIG_FEATURE_KILL_DELAY);
792                         for (a = init_action_list; a; a = a->next)
793                                 if (a->action_type == 0 && a->pid != 0)
794                                         kill(a->pid, SIGKILL);
795                         _exit(EXIT_SUCCESS);
796                 }
797         }
798 #endif
799
800         /* Remove stale entries and SYSINIT entries.
801          * We never rerun SYSINIT entries anyway,
802          * removing them too saves a few bytes */
803         nextp = &init_action_list;
804         while ((a = *nextp) != NULL) {
805                 if ((a->action_type & ~SYSINIT) == 0) {
806                         *nextp = a->next;
807                         free(a);
808                 } else {
809                         nextp = &a->next;
810                 }
811         }
812
813         /* Not needed: */
814         /* run_actions(RESPAWN | ASKFIRST); */
815         /* - we return to main loop, which does this automagically */
816 }
817 #endif
818
819 static int check_delayed_sigs(void)
820 {
821         int sigs_seen = 0;
822
823         while (1) {
824                 smallint sig = bb_got_signal;
825
826                 if (!sig)
827                         return sigs_seen;
828                 bb_got_signal = 0;
829                 sigs_seen = 1;
830 #if ENABLE_FEATURE_USE_INITTAB
831                 if (sig == SIGHUP)
832                         reload_inittab();
833 #endif
834                 if (sig == SIGINT)
835                         run_actions(CTRLALTDEL);
836         }
837 }
838
839 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
840 int init_main(int argc UNUSED_PARAM, char **argv)
841 {
842         die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
843
844         if (argv[1] && !strcmp(argv[1], "-q")) {
845                 return kill(1, SIGHUP);
846         }
847
848         if (!DEBUG_INIT) {
849                 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
850                 if (getpid() != 1
851                  && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
852                 ) {
853                         bb_show_usage();
854                 }
855                 /* Turn off rebooting via CTL-ALT-DEL - we get a
856                  * SIGINT on CAD so we can shut things down gracefully... */
857                 reboot(RB_DISABLE_CAD); /* misnomer */
858         }
859
860         /* Figure out where the default console should be */
861         console_init();
862         set_sane_term();
863         xchdir("/");
864         setsid();
865
866         /* Make sure environs is set to something sane */
867         putenv((char *) "HOME=/");
868         putenv((char *) bb_PATH_root_path);
869         putenv((char *) "SHELL=/bin/sh");
870         putenv((char *) "USER=root"); /* needed? why? */
871
872         if (argv[1])
873                 xsetenv("RUNLEVEL", argv[1]);
874
875 #if ENABLE_FEATURE_EXTRA_QUIET
876         /* Hello world */
877         message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
878 #endif
879
880         /* Make sure there is enough memory to do something useful. */
881         if (ENABLE_SWAPONOFF) {
882                 struct sysinfo info;
883
884                 if (sysinfo(&info) == 0
885                  && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
886                 ) {
887                         message(L_CONSOLE, "Low memory, forcing swapon");
888                         /* swapon -a requires /proc typically */
889                         new_init_action(SYSINIT, "mount -t proc proc /proc", "");
890                         /* Try to turn on swap */
891                         new_init_action(SYSINIT, "swapon -a", "");
892                         run_actions(SYSINIT);   /* wait and removing */
893                 }
894         }
895
896         /* Check if we are supposed to be in single user mode */
897         if (argv[1]
898          && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
899         ) {
900                 /* ??? shouldn't we set RUNLEVEL="b" here? */
901                 /* Start a shell on console */
902                 new_init_action(RESPAWN, bb_default_login_shell, "");
903         } else {
904                 /* Not in single user mode - see what inittab says */
905
906                 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
907                  * then parse_inittab() simply adds in some default
908                  * actions(i.e., INIT_SCRIPT and a pair
909                  * of "askfirst" shells */
910                 parse_inittab();
911         }
912
913 #if ENABLE_SELINUX
914         if (getenv("SELINUX_INIT") == NULL) {
915                 int enforce = 0;
916
917                 putenv((char*)"SELINUX_INIT=YES");
918                 if (selinux_init_load_policy(&enforce) == 0) {
919                         BB_EXECVP(argv[0], argv);
920                 } else if (enforce > 0) {
921                         /* SELinux in enforcing mode but load_policy failed */
922                         message(L_CONSOLE, "can't load SELinux Policy. "
923                                 "Machine is in enforcing mode. Halting now.");
924                         exit(EXIT_FAILURE);
925                 }
926         }
927 #endif
928
929         /* Make the command line just say "init"  - thats all, nothing else */
930         strncpy(argv[0], "init", strlen(argv[0]));
931         /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
932         while (*++argv)
933                 memset(*argv, 0, strlen(*argv));
934
935         /* Set up signal handlers */
936         if (!DEBUG_INIT) {
937                 struct sigaction sa;
938
939                 bb_signals(0
940                         + (1 << SIGUSR1) /* halt */
941                         + (1 << SIGTERM) /* reboot */
942                         + (1 << SIGUSR2) /* poweroff */
943                         , halt_reboot_pwoff);
944                 signal(SIGQUIT, restart_handler); /* re-exec another init */
945
946                 /* Stop handler must allow only SIGCONT inside itself */
947                 memset(&sa, 0, sizeof(sa));
948                 sigfillset(&sa.sa_mask);
949                 sigdelset(&sa.sa_mask, SIGCONT);
950                 sa.sa_handler = stop_handler;
951                 /* NB: sa_flags doesn't have SA_RESTART.
952                  * It must be able to interrupt wait().
953                  */
954                 sigaction_set(SIGTSTP, &sa); /* pause */
955                 /* Does not work as intended, at least in 2.6.20.
956                  * SIGSTOP is simply ignored by init:
957                  */
958                 sigaction_set(SIGSTOP, &sa); /* pause */
959
960                 /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),
961                  * setting handler without SA_RESTART flag.
962                  */
963                 bb_signals_recursive_norestart((1 << SIGINT), record_signo);
964         }
965
966         /* Set up "reread /etc/inittab" handler.
967          * Handler is set up without SA_RESTART, it will interrupt syscalls.
968          */
969         if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
970                 bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
971
972         /* Now run everything that needs to be run */
973         /* First run the sysinit command */
974         run_actions(SYSINIT);
975         check_delayed_sigs();
976         /* Next run anything that wants to block */
977         run_actions(WAIT);
978         check_delayed_sigs();
979         /* Next run anything to be run only once */
980         run_actions(ONCE);
981
982         /* Now run the looping stuff for the rest of forever.
983          */
984         while (1) {
985                 int maybe_WNOHANG;
986
987                 maybe_WNOHANG = check_delayed_sigs();
988
989                 /* (Re)run the respawn/askfirst stuff */
990                 run_actions(RESPAWN | ASKFIRST);
991                 maybe_WNOHANG |= check_delayed_sigs();
992
993                 /* Don't consume all CPU time - sleep a bit */
994                 sleep(1);
995                 maybe_WNOHANG |= check_delayed_sigs();
996
997                 /* Wait for any child process(es) to exit.
998                  *
999                  * If check_delayed_sigs above reported that a signal
1000                  * was caught, wait will be nonblocking. This ensures
1001                  * that if SIGHUP has reloaded inittab, respawn and askfirst
1002                  * actions will not be delayed until next child death.
1003                  */
1004                 if (maybe_WNOHANG)
1005                         maybe_WNOHANG = WNOHANG;
1006                 while (1) {
1007                         pid_t wpid;
1008                         struct init_action *a;
1009
1010                         /* If signals happen _in_ the wait, they interrupt it,
1011                          * bb_signals_recursive_norestart set them up that way
1012                          */
1013                         wpid = waitpid(-1, NULL, maybe_WNOHANG);
1014                         if (wpid <= 0)
1015                                 break;
1016
1017                         a = mark_terminated(wpid);
1018                         if (a) {
1019                                 message(L_LOG, "process '%s' (pid %d) exited. "
1020                                                 "Scheduling for restart.",
1021                                                 a->command, wpid);
1022                         }
1023                         /* See if anyone else is waiting to be reaped */
1024                         maybe_WNOHANG = WNOHANG;
1025                 }
1026         } /* while (1) */
1027 }