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