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