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