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 */
59 * When CORE_ENABLE_FLAG_FILE exists, setrlimit is called before
60 * process is spawned to set corelimit to unlimited.
62 #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
63 #include <sys/resource.h>
66 #ifndef KERNEL_VERSION
67 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
71 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
72 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
73 #define VT_LOG "/dev/tty3" /* Virtual console */
74 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
75 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
76 #define SHELL "/bin/sh" /* Default shell */
77 #define INITTAB "/etc/inittab" /* inittab file location */
79 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
85 /* Allowed init action types */
95 /* A mapping between "inittab" action name strings and action type codes. */
96 typedef struct initActionType {
98 initActionEnum action;
101 static const struct initActionType actions[] = {
102 {"sysinit", SYSINIT},
103 {"respawn", RESPAWN},
104 {"askfirst", ASKFIRST},
107 {"ctrlaltdel", CTRLALTDEL},
111 /* Set up a linked list of initActions, to be read from inittab */
112 typedef struct initActionTag initAction;
113 struct initActionTag {
118 initActionEnum action;
120 initAction *initActionList = NULL;
123 static char *secondConsole = VT_SECONDARY;
124 static char *log = VT_LOG;
125 static int kernelVersion = 0;
126 static char termType[32] = "TERM=linux";
127 static char console[32] = _PATH_CONSOLE;
129 static void delete_initAction(initAction * action);
132 /* Print a message to the specified device.
133 * Device may be bitwise-or'd from LOG | CONSOLE */
134 static void message(int device, char *fmt, ...)
141 /* Log the message to syslogd */
145 va_start(arguments, fmt);
146 vsnprintf(msg, sizeof(msg), fmt, arguments);
148 openlog("init", 0, LOG_USER);
149 syslog(LOG_USER|LOG_INFO, msg);
153 static int log_fd = -1;
155 /* Take full control of the log tty, and never close it.
156 * It's mine, all mine! Muhahahaha! */
159 /* don't even try to log, because there is no such console */
161 /* log to main console instead */
163 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
165 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
171 if ((device & LOG) && (log_fd >= 0)) {
172 va_start(arguments, fmt);
173 vdprintf(log_fd, fmt, arguments);
178 if (device & CONSOLE) {
179 /* Always send console messages to /dev/console so people will see them. */
182 device_open(_PATH_CONSOLE,
183 O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
184 va_start(arguments, fmt);
185 vdprintf(fd, fmt, arguments);
189 fprintf(stderr, "Bummer, can't print: ");
190 va_start(arguments, fmt);
191 vfprintf(stderr, fmt, arguments);
199 /* Set terminal settings to reasonable defaults */
200 void set_term(int fd)
206 /* set control chars */
207 tty.c_cc[VINTR] = 3; /* C-c */
208 tty.c_cc[VQUIT] = 28; /* C-\ */
209 tty.c_cc[VERASE] = 127; /* C-? */
210 tty.c_cc[VKILL] = 21; /* C-u */
211 tty.c_cc[VEOF] = 4; /* C-d */
212 tty.c_cc[VSTART] = 17; /* C-q */
213 tty.c_cc[VSTOP] = 19; /* C-s */
214 tty.c_cc[VSUSP] = 26; /* C-z */
216 /* use line dicipline 0 */
219 /* Make it be sane */
220 tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
221 tty.c_cflag |= HUPCL|CLOCAL;
224 tty.c_iflag = ICRNL | IXON | IXOFF;
227 tty.c_oflag = OPOST | ONLCR;
231 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
233 tcsetattr(fd, TCSANOW, &tty);
236 /* How much memory does this machine have? */
237 static int check_free_memory()
242 if (sysinfo(&info) != 0) {
243 message(LOG, "Error checking free memory: %s\n", strerror(errno));
247 return((info.totalram+info.totalswap)/1024);
250 static void console_init()
253 int tried_devcons = 0;
254 int tried_vtprimary = 0;
256 struct serial_struct sr;
259 if ((s = getenv("TERM")) != NULL) {
260 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
263 if ((s = getenv("CONSOLE")) != NULL) {
264 snprintf(console, sizeof(console) - 1, "%s", s);
267 /* sparc kernel supports console=tty[ab] parameter which is also
268 * passed to init, so catch it here */
269 else if ((s = getenv("console")) != NULL) {
270 /* remap tty[ab] to /dev/ttyS[01] */
271 if (strcmp(s, "ttya") == 0)
272 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON0);
273 else if (strcmp(s, "ttyb") == 0)
274 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON1);
278 /* 2.2 kernels: identify the real console backend and try to use it */
279 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
280 /* this is a serial console */
281 snprintf(console, sizeof(console) - 1, "/dev/ttyS%d", sr.line);
282 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
283 /* this is linux virtual tty */
284 snprintf(console, sizeof(console) - 1, "/dev/tty%d",
287 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
292 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
293 /* Can't open selected console -- try /dev/console */
294 if (!tried_devcons) {
296 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
299 /* Can't open selected console -- try vt1 */
300 if (!tried_vtprimary) {
302 snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
308 /* Perhaps we should panic here? */
309 snprintf(console, sizeof(console) - 1, "/dev/null");
311 /* check for serial console and disable logging to tty3 & running a
313 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
315 secondConsole = NULL;
316 /* Force the TERM setting to vt102 for serial console --
317 * iff TERM is set to linux (the default) */
318 if (strcmp( termType, "TERM=linux" ) == 0)
319 snprintf(termType, sizeof(termType) - 1, "TERM=vt102");
320 message(LOG | CONSOLE,
321 "serial console detected. Disabling virtual terminals.\r\n");
325 message(LOG, "console=%s\n", console);
328 static pid_t run(char *command, char *terminal, int get_enter)
335 static const char press_enter[] =
337 "\nPlease press Enter to activate this console. ";
338 char *environment[] = {
340 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
348 if ((pid = fork()) == 0) {
355 /* Reset signal handlers set for parent process */
356 signal(SIGUSR1, SIG_DFL);
357 signal(SIGUSR2, SIG_DFL);
358 signal(SIGINT, SIG_DFL);
359 signal(SIGTERM, SIG_DFL);
360 signal(SIGHUP, SIG_DFL);
362 if ((fd = device_open(terminal, O_RDWR)) < 0) {
363 message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
369 tcsetpgrp(0, getpgrp());
372 if (get_enter == TRUE) {
374 * Save memory by not exec-ing anything large (like a shell)
375 * before the user wants it. This is critical if swap is not
376 * enabled and the system has low memory. Generally this will
377 * be run on the second virtual console, and the first will
378 * be allowed to start a shell or whatever an init script
383 pid_t shell_pgid = getpid();
384 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
385 command, shell_pgid, terminal);
387 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
388 read(fileno(stdin), &c, 1);
392 /* Log the process name and args */
393 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
394 shell_pgid, terminal, command);
397 /* See if any special /bin/sh requiring characters are present */
398 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
401 strcpy(buf, "exec ");
402 strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
406 /* Convert command (char*) into cmd (char**, one word per string) */
407 for (tmpCmd = command, i = 0;
408 (tmpCmd = strsep(&command, " \t")) != NULL;) {
409 if (*tmpCmd != '\0') {
420 if (stat (CORE_ENABLE_FLAG_FILE, &sb) == 0) {
422 limit.rlim_cur = RLIM_INFINITY;
423 limit.rlim_max = RLIM_INFINITY;
424 setrlimit(RLIMIT_CORE, &limit);
428 /* Now run it. The new program will take over this PID,
429 * so nothing further in init.c should be run. */
430 execve(cmd[0], cmd, environment);
432 /* We're still here? Some error happened. */
433 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
440 static int waitfor(char *command, char *terminal, int get_enter)
443 int pid = run(command, terminal, get_enter);
446 wpid = wait(&status);
447 if (wpid > 0 && wpid != pid) {
456 /* Make sure there is enough memory to do something useful. *
457 * Calls "swapon -a" if needed so be sure /etc/fstab is present... */
458 static void check_memory()
462 if (check_free_memory() > 1000)
465 if (stat("/etc/fstab", &statBuf) == 0) {
466 /* Try to turn on swap */
467 system("/sbin/swapon -a");
468 if (check_free_memory() < 1000)
476 "Sorry, your computer does not have enough memory.\r\n");
481 /* Run all commands to be run right before halt/reboot */
482 static void run_lastAction(void)
485 for (a = initActionList; a; a = a->nextPtr) {
486 if (a->action == CTRLALTDEL) {
487 waitfor(a->process, a->console, FALSE);
488 delete_initAction(a);
495 static void shutdown_system(void)
498 /* first disable our SIGHUP signal */
499 signal(SIGHUP, SIG_DFL);
501 /* Allow Ctrl-Alt-Del to reboot system. */
502 reboot(RB_ENABLE_CAD);
504 message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
507 /* Send signals to every process _except_ pid 1 */
508 message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
513 message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
517 /* run everything to be run at "ctrlaltdel" */
521 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
522 /* bdflush, kupdate not needed for kernels >2.2.11 */
528 static void halt_signal(int sig)
532 "The system is halted. Press %s or turn off power\r\n",
533 (secondConsole == NULL) /* serial console */
534 ? "Reset" : "CTRL-ALT-DEL");
537 /* allow time for last message to reach serial console */
540 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
542 reboot(RB_POWER_OFF);
545 reboot(RB_HALT_SYSTEM);
549 static void reboot_signal(int sig)
552 message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
555 /* allow time for last message to reach serial console */
562 #if defined BB_FEATURE_INIT_CHROOT
564 #if ! defined BB_FEATURE_USE_PROCFS
565 #error Sorry, I depend on the /proc filesystem right now.
568 static void check_chroot(int sig)
570 char *argv_init[2] = { "init", NULL, };
571 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
572 char rootpath[256], *tc;
575 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
577 "SIGHUP recived, but could not open proc file\r\n");
581 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
583 "SIGHUP recived, but could not read proc file\r\n");
589 if (rootpath[0] == '\0') {
591 "SIGHUP recived, but new root is not valid: %s\r\n",
597 tc = strrchr(rootpath, '\n');
600 /* Ok, making it this far means we commit */
601 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
604 /* kill all other programs first */
605 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
610 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
615 /* ok, we don't need /proc anymore. we also assume that the signaling
616 * process left the rest of the filesystems alone for us */
619 /* Ok, now we chroot. Hopefully we only have two things mounted, the
620 * new chroot'd mount point, and the old "/" mount. s,
621 * we go ahead and unmount the old "/". This should trigger the kernel
622 * to set things up the Right Way(tm). */
624 if (!chroot(rootpath))
627 /* If the chroot fails, we are already too far to turn back, so we
628 * continue and hope that executing init below will revive the system */
630 /* close all of our descriptors and open new ones */
634 open("/dev/console", O_RDWR, 0);
638 message(CONSOLE, "Executing real init...\r\n");
639 /* execute init in the (hopefully) new root */
640 execve("/sbin/init", argv_init, envp_init);
643 "ERROR: Could not exec new init. Press %s to reboot.\r\n",
644 (secondConsole == NULL) /* serial console */
645 ? "Reset" : "CTRL-ALT-DEL");
648 #endif /* BB_FEATURE_INIT_CHROOT */
650 #endif /* ! DEBUG_INIT */
652 void new_initAction(initActionEnum action, char *process, char *cons)
654 initAction *newAction;
659 /* If BusyBox detects that a serial console is in use,
660 * then entries not refering to the console or null devices will _not_ be run.
661 * The exception to this rule is the null device.
663 if (secondConsole == NULL && strcmp(cons, console)
664 && strcmp(cons, "/dev/null"))
667 newAction = calloc((size_t) (1), sizeof(initAction));
669 message(LOG | CONSOLE, "Memory allocation failure\n");
673 newAction->nextPtr = initActionList;
674 initActionList = newAction;
675 strncpy(newAction->process, process, 255);
676 newAction->action = action;
677 strncpy(newAction->console, cons, 255);
679 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
680 // newAction->process, newAction->action, newAction->console);
683 static void delete_initAction(initAction * action)
685 initAction *a, *b = NULL;
687 for (a = initActionList; a; b = a, a = a->nextPtr) {
690 initActionList = a->nextPtr;
692 b->nextPtr = a->nextPtr;
700 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
701 * then parse_inittab() simply adds in some default
702 * actions(i.e runs INIT_SCRIPT and then starts a pair
703 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
704 * _is_ defined, but /etc/inittab is missing, this
705 * results in the same set of default behaviors.
707 void parse_inittab(void)
709 #ifdef BB_FEATURE_USE_INITTAB
711 char buf[256], lineAsRead[256], tmpConsole[256];
713 const struct initActionType *a = actions;
717 file = fopen(INITTAB, "r");
719 /* No inittab file -- set up some default behavior */
721 /* Swapoff on halt/reboot */
722 new_initAction(CTRLALTDEL, "/sbin/swapoff -a > /dev/null 2>&1", console);
723 /* Umount all filesystems on halt/reboot */
724 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
725 /* Askfirst shell on tty1 */
726 new_initAction(ASKFIRST, SHELL, console);
727 /* Askfirst shell on tty2 */
728 if (secondConsole != NULL)
729 new_initAction(ASKFIRST, SHELL, secondConsole);
731 new_initAction(SYSINIT, INIT_SCRIPT, console);
734 #ifdef BB_FEATURE_USE_INITTAB
737 while (fgets(buf, 255, file) != NULL) {
739 for (p = buf; *p == ' ' || *p == '\t'; p++);
740 if (*p == '#' || *p == '\n')
743 /* Trim the trailing \n */
744 q = strrchr(p, '\n');
748 /* Keep a copy around for posterity's sake (and error msgs) */
749 strcpy(lineAsRead, buf);
751 /* Grab the ID field */
754 if (p != NULL || *(p + 1) != '\0') {
759 /* Now peel off the process field from the end
762 if (q == NULL || *(q + 1) == '\0') {
763 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
770 /* Now peel off the action field */
772 if (r == NULL || *(r + 1) == '\0') {
773 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
779 /* Ok, now process it */
781 while (a->name != 0) {
782 if (strcmp(a->name, r) == 0) {
786 strcpy(tmpConsole, "/dev/");
787 strncat(tmpConsole, s, 200);
788 if (stat(tmpConsole, &statBuf) != 0) {
789 message(LOG | CONSOLE,
790 "device '%s' does not exist. Did you read the directions?\n",
796 new_initAction(a->action, q, s);
804 /* Choke on an unknown action */
805 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
809 #endif /* BB_FEATURE_USE_INITTAB */
814 extern int init_main(int argc, char **argv)
821 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
823 #ifdef BB_FEATURE_LINUXRC
824 && strstr(argv[0], "linuxrc") == NULL
828 usage("init\n\nInit is the parent of all processes.\n\n"
829 "This version of init is designed to be run only "
832 /* Set up sig handlers -- be sure to
833 * clear all of these in run() */
834 signal(SIGUSR1, halt_signal);
835 signal(SIGUSR2, reboot_signal);
836 signal(SIGINT, reboot_signal);
837 signal(SIGTERM, reboot_signal);
838 #if defined BB_FEATURE_INIT_CHROOT
839 signal(SIGHUP, check_chroot);
842 /* Turn off rebooting via CTL-ALT-DEL -- we get a
843 * SIGINT on CAD so we can shut things down gracefully... */
844 reboot(RB_DISABLE_CAD);
847 /* Figure out what kernel this is running */
848 kernelVersion = get_kernel_revision();
850 /* Figure out where the default console should be */
853 /* Close whatever files are open, and reset the console. */
861 /* Make sure PATH is set to something sane */
862 putenv(_PATH_STDPATH);
867 #if ! defined BB_FEATURE_EXTRA_QUIET
871 "init started: BusyBox v%s (%s) multi-call binary\r\n",
875 #if ! defined BB_FEATURE_EXTRA_QUIET
879 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
880 getpid(), BB_VER, BB_BT);
884 /* Make sure there is enough memory to do something useful. */
887 /* Check if we are supposed to be in single user mode */
888 if (argc > 1 && (!strcmp(argv[1], "single") ||
889 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
890 /* Ask first then start a shell on tty2 */
891 if (secondConsole != NULL)
892 new_initAction(ASKFIRST, SHELL, secondConsole);
893 /* Start a shell on tty1 */
894 new_initAction(RESPAWN, SHELL, console);
896 /* Not in single user mode -- see what inittab says */
898 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
899 * then parse_inittab() simply adds in some default
900 * actions(i.e runs INIT_SCRIPT and then starts a pair
901 * of "askfirst" shells */
905 /* Fix up argv[0] to be certain we claim to be init */
906 strncpy(argv[0], "init", strlen(argv[0])+1);
908 strncpy(argv[1], "\0", strlen(argv[1])+1);
910 /* Now run everything that needs to be run */
912 /* First run the sysinit command */
913 for (a = initActionList; a; a = a->nextPtr) {
914 if (a->action == SYSINIT) {
915 waitfor(a->process, a->console, FALSE);
916 /* Now remove the "sysinit" entry from the list */
917 delete_initAction(a);
920 /* Next run anything that wants to block */
921 for (a = initActionList; a; a = a->nextPtr) {
922 if (a->action == WAIT) {
923 waitfor(a->process, a->console, FALSE);
924 /* Now remove the "wait" entry from the list */
925 delete_initAction(a);
928 /* Next run anything to be run only once */
929 for (a = initActionList; a; a = a->nextPtr) {
930 if (a->action == ONCE) {
931 run(a->process, a->console, FALSE);
932 /* Now remove the "once" entry from the list */
933 delete_initAction(a);
936 /* If there is nothing else to do, stop */
937 if (initActionList == NULL) {
938 message(LOG | CONSOLE,
939 "No more tasks for init -- sleeping forever.\n");
944 /* Now run the looping stuff for the rest of forever */
946 for (a = initActionList; a; a = a->nextPtr) {
947 /* Only run stuff with pid==0. If they have
948 * a pid, that means they are still running */
952 /* run the respawn stuff */
953 a->pid = run(a->process, a->console, FALSE);
956 /* run the askfirst stuff */
957 a->pid = run(a->process, a->console, TRUE);
959 /* silence the compiler's incessant whining */
965 /* Wait for a child process to exit */
966 wpid = wait(&status);
968 /* Find out who died and clean up their corpse */
969 for (a = initActionList; a; a = a->nextPtr) {
970 if (a->pid == wpid) {
973 "Process '%s' (pid %d) exited. Scheduling it for restart.\n",
984 c-file-style: "linux"