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 <linux/version.h>
54 #include <sys/syslog.h>
57 #if ! defined BB_FEATURE_USE_PROCFS
58 #error Sorry, I depend on the /proc filesystem right now.
61 #ifndef KERNEL_VERSION
62 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
66 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
67 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
68 #define VT_LOG "/dev/tty3" /* Virtual console */
69 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
70 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
71 #define SHELL "/bin/sh" /* Default shell */
72 #define INITTAB "/etc/inittab" /* inittab file location */
74 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
80 /* Allowed init action types */
90 /* And now a list of the actions we support in the version of init */
91 typedef struct initActionType {
93 initActionEnum action;
96 static const struct initActionType actions[] = {
99 {"askfirst", ASKFIRST},
102 {"ctrlaltdel", CTRLALTDEL},
106 /* Set up a linked list of initactions, to be read from inittab */
107 typedef struct initActionTag initAction;
108 struct initActionTag {
113 initActionEnum action;
115 initAction *initActionList = NULL;
118 static char *secondConsole = VT_SECONDARY;
119 static char *log = VT_LOG;
120 static int kernelVersion = 0;
121 static char termType[32] = "TERM=ansi";
122 static char console[32] = _PATH_CONSOLE;
123 static void delete_initAction(initAction * action);
126 /* print a message to the specified device:
127 * device may be bitwise-or'd from LOG | CONSOLE */
128 void message(int device, char *fmt, ...)
135 /* Log the message to syslogd */
139 va_start(arguments, fmt);
140 vsnprintf(msg, sizeof(msg), fmt, arguments);
142 openlog("init", 0, LOG_USER);
143 syslog(LOG_USER|LOG_INFO, msg);
147 static int log_fd = -1;
149 /* Take full control of the log tty, and never close it.
150 * It's mine, all mine! Muhahahaha! */
153 /* don't even try to log, because there is no such console */
155 /* log to main console instead */
157 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
159 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
165 if ((device & LOG) && (log_fd >= 0)) {
166 va_start(arguments, fmt);
167 vdprintf(log_fd, fmt, arguments);
172 if (device & CONSOLE) {
173 /* Always send console messages to /dev/console so people will see them. */
176 device_open(_PATH_CONSOLE,
177 O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
178 va_start(arguments, fmt);
179 vdprintf(fd, fmt, arguments);
183 fprintf(stderr, "Bummer, can't print: ");
184 va_start(arguments, fmt);
185 vfprintf(stderr, fmt, arguments);
193 /* Set terminal settings to reasonable defaults */
194 void set_term(int fd)
197 static const char control_characters[] = {
198 '\003', '\034', '\177', '\025', '\004', '\0',
199 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
200 '\017', '\027', '\026', '\0'
205 /* set control chars */
206 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
208 /* use line dicipline 0 */
211 /* Make it be sane */
212 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
213 //tty.c_cflag |= HUPCL|CLOCAL;
216 tty.c_iflag = ICRNL | IXON | IXOFF;
219 tty.c_oflag = OPOST | ONLCR;
223 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
225 tcsetattr(fd, TCSANOW, &tty);
228 /* How much memory does this machine have? */
229 static int mem_total()
232 char *p = "/proc/meminfo";
234 const char pattern[] = "MemTotal:";
236 if ((f = fopen(p, "r")) < 0) {
237 message(LOG, "Error opening %s: %s\n", p, strerror(errno));
240 while (NULL != fgets(s, 79, f)) {
241 p = strstr(s, pattern);
244 return (atoi(p + strlen(pattern)));
250 static void console_init()
253 int tried_devcons = 0;
254 int tried_vtprimary = 0;
255 struct serial_struct sr;
258 if ((s = getenv("TERM")) != NULL) {
259 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
262 if ((s = getenv("CONSOLE")) != NULL) {
263 snprintf(console, sizeof(console) - 1, "%s", s);
266 /* sparc kernel supports console=tty[ab] parameter which is also
267 * passed to init, so catch it here */
268 else if ((s = getenv("console")) != NULL) {
269 /* remap tty[ab] to /dev/ttyS[01] */
270 if (strcmp(s, "ttya") == 0)
271 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON0);
272 else if (strcmp(s, "ttyb") == 0)
273 snprintf(console, sizeof(console) - 1, "%s", SERIAL_CON1);
279 /* 2.2 kernels: identify the real console backend and try to use it */
280 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
281 /* this is a serial console */
282 snprintf(console, sizeof(console) - 1, "/dev/ttyS%d", sr.line);
283 } else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
284 /* this is linux virtual tty */
285 snprintf(console, sizeof(console) - 1, "/dev/tty%d",
288 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
293 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
294 /* Can't open selected console -- try /dev/console */
295 if (!tried_devcons) {
297 snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
300 /* Can't open selected console -- try vt1 */
301 if (!tried_vtprimary) {
303 snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
309 /* Perhaps we should panic here? */
310 snprintf(console, sizeof(console) - 1, "/dev/null");
312 /* check for serial console and disable logging to tty3 & running a
314 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
316 secondConsole = NULL;
317 message(LOG | CONSOLE,
318 "serial console detected. Disabling virtual terminals.\r\n");
322 message(LOG, "console=%s\n", console);
325 static pid_t run(char *command, char *terminal, int get_enter)
332 static const char press_enter[] =
334 "\nPlease press Enter to activate this console. ";
335 char *environment[] = {
337 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
345 if ((pid = fork()) == 0) {
347 pid_t shell_pgid = getpid();
356 /* Reset signal handlers set for parent process */
357 signal(SIGUSR1, SIG_DFL);
358 signal(SIGUSR2, SIG_DFL);
359 signal(SIGINT, SIG_DFL);
360 signal(SIGTERM, SIG_DFL);
361 signal(SIGHUP, SIG_DFL);
363 if ((fd = device_open(terminal, O_RDWR)) < 0) {
364 message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
370 tcsetpgrp(0, getpgrp());
373 if (get_enter == TRUE) {
375 * Save memory by not exec-ing anything large (like a shell)
376 * before the user wants it. This is critical if swap is not
377 * enabled and the system has low memory. Generally this will
378 * be run on the second virtual console, and the first will
379 * be allowed to start a shell or whatever an init script
385 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
386 command, shell_pgid, terminal);
388 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
389 read(fileno(stdin), &c, 1);
393 /* Log the process name and args */
394 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
395 shell_pgid, terminal, command);
398 /* See if any special /bin/sh requiring characters are present */
399 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
402 strcpy(buf, "exec ");
403 strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
407 /* Convert command (char*) into cmd (char**, one word per string) */
408 for (tmpCmd = command, i = 0;
409 (tmpCmd = strsep(&command, " \t")) != NULL;) {
410 if (*tmpCmd != '\0') {
419 /* Now run it. The new program will take over this PID,
420 * so nothing further in init.c should be run. */
421 execve(cmd[0], cmd, environment);
423 /* We're still here? Some error happened. */
424 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
431 static int waitfor(char *command, char *terminal, int get_enter)
434 int pid = run(command, terminal, get_enter);
437 wpid = wait(&status);
438 if (wpid > 0 && wpid != pid) {
447 /* Make sure there is enough memory to do something useful. *
448 * Calls "swapon -a" if needed so be sure /etc/fstab is present... */
449 static void check_memory()
453 if (mem_total() > 3500)
456 if (stat("/etc/fstab", &statBuf) == 0) {
457 /* Try to turn on swap */
458 system("/sbin/swapon swapon -a");
459 if (mem_total() < 3500)
467 "Sorry, your computer does not have enough memory.\r\n");
472 /* Run all commands to be run right before halt/reboot */
473 static void run_lastAction(void)
476 for (a = initActionList; a; a = a->nextPtr) {
477 if (a->action == CTRLALTDEL) {
478 waitfor(a->process, a->console, FALSE);
479 delete_initAction(a);
486 static void shutdown_system(void)
489 /* first disable our SIGHUP signal */
490 signal(SIGHUP, SIG_DFL);
492 /* Allow Ctrl-Alt-Del to reboot system. */
493 reboot(RB_ENABLE_CAD);
495 message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
498 /* Send signals to every process _except_ pid 1 */
499 message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
504 message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
508 /* run everything to be run at "ctrlaltdel" */
512 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
513 /* bdflush, kupdate not needed for kernels >2.2.11 */
519 static void halt_signal(int sig)
523 "The system is halted. Press %s or turn off power\r\n",
524 (secondConsole == NULL) /* serial console */
525 ? "Reset" : "CTRL-ALT-DEL");
528 /* allow time for last message to reach serial console */
531 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
533 reboot(RB_POWER_OFF);
536 reboot(RB_HALT_SYSTEM);
540 static void reboot_signal(int sig)
543 message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
546 /* allow time for last message to reach serial console */
553 #if defined BB_FEATURE_INIT_CHROOT
554 static void check_chroot(int sig)
556 char *argv_init[2] = { "init", NULL, };
557 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
558 char rootpath[256], *tc;
561 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
563 "SIGHUP recived, but could not open proc file\r\n");
567 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
569 "SIGHUP recived, but could not read proc file\r\n");
575 if (rootpath[0] == '\0') {
577 "SIGHUP recived, but new root is not valid: %s\r\n",
583 tc = strrchr(rootpath, '\n');
586 /* Ok, making it this far means we commit */
587 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
590 /* kill all other programs first */
591 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
596 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
601 /* ok, we don't need /proc anymore. we also assume that the signaling
602 * process left the rest of the filesystems alone for us */
605 /* Ok, now we chroot. Hopefully we only have two things mounted, the
606 * new chroot'd mount point, and the old "/" mount. s,
607 * we go ahead and unmount the old "/". This should trigger the kernel
608 * to set things up the Right Way(tm). */
610 if (!chroot(rootpath))
613 /* If the chroot fails, we are already too far to turn back, so we
614 * continue and hope that executing init below will revive the system */
616 /* close all of our descriptors and open new ones */
620 open("/dev/console", O_RDWR, 0);
624 message(CONSOLE, "Executing real init...\r\n");
625 /* execute init in the (hopefully) new root */
626 execve("/sbin/init", argv_init, envp_init);
629 "ERROR: Could not exec new init. Press %s to reboot.\r\n",
630 (secondConsole == NULL) /* serial console */
631 ? "Reset" : "CTRL-ALT-DEL");
634 #endif /* BB_FEATURE_INIT_CHROOT */
636 #endif /* ! DEBUG_INIT */
638 void new_initAction(initActionEnum action, char *process, char *cons)
640 initAction *newAction;
645 /* If BusyBox detects that a serial console is in use,
646 * then entries not refering to the console or null devices will _not_ be run.
647 * The exception to this rule is the null device.
649 if (secondConsole == NULL && strcmp(cons, console)
650 && strcmp(cons, "/dev/null"))
653 newAction = calloc((size_t) (1), sizeof(initAction));
655 message(LOG | CONSOLE, "Memory allocation failure\n");
659 newAction->nextPtr = initActionList;
660 initActionList = newAction;
661 strncpy(newAction->process, process, 255);
662 newAction->action = action;
663 strncpy(newAction->console, cons, 255);
665 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
666 // newAction->process, newAction->action, newAction->console);
669 static void delete_initAction(initAction * action)
671 initAction *a, *b = NULL;
673 for (a = initActionList; a; b = a, a = a->nextPtr) {
676 initActionList = a->nextPtr;
678 b->nextPtr = a->nextPtr;
686 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
687 * then parse_inittab() simply adds in some default
688 * actions(i.e runs INIT_SCRIPT and then starts a pair
689 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
690 * _is_ defined, but /etc/inittab is missing, this
691 * results in the same set of default behaviors.
693 void parse_inittab(void)
695 #ifdef BB_FEATURE_USE_INITTAB
697 char buf[256], lineAsRead[256], tmpConsole[256];
699 const struct initActionType *a = actions;
703 file = fopen(INITTAB, "r");
705 /* No inittab file -- set up some default behavior */
707 /* Swapoff on halt/reboot */
708 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
709 /* Umount all filesystems on halt/reboot */
710 new_initAction(CTRLALTDEL, "/bin/umount -a -r > /dev/null 2>&1", console);
711 /* Askfirst shell on tty1 */
712 new_initAction(ASKFIRST, SHELL, console);
713 /* Askfirst shell on tty2 */
714 if (secondConsole != NULL)
715 new_initAction(ASKFIRST, SHELL, secondConsole);
717 new_initAction(SYSINIT, INIT_SCRIPT, console);
720 #ifdef BB_FEATURE_USE_INITTAB
723 while (fgets(buf, 255, file) != NULL) {
725 for (p = buf; *p == ' ' || *p == '\t'; p++);
726 if (*p == '#' || *p == '\n')
729 /* Trim the trailing \n */
730 q = strrchr(p, '\n');
734 /* Keep a copy around for posterity's sake (and error msgs) */
735 strcpy(lineAsRead, buf);
737 /* Grab the ID field */
740 if (p != NULL || *(p + 1) != '\0') {
745 /* Now peal off the process field from the end
748 if (q == NULL || *(q + 1) == '\0') {
749 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
756 /* Now peal off the action field */
758 if (r == NULL || *(r + 1) == '\0') {
759 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
765 /* Ok, now process it */
767 while (a->name != 0) {
768 if (strcmp(a->name, r) == 0) {
772 strcpy(tmpConsole, "/dev/");
773 strncat(tmpConsole, s, 200);
774 if (stat(tmpConsole, &statBuf) != 0) {
775 message(LOG | CONSOLE,
776 "device '%s' does not exist. Did you read the directions?\n",
782 new_initAction(a->action, q, s);
790 /* Choke on an unknown action */
791 message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
800 extern int init_main(int argc, char **argv)
807 /* Expect to be PID 1 if we are run as init (not linuxrc) */
808 if (getpid() != 1 && strstr(argv[0], "init") != 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 by the kernel\n");
812 /* Set up sig handlers -- be sure to
813 * clear all of these in run() */
814 signal(SIGUSR1, halt_signal);
815 signal(SIGUSR2, reboot_signal);
816 signal(SIGINT, reboot_signal);
817 signal(SIGTERM, reboot_signal);
818 #if defined BB_FEATURE_INIT_CHROOT
819 signal(SIGHUP, check_chroot);
822 /* Turn off rebooting via CTL-ALT-DEL -- we get a
823 * SIGINT on CAD so we can shut things down gracefully... */
824 reboot(RB_DISABLE_CAD);
827 /* Figure out where the default console should be */
830 /* Close whatever files are open, and reset the console. */
837 /* Make sure PATH is set to something sane */
838 putenv(_PATH_STDPATH);
842 message(LOG | CONSOLE,
843 "init started: BusyBox v%s (%s) multi-call binary\r\n",
846 message(LOG | CONSOLE,
847 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
848 getpid(), BB_VER, BB_BT);
853 if (mount("proc", "/proc", "proc", 0, 0) == 0) {
854 message(LOG | CONSOLE, "Mounting /proc: done.\n");
855 kernelVersion = get_kernel_revision();
857 message(LOG | CONSOLE, "Mounting /proc: failed!\n");
859 /* Make sure there is enough memory to do something useful. */
862 /* Check if we are supposed to be in single user mode */
863 if (argc > 1 && (!strcmp(argv[1], "single") ||
864 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
865 /* Ask first then start a shell on tty2 */
866 if (secondConsole != NULL)
867 new_initAction(ASKFIRST, SHELL, secondConsole);
868 /* Start a shell on tty1 */
869 new_initAction(RESPAWN, SHELL, console);
871 /* Not in single user mode -- see what inittab says */
873 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
874 * then parse_inittab() simply adds in some default
875 * actions(i.e runs INIT_SCRIPT and then starts a pair
876 * of "askfirst" shells */
880 /* Fix up argv[0] to be certain we claim to be init */
881 strncpy(argv[0], "init", strlen(argv[0])+1);
882 strncpy(argv[1], "\0", strlen(argv[1])+1);
884 /* Now run everything that needs to be run */
886 /* First run the sysinit command */
887 for (a = initActionList; a; a = a->nextPtr) {
888 if (a->action == SYSINIT) {
889 waitfor(a->process, a->console, FALSE);
890 /* Now remove the "sysinit" entry from the list */
891 delete_initAction(a);
894 /* Next run anything that wants to block */
895 for (a = initActionList; a; a = a->nextPtr) {
896 if (a->action == WAIT) {
897 waitfor(a->process, a->console, FALSE);
898 /* Now remove the "wait" entry from the list */
899 delete_initAction(a);
902 /* Next run anything to be run only once */
903 for (a = initActionList; a; a = a->nextPtr) {
904 if (a->action == ONCE) {
905 run(a->process, a->console, FALSE);
906 /* Now remove the "once" entry from the list */
907 delete_initAction(a);
910 /* If there is nothing else to do, stop */
911 if (initActionList == NULL) {
912 message(LOG | CONSOLE,
913 "No more tasks for init -- sleeping forever.\n");
918 /* Now run the looping stuff for the rest of forever */
920 for (a = initActionList; a; a = a->nextPtr) {
921 /* Only run stuff with pid==0. If they have
922 * a pid, that means they are still running */
926 /* run the respawn stuff */
927 a->pid = run(a->process, a->console, FALSE);
930 /* run the askfirst stuff */
931 a->pid = run(a->process, a->console, TRUE);
933 /* silence the compiler's incessant whining */
939 /* Wait for a child process to exit */
940 wpid = wait(&status);
942 /* Find out who died and clean up their corpse */
943 for (a = initActionList; a; a = a->nextPtr) {
944 if (a->pid == wpid) {
947 "Process '%s' (pid %d) exited. Scheduling it for restart.\n",