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.
40 #include <sys/types.h>
41 #include <sys/fcntl.h>
44 #include <sys/mount.h>
45 #include <sys/reboot.h>
46 #include <sys/kdaemon.h>
47 #include <sys/sysmacros.h>
48 #include <asm/types.h>
49 #include <linux/serial.h> /* for serial_struct */
50 #include <sys/vt.h> /* for vt_stat */
51 #include <sys/ioctl.h>
52 #include <sys/sysinfo.h> /* For check_free_memory() */
53 #include <linux/version.h>
55 #include <sys/syslog.h>
58 #ifndef KERNEL_VERSION
59 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
63 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
64 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
65 #define VT_LOG "/dev/tty3" /* Virtual console */
66 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
67 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
68 #define SHELL "/bin/sh" /* Default shell */
69 #define INITTAB "/etc/inittab" /* inittab file location */
71 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
77 /* Allowed init action types */
87 /* And now a list of the actions we support in the version of init */
88 typedef struct initActionType {
90 initActionEnum action;
93 static const struct initActionType actions[] = {
96 {"askfirst", ASKFIRST},
99 {"ctrlaltdel", CTRLALTDEL},
103 /* Set up a linked list of initactions, to be read from inittab */
104 typedef struct initActionTag initAction;
105 struct initActionTag {
110 initActionEnum action;
112 initAction *initActionList = NULL;
115 static char *secondConsole = VT_SECONDARY;
116 static char *log = VT_LOG;
117 static int kernelVersion = 0;
118 static char termType[32] = "TERM=linux";
119 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 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.freeram/1024);
242 static void console_init()
245 int tried_devcons = 0;
246 int tried_vtprimary = 0;
248 struct serial_struct sr;
251 if ((s = getenv("TERM")) != NULL) {
252 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
255 if ((s = getenv("CONSOLE")) != NULL) {
256 snprintf(console, sizeof(console) - 1, "%s", s);
259 /* sparc kernel supports console=tty[ab] parameter which is also
260 * passed to init, so catch it here */
261 else if ((s = getenv("console")) != NULL) {
262 /* remap tty[ab] to /dev/ttyS[01] */
263 if (strcmp(s, "ttya") == 0)
264 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON0);
265 else if (strcmp(s, "ttyb") == 0)
266 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON1);
270 /* 2.2 kernels: identify the real console backend and try to use it */
271 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
272 /* this is a serial console */
273 snprintf(console, sizeof(console) - 1, "/dev/ttyS%d", sr.line);
274 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
275 /* this is linux virtual tty */
276 snprintf(console, sizeof(console) - 1, "/dev/tty%d",
279 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
284 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
285 /* Can't open selected console -- try /dev/console */
286 if (!tried_devcons) {
288 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
291 /* Can't open selected console -- try vt1 */
292 if (!tried_vtprimary) {
294 snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
300 /* Perhaps we should panic here? */
301 snprintf(console, sizeof(console) - 1, "/dev/null");
303 /* check for serial console and disable logging to tty3 & running a
305 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
307 secondConsole = NULL;
308 /* Force the TERM setting to vt102 for serial console --
309 * iff TERM is set to linux (the default) */
310 if (strcmp( termType, "TERM=linux" ) == 0)
311 snprintf(termType, sizeof(termType) - 1, "TERM=vt102");
312 message(LOG | CONSOLE,
313 "serial console detected. Disabling virtual terminals.\r\n");
317 message(LOG, "console=%s\n", console);
320 static pid_t run(char *command, char *terminal, int get_enter)
327 static const char press_enter[] =
329 "\nPlease press Enter to activate this console. ";
330 char *environment[] = {
332 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
340 if ((pid = fork()) == 0) {
347 /* Reset signal handlers set for parent process */
348 signal(SIGUSR1, SIG_DFL);
349 signal(SIGUSR2, SIG_DFL);
350 signal(SIGINT, SIG_DFL);
351 signal(SIGTERM, SIG_DFL);
352 signal(SIGHUP, SIG_DFL);
354 if ((fd = device_open(terminal, O_RDWR)) < 0) {
355 message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
361 tcsetpgrp(0, getpgrp());
364 if (get_enter == TRUE) {
366 * Save memory by not exec-ing anything large (like a shell)
367 * before the user wants it. This is critical if swap is not
368 * enabled and the system has low memory. Generally this will
369 * be run on the second virtual console, and the first will
370 * be allowed to start a shell or whatever an init script
375 pid_t shell_pgid = getpid();
376 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
377 command, shell_pgid, terminal);
379 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
380 read(fileno(stdin), &c, 1);
384 /* Log the process name and args */
385 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
386 shell_pgid, terminal, command);
389 /* See if any special /bin/sh requiring characters are present */
390 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
393 strcpy(buf, "exec ");
394 strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
398 /* Convert command (char*) into cmd (char**, one word per string) */
399 for (tmpCmd = command, i = 0;
400 (tmpCmd = strsep(&command, " \t")) != NULL;) {
401 if (*tmpCmd != '\0') {
410 /* Now run it. The new program will take over this PID,
411 * so nothing further in init.c should be run. */
412 execve(cmd[0], cmd, environment);
414 /* We're still here? Some error happened. */
415 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
422 static int waitfor(char *command, char *terminal, int get_enter)
425 int pid = run(command, terminal, get_enter);
428 wpid = wait(&status);
429 if (wpid > 0 && wpid != pid) {
438 /* Make sure there is enough memory to do something useful. *
439 * Calls "swapon -a" if needed so be sure /etc/fstab is present... */
440 static void check_memory()
444 if (check_free_memory() > 1000)
447 if (stat("/etc/fstab", &statBuf) == 0) {
448 /* Try to turn on swap */
449 system("/sbin/swapon -a");
450 if (check_free_memory() < 1000)
458 "Sorry, your computer does not have enough memory.\r\n");
463 /* Run all commands to be run right before halt/reboot */
464 static void run_lastAction(void)
467 for (a = initActionList; a; a = a->nextPtr) {
468 if (a->action == CTRLALTDEL) {
469 waitfor(a->process, a->console, FALSE);
470 delete_initAction(a);
477 static void shutdown_system(void)
480 /* first disable our SIGHUP signal */
481 signal(SIGHUP, SIG_DFL);
483 /* Allow Ctrl-Alt-Del to reboot system. */
484 reboot(RB_ENABLE_CAD);
486 message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
489 /* Send signals to every process _except_ pid 1 */
490 message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
495 message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
499 /* run everything to be run at "ctrlaltdel" */
503 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
504 /* bdflush, kupdate not needed for kernels >2.2.11 */
510 static void halt_signal(int sig)
514 "The system is halted. Press %s or turn off power\r\n",
515 (secondConsole == NULL) /* serial console */
516 ? "Reset" : "CTRL-ALT-DEL");
519 /* allow time for last message to reach serial console */
522 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
524 reboot(RB_POWER_OFF);
527 reboot(RB_HALT_SYSTEM);
531 static void reboot_signal(int sig)
534 message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
537 /* allow time for last message to reach serial console */
544 #if defined BB_FEATURE_INIT_CHROOT
546 #if ! defined BB_FEATURE_USE_PROCFS
547 #error Sorry, I depend on the /proc filesystem right now.
550 static void check_chroot(int sig)
552 char *argv_init[2] = { "init", NULL, };
553 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
554 char rootpath[256], *tc;
557 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
559 "SIGHUP recived, but could not open proc file\r\n");
563 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
565 "SIGHUP recived, but could not read proc file\r\n");
571 if (rootpath[0] == '\0') {
573 "SIGHUP recived, but new root is not valid: %s\r\n",
579 tc = strrchr(rootpath, '\n');
582 /* Ok, making it this far means we commit */
583 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
586 /* kill all other programs first */
587 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
592 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
597 /* ok, we don't need /proc anymore. we also assume that the signaling
598 * process left the rest of the filesystems alone for us */
601 /* Ok, now we chroot. Hopefully we only have two things mounted, the
602 * new chroot'd mount point, and the old "/" mount. s,
603 * we go ahead and unmount the old "/". This should trigger the kernel
604 * to set things up the Right Way(tm). */
606 if (!chroot(rootpath))
609 /* If the chroot fails, we are already too far to turn back, so we
610 * continue and hope that executing init below will revive the system */
612 /* close all of our descriptors and open new ones */
616 open("/dev/console", O_RDWR, 0);
620 message(CONSOLE, "Executing real init...\r\n");
621 /* execute init in the (hopefully) new root */
622 execve("/sbin/init", argv_init, envp_init);
625 "ERROR: Could not exec new init. Press %s to reboot.\r\n",
626 (secondConsole == NULL) /* serial console */
627 ? "Reset" : "CTRL-ALT-DEL");
630 #endif /* BB_FEATURE_INIT_CHROOT */
632 #endif /* ! DEBUG_INIT */
634 void new_initAction(initActionEnum action, char *process, char *cons)
636 initAction *newAction;
641 /* If BusyBox detects that a serial console is in use,
642 * then entries not refering to the console or null devices will _not_ be run.
643 * The exception to this rule is the null device.
645 if (secondConsole == NULL && strcmp(cons, console)
646 && strcmp(cons, "/dev/null"))
649 newAction = calloc((size_t) (1), sizeof(initAction));
651 message(LOG | CONSOLE, "Memory allocation failure\n");
655 newAction->nextPtr = initActionList;
656 initActionList = newAction;
657 strncpy(newAction->process, process, 255);
658 newAction->action = action;
659 strncpy(newAction->console, cons, 255);
661 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
662 // newAction->process, newAction->action, newAction->console);
665 static void delete_initAction(initAction * action)
667 initAction *a, *b = NULL;
669 for (a = initActionList; a; b = a, a = a->nextPtr) {
672 initActionList = a->nextPtr;
674 b->nextPtr = a->nextPtr;
682 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
683 * then parse_inittab() simply adds in some default
684 * actions(i.e runs INIT_SCRIPT and then starts a pair
685 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
686 * _is_ defined, but /etc/inittab is missing, this
687 * results in the same set of default behaviors.
689 void parse_inittab(void)
691 #ifdef BB_FEATURE_USE_INITTAB
693 char buf[256], lineAsRead[256], tmpConsole[256];
695 const struct initActionType *a = actions;
699 file = fopen(INITTAB, "r");
701 /* No inittab file -- set up some default behavior */
703 /* Swapoff on halt/reboot */
704 new_initAction(CTRLALTDEL, "/sbin/swapoff -a > /dev/null 2>&1", console);
705 /* Umount all filesystems on halt/reboot */
706 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
707 /* Askfirst shell on tty1 */
708 new_initAction(ASKFIRST, SHELL, console);
709 /* Askfirst shell on tty2 */
710 if (secondConsole != NULL)
711 new_initAction(ASKFIRST, SHELL, secondConsole);
713 new_initAction(SYSINIT, INIT_SCRIPT, console);
716 #ifdef BB_FEATURE_USE_INITTAB
719 while (fgets(buf, 255, file) != NULL) {
721 for (p = buf; *p == ' ' || *p == '\t'; p++);
722 if (*p == '#' || *p == '\n')
725 /* Trim the trailing \n */
726 q = strrchr(p, '\n');
730 /* Keep a copy around for posterity's sake (and error msgs) */
731 strcpy(lineAsRead, buf);
733 /* Grab the ID field */
736 if (p != NULL || *(p + 1) != '\0') {
741 /* Now peal off the process field from the end
744 if (q == NULL || *(q + 1) == '\0') {
745 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
752 /* Now peal off the action field */
754 if (r == NULL || *(r + 1) == '\0') {
755 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
761 /* Ok, now process it */
763 while (a->name != 0) {
764 if (strcmp(a->name, r) == 0) {
768 strcpy(tmpConsole, "/dev/");
769 strncat(tmpConsole, s, 200);
770 if (stat(tmpConsole, &statBuf) != 0) {
771 message(LOG | CONSOLE,
772 "device '%s' does not exist. Did you read the directions?\n",
778 new_initAction(a->action, q, s);
786 /* Choke on an unknown action */
787 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
796 extern int init_main(int argc, char **argv)
803 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
805 #ifdef BB_FEATURE_LINUXRC
806 && strstr(argv[0], "linuxrc") == NULL
810 usage("init\n\nInit is the parent of all processes.\n\n"
811 "This version of init is designed to be run only "
814 /* Set up sig handlers -- be sure to
815 * clear all of these in run() */
816 signal(SIGUSR1, halt_signal);
817 signal(SIGUSR2, reboot_signal);
818 signal(SIGINT, reboot_signal);
819 signal(SIGTERM, reboot_signal);
820 #if defined BB_FEATURE_INIT_CHROOT
821 signal(SIGHUP, check_chroot);
824 /* Turn off rebooting via CTL-ALT-DEL -- we get a
825 * SIGINT on CAD so we can shut things down gracefully... */
826 reboot(RB_DISABLE_CAD);
829 /* Figure out where the default console should be */
832 /* Close whatever files are open, and reset the console. */
839 /* Make sure PATH is set to something sane */
840 putenv(_PATH_STDPATH);
845 #if ! defined BB_FEATURE_EXTRA_QUIET
849 "init started: BusyBox v%s (%s) multi-call binary\r\n",
853 #if ! defined BB_FEATURE_EXTRA_QUIET
857 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
858 getpid(), BB_VER, BB_BT);
862 /* Make sure there is enough memory to do something useful. */
865 /* Check if we are supposed to be in single user mode */
866 if (argc > 1 && (!strcmp(argv[1], "single") ||
867 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
868 /* Ask first then start a shell on tty2 */
869 if (secondConsole != NULL)
870 new_initAction(ASKFIRST, SHELL, secondConsole);
871 /* Start a shell on tty1 */
872 new_initAction(RESPAWN, SHELL, console);
874 /* Not in single user mode -- see what inittab says */
876 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
877 * then parse_inittab() simply adds in some default
878 * actions(i.e runs INIT_SCRIPT and then starts a pair
879 * of "askfirst" shells */
883 /* Fix up argv[0] to be certain we claim to be init */
884 strncpy(argv[0], "init", strlen(argv[0])+1);
886 strncpy(argv[1], "\0", strlen(argv[1])+1);
888 /* Now run everything that needs to be run */
890 /* First run the sysinit command */
891 for (a = initActionList; a; a = a->nextPtr) {
892 if (a->action == SYSINIT) {
893 waitfor(a->process, a->console, FALSE);
894 /* Now remove the "sysinit" entry from the list */
895 delete_initAction(a);
898 /* Next run anything that wants to block */
899 for (a = initActionList; a; a = a->nextPtr) {
900 if (a->action == WAIT) {
901 waitfor(a->process, a->console, FALSE);
902 /* Now remove the "wait" entry from the list */
903 delete_initAction(a);
906 /* Next run anything to be run only once */
907 for (a = initActionList; a; a = a->nextPtr) {
908 if (a->action == ONCE) {
909 run(a->process, a->console, FALSE);
910 /* Now remove the "once" entry from the list */
911 delete_initAction(a);
914 /* If there is nothing else to do, stop */
915 if (initActionList == NULL) {
916 message(LOG | CONSOLE,
917 "No more tasks for init -- sleeping forever.\n");
922 /* Now run the looping stuff for the rest of forever */
924 for (a = initActionList; a; a = a->nextPtr) {
925 /* Only run stuff with pid==0. If they have
926 * a pid, that means they are still running */
930 /* run the respawn stuff */
931 a->pid = run(a->process, a->console, FALSE);
934 /* run the askfirst stuff */
935 a->pid = run(a->process, a->console, TRUE);
937 /* silence the compiler's incessant whining */
943 /* Wait for a child process to exit */
944 wpid = wait(&status);
946 /* Find out who died and clean up their corpse */
947 for (a = initActionList; a; a = a->nextPtr) {
948 if (a->pid == wpid) {
951 "Process '%s' (pid %d) exited. Scheduling it for restart.\n",
962 c-file-style: "linux"