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