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