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