1 /* vi: set sw=4 ts=4: */
3 * Mini init implementation for busybox
6 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
7 * Adjusted by so many folks, it's impossible to keep track.
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.
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.
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
25 /* Turn this on to disable all the dangerous
26 rebooting stuff when debugging.
31 #include <asm/types.h>
33 #include <linux/serial.h> /* for serial_struct */
34 #include <linux/version.h>
41 #include <sys/fcntl.h>
42 #include <sys/ioctl.h>
43 #include <sys/kdaemon.h>
44 #include <sys/mount.h>
45 #include <sys/reboot.h>
46 #include <sys/sysinfo.h> /* For check_free_memory() */
48 # include <sys/syslog.h>
50 #include <sys/sysmacros.h>
51 #include <sys/types.h>
52 #include <sys/vt.h> /* for vt_stat */
58 #if defined BB_FEATURE_INIT_COREDUMPS
60 * When a file named CORE_ENABLE_FLAG_FILE exists, setrlimit is called
61 * before processes are spawned to set core file size as unlimited.
62 * This is for debugging only. Don't use this is production, unless
63 * you want core dumps lying about....
65 #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
66 #include <sys/resource.h>
70 #ifndef KERNEL_VERSION
71 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
75 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
76 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
77 #define VT_LOG "/dev/tty3" /* Virtual console */
78 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
79 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
80 #define SHELL "/bin/sh" /* Default shell */
81 #define INITTAB "/etc/inittab" /* inittab file location */
83 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
89 /* Allowed init action types */
99 /* A mapping between "inittab" action name strings and action type codes. */
100 typedef struct initActionType {
102 initActionEnum action;
105 static const struct initActionType actions[] = {
106 {"sysinit", SYSINIT},
107 {"respawn", RESPAWN},
108 {"askfirst", ASKFIRST},
111 {"ctrlaltdel", CTRLALTDEL},
115 /* Set up a linked list of initActions, to be read from inittab */
116 typedef struct initActionTag initAction;
117 struct initActionTag {
122 initActionEnum action;
124 initAction *initActionList = NULL;
127 static char *secondConsole = VT_SECONDARY;
128 static char *log = VT_LOG;
129 static int kernelVersion = 0;
130 static char termType[32] = "TERM=linux";
131 static char console[32] = _PATH_CONSOLE;
133 static void delete_initAction(initAction * action);
136 /* Print a message to the specified device.
137 * Device may be bitwise-or'd from LOG | CONSOLE */
138 static void message(int device, char *fmt, ...)
139 __attribute__ ((format (printf, 2, 3)));
140 static void message(int device, char *fmt, ...)
147 /* Log the message to syslogd */
151 va_start(arguments, fmt);
152 vsnprintf(msg, sizeof(msg), fmt, arguments);
154 openlog("init", 0, LOG_USER);
155 syslog(LOG_USER|LOG_INFO, msg);
159 static int log_fd = -1;
161 /* Take full control of the log tty, and never close it.
162 * It's mine, all mine! Muhahahaha! */
165 /* don't even try to log, because there is no such console */
167 /* log to main console instead */
169 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
171 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
177 if ((device & LOG) && (log_fd >= 0)) {
178 va_start(arguments, fmt);
179 vdprintf(log_fd, fmt, arguments);
184 if (device & CONSOLE) {
185 /* Always send console messages to /dev/console so people will see them. */
188 device_open(_PATH_CONSOLE,
189 O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
190 va_start(arguments, fmt);
191 vdprintf(fd, fmt, arguments);
195 fprintf(stderr, "Bummer, can't print: ");
196 va_start(arguments, fmt);
197 vfprintf(stderr, fmt, arguments);
204 #define CTRLCHAR(ch) ((ch)&0x1f)
206 /* Set terminal settings to reasonable defaults */
207 void set_term(int fd)
213 /* set control chars */
214 tty.c_cc[VINTR] = CTRLCHAR('C'); /* Ctrl-C */
215 tty.c_cc[VQUIT] = CTRLCHAR('\\'); /* Ctrl-\ */
216 tty.c_cc[VERASE] = CTRLCHAR('?'); /* Ctrl-? */
217 tty.c_cc[VKILL] = CTRLCHAR('U'); /* Ctrl-U */
218 tty.c_cc[VEOF] = CTRLCHAR('D'); /* Ctrl-D */
219 tty.c_cc[VSTOP] = CTRLCHAR('S'); /* Ctrl-S */
220 tty.c_cc[VSTART] = CTRLCHAR('Q'); /* Ctrl-Q */
221 tty.c_cc[VSUSP] = CTRLCHAR('Z'); /* Ctrl-Z */
223 /* use line dicipline 0 */
226 /* Make it be sane */
227 tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
228 tty.c_cflag |= HUPCL|CLOCAL;
231 tty.c_iflag = ICRNL | IXON | IXOFF;
234 tty.c_oflag = OPOST | ONLCR;
238 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
240 tcsetattr(fd, TCSANOW, &tty);
243 /* How much memory does this machine have? */
244 static int check_free_memory()
249 if (sysinfo(&info) != 0) {
250 message(LOG, "Error checking free memory: %s\n", strerror(errno));
254 return((info.totalram+info.totalswap)/1024);
257 static void console_init()
260 int tried_devcons = 0;
261 int tried_vtprimary = 0;
263 struct serial_struct sr;
266 if ((s = getenv("TERM")) != NULL) {
267 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
270 if ((s = getenv("CONSOLE")) != NULL) {
271 snprintf(console, sizeof(console) - 1, "%s", s);
274 /* sparc kernel supports console=tty[ab] parameter which is also
275 * passed to init, so catch it here */
276 else if ((s = getenv("console")) != NULL) {
277 /* remap tty[ab] to /dev/ttyS[01] */
278 if (strcmp(s, "ttya") == 0)
279 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON0);
280 else if (strcmp(s, "ttyb") == 0)
281 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON1);
285 /* 2.2 kernels: identify the real console backend and try to use it */
286 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
287 /* this is a serial console */
288 snprintf(console, sizeof(console) - 1, "/dev/ttyS%d", sr.line);
289 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
290 /* this is linux virtual tty */
291 snprintf(console, sizeof(console) - 1, "/dev/tty%d",
294 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
299 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
300 /* Can't open selected console -- try /dev/console */
301 if (!tried_devcons) {
303 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
306 /* Can't open selected console -- try vt1 */
307 if (!tried_vtprimary) {
309 snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
315 /* Perhaps we should panic here? */
316 snprintf(console, sizeof(console) - 1, "/dev/null");
318 /* check for serial console and disable logging to tty3 & running a
320 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
322 secondConsole = NULL;
323 /* Force the TERM setting to vt102 for serial console --
324 * iff TERM is set to linux (the default) */
325 if (strcmp( termType, "TERM=linux" ) == 0)
326 snprintf(termType, sizeof(termType) - 1, "TERM=vt102");
327 message(LOG | CONSOLE,
328 "serial console detected. Disabling virtual terminals.\r\n");
332 message(LOG, "console=%s\n", console);
335 static pid_t run(char *command, char *terminal, int get_enter)
342 static const char press_enter[] =
344 "\nPlease press Enter to activate this console. ";
345 char *environment[] = {
347 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
355 if ((pid = fork()) == 0) {
362 /* Reset signal handlers set for parent process */
363 signal(SIGUSR1, SIG_DFL);
364 signal(SIGUSR2, SIG_DFL);
365 signal(SIGINT, SIG_DFL);
366 signal(SIGTERM, SIG_DFL);
367 signal(SIGHUP, SIG_DFL);
369 if ((fd = device_open(terminal, O_RDWR)) < 0) {
370 message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
376 tcsetpgrp(0, getpgrp());
379 if (get_enter == TRUE) {
381 * Save memory by not exec-ing anything large (like a shell)
382 * before the user wants it. This is critical if swap is not
383 * enabled and the system has low memory. Generally this will
384 * be run on the second virtual console, and the first will
385 * be allowed to start a shell or whatever an init script
390 pid_t shell_pgid = getpid();
391 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
392 command, shell_pgid, terminal);
394 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
395 read(fileno(stdin), &c, 1);
399 /* Log the process name and args */
400 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
401 shell_pgid, terminal, command);
404 /* See if any special /bin/sh requiring characters are present */
405 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
408 strcpy(buf, "exec ");
409 strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
413 /* Convert command (char*) into cmd (char**, one word per string) */
414 for (tmpCmd = command, i = 0;
415 (tmpCmd = strsep(&command, " \t")) != NULL;) {
416 if (*tmpCmd != '\0') {
425 #if defined BB_FEATURE_INIT_COREDUMPS
428 if (stat (CORE_ENABLE_FLAG_FILE, &sb) == 0) {
430 limit.rlim_cur = RLIM_INFINITY;
431 limit.rlim_max = RLIM_INFINITY;
432 setrlimit(RLIMIT_CORE, &limit);
437 /* Now run it. The new program will take over this PID,
438 * so nothing further in init.c should be run. */
439 execve(cmd[0], cmd, environment);
441 /* We're still here? Some error happened. */
442 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
449 static int waitfor(char *command, char *terminal, int get_enter)
452 int pid = run(command, terminal, get_enter);
455 wpid = wait(&status);
456 if (wpid > 0 && wpid != pid) {
465 /* Make sure there is enough memory to do something useful. *
466 * Calls "swapon -a" if needed so be sure /etc/fstab is present... */
467 static void check_memory()
471 if (check_free_memory() > 1000)
474 if (stat("/etc/fstab", &statBuf) == 0) {
475 /* swapon -a requires /proc typically */
476 waitfor("mount proc /proc -t proc", console, FALSE);
477 /* Try to turn on swap */
478 waitfor("swapon -a", console, FALSE);
479 if (check_free_memory() < 1000)
487 "Sorry, your computer does not have enough memory.\r\n");
492 /* Run all commands to be run right before halt/reboot */
493 static void run_lastAction(void)
496 for (a = initActionList; a; a = a->nextPtr) {
497 if (a->action == CTRLALTDEL) {
498 waitfor(a->process, a->console, FALSE);
499 delete_initAction(a);
506 static void shutdown_system(void)
509 /* first disable our SIGHUP signal */
510 signal(SIGHUP, SIG_DFL);
512 /* Allow Ctrl-Alt-Del to reboot system. */
513 reboot(RB_ENABLE_CAD);
515 message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
518 /* Send signals to every process _except_ pid 1 */
519 message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
524 message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
528 /* run everything to be run at "ctrlaltdel" */
532 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
533 /* bdflush, kupdate not needed for kernels >2.2.11 */
539 static void halt_signal(int sig)
543 "The system is halted. Press %s or turn off power\r\n",
544 (secondConsole == NULL) /* serial console */
545 ? "Reset" : "CTRL-ALT-DEL");
548 /* allow time for last message to reach serial console */
551 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
553 reboot(RB_POWER_OFF);
556 reboot(RB_HALT_SYSTEM);
560 static void reboot_signal(int sig)
563 message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
566 /* allow time for last message to reach serial console */
573 #if defined BB_FEATURE_INIT_CHROOT
575 #if ! defined BB_FEATURE_USE_PROCFS
576 #error Sorry, I depend on the /proc filesystem right now.
579 static void check_chroot(int sig)
581 char *argv_init[2] = { "init", NULL, };
582 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
583 char rootpath[256], *tc;
586 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
588 "SIGHUP recived, but could not open proc file\r\n");
592 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
594 "SIGHUP recived, but could not read proc file\r\n");
600 if (rootpath[0] == '\0') {
602 "SIGHUP recived, but new root is not valid: %s\r\n",
608 tc = strrchr(rootpath, '\n');
611 /* Ok, making it this far means we commit */
612 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
615 /* kill all other programs first */
616 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
621 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
626 /* ok, we don't need /proc anymore. we also assume that the signaling
627 * process left the rest of the filesystems alone for us */
630 /* Ok, now we chroot. Hopefully we only have two things mounted, the
631 * new chroot'd mount point, and the old "/" mount. s,
632 * we go ahead and unmount the old "/". This should trigger the kernel
633 * to set things up the Right Way(tm). */
635 if (!chroot(rootpath))
638 /* If the chroot fails, we are already too far to turn back, so we
639 * continue and hope that executing init below will revive the system */
641 /* close all of our descriptors and open new ones */
645 open("/dev/console", O_RDWR, 0);
649 message(CONSOLE, "Executing real init...\r\n");
650 /* execute init in the (hopefully) new root */
651 execve("/sbin/init", argv_init, envp_init);
654 "ERROR: Could not exec new init. Press %s to reboot.\r\n",
655 (secondConsole == NULL) /* serial console */
656 ? "Reset" : "CTRL-ALT-DEL");
659 #endif /* BB_FEATURE_INIT_CHROOT */
661 #endif /* ! DEBUG_INIT */
663 void new_initAction(initActionEnum action, char *process, char *cons)
665 initAction *newAction;
670 /* If BusyBox detects that a serial console is in use,
671 * then entries not refering to the console or null devices will _not_ be run.
672 * The exception to this rule is the null device.
674 if (secondConsole == NULL && strcmp(cons, console)
675 && strcmp(cons, "/dev/null"))
678 newAction = calloc((size_t) (1), sizeof(initAction));
680 message(LOG | CONSOLE, "Memory allocation failure\n");
684 newAction->nextPtr = initActionList;
685 initActionList = newAction;
686 strncpy(newAction->process, process, 255);
687 newAction->action = action;
688 strncpy(newAction->console, cons, 255);
690 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
691 // newAction->process, newAction->action, newAction->console);
694 static void delete_initAction(initAction * action)
696 initAction *a, *b = NULL;
698 for (a = initActionList; a; b = a, a = a->nextPtr) {
701 initActionList = a->nextPtr;
703 b->nextPtr = a->nextPtr;
711 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
712 * then parse_inittab() simply adds in some default
713 * actions(i.e runs INIT_SCRIPT and then starts a pair
714 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
715 * _is_ defined, but /etc/inittab is missing, this
716 * results in the same set of default behaviors.
718 void parse_inittab(void)
720 #ifdef BB_FEATURE_USE_INITTAB
722 char buf[256], lineAsRead[256], tmpConsole[256];
724 const struct initActionType *a = actions;
728 file = fopen(INITTAB, "r");
730 /* No inittab file -- set up some default behavior */
732 /* Swapoff on halt/reboot */
733 new_initAction(CTRLALTDEL, "/sbin/swapoff -a > /dev/null 2>&1", console);
734 /* Umount all filesystems on halt/reboot */
735 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
736 /* Askfirst shell on tty1 */
737 new_initAction(ASKFIRST, SHELL, console);
738 /* Askfirst shell on tty2 */
739 if (secondConsole != NULL)
740 new_initAction(ASKFIRST, SHELL, secondConsole);
742 new_initAction(SYSINIT, INIT_SCRIPT, console);
745 #ifdef BB_FEATURE_USE_INITTAB
748 while (fgets(buf, 255, file) != NULL) {
750 for (p = buf; *p == ' ' || *p == '\t'; p++);
751 if (*p == '#' || *p == '\n')
754 /* Trim the trailing \n */
755 q = strrchr(p, '\n');
759 /* Keep a copy around for posterity's sake (and error msgs) */
760 strcpy(lineAsRead, buf);
762 /* Grab the ID field */
765 if (p != NULL || *(p + 1) != '\0') {
770 /* Now peel off the process field from the end
773 if (q == NULL || *(q + 1) == '\0') {
774 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
781 /* Now peel off the action field */
783 if (r == NULL || *(r + 1) == '\0') {
784 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
790 /* Ok, now process it */
792 while (a->name != 0) {
793 if (strcmp(a->name, r) == 0) {
797 strcpy(tmpConsole, "/dev/");
798 strncat(tmpConsole, s, 200);
799 if (stat(tmpConsole, &statBuf) != 0) {
800 message(LOG | CONSOLE,
801 "device '%s' does not exist. Did you read the directions?\n",
807 new_initAction(a->action, q, s);
815 /* Choke on an unknown action */
816 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
820 #endif /* BB_FEATURE_USE_INITTAB */
825 extern int init_main(int argc, char **argv)
832 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
834 #ifdef BB_FEATURE_LINUXRC
835 && strstr(argv[0], "linuxrc") == NULL
839 usage("init\n\nInit is the parent of all processes.\n\n"
840 "This version of init is designed to be run only "
843 /* Set up sig handlers -- be sure to
844 * clear all of these in run() */
845 signal(SIGUSR1, halt_signal);
846 signal(SIGUSR2, reboot_signal);
847 signal(SIGINT, reboot_signal);
848 signal(SIGTERM, reboot_signal);
849 #if defined BB_FEATURE_INIT_CHROOT
850 signal(SIGHUP, check_chroot);
853 /* Turn off rebooting via CTL-ALT-DEL -- we get a
854 * SIGINT on CAD so we can shut things down gracefully... */
855 reboot(RB_DISABLE_CAD);
858 /* Figure out what kernel this is running */
859 kernelVersion = get_kernel_revision();
861 /* Figure out where the default console should be */
864 /* Close whatever files are open, and reset the console. */
872 /* Make sure PATH is set to something sane */
873 putenv(_PATH_STDPATH);
878 #if ! defined BB_FEATURE_EXTRA_QUIET
882 "init started: BusyBox v%s (%s) multi-call binary\r\n",
886 #if ! defined BB_FEATURE_EXTRA_QUIET
890 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
891 getpid(), BB_VER, BB_BT);
895 /* Make sure there is enough memory to do something useful. */
898 /* Check if we are supposed to be in single user mode */
899 if (argc > 1 && (!strcmp(argv[1], "single") ||
900 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
901 /* Ask first then start a shell on tty2 */
902 if (secondConsole != NULL)
903 new_initAction(ASKFIRST, SHELL, secondConsole);
904 /* Start a shell on tty1 */
905 new_initAction(RESPAWN, SHELL, console);
907 /* Not in single user mode -- see what inittab says */
909 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
910 * then parse_inittab() simply adds in some default
911 * actions(i.e runs INIT_SCRIPT and then starts a pair
912 * of "askfirst" shells */
916 /* Fix up argv[0] to be certain we claim to be init */
917 strncpy(argv[0], "init", strlen(argv[0])+1);
919 strncpy(argv[1], "\0", strlen(argv[1])+1);
921 /* Now run everything that needs to be run */
923 /* First run the sysinit command */
924 for (a = initActionList; a; a = a->nextPtr) {
925 if (a->action == SYSINIT) {
926 waitfor(a->process, a->console, FALSE);
927 /* Now remove the "sysinit" entry from the list */
928 delete_initAction(a);
931 /* Next run anything that wants to block */
932 for (a = initActionList; a; a = a->nextPtr) {
933 if (a->action == WAIT) {
934 waitfor(a->process, a->console, FALSE);
935 /* Now remove the "wait" entry from the list */
936 delete_initAction(a);
939 /* Next run anything to be run only once */
940 for (a = initActionList; a; a = a->nextPtr) {
941 if (a->action == ONCE) {
942 run(a->process, a->console, FALSE);
943 /* Now remove the "once" entry from the list */
944 delete_initAction(a);
947 /* If there is nothing else to do, stop */
948 if (initActionList == NULL) {
949 message(LOG | CONSOLE,
950 "No more tasks for init -- sleeping forever.\n");
955 /* Now run the looping stuff for the rest of forever */
957 for (a = initActionList; a; a = a->nextPtr) {
958 /* Only run stuff with pid==0. If they have
959 * a pid, that means they are still running */
963 /* run the respawn stuff */
964 a->pid = run(a->process, a->console, FALSE);
967 /* run the askfirst stuff */
968 a->pid = run(a->process, a->console, TRUE);
970 /* silence the compiler's incessant whining */
976 /* Wait for a child process to exit */
977 wpid = wait(&status);
979 /* Find out who died and clean up their corpse */
980 for (a = initActionList; a; a = a->nextPtr) {
981 if (a->pid == wpid) {
984 "Process '%s' (pid %d) exited. Scheduling it for restart.\n",
995 c-file-style: "linux"