- remove useless variable "status" from init_main.
[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 <stdio.h>
13 #include <stdlib.h>
14 #include <errno.h>
15 #include <paths.h>
16 #include <signal.h>
17 #include <stdarg.h>
18 #include <string.h>
19 #include <termios.h>
20 #include <unistd.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include <sys/ioctl.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <sys/reboot.h>
27 #include "busybox.h"
28
29 #include "init_shared.h"
30
31
32 #ifdef CONFIG_SYSLOGD
33 # include <sys/syslog.h>
34 #endif
35
36
37 #ifdef CONFIG_SELINUX
38 # include <selinux/selinux.h>
39 #endif /* CONFIG_SELINUX */
40
41
42 #define INIT_BUFFS_SIZE 256
43
44 /* From <linux/vt.h> */
45 struct vt_stat {
46         unsigned short v_active;        /* active vt */
47         unsigned short v_signal;        /* signal to send */
48         unsigned short v_state; /* vt bitmask */
49 };
50 enum { VT_GETSTATE = 0x5603 };  /* get global vt state info */
51
52 /* From <linux/serial.h> */
53 struct serial_struct {
54         int     type;
55         int     line;
56         unsigned int    port;
57         int     irq;
58         int     flags;
59         int     xmit_fifo_size;
60         int     custom_divisor;
61         int     baud_base;
62         unsigned short  close_delay;
63         char    io_type;
64         char    reserved_char[1];
65         int     hub6;
66         unsigned short  closing_wait; /* time to wait before closing */
67         unsigned short  closing_wait2; /* no longer used... */
68         unsigned char   *iomem_base;
69         unsigned short  iomem_reg_shift;
70         unsigned int    port_high;
71         unsigned long   iomap_base;     /* cookie passed into ioremap */
72         int     reserved[1];
73 };
74
75
76 #ifndef _PATH_STDPATH
77 #define _PATH_STDPATH   "/usr/bin:/bin:/usr/sbin:/sbin"
78 #endif
79
80 #if defined CONFIG_FEATURE_INIT_COREDUMPS
81 /*
82  * When a file named CORE_ENABLE_FLAG_FILE exists, setrlimit is called
83  * before processes are spawned to set core file size as unlimited.
84  * This is for debugging only.  Don't use this is production, unless
85  * you want core dumps lying about....
86  */
87 #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
88 #include <sys/resource.h>
89 #endif
90
91 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
92
93 #define INITTAB      "/etc/inittab"     /* inittab file location */
94 #ifndef INIT_SCRIPT
95 #define INIT_SCRIPT  "/etc/init.d/rcS"  /* Default sysinit script. */
96 #endif
97
98 #define MAXENV  16              /* Number of env. vars */
99
100 #define CONSOLE_BUFF_SIZE 32
101
102 /* Allowed init action types */
103 #define SYSINIT     0x001
104 #define RESPAWN     0x002
105 #define ASKFIRST    0x004
106 #define WAIT        0x008
107 #define ONCE        0x010
108 #define CTRLALTDEL  0x020
109 #define SHUTDOWN    0x040
110 #define RESTART     0x080
111
112 /* A mapping between "inittab" action name strings and action type codes. */
113 struct init_action_type {
114         const char *name;
115         int action;
116 };
117
118 static const struct init_action_type actions[] = {
119         {"sysinit", SYSINIT},
120         {"respawn", RESPAWN},
121         {"askfirst", ASKFIRST},
122         {"wait", WAIT},
123         {"once", ONCE},
124         {"ctrlaltdel", CTRLALTDEL},
125         {"shutdown", SHUTDOWN},
126         {"restart", RESTART},
127         {0, 0}
128 };
129
130 /* Set up a linked list of init_actions, to be read from inittab */
131 struct init_action {
132         pid_t pid;
133         char command[INIT_BUFFS_SIZE];
134         char terminal[CONSOLE_BUFF_SIZE];
135         struct init_action *next;
136         int action;
137 };
138
139 /* Static variables */
140 static struct init_action *init_action_list = NULL;
141 static char console[CONSOLE_BUFF_SIZE] = _PATH_CONSOLE;
142
143 #ifndef CONFIG_SYSLOGD
144 static char *log_console = VC_5;
145 #endif
146 static sig_atomic_t got_cont = 0;
147
148 enum {
149         LOG = 0x1,
150         CONSOLE = 0x2,
151
152 #if defined CONFIG_FEATURE_EXTRA_QUIET
153         MAYBE_CONSOLE = 0x0,
154 #else
155         MAYBE_CONSOLE = CONSOLE,
156 #endif
157
158 #ifndef RB_HALT_SYSTEM
159         RB_HALT_SYSTEM = 0xcdef0123,
160         RB_ENABLE_CAD = 0x89abcdef,
161         RB_DISABLE_CAD = 0,
162         RB_POWER_OFF = 0x4321fedc,
163         RB_AUTOBOOT = 0x01234567,
164 #endif
165 };
166
167 static const char * const environment[] = {
168         "HOME=/",
169         "PATH=" _PATH_STDPATH,
170         "SHELL=/bin/sh",
171         "USER=root",
172         NULL
173 };
174
175 /* Function prototypes */
176 static void delete_init_action(struct init_action *a);
177 static int waitfor(const struct init_action *a, pid_t pid);
178 static void halt_signal(int sig);
179
180
181 static void loop_forever(void)
182 {
183         while (1)
184                 sleep(1);
185 }
186
187 /* Print a message to the specified device.
188  * Device may be bitwise-or'd from LOG | CONSOLE */
189 #if ENABLE_DEBUG_INIT
190 #define messageD message
191 #else
192 static inline void messageD(int ATTRIBUTE_UNUSED device,
193                                 const char ATTRIBUTE_UNUSED *fmt, ...)
194 {
195 }
196 #endif
197 static void message(int device, const char *fmt, ...)
198         __attribute__ ((format(printf, 2, 3)));
199 static void message(int device, const char *fmt, ...)
200 {
201         va_list arguments;
202         int l;
203         RESERVE_CONFIG_BUFFER(msg, 1024);
204 #ifndef CONFIG_SYSLOGD
205         static int log_fd = -1;
206 #endif
207
208         msg[0] = '\r';
209                 va_start(arguments, fmt);
210         l = vsnprintf(msg + 1, 1024 - 2, fmt, arguments) + 1;
211                 va_end(arguments);
212
213 #ifdef CONFIG_SYSLOGD
214         /* Log the message to syslogd */
215         if (device & LOG) {
216                 /* don`t out "\r\n" */
217                 openlog(bb_applet_name, 0, LOG_DAEMON);
218                 syslog(LOG_INFO, "%s", msg + 1);
219                 closelog();
220         }
221
222         msg[l++] = '\n';
223         msg[l] = 0;
224 #else
225
226         msg[l++] = '\n';
227         msg[l] = 0;
228         /* Take full control of the log tty, and never close it.
229          * It's mine, all mine!  Muhahahaha! */
230         if (log_fd < 0) {
231                 if ((log_fd = device_open(log_console, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
232                         log_fd = -2;
233                         bb_error_msg("Bummer, can't write to log on %s!", log_console);
234                         device = CONSOLE;
235                 } else {
236                         fcntl(log_fd, F_SETFD, FD_CLOEXEC);
237                 }
238         }
239         if ((device & LOG) && (log_fd >= 0)) {
240                 bb_full_write(log_fd, msg, l);
241         }
242 #endif
243
244         if (device & CONSOLE) {
245                 int fd = device_open(_PATH_CONSOLE,
246                                         O_WRONLY | O_NOCTTY | O_NONBLOCK);
247                 /* Always send console messages to /dev/console so people will see them. */
248                 if (fd >= 0) {
249                         bb_full_write(fd, msg, l);
250                         close(fd);
251 #if ENABLE_DEBUG_INIT
252                 /* all descriptors may be closed */
253                 } else {
254                         bb_error_msg("Bummer, can't print: ");
255                         va_start(arguments, fmt);
256                         vfprintf(stderr, fmt, arguments);
257                         va_end(arguments);
258 #endif
259                 }
260         }
261         RELEASE_CONFIG_BUFFER(msg);
262 }
263
264 /* Set terminal settings to reasonable defaults */
265 static void set_term(void)
266 {
267         struct termios tty;
268
269         tcgetattr(STDIN_FILENO, &tty);
270
271         /* set control chars */
272         tty.c_cc[VINTR] = 3;    /* C-c */
273         tty.c_cc[VQUIT] = 28;   /* C-\ */
274         tty.c_cc[VERASE] = 127; /* C-? */
275         tty.c_cc[VKILL] = 21;   /* C-u */
276         tty.c_cc[VEOF] = 4;     /* C-d */
277         tty.c_cc[VSTART] = 17;  /* C-q */
278         tty.c_cc[VSTOP] = 19;   /* C-s */
279         tty.c_cc[VSUSP] = 26;   /* C-z */
280
281         /* use line dicipline 0 */
282         tty.c_line = 0;
283
284         /* Make it be sane */
285         tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
286         tty.c_cflag |= CREAD | HUPCL | CLOCAL;
287
288
289         /* input modes */
290         tty.c_iflag = ICRNL | IXON | IXOFF;
291
292         /* output modes */
293         tty.c_oflag = OPOST | ONLCR;
294
295         /* local modes */
296         tty.c_lflag =
297                 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
298
299         tcsetattr(STDIN_FILENO, TCSANOW, &tty);
300 }
301
302 static void console_init(void)
303 {
304         int fd;
305         int tried = 0;
306         struct vt_stat vt;
307         struct serial_struct sr;
308         char *s;
309
310         if ((s = getenv("CONSOLE")) != NULL || (s = getenv("console")) != NULL) {
311                 safe_strncpy(console, s, sizeof(console));
312 #if 0 /* #cpu(sparc) */
313         /* sparc kernel supports console=tty[ab] parameter which is also
314          * passed to init, so catch it here */
315                 /* remap tty[ab] to /dev/ttyS[01] */
316                 if (strcmp(s, "ttya") == 0)
317                         safe_strncpy(console, SC_0, sizeof(console));
318                 else if (strcmp(s, "ttyb") == 0)
319                         safe_strncpy(console, SC_1, sizeof(console));
320 #endif
321         } else {
322                 /* 2.2 kernels: identify the real console backend and try to use it */
323                 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
324                         /* this is a serial console */
325                         snprintf(console, sizeof(console) - 1, SC_FORMAT, sr.line);
326                 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
327                         /* this is linux virtual tty */
328                         snprintf(console, sizeof(console) - 1, VC_FORMAT, vt.v_active);
329                 } else {
330                         safe_strncpy(console, _PATH_CONSOLE, sizeof(console));
331                         tried++;
332                 }
333         }
334
335         while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0 && tried < 2) {
336                 /* Can't open selected console -- try
337                         logical system console and VT_MASTER */
338                 safe_strncpy(console, (tried == 0 ? _PATH_CONSOLE : CURRENT_VC),
339                                                         sizeof(console));
340                 tried++;
341         }
342         if (fd < 0) {
343                 /* Perhaps we should panic here? */
344 #ifndef CONFIG_SYSLOGD
345                 log_console =
346 #endif
347                 safe_strncpy(console, bb_dev_null, sizeof(console));
348         } else {
349                 s = getenv("TERM");
350                 /* check for serial console */
351                 if (ioctl(fd, TIOCGSERIAL, &sr) == 0) {
352                         /* Force the TERM setting to vt102 for serial console --
353                          * if TERM is set to linux (the default) */
354                         if (s == NULL || strcmp(s, "linux") == 0)
355                                 putenv("TERM=vt102");
356 #ifndef CONFIG_SYSLOGD
357                         log_console = console;
358 #endif
359                 } else {
360                         if (s == NULL)
361                                 putenv("TERM=linux");
362                 }
363                 close(fd);
364         }
365         messageD(LOG, "console=%s", console);
366 }
367
368 static void fixup_argv(int argc, char **argv, char *new_argv0)
369 {
370         int len;
371
372         /* Fix up argv[0] to be certain we claim to be init */
373         len = strlen(argv[0]);
374         memset(argv[0], 0, len);
375         safe_strncpy(argv[0], new_argv0, len + 1);
376
377         /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
378         len = 1;
379         while (argc > len) {
380                 memset(argv[len], 0, strlen(argv[len]));
381                 len++;
382         }
383 }
384
385 /* Open the new terminal device */
386 static void open_new_terminal(const char *device, char fail) {
387         struct stat sb;
388
389         if ((device_open(device, O_RDWR)) < 0) {
390                 if (stat(device, &sb) != 0) {
391                         message(LOG | CONSOLE, "device '%s' does not exist.", device);
392                 } else {
393                         message(LOG | CONSOLE, "Bummer, can't open %s", device);
394                 }
395                 if (fail)
396                         _exit(1);
397                 /* else */
398                 halt_signal(SIGUSR1);
399         }
400 }
401
402 static pid_t run(const struct init_action *a)
403 {
404         int i;
405         pid_t pid;
406         char *s, *tmpCmd, *cmd[INIT_BUFFS_SIZE], *cmdpath;
407         char buf[INIT_BUFFS_SIZE + 6];  /* INIT_BUFFS_SIZE+strlen("exec ")+1 */
408         sigset_t nmask, omask;
409         static const char press_enter[] =
410 #ifdef CUSTOMIZED_BANNER
411 #include CUSTOMIZED_BANNER
412 #endif
413                 "\nPlease press Enter to activate this console. ";
414
415         /* Block sigchild while forking.  */
416         sigemptyset(&nmask);
417         sigaddset(&nmask, SIGCHLD);
418         sigprocmask(SIG_BLOCK, &nmask, &omask);
419
420         if ((pid = fork()) == 0) {
421
422                 /* Clean up */
423                 close(0);
424                 close(1);
425                 close(2);
426                 sigprocmask(SIG_SETMASK, &omask, NULL);
427
428                 /* Reset signal handlers that were set by the parent process */
429                 signal(SIGUSR1, SIG_DFL);
430                 signal(SIGUSR2, SIG_DFL);
431                 signal(SIGINT, SIG_DFL);
432                 signal(SIGTERM, SIG_DFL);
433                 signal(SIGHUP, SIG_DFL);
434                 signal(SIGQUIT, SIG_DFL);
435                 signal(SIGCONT, SIG_DFL);
436                 signal(SIGSTOP, SIG_DFL);
437                 signal(SIGTSTP, SIG_DFL);
438
439                 /* Create a new session and make ourself the process
440                  * group leader */
441                 setsid();
442
443                 /* Open the new terminal device */
444                 open_new_terminal(a->terminal, 1);
445
446                 /* Make sure the terminal will act fairly normal for us */
447                 set_term();
448                 /* Setup stdout, stderr for the new process so
449                  * they point to the supplied terminal */
450                 dup(0);
451                 dup(0);
452
453                 /* If the init Action requires us to wait, then force the
454                  * supplied terminal to be the controlling tty. */
455                 if (a->action & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
456
457                         /* Now fork off another process to just hang around */
458                         if ((pid = fork()) < 0) {
459                                 message(LOG | CONSOLE, "Can't fork!");
460                                 _exit(1);
461                         }
462
463                         if (pid > 0) {
464
465                                 /* We are the parent -- wait till the child is done */
466                                 signal(SIGINT, SIG_IGN);
467                                 signal(SIGTSTP, SIG_IGN);
468                                 signal(SIGQUIT, SIG_IGN);
469                                 signal(SIGCHLD, SIG_DFL);
470
471                                 waitfor(NULL, pid);
472                                 /* See if stealing the controlling tty back is necessary */
473                                 if (tcgetpgrp(0) != getpid())
474                                         _exit(0);
475
476                                 /* Use a temporary process to steal the controlling tty. */
477                                 if ((pid = fork()) < 0) {
478                                         message(LOG | CONSOLE, "Can't fork!");
479                                         _exit(1);
480                                 }
481                                 if (pid == 0) {
482                                         setsid();
483                                         ioctl(0, TIOCSCTTY, 1);
484                                         _exit(0);
485                                 }
486                                 waitfor(NULL, pid);
487                                 _exit(0);
488                         }
489
490                         /* Now fall though to actually execute things */
491                 }
492
493                 /* See if any special /bin/sh requiring characters are present */
494                 if (strpbrk(a->command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
495                         cmd[0] = (char *)DEFAULT_SHELL;
496                         cmd[1] = "-c";
497                         cmd[2] = strcat(strcpy(buf, "exec "), a->command);
498                         cmd[3] = NULL;
499                 } else {
500                         /* Convert command (char*) into cmd (char**, one word per string) */
501                         strcpy(buf, a->command);
502                         s = buf;
503                         for (tmpCmd = buf, i = 0; (tmpCmd = strsep(&s, " \t")) != NULL;) {
504                                 if (*tmpCmd != '\0') {
505                                         cmd[i] = tmpCmd;
506                                         i++;
507                                 }
508                         }
509                         cmd[i] = NULL;
510                 }
511
512                 cmdpath = cmd[0];
513
514                 /*
515                    Interactive shells want to see a dash in argv[0].  This
516                    typically is handled by login, argv will be setup this
517                    way if a dash appears at the front of the command path
518                    (like "-/bin/sh").
519                  */
520
521                 if (*cmdpath == '-') {
522
523                         /* skip over the dash */
524                         ++cmdpath;
525
526                         /* find the last component in the command pathname */
527                         s = bb_get_last_path_component(cmdpath);
528
529                         /* make a new argv[0] */
530                         if ((cmd[0] = malloc(strlen(s) + 2)) == NULL) {
531                                 message(LOG | CONSOLE, bb_msg_memory_exhausted);
532                                 cmd[0] = cmdpath;
533                         } else {
534                                 cmd[0][0] = '-';
535                                 strcpy(cmd[0] + 1, s);
536                         }
537 #ifdef CONFIG_FEATURE_INIT_SCTTY
538                         /* Establish this process as session leader and
539                          * (attempt) to make the tty (if any) a controlling tty.
540                          */
541                         (void) setsid();
542                         (void) ioctl(0, TIOCSCTTY, 0/*don't steal it*/);
543 #endif
544                 }
545
546 #if !defined(__UCLIBC__) || defined(__ARCH_HAS_MMU__)
547                 if (a->action & ASKFIRST) {
548                         char c;
549                         /*
550                          * Save memory by not exec-ing anything large (like a shell)
551                          * before the user wants it. This is critical if swap is not
552                          * enabled and the system has low memory. Generally this will
553                          * be run on the second virtual console, and the first will
554                          * be allowed to start a shell or whatever an init script
555                          * specifies.
556                          */
557                         messageD(LOG, "Waiting for enter to start '%s'"
558                                                 "(pid %d, terminal %s)\n",
559                                           cmdpath, getpid(), a->terminal);
560                         bb_full_write(1, press_enter, sizeof(press_enter) - 1);
561                         while(read(0, &c, 1) == 1 && c != '\n')
562                                 ;
563                 }
564 #endif
565
566                 /* Log the process name and args */
567                 message(LOG, "Starting pid %d, console %s: '%s'",
568                                   getpid(), a->terminal, cmdpath);
569
570 #if defined CONFIG_FEATURE_INIT_COREDUMPS
571                 {
572                         struct stat sb;
573                         if (stat(CORE_ENABLE_FLAG_FILE, &sb) == 0) {
574                                 struct rlimit limit;
575
576                                 limit.rlim_cur = RLIM_INFINITY;
577                                 limit.rlim_max = RLIM_INFINITY;
578                                 setrlimit(RLIMIT_CORE, &limit);
579                         }
580                 }
581 #endif
582
583                 /* Now run it.  The new program will take over this PID,
584                  * so nothing further in init.c should be run. */
585                 execv(cmdpath, cmd);
586
587                 /* We're still here?  Some error happened. */
588                 message(LOG | CONSOLE, "Bummer, could not run '%s': %m", cmdpath);
589                 _exit(-1);
590         }
591         sigprocmask(SIG_SETMASK, &omask, NULL);
592         return pid;
593 }
594
595 static int waitfor(const struct init_action *a, pid_t pid)
596 {
597         int runpid;
598         int status, wpid;
599
600         runpid = (NULL == a)? pid : run(a);
601         while (1) {
602                 wpid = waitpid(runpid,&status,0);
603                 if (wpid == runpid)
604                         break;
605                 if (wpid == -1 && errno == ECHILD) {
606                         /* we missed its termination */
607                         break;
608                 }
609                 /* FIXME other errors should maybe trigger an error, but allow
610                  * the program to continue */
611         }
612         return wpid;
613 }
614
615 /* Run all commands of a particular type */
616 static void run_actions(int action)
617 {
618         struct init_action *a, *tmp;
619
620         for (a = init_action_list; a; a = tmp) {
621                 tmp = a->next;
622                 if (a->action == action) {
623                         if (access(a->terminal, R_OK | W_OK)) {
624                                 delete_init_action(a);
625                         } else if (a->action & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN | RESTART)) {
626                                 waitfor(a, 0);
627                                 delete_init_action(a);
628                         } else if (a->action & ONCE) {
629                                 run(a);
630                                 delete_init_action(a);
631                         } else if (a->action & (RESPAWN | ASKFIRST)) {
632                                 /* Only run stuff with pid==0.  If they have
633                                  * a pid, that means it is still running */
634                                 if (a->pid == 0) {
635                                         a->pid = run(a);
636                                 }
637                         }
638                 }
639         }
640 }
641
642 #if !ENABLE_DEBUG_INIT
643 static void init_reboot(unsigned long magic)
644 {
645         pid_t pid;
646         /* We have to fork here, since the kernel calls do_exit(0) in
647          * linux/kernel/sys.c, which can cause the machine to panic when
648          * the init process is killed.... */
649         if ((pid = fork()) == 0) {
650                 reboot(magic);
651                 _exit(0);
652         }
653         waitpid (pid, NULL, 0);
654 }
655
656 static void shutdown_system(void)
657 {
658         sigset_t block_signals;
659
660         /* run everything to be run at "shutdown".  This is done _prior_
661          * to killing everything, in case people wish to use scripts to
662          * shut things down gracefully... */
663         run_actions(SHUTDOWN);
664
665         /* first disable all our signals */
666         sigemptyset(&block_signals);
667         sigaddset(&block_signals, SIGHUP);
668         sigaddset(&block_signals, SIGQUIT);
669         sigaddset(&block_signals, SIGCHLD);
670         sigaddset(&block_signals, SIGUSR1);
671         sigaddset(&block_signals, SIGUSR2);
672         sigaddset(&block_signals, SIGINT);
673         sigaddset(&block_signals, SIGTERM);
674         sigaddset(&block_signals, SIGCONT);
675         sigaddset(&block_signals, SIGSTOP);
676         sigaddset(&block_signals, SIGTSTP);
677         sigprocmask(SIG_BLOCK, &block_signals, NULL);
678
679         /* Allow Ctrl-Alt-Del to reboot system. */
680         init_reboot(RB_ENABLE_CAD);
681
682         message(CONSOLE | LOG, "The system is going down NOW !!");
683         sync();
684
685         /* Send signals to every process _except_ pid 1 */
686         message(CONSOLE | LOG, "Sending SIGTERM to all processes.");
687         kill(-1, SIGTERM);
688         sleep(1);
689         sync();
690
691         message(CONSOLE | LOG, "Sending SIGKILL to all processes.");
692         kill(-1, SIGKILL);
693         sleep(1);
694
695         sync();
696 }
697
698 static void exec_signal(int sig ATTRIBUTE_UNUSED)
699 {
700         struct init_action *a, *tmp;
701         sigset_t unblock_signals;
702
703         for (a = init_action_list; a; a = tmp) {
704                 tmp = a->next;
705                 if (a->action & RESTART) {
706                         shutdown_system();
707
708                         /* unblock all signals, blocked in shutdown_system() */
709                         sigemptyset(&unblock_signals);
710                         sigaddset(&unblock_signals, SIGHUP);
711                         sigaddset(&unblock_signals, SIGQUIT);
712                         sigaddset(&unblock_signals, SIGCHLD);
713                         sigaddset(&unblock_signals, SIGUSR1);
714                         sigaddset(&unblock_signals, SIGUSR2);
715                         sigaddset(&unblock_signals, SIGINT);
716                         sigaddset(&unblock_signals, SIGTERM);
717                         sigaddset(&unblock_signals, SIGCONT);
718                         sigaddset(&unblock_signals, SIGSTOP);
719                         sigaddset(&unblock_signals, SIGTSTP);
720                         sigprocmask(SIG_UNBLOCK, &unblock_signals, NULL);
721
722                         /* Close whatever files are open. */
723                         close(0);
724                         close(1);
725                         close(2);
726
727                         /* Open the new terminal device */
728                         open_new_terminal(a->terminal, 0);
729
730                         /* Make sure the terminal will act fairly normal for us */
731                         set_term();
732                         /* Setup stdout, stderr on the supplied terminal */
733                         dup(0);
734                         dup(0);
735
736                         messageD(CONSOLE | LOG, "Trying to re-exec %s", a->command);
737                         execl(a->command, a->command, NULL);
738
739                         message(CONSOLE | LOG, "exec of '%s' failed: %m",
740                                         a->command);
741                         sync();
742                         sleep(2);
743                         init_reboot(RB_HALT_SYSTEM);
744                         loop_forever();
745                 }
746         }
747 }
748
749 static void halt_signal(int sig ATTRIBUTE_UNUSED)
750 {
751         shutdown_system();
752         message(CONSOLE | LOG, "The system is halted.");
753         sync();
754
755         /* allow time for last message to reach serial console */
756         sleep(2);
757
758         if (sig == SIGUSR2)
759                 init_reboot(RB_POWER_OFF);
760         else
761                 init_reboot(RB_HALT_SYSTEM);
762
763         loop_forever();
764 }
765
766 static void reboot_signal(int sig ATTRIBUTE_UNUSED)
767 {
768         shutdown_system();
769         message(CONSOLE | LOG, "Please stand by while rebooting the system.");
770         sync();
771
772         /* allow time for last message to reach serial console */
773         sleep(2);
774
775         init_reboot(RB_AUTOBOOT);
776
777         loop_forever();
778 }
779
780 static void ctrlaltdel_signal(int sig ATTRIBUTE_UNUSED)
781 {
782         run_actions(CTRLALTDEL);
783 }
784
785 /* The SIGSTOP & SIGTSTP handler */
786 static void stop_handler(int sig ATTRIBUTE_UNUSED)
787 {
788         int saved_errno = errno;
789
790         got_cont = 0;
791         while (!got_cont)
792                 pause();
793         got_cont = 0;
794         errno = saved_errno;
795 }
796
797 /* The SIGCONT handler */
798 static void cont_handler(int sig ATTRIBUTE_UNUSED)
799 {
800         got_cont = 1;
801 }
802
803 #endif                                                  /* ! ENABLE_DEBUG_INIT */
804
805 static void new_init_action(int action, const char *command, const char *cons)
806 {
807         struct init_action *new_action, *a, *last;
808
809         if (*cons == '\0')
810                 cons = console;
811
812         if (strcmp(cons, bb_dev_null) == 0 && (action & ASKFIRST))
813                 return;
814
815         new_action = calloc((size_t) (1), sizeof(struct init_action));
816         if (!new_action) {
817                 message(LOG | CONSOLE, "Memory allocation failure");
818                 loop_forever();
819         }
820
821         /* Append to the end of the list */
822         for (a = last = init_action_list; a; a = a->next) {
823                 /* don't enter action if it's already in the list,
824                  * but do overwrite existing actions */
825                 if ((strcmp(a->command, command) == 0) &&
826                     (strcmp(a->terminal, cons) ==0)) {
827                         a->action = action;
828                         free(new_action);
829                         return;
830                 }
831                 last = a;
832         }
833         if (last) {
834                 last->next = new_action;
835         } else {
836                 init_action_list = new_action;
837         }
838         strcpy(new_action->command, command);
839         new_action->action = action;
840         strcpy(new_action->terminal, cons);
841 #if 0   /* calloc zeroed always */
842         new_action->pid = 0;
843 #endif
844         messageD(LOG|CONSOLE, "command='%s' action='%d' terminal='%s'\n",
845                 new_action->command, new_action->action, new_action->terminal);
846 }
847
848 static void delete_init_action(struct init_action *action)
849 {
850         struct init_action *a, *b = NULL;
851
852         for (a = init_action_list; a; b = a, a = a->next) {
853                 if (a == action) {
854                         if (b == NULL) {
855                                 init_action_list = a->next;
856                         } else {
857                                 b->next = a->next;
858                         }
859                         free(a);
860                         break;
861                 }
862         }
863 }
864
865 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
866  * then parse_inittab() simply adds in some default
867  * actions(i.e., runs INIT_SCRIPT and then starts a pair
868  * of "askfirst" shells).  If CONFIG_FEATURE_USE_INITTAB
869  * _is_ defined, but /etc/inittab is missing, this
870  * results in the same set of default behaviors.
871  */
872 static void parse_inittab(void)
873 {
874 #ifdef CONFIG_FEATURE_USE_INITTAB
875         FILE *file;
876         char buf[INIT_BUFFS_SIZE], lineAsRead[INIT_BUFFS_SIZE];
877         char tmpConsole[CONSOLE_BUFF_SIZE];
878         char *id, *runlev, *action, *command, *eol;
879         const struct init_action_type *a = actions;
880
881
882         file = fopen(INITTAB, "r");
883         if (file == NULL) {
884                 /* No inittab file -- set up some default behavior */
885 #endif
886                 /* Reboot on Ctrl-Alt-Del */
887                 new_init_action(CTRLALTDEL, "/sbin/reboot", "");
888                 /* Umount all filesystems on halt/reboot */
889                 new_init_action(SHUTDOWN, "/bin/umount -a -r", "");
890                 /* Swapoff on halt/reboot */
891                 if(ENABLE_SWAPONOFF) new_init_action(SHUTDOWN, "/sbin/swapoff -a", "");
892                 /* Prepare to restart init when a HUP is received */
893                 new_init_action(RESTART, "/sbin/init", "");
894                 /* Askfirst shell on tty1-4 */
895                 new_init_action(ASKFIRST, bb_default_login_shell, "");
896                 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
897                 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
898                 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
899                 /* sysinit */
900                 new_init_action(SYSINIT, INIT_SCRIPT, "");
901
902                 return;
903 #ifdef CONFIG_FEATURE_USE_INITTAB
904         }
905
906         while (fgets(buf, INIT_BUFFS_SIZE, file) != NULL) {
907                 /* Skip leading spaces */
908                 for (id = buf; *id == ' ' || *id == '\t'; id++);
909
910                 /* Skip the line if it's a comment */
911                 if (*id == '#' || *id == '\n')
912                         continue;
913
914                 /* Trim the trailing \n */
915                 eol = strrchr(id, '\n');
916                 if (eol != NULL)
917                         *eol = '\0';
918
919                 /* Keep a copy around for posterity's sake (and error msgs) */
920                 strcpy(lineAsRead, buf);
921
922                 /* Separate the ID field from the runlevels */
923                 runlev = strchr(id, ':');
924                 if (runlev == NULL || *(runlev + 1) == '\0') {
925                         message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
926                         continue;
927                 } else {
928                         *runlev = '\0';
929                         ++runlev;
930                 }
931
932                 /* Separate the runlevels from the action */
933                 action = strchr(runlev, ':');
934                 if (action == NULL || *(action + 1) == '\0') {
935                         message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
936                         continue;
937                 } else {
938                         *action = '\0';
939                         ++action;
940                 }
941
942                 /* Separate the action from the command */
943                 command = strchr(action, ':');
944                 if (command == NULL || *(command + 1) == '\0') {
945                         message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
946                         continue;
947                 } else {
948                         *command = '\0';
949                         ++command;
950                 }
951
952                 /* Ok, now process it */
953                 for (a = actions; a->name != 0; a++) {
954                         if (strcmp(a->name, action) == 0) {
955                                 if (*id != '\0') {
956                                         if(strncmp(id, "/dev/", 5) == 0)
957                                                 id += 5;
958                                         strcpy(tmpConsole, "/dev/");
959                                         safe_strncpy(tmpConsole + 5, id,
960                                                 CONSOLE_BUFF_SIZE - 5);
961                                         id = tmpConsole;
962                                 }
963                                 new_init_action(a->action, command, id);
964                                 break;
965                         }
966                 }
967                 if (a->name == 0) {
968                         /* Choke on an unknown action */
969                         message(LOG | CONSOLE, "Bad inittab entry: %s", lineAsRead);
970                 }
971         }
972         fclose(file);
973         return;
974 #endif                                                  /* CONFIG_FEATURE_USE_INITTAB */
975 }
976
977 #ifdef CONFIG_FEATURE_USE_INITTAB
978 static void reload_signal(int sig ATTRIBUTE_UNUSED)
979 {
980         struct init_action *a, *tmp;
981
982         message(LOG, "Reloading /etc/inittab");
983
984         /* disable old entrys */
985         for (a = init_action_list; a; a = a->next ) {
986                 a->action = ONCE;
987         }
988
989         parse_inittab();
990
991         /* remove unused entrys */
992         for (a = init_action_list; a; a = tmp) {
993                 tmp = a->next;
994                 if (a->action & (ONCE | SYSINIT | WAIT ) &&
995                                 a->pid == 0 ) {
996                         delete_init_action(a);
997                 }
998         }
999         run_actions(RESPAWN);
1000         return;
1001 }
1002 #endif                                                  /* CONFIG_FEATURE_USE_INITTAB */
1003
1004 int init_main(int argc, char **argv)
1005 {
1006         struct init_action *a;
1007         pid_t wpid;
1008
1009         if (argc > 1 && !strcmp(argv[1], "-q")) {
1010                 return kill(1,SIGHUP);
1011         }
1012 #if !ENABLE_DEBUG_INIT
1013         /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
1014         if (getpid() != 1 &&
1015                 (!ENABLE_FEATURE_INITRD || !strstr(bb_applet_name, "linuxrc")))
1016         {
1017                 bb_show_usage();
1018         }
1019         /* Set up sig handlers  -- be sure to
1020          * clear all of these in run() */
1021         signal(SIGHUP, exec_signal);
1022         signal(SIGQUIT, exec_signal);
1023         signal(SIGUSR1, halt_signal);
1024         signal(SIGUSR2, halt_signal);
1025         signal(SIGINT, ctrlaltdel_signal);
1026         signal(SIGTERM, reboot_signal);
1027         signal(SIGCONT, cont_handler);
1028         signal(SIGSTOP, stop_handler);
1029         signal(SIGTSTP, stop_handler);
1030
1031         /* Turn off rebooting via CTL-ALT-DEL -- we get a
1032          * SIGINT on CAD so we can shut things down gracefully... */
1033         init_reboot(RB_DISABLE_CAD);
1034 #endif
1035
1036         /* Figure out where the default console should be */
1037         console_init();
1038
1039         /* Close whatever files are open, and reset the console. */
1040         close(0);
1041         close(1);
1042         close(2);
1043
1044         if (device_open(console, O_RDWR | O_NOCTTY) == 0) {
1045                 set_term();
1046                 close(0);
1047         }
1048
1049         chdir("/");
1050         setsid();
1051         {
1052                 const char * const *e;
1053                 /* Make sure environs is set to something sane */
1054                 for(e = environment; *e; e++)
1055                         putenv((char *) *e);
1056         }
1057         /* Hello world */
1058         message(MAYBE_CONSOLE | LOG, "init started:  %s", bb_msg_full_version);
1059
1060         /* Make sure there is enough memory to do something useful. */
1061         if (ENABLE_SWAPONOFF) {
1062                 struct sysinfo info;
1063
1064                 if (!sysinfo(&info) &&
1065                         (info.mem_unit ? : 1) * (long long)info.totalram < MEGABYTE)
1066                 {
1067                         message(CONSOLE,"Low memory: forcing swapon.");
1068                         /* swapon -a requires /proc typically */
1069                         new_init_action(SYSINIT, "/bin/mount -t proc proc /proc", "");
1070                         /* Try to turn on swap */
1071                         new_init_action(SYSINIT, "/sbin/swapon -a", "");
1072                         run_actions(SYSINIT);   /* wait and removing */
1073                 }
1074         }
1075
1076         /* Check if we are supposed to be in single user mode */
1077         if (argc > 1 && (!strcmp(argv[1], "single") ||
1078                                          !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
1079                 /* Start a shell on console */
1080                 new_init_action(RESPAWN, bb_default_login_shell, "");
1081         } else {
1082                 /* Not in single user mode -- see what inittab says */
1083
1084                 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
1085                  * then parse_inittab() simply adds in some default
1086                  * actions(i.e., runs INIT_SCRIPT and then starts a pair
1087                  * of "askfirst" shells */
1088                 parse_inittab();
1089         }
1090
1091 #ifdef CONFIG_SELINUX
1092         if (getenv("SELINUX_INIT") == NULL) {
1093                 int enforce = 0;
1094
1095                 putenv("SELINUX_INIT=YES");
1096                 if (selinux_init_load_policy(&enforce) == 0) {
1097                         execv(argv[0], argv);
1098                 } else if (enforce > 0) {
1099                         /* SELinux in enforcing mode but load_policy failed */
1100                         /* At this point, we probably can't open /dev/console, so log() won't work */
1101                         message(CONSOLE,"Unable to load SELinux Policy. Machine is in enforcing mode. Halting now.");
1102                         exit(1);
1103                 }
1104         }
1105 #endif /* CONFIG_SELINUX */
1106
1107         /* Make the command line just say "init"  -- thats all, nothing else */
1108         fixup_argv(argc, argv, "init");
1109
1110         /* Now run everything that needs to be run */
1111
1112         /* First run the sysinit command */
1113         run_actions(SYSINIT);
1114
1115         /* Next run anything that wants to block */
1116         run_actions(WAIT);
1117
1118         /* Next run anything to be run only once */
1119         run_actions(ONCE);
1120
1121 #ifdef CONFIG_FEATURE_USE_INITTAB
1122         /* Redefine SIGHUP to reread /etc/inittab */
1123         signal(SIGHUP, reload_signal);
1124 #else
1125         signal(SIGHUP, SIG_IGN);
1126 #endif /* CONFIG_FEATURE_USE_INITTAB */
1127
1128
1129         /* Now run the looping stuff for the rest of forever */
1130         while (1) {
1131                 /* run the respawn stuff */
1132                 run_actions(RESPAWN);
1133
1134                 /* run the askfirst stuff */
1135                 run_actions(ASKFIRST);
1136
1137                 /* Don't consume all CPU time -- sleep a bit */
1138                 sleep(1);
1139
1140                 /* Wait for a child process to exit */
1141                 wpid = wait(NULL);
1142                 while (wpid > 0) {
1143                         /* Find out who died and clean up their corpse */
1144                         for (a = init_action_list; a; a = a->next) {
1145                                 if (a->pid == wpid) {
1146                                         /* Set the pid to 0 so that the process gets
1147                                          * restarted by run_actions() */
1148                                         a->pid = 0;
1149                                         message(LOG, "Process '%s' (pid %d) exited.  "
1150                                                         "Scheduling it for restart.",
1151                                                         a->command, wpid);
1152                                 }
1153                         }
1154                         /* see if anyone else is waiting to be reaped */
1155                         wpid = waitpid (-1, NULL, WNOHANG);
1156                 }
1157         }
1158 }