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