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