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