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