b59e9a1473488cc7c94ac18acf0e8348167d8ce6
[oweals/busybox.git] / 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 <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdarg.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <termios.h>
39 #include <paths.h>
40 #include <sys/types.h>
41 #include <sys/fcntl.h>
42 #include <sys/wait.h>
43 #include <string.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>
53 #ifdef BB_SYSLOGD
54 #include <sys/syslog.h>
55 #endif
56
57 #if ! defined BB_FEATURE_USE_PROCFS
58 #error Sorry, I depend on the /proc filesystem right now.
59 #endif
60
61 #ifndef KERNEL_VERSION
62 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
63 #endif
64
65
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 */
73 #ifndef INIT_SCRIPT
74 #define INIT_SCRIPT     "/etc/init.d/rcS"       /* Default sysinit script. */
75 #endif
76
77 #define LOG             0x1
78 #define CONSOLE         0x2
79
80 /* Allowed init action types */
81 typedef enum {
82         SYSINIT = 1,
83         RESPAWN,
84         ASKFIRST,
85         WAIT,
86         ONCE,
87         CTRLALTDEL
88 } initActionEnum;
89
90 /* And now a list of the actions we support in the version of init */
91 typedef struct initActionType {
92         const char *name;
93         initActionEnum action;
94 } initActionType;
95
96 static const struct initActionType actions[] = {
97         {"sysinit", SYSINIT},
98         {"respawn", RESPAWN},
99         {"askfirst", ASKFIRST},
100         {"wait", WAIT},
101         {"once", ONCE},
102         {"ctrlaltdel", CTRLALTDEL},
103         {0}
104 };
105
106 /* Set up a linked list of initactions, to be read from inittab */
107 typedef struct initActionTag initAction;
108 struct initActionTag {
109         pid_t pid;
110         char process[256];
111         char console[256];
112         initAction *nextPtr;
113         initActionEnum action;
114 };
115 initAction *initActionList = NULL;
116
117
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);
124
125
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, ...)
129 {
130         va_list arguments;
131         int fd;
132
133 #ifdef BB_SYSLOGD
134
135         /* Log the message to syslogd */
136         if (device & LOG) {
137                 char msg[1024];
138
139                 va_start(arguments, fmt);
140                 vsnprintf(msg, sizeof(msg), fmt, arguments);
141                 va_end(arguments);
142                 openlog("init", 0, LOG_USER);
143                 syslog(LOG_USER|LOG_INFO, msg);
144                 closelog();
145         }
146 #else
147         static int log_fd = -1;
148
149         /* Take full control of the log tty, and never close it.
150          * It's mine, all mine!  Muhahahaha! */
151         if (log_fd < 0) {
152                 if (log == NULL) {
153                         /* don't even try to log, because there is no such console */
154                         log_fd = -2;
155                         /* log to main console instead */
156                         device = CONSOLE;
157                 } else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
158                         log_fd = -2;
159                         fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
160                         fflush(stderr);
161                         log = NULL;
162                         device = CONSOLE;
163                 }
164         }
165         if ((device & LOG) && (log_fd >= 0)) {
166                 va_start(arguments, fmt);
167                 vdprintf(log_fd, fmt, arguments);
168                 va_end(arguments);
169         }
170 #endif
171
172         if (device & CONSOLE) {
173                 /* Always send console messages to /dev/console so people will see them. */
174                 if (
175                         (fd =
176                          device_open(_PATH_CONSOLE,
177                                                  O_WRONLY | O_NOCTTY | O_NDELAY)) >= 0) {
178                         va_start(arguments, fmt);
179                         vdprintf(fd, fmt, arguments);
180                         va_end(arguments);
181                         close(fd);
182                 } else {
183                         fprintf(stderr, "Bummer, can't print: ");
184                         va_start(arguments, fmt);
185                         vfprintf(stderr, fmt, arguments);
186                         fflush(stderr);
187                         va_end(arguments);
188                 }
189         }
190 }
191
192
193 /* Set terminal settings to reasonable defaults */
194 void set_term(int fd)
195 {
196         struct termios tty;
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'
201         };
202
203         tcgetattr(fd, &tty);
204
205         /* set control chars */
206         memcpy(tty.c_cc, control_characters, sizeof(control_characters));
207
208         /* use line dicipline 0 */
209         tty.c_line = 0;
210
211         /* Make it be sane */
212         //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
213         //tty.c_cflag |= HUPCL|CLOCAL;
214
215         /* input modes */
216         tty.c_iflag = ICRNL | IXON | IXOFF;
217
218         /* output modes */
219         tty.c_oflag = OPOST | ONLCR;
220
221         /* local modes */
222         tty.c_lflag =
223                 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
224
225         tcsetattr(fd, TCSANOW, &tty);
226 }
227
228 /* How much memory does this machine have? */
229 static int mem_total()
230 {
231         char s[80];
232         char *p = "/proc/meminfo";
233         FILE *f;
234         const char pattern[] = "MemTotal:";
235
236         if ((f = fopen(p, "r")) < 0) {
237                 message(LOG, "Error opening %s: %s\n", p, strerror(errno));
238                 return -1;
239         }
240         while (NULL != fgets(s, 79, f)) {
241                 p = strstr(s, pattern);
242                 if (NULL != p) {
243                         fclose(f);
244                         return (atoi(p + strlen(pattern)));
245                 }
246         }
247         return -1;
248 }
249
250 static void console_init()
251 {
252         int fd;
253         int tried_devcons = 0;
254         int tried_vtprimary = 0;
255         struct serial_struct sr;
256         char *s;
257
258         if ((s = getenv("TERM")) != NULL) {
259                 snprintf(termType, sizeof(termType) - 1, "TERM=%s", s);
260         }
261
262         if ((s = getenv("CONSOLE")) != NULL) {
263                 snprintf(console, sizeof(console) - 1, "%s", s);
264         }
265 #if #cpu(sparc)
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);
274         }
275 #endif
276         else {
277                 struct vt_stat vt;
278
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",
286                                          vt.v_active);
287                 } else {
288                         snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
289                         tried_devcons++;
290                 }
291         }
292
293         while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
294                 /* Can't open selected console -- try /dev/console */
295                 if (!tried_devcons) {
296                         tried_devcons++;
297                         snprintf(console, sizeof(console) - 1, "%s", _PATH_CONSOLE);
298                         continue;
299                 }
300                 /* Can't open selected console -- try vt1 */
301                 if (!tried_vtprimary) {
302                         tried_vtprimary++;
303                         snprintf(console, sizeof(console) - 1, "%s", VT_PRIMARY);
304                         continue;
305                 }
306                 break;
307         }
308         if (fd < 0) {
309                 /* Perhaps we should panic here? */
310                 snprintf(console, sizeof(console) - 1, "/dev/null");
311         } else {
312                 /* check for serial console and disable logging to tty3 & running a
313                    * shell to tty2 */
314                 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
315                         log = NULL;
316                         secondConsole = NULL;
317                         message(LOG | CONSOLE,
318                                         "serial console detected.  Disabling virtual terminals.\r\n");
319                 }
320                 close(fd);
321         }
322         message(LOG, "console=%s\n", console);
323 }
324
325 static pid_t run(char *command, char *terminal, int get_enter)
326 {
327         int i, fd;
328         pid_t pid;
329         char *tmpCmd;
330         char *cmd[255];
331         char buf[255];
332         static const char press_enter[] =
333
334                 "\nPlease press Enter to activate this console. ";
335         char *environment[] = {
336                 "HOME=/",
337                 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
338                 "SHELL=/bin/sh",
339                 termType,
340                 "USER=root",
341                 0
342         };
343
344
345         if ((pid = fork()) == 0) {
346 #ifdef DEBUG_INIT
347                 pid_t shell_pgid = getpid();
348 #endif
349
350                 /* Clean up */
351                 close(0);
352                 close(1);
353                 close(2);
354                 setsid();
355
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);
362
363                 if ((fd = device_open(terminal, O_RDWR)) < 0) {
364                         message(LOG | CONSOLE, "Bummer, can't open %s\r\n", terminal);
365                         exit(1);
366                 }
367                 dup2(fd, 0);
368                 dup2(fd, 1);
369                 dup2(fd, 2);
370                 tcsetpgrp(0, getpgrp());
371                 set_term(0);
372
373                 if (get_enter == TRUE) {
374                         /*
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 
380                          * specifies.
381                          */
382                         char c;
383
384 #ifdef DEBUG_INIT
385                         message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
386                                         command, shell_pgid, terminal);
387 #endif
388                         write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
389                         read(fileno(stdin), &c, 1);
390                 }
391
392 #ifdef DEBUG_INIT
393                 /* Log the process name and args */
394                 message(LOG, "Starting pid %d, console %s: '%s'\r\n",
395                                 shell_pgid, terminal, command);
396 #endif
397
398                 /* See if any special /bin/sh requiring characters are present */
399                 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
400                         cmd[0] = SHELL;
401                         cmd[1] = "-c";
402                         strcpy(buf, "exec ");
403                         strncat(buf, command, sizeof(buf) - strlen(buf) - 1);
404                         cmd[2] = buf;
405                         cmd[3] = NULL;
406                 } else {
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') {
411                                         cmd[i] = tmpCmd;
412                                         tmpCmd++;
413                                         i++;
414                                 }
415                         }
416                         cmd[i] = NULL;
417                 }
418
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);
422
423                 /* We're still here?  Some error happened. */
424                 message(LOG | CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
425                                 strerror(errno));
426                 exit(-1);
427         }
428         return pid;
429 }
430
431 static int waitfor(char *command, char *terminal, int get_enter)
432 {
433         int status, wpid;
434         int pid = run(command, terminal, get_enter);
435
436         while (1) {
437                 wpid = wait(&status);
438                 if (wpid > 0 && wpid != pid) {
439                         continue;
440                 }
441                 if (wpid == pid)
442                         break;
443         }
444         return wpid;
445 }
446
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()
450 {
451         struct stat statBuf;
452
453         if (mem_total() > 3500)
454                 return;
455
456         if (stat("/etc/fstab", &statBuf) == 0) {
457                 /* Try to turn on swap */
458                 system("/sbin/swapon -a");
459                 if (mem_total() < 3500)
460                         goto goodnight;
461         } else
462                 goto goodnight;
463         return;
464
465   goodnight:
466         message(CONSOLE,
467                         "Sorry, your computer does not have enough memory.\r\n");
468         while (1)
469                 sleep(1);
470 }
471
472 /* Run all commands to be run right before halt/reboot */
473 static void run_lastAction(void)
474 {
475         initAction *a;
476         for (a = initActionList; a; a = a->nextPtr) {
477                 if (a->action == CTRLALTDEL) {
478                         waitfor(a->process, a->console, FALSE);
479                         delete_initAction(a);
480                 }
481         }
482 }
483
484
485 #ifndef DEBUG_INIT
486 static void shutdown_system(void)
487 {
488
489         /* first disable our SIGHUP signal */
490         signal(SIGHUP, SIG_DFL);
491
492         /* Allow Ctrl-Alt-Del to reboot system. */
493         reboot(RB_ENABLE_CAD);
494
495         message(CONSOLE|LOG, "\r\nThe system is going down NOW !!\r\n");
496         sync();
497
498         /* Send signals to every process _except_ pid 1 */
499         message(CONSOLE|LOG, "Sending SIGTERM to all processes.\r\n");
500         kill(-1, SIGTERM);
501         sleep(1);
502         sync();
503
504         message(CONSOLE|LOG, "Sending SIGKILL to all processes.\r\n");
505         kill(-1, SIGKILL);
506         sleep(1);
507
508         /* run everything to be run at "ctrlaltdel" */
509         run_lastAction();
510
511         sync();
512         if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
513                 /* bdflush, kupdate not needed for kernels >2.2.11 */
514                 bdflush(1, 0);
515                 sync();
516         }
517 }
518
519 static void halt_signal(int sig)
520 {
521         shutdown_system();
522         message(CONSOLE|LOG,
523                         "The system is halted. Press %s or turn off power\r\n",
524                         (secondConsole == NULL) /* serial console */
525                         ? "Reset" : "CTRL-ALT-DEL");
526         sync();
527
528         /* allow time for last message to reach serial console */
529         sleep(2);
530
531 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
532         if (sig == SIGUSR2)
533                 reboot(RB_POWER_OFF);
534         else
535 #endif
536                 reboot(RB_HALT_SYSTEM);
537         exit(0);
538 }
539
540 static void reboot_signal(int sig)
541 {
542         shutdown_system();
543         message(CONSOLE|LOG, "Please stand by while rebooting the system.\r\n");
544         sync();
545
546         /* allow time for last message to reach serial console */
547         sleep(2);
548
549         reboot(RB_AUTOBOOT);
550         exit(0);
551 }
552
553 #if defined BB_FEATURE_INIT_CHROOT
554 static void check_chroot(int sig)
555 {
556         char *argv_init[2] = { "init", NULL, };
557         char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
558         char rootpath[256], *tc;
559         int fd;
560
561         if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
562                 message(CONSOLE,
563                                 "SIGHUP recived, but could not open proc file\r\n");
564                 sleep(2);
565                 return;
566         }
567         if (read(fd, rootpath, sizeof(rootpath)) == -1) {
568                 message(CONSOLE,
569                                 "SIGHUP recived, but could not read proc file\r\n");
570                 sleep(2);
571                 return;
572         }
573         close(fd);
574
575         if (rootpath[0] == '\0') {
576                 message(CONSOLE,
577                                 "SIGHUP recived, but new root is not valid: %s\r\n",
578                                 rootpath);
579                 sleep(2);
580                 return;
581         }
582
583         tc = strrchr(rootpath, '\n');
584         *tc = '\0';
585
586         /* Ok, making it this far means we commit */
587         message(CONSOLE, "Please stand by, changing root to `%s'.\r\n",
588                         rootpath);
589
590         /* kill all other programs first */
591         message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
592         kill(-1, SIGTERM);
593         sleep(2);
594         sync();
595
596         message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
597         kill(-1, SIGKILL);
598         sleep(2);
599         sync();
600
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 */
603         umount("/proc");
604
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). */
609
610         if (!chroot(rootpath))
611                 umount("/dev/root");
612
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 */
615
616         /* close all of our descriptors and open new ones */
617         close(0);
618         close(1);
619         close(2);
620         open("/dev/console", O_RDWR, 0);
621         dup(0);
622         dup(0);
623
624         message(CONSOLE, "Executing real init...\r\n");
625         /* execute init in the (hopefully) new root */
626         execve("/sbin/init", argv_init, envp_init);
627
628         message(CONSOLE,
629                         "ERROR: Could not exec new init. Press %s to reboot.\r\n",
630                         (secondConsole == NULL) /* serial console */
631                         ? "Reset" : "CTRL-ALT-DEL");
632         return;
633 }
634 #endif                                                  /* BB_FEATURE_INIT_CHROOT */
635
636 #endif                                                  /* ! DEBUG_INIT */
637
638 void new_initAction(initActionEnum action, char *process, char *cons)
639 {
640         initAction *newAction;
641
642         if (*cons == '\0')
643                 cons = console;
644
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.
648          */
649         if (secondConsole == NULL && strcmp(cons, console)
650                 && strcmp(cons, "/dev/null"))
651                 return;
652
653         newAction = calloc((size_t) (1), sizeof(initAction));
654         if (!newAction) {
655                 message(LOG | CONSOLE, "Memory allocation failure\n");
656                 while (1)
657                         sleep(1);
658         }
659         newAction->nextPtr = initActionList;
660         initActionList = newAction;
661         strncpy(newAction->process, process, 255);
662         newAction->action = action;
663         strncpy(newAction->console, cons, 255);
664         newAction->pid = 0;
665 //    message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
666 //      newAction->process, newAction->action, newAction->console);
667 }
668
669 static void delete_initAction(initAction * action)
670 {
671         initAction *a, *b = NULL;
672
673         for (a = initActionList; a; b = a, a = a->nextPtr) {
674                 if (a == action) {
675                         if (b == NULL) {
676                                 initActionList = a->nextPtr;
677                         } else {
678                                 b->nextPtr = a->nextPtr;
679                         }
680                         free(a);
681                         break;
682                 }
683         }
684 }
685
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.
692  * */
693 void parse_inittab(void)
694 {
695 #ifdef BB_FEATURE_USE_INITTAB
696         FILE *file;
697         char buf[256], lineAsRead[256], tmpConsole[256];
698         char *p, *q, *r, *s;
699         const struct initActionType *a = actions;
700         int foundIt;
701
702
703         file = fopen(INITTAB, "r");
704         if (file == NULL) {
705                 /* No inittab file -- set up some default behavior */
706 #endif
707                 /* Swapoff on halt/reboot */
708                 new_initAction(CTRLALTDEL, "/sbin/swapoff -a > /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);
716                 /* sysinit */
717                 new_initAction(SYSINIT, INIT_SCRIPT, console);
718
719                 return;
720 #ifdef BB_FEATURE_USE_INITTAB
721         }
722
723         while (fgets(buf, 255, file) != NULL) {
724                 foundIt = FALSE;
725                 for (p = buf; *p == ' ' || *p == '\t'; p++);
726                 if (*p == '#' || *p == '\n')
727                         continue;
728
729                 /* Trim the trailing \n */
730                 q = strrchr(p, '\n');
731                 if (q != NULL)
732                         *q = '\0';
733
734                 /* Keep a copy around for posterity's sake (and error msgs) */
735                 strcpy(lineAsRead, buf);
736
737                 /* Grab the ID field */
738                 s = p;
739                 p = strchr(p, ':');
740                 if (p != NULL || *(p + 1) != '\0') {
741                         *p = '\0';
742                         ++p;
743                 }
744
745                 /* Now peal off the process field from the end
746                  * of the string */
747                 q = strrchr(p, ':');
748                 if (q == NULL || *(q + 1) == '\0') {
749                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
750                         continue;
751                 } else {
752                         *q = '\0';
753                         ++q;
754                 }
755
756                 /* Now peal off the action field */
757                 r = strrchr(p, ':');
758                 if (r == NULL || *(r + 1) == '\0') {
759                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
760                         continue;
761                 } else {
762                         ++r;
763                 }
764
765                 /* Ok, now process it */
766                 a = actions;
767                 while (a->name != 0) {
768                         if (strcmp(a->name, r) == 0) {
769                                 if (*s != '\0') {
770                                         struct stat statBuf;
771
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",
777                                                                 tmpConsole);
778                                                 break;
779                                         }
780                                         s = tmpConsole;
781                                 }
782                                 new_initAction(a->action, q, s);
783                                 foundIt = TRUE;
784                         }
785                         a++;
786                 }
787                 if (foundIt == TRUE)
788                         continue;
789                 else {
790                         /* Choke on an unknown action */
791                         message(LOG | CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
792                 }
793         }
794         return;
795 #endif
796 }
797
798
799
800 extern int init_main(int argc, char **argv)
801 {
802         initAction *a;
803         pid_t wpid;
804         int status;
805
806 #ifndef DEBUG_INIT
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");
811         }
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);
820 #endif
821
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);
825 #endif
826
827         /* Figure out where the default console should be */
828         console_init();
829
830         /* Close whatever files are open, and reset the console. */
831         close(0);
832         close(1);
833         close(2);
834         set_term(0);
835         setsid();
836
837         /* Make sure PATH is set to something sane */
838         putenv(_PATH_STDPATH);
839
840         /* Hello world */
841 #ifndef DEBUG_INIT
842         message(LOG | CONSOLE,
843                         "init started:  BusyBox v%s (%s) multi-call binary\r\n",
844                         BB_VER, BB_BT);
845 #else
846         message(LOG | CONSOLE,
847                         "init(%d) started:  BusyBox v%s (%s) multi-call binary\r\n",
848                         getpid(), BB_VER, BB_BT);
849 #endif
850
851
852         /* Mount /proc */
853         if (mount("proc", "/proc", "proc", 0, 0) == 0) {
854                 message(LOG | CONSOLE, "Mounting /proc: done.\n");
855                 kernelVersion = get_kernel_revision();
856         } else
857                 message(LOG | CONSOLE, "Mounting /proc: failed!\n");
858
859         /* Make sure there is enough memory to do something useful. */
860         check_memory();
861
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);
870         } else {
871                 /* Not in single user mode -- see what inittab says */
872
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 */
877                 parse_inittab();
878         }
879         
880         /* Fix up argv[0] to be certain we claim to be init */
881         strncpy(argv[0], "init", strlen(argv[0])+1);
882         if (argc > 1)
883                 strncpy(argv[1], "\0", strlen(argv[1])+1);
884
885         /* Now run everything that needs to be run */
886
887         /* First run the sysinit command */
888         for (a = initActionList; a; a = a->nextPtr) {
889                 if (a->action == SYSINIT) {
890                         waitfor(a->process, a->console, FALSE);
891                         /* Now remove the "sysinit" entry from the list */
892                         delete_initAction(a);
893                 }
894         }
895         /* Next run anything that wants to block */
896         for (a = initActionList; a; a = a->nextPtr) {
897                 if (a->action == WAIT) {
898                         waitfor(a->process, a->console, FALSE);
899                         /* Now remove the "wait" entry from the list */
900                         delete_initAction(a);
901                 }
902         }
903         /* Next run anything to be run only once */
904         for (a = initActionList; a; a = a->nextPtr) {
905                 if (a->action == ONCE) {
906                         run(a->process, a->console, FALSE);
907                         /* Now remove the "once" entry from the list */
908                         delete_initAction(a);
909                 }
910         }
911         /* If there is nothing else to do, stop */
912         if (initActionList == NULL) {
913                 message(LOG | CONSOLE,
914                                 "No more tasks for init -- sleeping forever.\n");
915                 while (1)
916                         sleep(1);
917         }
918
919         /* Now run the looping stuff for the rest of forever */
920         while (1) {
921                 for (a = initActionList; a; a = a->nextPtr) {
922                         /* Only run stuff with pid==0.  If they have
923                          * a pid, that means they are still running */
924                         if (a->pid == 0) {
925                                 switch (a->action) {
926                                 case RESPAWN:
927                                         /* run the respawn stuff */
928                                         a->pid = run(a->process, a->console, FALSE);
929                                         break;
930                                 case ASKFIRST:
931                                         /* run the askfirst stuff */
932                                         a->pid = run(a->process, a->console, TRUE);
933                                         break;
934                                         /* silence the compiler's incessant whining */
935                                 default:
936                                         break;
937                                 }
938                         }
939                 }
940                 /* Wait for a child process to exit */
941                 wpid = wait(&status);
942                 if (wpid > 0) {
943                         /* Find out who died and clean up their corpse */
944                         for (a = initActionList; a; a = a->nextPtr) {
945                                 if (a->pid == wpid) {
946                                         a->pid = 0;
947                                         message(LOG,
948                                                         "Process '%s' (pid %d) exited.  Scheduling it for restart.\n",
949                                                         a->process, wpid);
950                                 }
951                         }
952                 }
953                 sleep(1);
954         }
955 }