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