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