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