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 */
57 #ifndef KERNEL_VERSION
58 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
62 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
63 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
64 #define VT_LOG "/dev/tty3" /* Virtual console */
65 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
66 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
67 #define SHELL "/bin/sh" /* Default shell */
68 #define INITTAB "/etc/inittab" /* inittab file location */
70 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
76 /* Allowed init action types */
86 /* A mapping between "inittab" action name strings and action type codes. */
87 typedef struct initActionType {
89 initActionEnum action;
92 static const struct initActionType actions[] = {
95 {"askfirst", ASKFIRST},
98 {"ctrlaltdel", CTRLALTDEL},
102 /* Set up a linked list of initActions, to be read from inittab */
103 typedef struct initActionTag initAction;
104 struct initActionTag {
109 initActionEnum action;
111 initAction *initActionList = NULL;
114 static char *secondConsole = VT_SECONDARY;
115 static char *log = VT_LOG;
116 static int kernelVersion = 0;
117 static char termType[32] = "TERM=linux";
118 static char console[32] = _PATH_CONSOLE;
120 static void delete_initAction(initAction * action);
123 /* Print a message to the specified device.
124 * Device may be bitwise-or'd from LOG | CONSOLE */
125 static void message(int device, char *fmt, ...)
132 /* Log the message to syslogd */
136 va_start(arguments, fmt);
137 vsnprintf(msg, sizeof(msg), fmt, arguments);
139 openlog("init", 0, LOG_USER);
140 syslog(LOG_USER|LOG_INFO, msg);
144 static int log_fd = -1;
146 /* Take full control of the log tty, and never close it.
147 * It's mine, all mine! Muhahahaha! */
150 /* don't even try to log, because there is no such console */
152 /* log to main console instead */
154 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
156 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
162 if ((device & LOG) && (log_fd >= 0)) {
163 va_start(arguments, fmt);
164 vdprintf(log_fd, fmt, arguments);
169 if (device & CONSOLE) {
170 /* Always send console messages to /dev/console so people will see them. */
173 device_open(_PATH_CONSOLE,
174 O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
175 va_start(arguments, fmt);
176 vdprintf(fd, fmt, arguments);
180 fprintf(stderr, "Bummer, can't print: ");
181 va_start(arguments, fmt);
182 vfprintf(stderr, fmt, arguments);
190 /* Set terminal settings to reasonable defaults */
191 void set_term(int fd)
197 /* set control chars */
198 tty.c_cc[VINTR] = 3; /* C-c */
199 tty.c_cc[VQUIT] = 28; /* C-\ */
200 tty.c_cc[VERASE] = 127; /* C-? */
201 tty.c_cc[VKILL] = 21; /* C-u */
202 tty.c_cc[VEOF] = 4; /* C-d */
203 tty.c_cc[VSTART] = 17; /* C-q */
204 tty.c_cc[VSTOP] = 19; /* C-s */
205 tty.c_cc[VSUSP] = 26; /* C-z */
207 /* use line dicipline 0 */
210 /* Make it be sane */
211 tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
212 tty.c_cflag |= HUPCL|CLOCAL;
215 tty.c_iflag = ICRNL | IXON | IXOFF;
218 tty.c_oflag = OPOST | ONLCR;
222 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
224 tcsetattr(fd, TCSANOW, &tty);
227 /* How much memory does this machine have? */
228 static int check_free_memory()
233 if (sysinfo(&info) != 0) {
234 message(LOG, "Error checking free memory: %s\n", strerror(errno));
238 return((info.totalram+info.totalswap)/1024);
241 static void console_init()
244 int tried_devcons = 0;
245 int tried_vtprimary = 0;
247 struct serial_struct sr;
250 if ((s = getenv("TERM")) != NULL) {
251 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
254 if ((s = getenv("CONSOLE")) != NULL) {
255 snprintf(console, sizeof(console) - 1, "%s", s);
258 /* sparc kernel supports console=tty[ab] parameter which is also
259 * passed to init, so catch it here */
260 else if ((s = getenv("console")) != NULL) {
261 /* remap tty[ab] to /dev/ttyS[01] */
262 if (strcmp(s, "ttya") == 0)
263 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON0);
264 else if (strcmp(s, "ttyb") == 0)
265 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON1);
269 /* 2.2 kernels: identify the real console backend and try to use it */
270 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
271 /* this is a serial console */
272 snprintf(console, sizeof(console) - 1, "/dev/ttyS%d", sr.line);
273 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
274 /* this is linux virtual tty */
275 snprintf(console, sizeof(console) - 1, "/dev/tty%d",
278 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
283 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
284 /* Can't open selected console -- try /dev/console */
285 if (!tried_devcons) {
287 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
290 /* Can't open selected console -- try vt1 */
291 if (!tried_vtprimary) {
293 snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
299 /* Perhaps we should panic here? */
300 snprintf(console, sizeof(console) - 1, "/dev/null");
302 /* check for serial console and disable logging to tty3 & running a
304 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
306 secondConsole = NULL;
307 /* Force the TERM setting to vt102 for serial console --
308 * iff TERM is set to linux (the default) */
309 if (strcmp( termType, "TERM=linux" ) == 0)
310 snprintf(termType, sizeof(termType) - 1, "TERM=vt102");
311 message(LOG | CONSOLE,
312 "serial console detected. Disabling virtual terminals.\r\n");
316 message(LOG, "console=%s\n", console);
319 static pid_t run(char *command, char *terminal, int get_enter)
326 static const char press_enter[] =
328 "\nPlease press Enter to activate this console. ";
329 char *environment[] = {
331 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
339 if ((pid = fork()) == 0) {
346 /* Reset signal handlers set for parent process */
347 signal(SIGUSR1, SIG_DFL);
348 signal(SIGUSR2, SIG_DFL);
349 signal(SIGINT, SIG_DFL);
350 signal(SIGTERM, SIG_DFL);
351 signal(SIGHUP, SIG_DFL);
353 if ((fd = device_open(terminal, O_RDWR)) < 0) {
354 message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
360 tcsetpgrp(0, getpgrp());
363 if (get_enter == TRUE) {
365 * Save memory by not exec-ing anything large (like a shell)
366 * before the user wants it. This is critical if swap is not
367 * enabled and the system has low memory. Generally this will
368 * be run on the second virtual console, and the first will
369 * be allowed to start a shell or whatever an init script
374 pid_t shell_pgid = getpid();
375 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
376 command, shell_pgid, terminal);
378 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
379 read(fileno(stdin), &c, 1);
383 /* Log the process name and args */
384 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
385 shell_pgid, terminal, command);
388 /* See if any special /bin/sh requiring characters are present */
389 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
392 strcpy(buf, "exec ");
393 strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
397 /* Convert command (char*) into cmd (char**, one word per string) */
398 for (tmpCmd = command, i = 0;
399 (tmpCmd = strsep(&command, " \t")) != NULL;) {
400 if (*tmpCmd != '\0') {
409 /* Now run it. The new program will take over this PID,
410 * so nothing further in init.c should be run. */
411 execve(cmd[0], cmd, environment);
413 /* We're still here? Some error happened. */
414 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
421 static int waitfor(char *command, char *terminal, int get_enter)
424 int pid = run(command, terminal, get_enter);
427 wpid = wait(&status);
428 if (wpid > 0 && wpid != pid) {
437 /* Make sure there is enough memory to do something useful. *
438 * Calls "swapon -a" if needed so be sure /etc/fstab is present... */
439 static void check_memory()
443 if (check_free_memory() > 1000)
446 if (stat("/etc/fstab", &statBuf) == 0) {
447 /* Try to turn on swap */
448 system("/sbin/swapon -a");
449 if (check_free_memory() < 1000)
457 "Sorry, your computer does not have enough memory.\r\n");
462 /* Run all commands to be run right before halt/reboot */
463 static void run_lastAction(void)
466 for (a = initActionList; a; a = a->nextPtr) {
467 if (a->action == CTRLALTDEL) {
468 waitfor(a->process, a->console, FALSE);
469 delete_initAction(a);
476 static void shutdown_system(void)
479 /* first disable our SIGHUP signal */
480 signal(SIGHUP, SIG_DFL);
482 /* Allow Ctrl-Alt-Del to reboot system. */
483 reboot(RB_ENABLE_CAD);
485 message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
488 /* Send signals to every process _except_ pid 1 */
489 message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
494 message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
498 /* run everything to be run at "ctrlaltdel" */
502 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
503 /* bdflush, kupdate not needed for kernels >2.2.11 */
509 static void halt_signal(int sig)
513 "The system is halted. Press %s or turn off power\r\n",
514 (secondConsole == NULL) /* serial console */
515 ? "Reset" : "CTRL-ALT-DEL");
518 /* allow time for last message to reach serial console */
521 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
523 reboot(RB_POWER_OFF);
526 reboot(RB_HALT_SYSTEM);
530 static void reboot_signal(int sig)
533 message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
536 /* allow time for last message to reach serial console */
543 #if defined BB_FEATURE_INIT_CHROOT
545 #if ! defined BB_FEATURE_USE_PROCFS
546 #error Sorry, I depend on the /proc filesystem right now.
549 static void check_chroot(int sig)
551 char *argv_init[2] = { "init", NULL, };
552 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
553 char rootpath[256], *tc;
556 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
558 "SIGHUP recived, but could not open proc file\r\n");
562 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
564 "SIGHUP recived, but could not read proc file\r\n");
570 if (rootpath[0] == '\0') {
572 "SIGHUP recived, but new root is not valid: %s\r\n",
578 tc = strrchr(rootpath, '\n');
581 /* Ok, making it this far means we commit */
582 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
585 /* kill all other programs first */
586 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
591 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
596 /* ok, we don't need /proc anymore. we also assume that the signaling
597 * process left the rest of the filesystems alone for us */
600 /* Ok, now we chroot. Hopefully we only have two things mounted, the
601 * new chroot'd mount point, and the old "/" mount. s,
602 * we go ahead and unmount the old "/". This should trigger the kernel
603 * to set things up the Right Way(tm). */
605 if (!chroot(rootpath))
608 /* If the chroot fails, we are already too far to turn back, so we
609 * continue and hope that executing init below will revive the system */
611 /* close all of our descriptors and open new ones */
615 open("/dev/console", O_RDWR, 0);
619 message(CONSOLE, "Executing real init...\r\n");
620 /* execute init in the (hopefully) new root */
621 execve("/sbin/init", argv_init, envp_init);
624 "ERROR: Could not exec new init. Press %s to reboot.\r\n",
625 (secondConsole == NULL) /* serial console */
626 ? "Reset" : "CTRL-ALT-DEL");
629 #endif /* BB_FEATURE_INIT_CHROOT */
631 #endif /* ! DEBUG_INIT */
633 void new_initAction(initActionEnum action, char *process, char *cons)
635 initAction *newAction;
640 /* If BusyBox detects that a serial console is in use,
641 * then entries not refering to the console or null devices will _not_ be run.
642 * The exception to this rule is the null device.
644 if (secondConsole == NULL && strcmp(cons, console)
645 && strcmp(cons, "/dev/null"))
648 newAction = calloc((size_t) (1), sizeof(initAction));
650 message(LOG | CONSOLE, "Memory allocation failure\n");
654 newAction->nextPtr = initActionList;
655 initActionList = newAction;
656 strncpy(newAction->process, process, 255);
657 newAction->action = action;
658 strncpy(newAction->console, cons, 255);
660 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
661 // newAction->process, newAction->action, newAction->console);
664 static void delete_initAction(initAction * action)
666 initAction *a, *b = NULL;
668 for (a = initActionList; a; b = a, a = a->nextPtr) {
671 initActionList = a->nextPtr;
673 b->nextPtr = a->nextPtr;
681 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
682 * then parse_inittab() simply adds in some default
683 * actions(i.e runs INIT_SCRIPT and then starts a pair
684 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
685 * _is_ defined, but /etc/inittab is missing, this
686 * results in the same set of default behaviors.
688 void parse_inittab(void)
690 #ifdef BB_FEATURE_USE_INITTAB
692 char buf[256], lineAsRead[256], tmpConsole[256];
694 const struct initActionType *a = actions;
698 file = fopen(INITTAB, "r");
700 /* No inittab file -- set up some default behavior */
702 /* Swapoff on halt/reboot */
703 new_initAction(CTRLALTDEL, "/sbin/swapoff -a > /dev/null 2>&1", console);
704 /* Umount all filesystems on halt/reboot */
705 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
706 /* Askfirst shell on tty1 */
707 new_initAction(ASKFIRST, SHELL, console);
708 /* Askfirst shell on tty2 */
709 if (secondConsole != NULL)
710 new_initAction(ASKFIRST, SHELL, secondConsole);
712 new_initAction(SYSINIT, INIT_SCRIPT, console);
715 #ifdef BB_FEATURE_USE_INITTAB
718 while (fgets(buf, 255, file) != NULL) {
720 for (p = buf; *p == ' ' || *p == '\t'; p++);
721 if (*p == '#' || *p == '\n')
724 /* Trim the trailing \n */
725 q = strrchr(p, '\n');
729 /* Keep a copy around for posterity's sake (and error msgs) */
730 strcpy(lineAsRead, buf);
732 /* Grab the ID field */
735 if (p != NULL || *(p + 1) != '\0') {
740 /* Now peel off the process field from the end
743 if (q == NULL || *(q + 1) == '\0') {
744 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
751 /* Now peel off the action field */
753 if (r == NULL || *(r + 1) == '\0') {
754 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
760 /* Ok, now process it */
762 while (a->name != 0) {
763 if (strcmp(a->name, r) == 0) {
767 strcpy(tmpConsole, "/dev/");
768 strncat(tmpConsole, s, 200);
769 if (stat(tmpConsole, &statBuf) != 0) {
770 message(LOG | CONSOLE,
771 "device '%s' does not exist. Did you read the directions?\n",
777 new_initAction(a->action, q, s);
785 /* Choke on an unknown action */
786 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
790 #endif /* BB_FEATURE_USE_INITTAB */
795 extern int init_main(int argc, char **argv)
802 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
804 #ifdef BB_FEATURE_LINUXRC
805 && strstr(argv[0], "linuxrc") == NULL
809 usage("init\n\nInit is the parent of all processes.\n\n"
810 "This version of init is designed to be run only "
813 /* Set up sig handlers -- be sure to
814 * clear all of these in run() */
815 signal(SIGUSR1, halt_signal);
816 signal(SIGUSR2, reboot_signal);
817 signal(SIGINT, reboot_signal);
818 signal(SIGTERM, reboot_signal);
819 #if defined BB_FEATURE_INIT_CHROOT
820 signal(SIGHUP, check_chroot);
823 /* Turn off rebooting via CTL-ALT-DEL -- we get a
824 * SIGINT on CAD so we can shut things down gracefully... */
825 reboot(RB_DISABLE_CAD);
828 /* Figure out where the default console should be */
831 /* Close whatever files are open, and reset the console. */
838 /* Make sure PATH is set to something sane */
839 putenv(_PATH_STDPATH);
844 #if ! defined BB_FEATURE_EXTRA_QUIET
848 "init started: BusyBox v%s (%s) multi-call binary\r\n",
852 #if ! defined BB_FEATURE_EXTRA_QUIET
856 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
857 getpid(), BB_VER, BB_BT);
861 /* Make sure there is enough memory to do something useful. */
864 /* Check if we are supposed to be in single user mode */
865 if (argc > 1 && (!strcmp(argv[1], "single") ||
866 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
867 /* Ask first then start a shell on tty2 */
868 if (secondConsole != NULL)
869 new_initAction(ASKFIRST, SHELL, secondConsole);
870 /* Start a shell on tty1 */
871 new_initAction(RESPAWN, SHELL, console);
873 /* Not in single user mode -- see what inittab says */
875 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
876 * then parse_inittab() simply adds in some default
877 * actions(i.e runs INIT_SCRIPT and then starts a pair
878 * of "askfirst" shells */
882 /* Fix up argv[0] to be certain we claim to be init */
883 strncpy(argv[0], "init", strlen(argv[0])+1);
885 strncpy(argv[1], "\0", strlen(argv[1])+1);
887 /* Now run everything that needs to be run */
889 /* First run the sysinit command */
890 for (a = initActionList; a; a = a->nextPtr) {
891 if (a->action == SYSINIT) {
892 waitfor(a->process, a->console, FALSE);
893 /* Now remove the "sysinit" entry from the list */
894 delete_initAction(a);
897 /* Next run anything that wants to block */
898 for (a = initActionList; a; a = a->nextPtr) {
899 if (a->action == WAIT) {
900 waitfor(a->process, a->console, FALSE);
901 /* Now remove the "wait" entry from the list */
902 delete_initAction(a);
905 /* Next run anything to be run only once */
906 for (a = initActionList; a; a = a->nextPtr) {
907 if (a->action == ONCE) {
908 run(a->process, a->console, FALSE);
909 /* Now remove the "once" entry from the list */
910 delete_initAction(a);
913 /* If there is nothing else to do, stop */
914 if (initActionList == NULL) {
915 message(LOG | CONSOLE,
916 "No more tasks for init -- sleeping forever.\n");
921 /* Now run the looping stuff for the rest of forever */
923 for (a = initActionList; a; a = a->nextPtr) {
924 /* Only run stuff with pid==0. If they have
925 * a pid, that means they are still running */
929 /* run the respawn stuff */
930 a->pid = run(a->process, a->console, FALSE);
933 /* run the askfirst stuff */
934 a->pid = run(a->process, a->console, TRUE);
936 /* silence the compiler's incessant whining */
942 /* Wait for a child process to exit */
943 wpid = wait(&status);
945 /* Find out who died and clean up their corpse */
946 for (a = initActionList; a; a = a->nextPtr) {
947 if (a->pid == wpid) {
950 "Process '%s' (pid %d) exited. Scheduling it for restart.\n",
961 c-file-style: "linux"