minor changes to mount/umount to support-by-ignoring the "-v" flag.
[oweals/busybox.git] / init / init.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini init implementation for busybox
4  *
5  *
6  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
7  * Adjusted by so many folks, it's impossible to keep track.
8  *
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.
13  *
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.
18  *
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
22  *
23  */
24
25 /* Turn this on to disable all the dangerous 
26    rebooting stuff when debugging.
27 #define DEBUG_INIT
28 */
29
30 #include "internal.h"
31 #include <asm/types.h>
32 #include <errno.h>
33 #include <linux/serial.h>               /* for serial_struct */
34 #include <linux/version.h>
35 #include <paths.h>
36 #include <signal.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.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() */
47 #ifdef BB_SYSLOGD
48 # include <sys/syslog.h>
49 #endif
50 #include <sys/sysmacros.h>
51 #include <sys/types.h>
52 #include <sys/vt.h>                             /* for vt_stat */
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <unistd.h>
56
57
58 /*
59  * When CORE_ENABLE_FLAG_FILE exists, setrlimit is called before
60  * process is spawned to set corelimit to unlimited.
61  */
62 #define CORE_ENABLE_FLAG_FILE "/.init_enable_core"
63 #include <sys/resource.h>
64 #include <sys/time.h>
65
66 #ifndef KERNEL_VERSION
67 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
68 #endif
69
70
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 */
78 #ifndef INIT_SCRIPT
79 #define INIT_SCRIPT  "/etc/init.d/rcS"   /* Default sysinit script. */
80 #endif
81
82 #define LOG     0x1
83 #define CONSOLE 0x2
84
85 /* Allowed init action types */
86 typedef enum {
87         SYSINIT = 1,
88         RESPAWN,
89         ASKFIRST,
90         WAIT,
91         ONCE,
92         CTRLALTDEL
93 } initActionEnum;
94
95 /* A mapping between "inittab" action name strings and action type codes. */
96 typedef struct initActionType {
97         const char *name;
98         initActionEnum action;
99 } initActionType;
100
101 static const struct initActionType actions[] = {
102         {"sysinit", SYSINIT},
103         {"respawn", RESPAWN},
104         {"askfirst", ASKFIRST},
105         {"wait", WAIT},
106         {"once", ONCE},
107         {"ctrlaltdel", CTRLALTDEL},
108         {0}
109 };
110
111 /* Set up a linked list of initActions, to be read from inittab */
112 typedef struct initActionTag initAction;
113 struct initActionTag {
114         pid_t pid;
115         char process[256];
116         char console[256];
117         initAction *nextPtr;
118         initActionEnum action;
119 };
120 initAction *initActionList = NULL;
121
122
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;
128
129 static void delete_initAction(initAction * action);
130
131
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, ...)
135 {
136         va_list arguments;
137         int fd;
138
139 #ifdef BB_SYSLOGD
140
141         /* Log the message to syslogd */
142         if (device & LOG) {
143                 char msg[1024];
144
145                 va_start(arguments, fmt);
146                 vsnprintf(msg, sizeof(msg), fmt, arguments);
147                 va_end(arguments);
148                 openlog("init", 0, LOG_USER);
149                 syslog(LOG_USER|LOG_INFO, msg);
150                 closelog();
151         }
152 #else
153         static int log_fd = -1;
154
155         /* Take full control of the log tty, and never close it.
156          * It's mine, all mine!  Muhahahaha! */
157         if (log_fd < 0) {
158                 if (log == NULL) {
159                         /* don't even try to log, because there is no such console */
160                         log_fd = -2;
161                         /* log to main console instead */
162                         device = CONSOLE;
163                 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
164                         log_fd = -2;
165                         fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
166                         fflush(stderr);
167                         log = NULL;
168                         device = CONSOLE;
169                 }
170         }
171         if ((device & LOG) && (log_fd >= 0)) {
172                 va_start(arguments, fmt);
173                 vdprintf(log_fd, fmt, arguments);
174                 va_end(arguments);
175         }
176 #endif
177
178         if (device & CONSOLE) {
179                 /* Always send console messages to /dev/console so people will see them. */
180                 if (
181                         (fd =
182                          device_open(_PATH_CONSOLE,
183                                                  O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
184                         va_start(arguments, fmt);
185                         vdprintf(fd, fmt, arguments);
186                         va_end(arguments);
187                         close(fd);
188                 } else {
189                         fprintf(stderr, "Bummer, can't print: ");
190                         va_start(arguments, fmt);
191                         vfprintf(stderr, fmt, arguments);
192                         fflush(stderr);
193                         va_end(arguments);
194                 }
195         }
196 }
197
198
199 /* Set terminal settings to reasonable defaults */
200 void set_term(int fd)
201 {
202         struct termios tty;
203
204         tcgetattr(fd, &tty);
205
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 */
215
216         /* use line dicipline 0 */
217         tty.c_line = 0;
218
219         /* Make it be sane */
220         tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
221         tty.c_cflag |= HUPCL|CLOCAL;
222
223         /* input modes */
224         tty.c_iflag = ICRNL | IXON | IXOFF;
225
226         /* output modes */
227         tty.c_oflag = OPOST | ONLCR;
228
229         /* local modes */
230         tty.c_lflag =
231                 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
232
233         tcsetattr(fd, TCSANOW, &tty);
234 }
235
236 /* How much memory does this machine have? */
237 static int check_free_memory()
238 {
239         struct sysinfo info;
240
241         sysinfo(&info);
242         if (sysinfo(&info) != 0) {
243                 message(LOG, "Error checking free memory: %s\n", strerror(errno));
244                 return -1;
245         }
246
247         return((info.totalram+info.totalswap)/1024);
248 }
249
250 static void console_init()
251 {
252         int fd;
253         int tried_devcons = 0;
254         int tried_vtprimary = 0;
255         struct vt_stat vt;
256         struct serial_struct sr;
257         char *s;
258
259         if ((s = getenv("TERM")) != NULL) {
260                 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
261         }
262
263         if ((s = getenv("CONSOLE")) != NULL) {
264                 snprintf(console, sizeof(console) - 1, "%s", s);
265         }
266 #if #cpu(sparc)
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);
275         }
276 #endif
277         else {
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",
285                                          vt.v_active);
286                 } else {
287                         snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
288                         tried_devcons++;
289                 }
290         }
291
292         while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
293                 /* Can't open selected console -- try /dev/console */
294                 if (!tried_devcons) {
295                         tried_devcons++;
296                         snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
297                         continue;
298                 }
299                 /* Can't open selected console -- try vt1 */
300                 if (!tried_vtprimary) {
301                         tried_vtprimary++;
302                         snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
303                         continue;
304                 }
305                 break;
306         }
307         if (fd < 0) {
308                 /* Perhaps we should panic here? */
309                 snprintf(console, sizeof(console) - 1, "/dev/null");
310         } else {
311                 /* check for serial console and disable logging to tty3 & running a
312                    * shell to tty2 */
313                 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
314                         log = NULL;
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");
322                 }
323                 close(fd);
324         }
325         message(LOG, "console=%s\n", console);
326 }
327
328 static pid_t run(char *command, char *terminal, int get_enter)
329 {
330         int i, fd;
331         pid_t pid;
332         char *tmpCmd;
333         char *cmd[255];
334         char buf[255];
335         static const char press_enter[] =
336
337                 "\nPlease press Enter to activate this console. ";
338         char *environment[] = {
339                 "HOME=/",
340                 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
341                 "SHELL=/bin/sh",
342                 termType,
343                 "USER=root",
344                 0
345         };
346
347
348         if ((pid = fork()) == 0) {
349                 /* Clean up */
350                 close(0);
351                 close(1);
352                 close(2);
353                 setsid();
354
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);
361
362                 if ((fd = device_open(terminal, O_RDWR)) < 0) {
363                         message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
364                         exit(1);
365                 }
366                 dup2(fd, 0);
367                 dup2(fd, 1);
368                 dup2(fd, 2);
369                 tcsetpgrp(0, getpgrp());
370                 set_term(0);
371
372                 if (get_enter == TRUE) {
373                         /*
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 
379                          * specifies.
380                          */
381                         char c;
382 #ifdef DEBUG_INIT
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);
386 #endif
387                         write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
388                         read(fileno(stdin), &c, 1);
389                 }
390
391 #ifdef DEBUG_INIT
392                 /* Log the process name and args */
393                 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
394                                 shell_pgid, terminal, command);
395 #endif
396
397                 /* See if any special /bin/sh requiring characters are present */
398                 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
399                         cmd[0] = SHELL;
400                         cmd[1] = "-c";
401                         strcpy(buf, "exec ");
402                         strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
403                         cmd[2] = buf;
404                         cmd[3] = NULL;
405                 } else {
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') {
410                                         cmd[i] = tmpCmd;
411                                         tmpCmd++;
412                                         i++;
413                                 }
414                         }
415                         cmd[i] = NULL;
416                 }
417
418                 {
419                         struct stat sb;
420                         if (stat (CORE_ENABLE_FLAG_FILE, &sb) == 0) {
421                                 struct rlimit limit;
422                                 limit.rlim_cur = RLIM_INFINITY;
423                                 limit.rlim_max = RLIM_INFINITY;
424                                 setrlimit(RLIMIT_CORE, &limit);
425                         }
426                 }
427
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);
431
432                 /* We're still here?  Some error happened. */
433                 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
434                                 strerror(errno));
435                 exit(-1);
436         }
437         return pid;
438 }
439
440 static int waitfor(char *command, char *terminal, int get_enter)
441 {
442         int status, wpid;
443         int pid = run(command, terminal, get_enter);
444
445         while (1) {
446                 wpid = wait(&status);
447                 if (wpid > 0 && wpid != pid) {
448                         continue;
449                 }
450                 if (wpid == pid)
451                         break;
452         }
453         return wpid;
454 }
455
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()
459 {
460         struct stat statBuf;
461
462         if (check_free_memory() > 1000)
463                 return;
464
465         if (stat("/etc/fstab", &statBuf) == 0) {
466                 /* Try to turn on swap */
467                 system("/sbin/swapon -a");
468                 if (check_free_memory() < 1000)
469                         goto goodnight;
470         } else
471                 goto goodnight;
472         return;
473
474   goodnight:
475         message(CONSOLE,
476                         "Sorry, your computer does not have enough memory.\r\n");
477         while (1)
478                 sleep(1);
479 }
480
481 /* Run all commands to be run right before halt/reboot */
482 static void run_lastAction(void)
483 {
484         initAction *a;
485         for (a = initActionList; a; a = a->nextPtr) {
486                 if (a->action == CTRLALTDEL) {
487                         waitfor(a->process, a->console, FALSE);
488                         delete_initAction(a);
489                 }
490         }
491 }
492
493
494 #ifndef DEBUG_INIT
495 static void shutdown_system(void)
496 {
497
498         /* first disable our SIGHUP signal */
499         signal(SIGHUP, SIG_DFL);
500
501         /* Allow Ctrl-Alt-Del to reboot system. */
502         reboot(RB_ENABLE_CAD);
503
504         message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
505         sync();
506
507         /* Send signals to every process _except_ pid 1 */
508         message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
509         kill(-1, SIGTERM);
510         sleep(1);
511         sync();
512
513         message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
514         kill(-1, SIGKILL);
515         sleep(1);
516
517         /* run everything to be run at "ctrlaltdel" */
518         run_lastAction();
519
520         sync();
521         if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
522                 /* bdflush, kupdate not needed for kernels >2.2.11 */
523                 bdflush(1, 0);
524                 sync();
525         }
526 }
527
528 static void halt_signal(int sig)
529 {
530         shutdown_system();
531         message(CONSOLE|LOG,
532                         "The system is halted. Press %s or turn off power\r\n",
533                         (secondConsole == NULL) /* serial console */
534                         ? "Reset" : "CTRL-ALT-DEL");
535         sync();
536
537         /* allow time for last message to reach serial console */
538         sleep(2);
539
540 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
541         if (sig == SIGUSR2)
542                 reboot(RB_POWER_OFF);
543         else
544 #endif
545                 reboot(RB_HALT_SYSTEM);
546         exit(0);
547 }
548
549 static void reboot_signal(int sig)
550 {
551         shutdown_system();
552         message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
553         sync();
554
555         /* allow time for last message to reach serial console */
556         sleep(2);
557
558         reboot(RB_AUTOBOOT);
559         exit(0);
560 }
561
562 #if defined BB_FEATURE_INIT_CHROOT
563
564 #if ! defined BB_FEATURE_USE_PROCFS
565 #error Sorry, I depend on the /proc filesystem right now.
566 #endif
567
568 static void check_chroot(int sig)
569 {
570         char *argv_init[2] = { "init", NULL, };
571         char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
572         char rootpath[256], *tc;
573         int fd;
574
575         if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
576                 message(CONSOLE,
577                                 "SIGHUP recived, but could not open proc file\r\n");
578                 sleep(2);
579                 return;
580         }
581         if (read(fd, rootpath, sizeof(rootpath)) == -1) {
582                 message(CONSOLE,
583                                 "SIGHUP recived, but could not read proc file\r\n");
584                 sleep(2);
585                 return;
586         }
587         close(fd);
588
589         if (rootpath[0] == '\0') {
590                 message(CONSOLE,
591                                 "SIGHUP recived, but new root is not valid: %s\r\n",
592                                 rootpath);
593                 sleep(2);
594                 return;
595         }
596
597         tc = strrchr(rootpath, '\n');
598         *tc = '\0';
599
600         /* Ok, making it this far means we commit */
601         message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
602                         rootpath);
603
604         /* kill all other programs first */
605         message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
606         kill(-1, SIGTERM);
607         sleep(2);
608         sync();
609
610         message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
611         kill(-1, SIGKILL);
612         sleep(2);
613         sync();
614
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 */
617         umount("/proc");
618
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). */
623
624         if (!chroot(rootpath))
625                 umount("/dev/root");
626
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 */
629
630         /* close all of our descriptors and open new ones */
631         close(0);
632         close(1);
633         close(2);
634         open("/dev/console", O_RDWR, 0);
635         dup(0);
636         dup(0);
637
638         message(CONSOLE, "Executing real init...\r\n");
639         /* execute init in the (hopefully) new root */
640         execve("/sbin/init", argv_init, envp_init);
641
642         message(CONSOLE,
643                         "ERROR: Could not exec new init. Press %s to reboot.\r\n",
644                         (secondConsole == NULL) /* serial console */
645                         ? "Reset" : "CTRL-ALT-DEL");
646         return;
647 }
648 #endif                                                  /* BB_FEATURE_INIT_CHROOT */
649
650 #endif                                                  /* ! DEBUG_INIT */
651
652 void new_initAction(initActionEnum action, char *process, char *cons)
653 {
654         initAction *newAction;
655
656         if (*cons == '\0')
657                 cons = console;
658
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.
662          */
663         if (secondConsole == NULL && strcmp(cons, console)
664                 && strcmp(cons, "/dev/null"))
665                 return;
666
667         newAction = calloc((size_t) (1), sizeof(initAction));
668         if (!newAction) {
669                 message(LOG | CONSOLE, "Memory allocation failure\n");
670                 while (1)
671                         sleep(1);
672         }
673         newAction->nextPtr = initActionList;
674         initActionList = newAction;
675         strncpy(newAction->process, process, 255);
676         newAction->action = action;
677         strncpy(newAction->console, cons, 255);
678         newAction->pid = 0;
679 //    message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
680 //      newAction->process, newAction->action, newAction->console);
681 }
682
683 static void delete_initAction(initAction * action)
684 {
685         initAction *a, *b = NULL;
686
687         for (a = initActionList; a; b = a, a = a->nextPtr) {
688                 if (a == action) {
689                         if (b == NULL) {
690                                 initActionList = a->nextPtr;
691                         } else {
692                                 b->nextPtr = a->nextPtr;
693                         }
694                         free(a);
695                         break;
696                 }
697         }
698 }
699
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.
706  * */
707 void parse_inittab(void)
708 {
709 #ifdef BB_FEATURE_USE_INITTAB
710         FILE *file;
711         char buf[256], lineAsRead[256], tmpConsole[256];
712         char *p, *q, *r, *s;
713         const struct initActionType *a = actions;
714         int foundIt;
715
716
717         file = fopen(INITTAB, "r");
718         if (file == NULL) {
719                 /* No inittab file -- set up some default behavior */
720 #endif
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);
730                 /* sysinit */
731                 new_initAction(SYSINIT, INIT_SCRIPT, console);
732
733                 return;
734 #ifdef BB_FEATURE_USE_INITTAB
735         }
736
737         while (fgets(buf, 255, file) != NULL) {
738                 foundIt = FALSE;
739                 for (p = buf; *p == ' ' || *p == '\t'; p++);
740                 if (*p == '#' || *p == '\n')
741                         continue;
742
743                 /* Trim the trailing \n */
744                 q = strrchr(p, '\n');
745                 if (q != NULL)
746                         *q = '\0';
747
748                 /* Keep a copy around for posterity's sake (and error msgs) */
749                 strcpy(lineAsRead, buf);
750
751                 /* Grab the ID field */
752                 s = p;
753                 p = strchr(p, ':');
754                 if (p != NULL || *(p + 1) != '\0') {
755                         *p = '\0';
756                         ++p;
757                 }
758
759                 /* Now peel off the process field from the end
760                  * of the string */
761                 q = strrchr(p, ':');
762                 if (q == NULL || *(q + 1) == '\0') {
763                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
764                         continue;
765                 } else {
766                         *q = '\0';
767                         ++q;
768                 }
769
770                 /* Now peel off the action field */
771                 r = strrchr(p, ':');
772                 if (r == NULL || *(r + 1) == '\0') {
773                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
774                         continue;
775                 } else {
776                         ++r;
777                 }
778
779                 /* Ok, now process it */
780                 a = actions;
781                 while (a->name != 0) {
782                         if (strcmp(a->name, r) == 0) {
783                                 if (*s != '\0') {
784                                         struct stat statBuf;
785
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",
791                                                                 tmpConsole);
792                                                 break;
793                                         }
794                                         s = tmpConsole;
795                                 }
796                                 new_initAction(a->action, q, s);
797                                 foundIt = TRUE;
798                         }
799                         a++;
800                 }
801                 if (foundIt == TRUE)
802                         continue;
803                 else {
804                         /* Choke on an unknown action */
805                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
806                 }
807         }
808         return;
809 #endif /* BB_FEATURE_USE_INITTAB */
810 }
811
812
813
814 extern int init_main(int argc, char **argv)
815 {
816         initAction *a;
817         pid_t wpid;
818         int status;
819
820 #ifndef DEBUG_INIT
821         /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
822         if (getpid() != 1
823 #ifdef BB_FEATURE_LINUXRC
824                         && strstr(argv[0], "linuxrc") == NULL
825 #endif
826                           )
827         {
828                         usage("init\n\nInit is the parent of all processes.\n\n"
829                                   "This version of init is designed to be run only "
830                                   "by the kernel.\n");
831         }
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);
840 #endif
841
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);
845 #endif
846
847         /* Figure out what kernel this is running */
848         kernelVersion = get_kernel_revision();
849
850         /* Figure out where the default console should be */
851         console_init();
852
853         /* Close whatever files are open, and reset the console. */
854         close(0);
855         close(1);
856         close(2);
857         set_term(0);
858         chdir("/");
859         setsid();
860
861         /* Make sure PATH is set to something sane */
862         putenv(_PATH_STDPATH);
863
864         /* Hello world */
865 #ifndef DEBUG_INIT
866         message(
867 #if ! defined BB_FEATURE_EXTRA_QUIET
868                         CONSOLE|
869 #endif
870                         LOG,
871                         "init started:  BusyBox v%s (%s) multi-call binary\r\n",
872                         BB_VER, BB_BT);
873 #else
874         message(
875 #if ! defined BB_FEATURE_EXTRA_QUIET
876                         CONSOLE|
877 #endif
878                         LOG,
879                         "init(%d) started:  BusyBox v%s (%s) multi-call binary\r\n",
880                         getpid(), BB_VER, BB_BT);
881 #endif
882
883
884         /* Make sure there is enough memory to do something useful. */
885         check_memory();
886
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);
895         } else {
896                 /* Not in single user mode -- see what inittab says */
897
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 */
902                 parse_inittab();
903         }
904
905         /* Fix up argv[0] to be certain we claim to be init */
906         strncpy(argv[0], "init", strlen(argv[0])+1);
907         if (argc > 1)
908                 strncpy(argv[1], "\0", strlen(argv[1])+1);
909
910         /* Now run everything that needs to be run */
911
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);
918                 }
919         }
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);
926                 }
927         }
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);
934                 }
935         }
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");
940                 while (1)
941                         sleep(1);
942         }
943
944         /* Now run the looping stuff for the rest of forever */
945         while (1) {
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 */
949                         if (a->pid == 0) {
950                                 switch (a->action) {
951                                 case RESPAWN:
952                                         /* run the respawn stuff */
953                                         a->pid = run(a->process, a->console, FALSE);
954                                         break;
955                                 case ASKFIRST:
956                                         /* run the askfirst stuff */
957                                         a->pid = run(a->process, a->console, TRUE);
958                                         break;
959                                         /* silence the compiler's incessant whining */
960                                 default:
961                                         break;
962                                 }
963                         }
964                 }
965                 /* Wait for a child process to exit */
966                 wpid = wait(&status);
967                 if (wpid > 0) {
968                         /* Find out who died and clean up their corpse */
969                         for (a = initActionList; a; a = a->nextPtr) {
970                                 if (a->pid == wpid) {
971                                         a->pid = 0;
972                                         message(LOG,
973                                                         "Process '%s' (pid %d) exited.  Scheduling it for restart.\n",
974                                                         a->process, wpid);
975                                 }
976                         }
977                 }
978                 sleep(1);
979         }
980 }
981
982 /*
983 Local Variables:
984 c-file-style: "linux"
985 c-basic-offset: 4
986 tab-width: 4
987 End:
988 */