2 * Mini init implementation for busybox
5 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6 * Adjusted by so many folks, it's impossible to keep track.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include <sys/types.h>
35 #include <sys/fcntl.h>
38 #include <sys/mount.h>
39 #include <sys/reboot.h>
40 #include <sys/kdaemon.h>
41 #include <sys/sysmacros.h>
42 #include <linux/serial.h> /* for serial_struct */
43 #include <sys/vt.h> /* for vt_stat */
44 #include <sys/ioctl.h>
45 #include <linux/version.h>
47 #include <sys/syslog.h>
50 #if ! defined BB_FEATURE_USE_PROCFS
51 #error Sorry, I depend on the /proc filesystem right now.
54 #ifndef KERNEL_VERSION
55 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
59 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
60 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
61 #define VT_LOG "/dev/tty3" /* Virtual console */
62 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
63 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
64 #define SHELL "/bin/sh" /* Default shell */
65 #define INITTAB "/etc/inittab" /* inittab file location */
67 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
73 /* Allowed init action types */
82 /* And now a list of the actions we support in the version of init */
83 typedef struct initActionType{
85 initActionEnum action;
88 static const struct initActionType actions[] = {
91 {"askfirst", ASKFIRST},
97 /* Set up a linked list of initactions, to be read from inittab */
98 typedef struct initActionTag initAction;
99 struct initActionTag {
104 initActionEnum action;
106 initAction* initActionList = NULL;
109 static char *secondConsole = VT_SECONDARY;
110 static char *log = VT_LOG;
111 static int kernelVersion = 0;
112 static char termType[32] = "TERM=ansi";
113 static char console[32] = _PATH_CONSOLE;
116 /* try to open up the specified device */
117 int device_open(char *device, int mode)
121 m = mode | O_NONBLOCK;
123 /* Retry up to 5 times */
124 for (f = 0; f < 5; f++)
125 if ((fd = open(device, m)) >= 0)
129 /* Reset original flags. */
131 fcntl(fd, F_SETFL, mode);
135 /* print a message to the specified device:
136 * device may be bitwise-or'd from LOG | CONSOLE */
137 void message(int device, char *fmt, ...)
144 /* Log the message to syslogd */
147 va_start(arguments, fmt);
148 vsnprintf(msg, sizeof(msg), fmt, arguments);
150 openlog( "init", 0, LOG_DAEMON);
151 syslog(LOG_DAEMON|LOG_NOTICE, msg);
156 static int log_fd=-1;
158 /* Take full control of the log tty, and never close it.
159 * It's mine, all mine! Muhahahaha! */
162 /* don't even try to log, because there is no such console */
164 /* log to main console instead */
167 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
169 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
174 if ( (device & LOG) && (log_fd >= 0) ) {
175 va_start(arguments, fmt);
176 vdprintf(log_fd, fmt, arguments);
181 if (device & CONSOLE) {
182 /* Always send console messages to /dev/console so people will see them. */
183 if ((fd = device_open(_PATH_CONSOLE, 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)
203 static const char control_characters[] = {
204 '\003', '\034', '\177', '\025', '\004', '\0',
205 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
206 '\017', '\027', '\026', '\0'
211 /* set control chars */
212 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
214 /* use line dicipline 0 */
217 /* Make it be sane */
218 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
219 //tty.c_cflag |= HUPCL|CLOCAL;
222 tty.c_iflag = ICRNL|IXON|IXOFF;
225 tty.c_oflag = OPOST|ONLCR;
228 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
230 tcsetattr(fd, TCSANOW, &tty);
233 /* How much memory does this machine have? */
234 static int mem_total()
237 char *p = "/proc/meminfo";
239 const char pattern[] = "MemTotal:";
241 if ((f = fopen(p, "r")) < 0) {
242 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
245 while (NULL != fgets(s, 79, f)) {
246 p = strstr(s, pattern);
249 return (atoi(p + strlen(pattern)));
255 static void console_init()
258 int tried_devcons = 0;
259 int tried_vtprimary = 0;
260 struct serial_struct sr;
263 if ((s = getenv("TERM")) != NULL) {
264 snprintf(termType,sizeof(termType)-1,"TERM=%s",s);
267 if ((s = getenv("CONSOLE")) != NULL) {
268 snprintf(console, sizeof(console)-1, "%s",s);
271 /* sparc kernel supports console=tty[ab] parameter which is also
272 * passed to init, so catch it here */
273 else if ((s = getenv("console")) != NULL) {
274 /* remap tty[ab] to /dev/ttyS[01] */
275 if (strcmp( s, "ttya" )==0)
276 snprintf(console, sizeof(console)-1, "%s", SERIAL_CON0);
277 else if (strcmp( s, "ttyb" )==0)
278 snprintf(console, sizeof(console)-1, "%s", SERIAL_CON1);
284 /* 2.2 kernels: identify the real console backend and try to use it */
285 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
286 /* this is a serial console */
287 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", vt.v_active);
293 snprintf(console, sizeof(console)-1, "%s", _PATH_CONSOLE);
298 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
299 /* Can't open selected console -- try /dev/console */
300 if (!tried_devcons) {
302 snprintf(console, sizeof(console)-1, "%s", _PATH_CONSOLE);
305 /* Can't open selected console -- try vt1 */
306 if (!tried_vtprimary) {
308 snprintf(console, sizeof(console)-1, "%s", VT_PRIMARY);
314 /* Perhaps we should panic here? */
315 snprintf(console, sizeof(console)-1, "/dev/null");
317 /* check for serial console and disable logging to tty3 & running a
319 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
320 message(LOG|CONSOLE, "serial console detected. Disabling virtual terminals.\r\n" );
322 secondConsole = NULL;
326 message(LOG, "console=%s\n", console );
329 static pid_t run(char* command,
330 char *terminal, int get_enter)
336 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) {
349 pid_t shell_pgid = getpid ();
357 /* Reset signal handlers set for parent process */
358 signal(SIGUSR1, SIG_DFL);
359 signal(SIGUSR2, SIG_DFL);
360 signal(SIGINT, SIG_DFL);
361 signal(SIGTERM, SIG_DFL);
363 if ((fd = device_open(terminal, O_RDWR)) < 0) {
364 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
382 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
383 command, shell_pgid, terminal );
384 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
385 read(fileno(stdin), &c, 1);
388 /* Log the process name and args */
389 message(LOG, "Starting pid %d, console %s: '",
390 shell_pgid, terminal, command);
392 /* Convert command (char*) into cmd (char**, one word per string) */
393 for (tmpCmd=command, i=0; (tmpCmd=strsep(&command, " \t")) != NULL;) {
394 if (*tmpCmd != '\0') {
396 message(LOG, "%s ", tmpCmd);
402 message(LOG, "'\r\n");
404 /* Now run it. The new program will take over this PID,
405 * so nothing further in init.c should be run. */
406 execve(cmd[0], cmd, environment);
408 /* We're still here? Some error happened. */
409 message(LOG|CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
416 static int waitfor(char* command,
417 char *terminal, int get_enter)
420 int pid = run( command, terminal, get_enter);
423 wpid = wait(&status);
425 message(LOG, "Process '%s' (pid %d) exited.\n",
435 /* Make sure there is enough memory to do something useful. *
436 * Calls swapon if needed so be sure /proc is mounted. */
437 static void check_memory()
441 if (mem_total() > 3500)
444 if (stat("/etc/fstab", &statBuf) == 0) {
445 /* Try to turn on swap */
446 waitfor("/bin/swapon swapon -a", log, FALSE);
447 if (mem_total() < 3500)
454 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
459 static void shutdown_system(void)
461 /* Allow Ctrl-Alt-Del to reboot system. */
462 reboot(RB_ENABLE_CAD);
463 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
466 /* Send signals to every process _except_ pid 1 */
467 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
472 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
476 message(CONSOLE, "Disabling swap.\r\n");
477 waitfor( "swapoff -a", console, FALSE);
478 message(CONSOLE, "Unmounting filesystems.\r\n");
479 waitfor("umount -a", console, FALSE);
481 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
482 /* bdflush, kupdate not needed for kernels >2.2.11 */
488 static void halt_signal(int sig)
492 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
494 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
496 reboot(RB_POWER_OFF);
499 reboot(RB_HALT_SYSTEM);
503 static void reboot_signal(int sig)
506 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
512 #if defined BB_FEATURE_INIT_CHROOT
513 static void check_chroot(int sig)
515 char *argv_init[2] = { "init", NULL, };
516 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
517 char rootpath[256], *tc;
520 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
521 message(CONSOLE, "SIGHUP recived, but could not open proc file\r\n");
525 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
526 message(CONSOLE, "SIGHUP recived, but could not read proc file\r\n");
532 if (rootpath[0] == '\0') {
533 message(CONSOLE, "SIGHUP recived, but new root is not valid: %s\r\n",
539 tc = strrchr(rootpath, '\n');
542 /* Ok, making it this far means we commit */
543 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n", rootpath);
545 /* kill all other programs first */
546 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
551 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
556 /* ok, we don't need /proc anymore. we also assume that the signaling
557 * process left the rest of the filesystems alone for us */
560 /* Ok, now we chroot. Hopefully we only have two things mounted, the
561 * new chroot'd mount point, and the old "/" mount. s,
562 * we go ahead and unmount the old "/". This should trigger the kernel
563 * to set things up the Right Way(tm). */
565 if (!chroot(rootpath))
568 /* If the chroot fails, we are already too far to turn back, so we
569 * continue and hope that executing init below will revive the system */
571 /* close all of our descriptors and open new ones */
575 open("/dev/console", O_RDWR, 0);
579 message(CONSOLE, "Executing real init...\r\n");
580 /* execute init in the (hopefully) new root */
581 execve("/sbin/init",argv_init,envp_init);
583 message(CONSOLE, "ERROR: Could not exec new init. Hit ctrl+alt+delete to reboot.\r\n");
586 #endif /* BB_FEATURE_INIT_CHROOT */
588 #endif /* ! DEBUG_INIT */
590 void new_initAction (initActionEnum action,
591 char* process, char* cons)
593 initAction* newAction;
595 /* If BusyBox detects that a serial console is in use,
596 * then entries containing non-empty id fields will _not_ be run.
597 * The exception to this rule is the null device.
599 if (secondConsole == NULL && (*cons != '\0' || strncmp(cons, "null", 4)))
602 newAction = calloc ((size_t)(1), sizeof(initAction));
604 message(LOG|CONSOLE,"Memory allocation failure\n");
607 newAction->nextPtr = initActionList;
608 initActionList = newAction;
609 strncpy( newAction->process, process, 255);
610 newAction->action = action;
612 strncpy(newAction->console, cons, 255);
614 strncpy(newAction->console, console, 255);
616 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
617 // newAction->process, newAction->action, newAction->console);
620 void delete_initAction (initAction *action)
622 initAction *a, *b=NULL;
623 for( a=initActionList ; a; b=a, a=a->nextPtr) {
624 if (a == action && b != NULL) {
625 b->nextPtr=a->nextPtr;
632 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
633 * then parse_inittab() simply adds in some default
634 * actions(i.e runs INIT_SCRIPT and then starts a pair
635 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
636 * _is_ defined, but /etc/inittab is missing, this
637 * results in the same set of default behaviors.
639 void parse_inittab(void)
641 #ifdef BB_FEATURE_USE_INITTAB
643 char buf[256], lineAsRead[256], tmpConsole[256];
645 const struct initActionType *a = actions;
649 file = fopen(INITTAB, "r");
651 /* No inittab file -- set up some default behavior */
653 /* Askfirst shell on tty1 */
654 new_initAction( ASKFIRST, SHELL, console );
655 /* Askfirst shell on tty2 */
656 if (secondConsole != NULL)
657 new_initAction( ASKFIRST, SHELL, secondConsole );
659 new_initAction( SYSINIT, INIT_SCRIPT, console );
662 #ifdef BB_FEATURE_USE_INITTAB
665 while ( fgets(buf, 255, file) != NULL) {
667 for(p = buf; *p == ' ' || *p == '\t'; p++);
668 if (*p == '#' || *p == '\n') continue;
670 /* Trim the trailing \n */
671 q = strrchr( p, '\n');
675 /* Keep a copy around for posterity's sake (and error msgs) */
676 strcpy(lineAsRead, buf);
678 /* Grab the ID field */
681 if ( p != NULL || *(p+1) != '\0' ) {
686 /* Now peal off the process field from the end
688 q = strrchr( p, ':');
689 if ( q == NULL || *(q+1) == '\0' ) {
690 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
697 /* Now peal off the action field */
698 r = strrchr( p, ':');
699 if ( r == NULL || *(r+1) == '\0') {
700 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
706 /* Ok, now process it */
708 while (a->name != 0) {
709 if (strcmp(a->name, r) == 0) {
712 strcpy(tmpConsole, "/dev/");
713 strncat(tmpConsole, s, 200);
714 if (stat(tmpConsole, &statBuf) != 0) {
715 message(LOG|CONSOLE, "device '%s' does not exist. Did you read the directions?\n", tmpConsole);
720 new_initAction( a->action, q, s);
728 /* Choke on an unknown action */
729 message(LOG|CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
736 extern int init_main(int argc, char **argv)
743 /* Expect to be PID 1 if we are run as init (not linuxrc) */
744 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
745 usage( "init\n\nInit is the parent of all processes.\n\n"
746 "This version of init is designed to be run only by the kernel\n");
748 /* Fix up argv[0] to be certain we claim to be init */
749 strncpy(argv[0], "init", strlen(argv[0]));
751 /* Set up sig handlers -- be sure to
752 * clear all of these in run() */
753 signal(SIGUSR1, halt_signal);
754 signal(SIGUSR2, reboot_signal);
755 signal(SIGINT, reboot_signal);
756 signal(SIGTERM, reboot_signal);
757 #if defined BB_FEATURE_INIT_CHROOT
758 signal(SIGHUP, check_chroot);
761 /* Turn off rebooting via CTL-ALT-DEL -- we get a
762 * SIGINT on CAD so we can shut things down gracefully... */
763 reboot(RB_DISABLE_CAD);
766 /* Figure out where the default console should be */
769 /* Close whatever files are open, and reset the console. */
776 /* Make sure PATH is set to something sane */
777 putenv(_PATH_STDPATH);
782 "init started: BusyBox v%s (%s) multi-call binary\r\n",
786 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
787 getpid(), BB_VER, BB_BT);
792 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
793 message(LOG|CONSOLE, "Mounting /proc: done.\n");
794 kernelVersion = get_kernel_revision();
796 message(LOG|CONSOLE, "Mounting /proc: failed!\n");
798 /* Make sure there is enough memory to do something useful. */
801 /* Check if we are supposed to be in single user mode */
802 if ( argc > 1 && (!strcmp(argv[1], "single") ||
803 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1")))
805 /* Ask first then start a shell on tty2 */
806 if (secondConsole != NULL)
807 new_initAction( ASKFIRST, SHELL, secondConsole);
808 /* Ask first then start a shell on tty1 */
809 new_initAction( ASKFIRST, SHELL, console);
811 /* Not in single user mode -- see what inittab says */
813 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
814 * then parse_inittab() simply adds in some default
815 * actions(i.e runs INIT_SCRIPT and then starts a pair
816 * of "askfirst" shells */
820 /* Now run everything that needs to be run */
822 /* First run the sysinit command */
823 for( a=initActionList ; a; a=a->nextPtr) {
824 if (a->action == SYSINIT) {
825 waitfor(a->process, a->console, FALSE);
826 /* Now remove the "sysinit" entry from the list */
827 delete_initAction( a);
830 /* Next run anything that wants to block */
831 for( a=initActionList ; a; a=a->nextPtr) {
832 if (a->action == WAIT) {
833 waitfor(a->process, a->console, FALSE);
834 /* Now remove the "wait" entry from the list */
835 delete_initAction( a);
838 /* Next run anything to be run only once */
839 for( a=initActionList ; a; a=a->nextPtr) {
840 if (a->action == ONCE) {
841 run(a->process, a->console, FALSE);
842 /* Now remove the "once" entry from the list */
843 delete_initAction( a);
846 /* If there is nothing else to do, stop */
847 if (initActionList == NULL) {
848 message(LOG|CONSOLE, "No more tasks for init -- sleeping forever.\n");
852 /* Now run the looping stuff for the rest of forever */
854 for( a=initActionList ; a; a=a->nextPtr) {
855 /* Only run stuff with pid==0. If they have
856 * a pid, that means they are still running */
860 /* run the respawn stuff */
861 a->pid = run(a->process, a->console, FALSE);
864 /* run the askfirst stuff */
865 a->pid = run(a->process, a->console, TRUE);
867 /* silence the compiler's incessant whining */
873 /* Wait for a child process to exit */
874 wpid = wait(&status);
876 /* Find out who died and clean up their corpse */
877 for( a=initActionList ; a; a=a->nextPtr) {
880 message(LOG, "Process '%s' (pid %d) exited. Scheduling it for restart.\n",