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