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