Magellan Linux

Contents of /trunk/mkinitrd-magellan/busybox/init/init.c

Parent Directory Parent Directory | Revision Log Revision Log


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