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