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 *console = _PATH_CONSOLE;
110 static char *secondConsole = VT_SECONDARY;
111 static char *log = VT_LOG;
112 static int kernelVersion = 0;
113 static char *termType = NULL;
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 syslog(LOG_DAEMON|LOG_NOTICE, msg);
154 static int log_fd=-1;
156 /* Take full control of the log tty, and never close it.
157 * It's mine, all mine! Muhahahaha! */
160 /* don't even try to log, because there is no such console */
162 /* log to main console instead */
165 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
167 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
172 if ( (device & LOG) && (log_fd >= 0) ) {
173 va_start(arguments, fmt);
174 vdprintf(log_fd, fmt, arguments);
179 if (device & CONSOLE) {
180 /* Always send console messages to /dev/console so people will see them. */
181 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
182 va_start(arguments, fmt);
183 vdprintf(fd, fmt, arguments);
187 fprintf(stderr, "Bummer, can't print: ");
188 va_start(arguments, fmt);
189 vfprintf(stderr, fmt, arguments);
197 /* Set terminal settings to reasonable defaults */
198 void set_term( int fd)
201 static const char control_characters[] = {
202 '\003', '\034', '\177', '\025', '\004', '\0',
203 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
204 '\017', '\027', '\026', '\0'
209 /* set control chars */
210 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
212 /* use line dicipline 0 */
215 /* Make it be sane */
216 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
217 //tty.c_cflag |= HUPCL|CLOCAL;
220 tty.c_iflag = ICRNL|IXON|IXOFF;
223 tty.c_oflag = OPOST|ONLCR;
226 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
228 tcsetattr(fd, TCSANOW, &tty);
231 /* How much memory does this machine have? */
232 static int mem_total()
235 char *p = "/proc/meminfo";
237 const char pattern[] = "MemTotal:";
239 if ((f = fopen(p, "r")) < 0) {
240 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
243 while (NULL != fgets(s, 79, f)) {
244 p = strstr(s, pattern);
247 return (atoi(p + strlen(pattern)));
253 static void console_init()
256 int tried_devcons = 0;
257 int tried_vtprimary = 0;
258 struct serial_struct sr;
261 if ((s = getenv("CONSOLE")) != NULL) {
264 termType = "TERM=vt100";
267 if ((s = getenv("CONSOLE")) != NULL) {
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 console = SERIAL_CON0;
277 else if (strcmp( s, "ttyb" )==0)
278 console = SERIAL_CON1;
283 static char the_console[13];
285 console = the_console;
286 /* 2.2 kernels: identify the real console backend and try to use it */
287 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
288 /* this is a serial console */
289 snprintf( the_console, sizeof the_console, "/dev/ttyS%d", sr.line );
291 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
292 /* this is linux virtual tty */
293 snprintf( the_console, sizeof the_console, "/dev/tty%d", vt.v_active );
295 console = _PATH_CONSOLE;
300 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
301 /* Can't open selected console -- try /dev/console */
302 if (!tried_devcons) {
304 console = _PATH_CONSOLE;
307 /* Can't open selected console -- try vt1 */
308 if (!tried_vtprimary) {
310 console = VT_PRIMARY;
316 /* Perhaps we should panic here? */
317 console = "/dev/null";
319 /* check for serial console and disable logging to tty3 & running a
321 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
322 message(LOG|CONSOLE, "serial console detected. Disabling virtual terminals.\r\n", console );
324 secondConsole = NULL;
328 message(LOG, "console=%s\n", console );
331 static pid_t run(char* command,
332 char *terminal, int get_enter)
338 static const char press_enter[] =
339 "\nPlease press Enter to activate this console. ";
340 static char * environment[] = {
342 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
348 environment[3]=termType;
351 if ((pid = fork()) == 0) {
352 pid_t shell_pgid = getpid ();
360 /* Reset signal handlers set for parent process */
361 signal(SIGUSR1, SIG_DFL);
362 signal(SIGUSR2, SIG_DFL);
363 signal(SIGINT, SIG_DFL);
364 signal(SIGTERM, SIG_DFL);
366 if ((fd = device_open(terminal, O_RDWR)) < 0) {
367 message(LOG|CONSOLE, "Bummer, can't open %s\r\n", terminal);
372 tcsetpgrp (0, getpgrp());
375 if (get_enter==TRUE) {
377 * Save memory by not exec-ing anything large (like a shell)
378 * before the user wants it. This is critical if swap is not
379 * enabled and the system has low memory. Generally this will
380 * be run on the second virtual console, and the first will
381 * 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 );
387 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
388 read(fileno(stdin), &c, 1);
391 /* Log the process name and args */
392 message(LOG|CONSOLE, "Starting pid %d, console %s: '",
393 shell_pgid, terminal, command);
395 /* Convert command (char*) into cmd (char**, one word per string) */
396 for (tmpCmd=command, i=0; (tmpCmd=strsep(&command, " \t")) != NULL;) {
397 if (*tmpCmd != '\0') {
399 message(LOG|CONSOLE, "%s ", tmpCmd);
405 message(LOG|CONSOLE, "'\r\n");
407 /* Now run it. The new program will take over this PID,
408 * so nothing further in init.c should be run. */
409 //execvp(cmd[0], cmd);
410 execve(cmd[0], cmd, environment);
412 /* We're still here? Some error happened. */
413 message(LOG|CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
420 static int waitfor(char* command,
421 char *terminal, int get_enter)
424 int pid = run( command, terminal, get_enter);
427 wpid = wait(&status);
429 message(LOG, "Process '%s' (pid %d) exited.\n",
439 /* Make sure there is enough memory to do something useful. *
440 * Calls swapon if needed so be sure /proc is mounted. */
441 static void check_memory()
445 if (mem_total() > 3500)
448 if (stat("/etc/fstab", &statBuf) == 0) {
449 /* Try to turn on swap */
450 waitfor("/bin/swapon swapon -a", log, FALSE);
451 if (mem_total() < 3500)
458 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
463 static void shutdown_system(void)
465 /* Allow Ctrl-Alt-Del to reboot system. */
466 reboot(RB_ENABLE_CAD);
467 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
470 /* Send signals to every process _except_ pid 1 */
471 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
476 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
480 message(CONSOLE, "Disabling swap.\r\n");
481 waitfor( "swapoff -a", console, FALSE);
482 message(CONSOLE, "Unmounting filesystems.\r\n");
483 waitfor("umount -a", console, FALSE);
485 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
486 /* bdflush, kupdate not needed for kernels >2.2.11 */
492 static void halt_signal(int sig)
496 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
498 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
500 reboot(RB_POWER_OFF);
503 reboot(RB_HALT_SYSTEM);
507 static void reboot_signal(int sig)
510 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
518 void new_initAction (initActionEnum action,
519 char* process, char* cons)
521 initAction* newAction;
523 /* If BusyBox detects that a serial console is in use,
524 * then entries containing non-empty id fields will _not_ be run.
526 if (secondConsole == NULL && *cons != '\0') {
530 newAction = calloc ((size_t)(1), sizeof(initAction));
532 message(LOG|CONSOLE,"Memory allocation failure\n");
535 newAction->nextPtr = initActionList;
536 initActionList = newAction;
537 strncpy( newAction->process, process, 255);
538 newAction->action = action;
540 strncpy(newAction->console, cons, 255);
542 strncpy(newAction->console, console, 255);
544 message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
545 newAction->process, newAction->action, newAction->console);
548 void delete_initAction (initAction *action)
550 initAction *a, *b=NULL;
551 for( a=initActionList ; a; b=a, a=a->nextPtr) {
552 if (a == action && b != NULL) {
553 b->nextPtr=a->nextPtr;
560 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
561 * then parse_inittab() simply adds in some default
562 * actions(i.e runs INIT_SCRIPT and then starts a pair
563 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
564 * _is_ defined, but /etc/inittab is missing, this
565 * results in the same set of default behaviors.
567 void parse_inittab(void)
569 #ifdef BB_FEATURE_USE_INITTAB
571 char buf[256], lineAsRead[256], tmpConsole[256];
573 const struct initActionType *a = actions;
577 file = fopen(INITTAB, "r");
579 /* No inittab file -- set up some default behavior */
581 /* Askfirst shell on tty1 */
582 new_initAction( ASKFIRST, SHELL, console );
583 /* Askfirst shell on tty2 */
584 if (secondConsole != NULL)
585 new_initAction( ASKFIRST, SHELL, secondConsole );
587 new_initAction( SYSINIT, INIT_SCRIPT, console );
590 #ifdef BB_FEATURE_USE_INITTAB
593 while ( fgets(buf, 255, file) != NULL) {
595 for(p = buf; *p == ' ' || *p == '\t'; p++);
596 if (*p == '#' || *p == '\n') continue;
598 /* Trim the trailing \n */
599 q = strrchr( p, '\n');
603 /* Keep a copy around for posterity's sake (and error msgs) */
604 strcpy(lineAsRead, buf);
606 /* Grab the ID field */
609 if ( p != NULL || *(p+1) != '\0' ) {
614 /* Now peal off the process field from the end
616 q = strrchr( p, ':');
617 if ( q == NULL || *(q+1) == '\0' ) {
618 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
625 /* Now peal off the action field */
626 r = strrchr( p, ':');
627 if ( r == NULL || *(r+1) == '\0') {
628 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
634 /* Ok, now process it */
636 while (a->name != 0) {
637 if (strcmp(a->name, r) == 0) {
640 strcpy(tmpConsole, "/dev/");
641 strncat(tmpConsole, s, 200);
642 if (stat(tmpConsole, &statBuf) != 0) {
643 message(LOG|CONSOLE, "device '%s' does not exist. Did you read the directions?\n", tmpConsole);
648 new_initAction( a->action, q, s);
656 /* Choke on an unknown action */
657 message(LOG|CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
664 extern int init_main(int argc, char **argv)
671 /* Expect to be PID 1 iff we are run as init (not linuxrc) */
672 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
673 usage( "init\n\nInit is the parent of all processes.\n\n"
674 "This version of init is designed to be run only by the kernel\n");
676 /* Set up sig handlers -- be sure to
677 * clear all of these in run() */
678 signal(SIGUSR1, halt_signal);
679 signal(SIGUSR2, reboot_signal);
680 signal(SIGINT, reboot_signal);
681 signal(SIGTERM, reboot_signal);
683 /* Turn off rebooting via CTL-ALT-DEL -- we get a
684 * SIGINT on CAD so we can shut things down gracefully... */
685 reboot(RB_DISABLE_CAD);
688 /* Figure out where the default console should be */
691 /* Close whatever files are open, and reset the console. */
698 /* Make sure PATH is set to something sane */
699 putenv(_PATH_STDPATH);
704 "init started: BusyBox v%s (%s) multi-call binary\r\n",
708 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
709 getpid(), BB_VER, BB_BT);
714 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
715 message(LOG|CONSOLE, "Mounting /proc: done.\n");
716 kernelVersion = get_kernel_revision();
718 message(LOG|CONSOLE, "Mounting /proc: failed!\n");
720 /* Make sure there is enough memory to do something useful. */
723 /* Check if we are supposed to be in single user mode */
724 if ( argc > 1 && (!strcmp(argv[1], "single") ||
725 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1")))
727 /* Ask first then start a shell on tty2 */
728 if (secondConsole != NULL)
729 new_initAction( ASKFIRST, SHELL, secondConsole);
730 /* Ask first then start a shell on tty1 */
731 new_initAction( ASKFIRST, SHELL, console);
733 /* Not in single user mode -- see what inittab says */
735 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
736 * then parse_inittab() simply adds in some default
737 * actions(i.e runs INIT_SCRIPT and then starts a pair
738 * of "askfirst" shells */
742 /* Now run everything that needs to be run */
744 /* First run the sysinit command */
745 for( a=initActionList ; a; a=a->nextPtr) {
746 if (a->action == SYSINIT) {
747 waitfor(a->process, a->console, FALSE);
748 /* Now remove the "sysinit" entry from the list */
749 delete_initAction( a);
752 /* Next run anything that wants to block */
753 for( a=initActionList ; a; a=a->nextPtr) {
754 if (a->action == WAIT) {
755 waitfor(a->process, a->console, FALSE);
756 /* Now remove the "wait" entry from the list */
757 delete_initAction( a);
760 /* Next run anything to be run only once */
761 for( a=initActionList ; a; a=a->nextPtr) {
762 if (a->action == ONCE) {
763 run(a->process, a->console, FALSE);
764 /* Now remove the "once" entry from the list */
765 delete_initAction( a);
768 /* If there is nothing else to do, stop */
769 if (initActionList == NULL) {
770 message(LOG|CONSOLE, "No more tasks for init -- sleeping forever.\n");
774 /* Now run the looping stuff for the rest of forever */
776 for( a=initActionList ; a; a=a->nextPtr) {
777 /* Only run stuff with pid==0. If they have
778 * a pid, that means they are still running */
782 /* run the respawn stuff */
783 a->pid = run(a->process, a->console, FALSE);
786 /* run the askfirst stuff */
787 a->pid = run(a->process, a->console, TRUE);
789 /* silence the compiler's incessant whining */
795 /* Wait for a child process to exit */
796 wpid = wait(&status);
798 /* Find out who died and clean up their corpse */
799 for( a=initActionList ; a; a=a->nextPtr) {
802 message(LOG, "Process '%s' (pid %d) exited. Scheduling it for restart.\n",