899e430400e22e582bc968fcff0c68c8f623eca4
[oweals/busybox.git] / init / init.c
1 /*
2  * Mini init implementation for busybox
3  *
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Adjusted by so many folks, it's impossible to keep track.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22  */
23
24 #include "internal.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <termios.h>
32 #include <sys/types.h>
33 #include <sys/fcntl.h>
34 #include <sys/wait.h>
35 #include <string.h>
36 #include <sys/mount.h>
37 #include <sys/reboot.h>
38 #include <sys/kdaemon.h>
39 #include <sys/sysmacros.h>
40 #include <linux/serial.h>       /* for serial_struct */
41 #include <sys/vt.h>             /* for vt_stat */
42 #include <sys/ioctl.h>
43
44 /* Turn this on to debug init so it won't reboot when killed */
45 //#define DEBUG_INIT
46
47 #define CONSOLE         "/dev/console"  /* Logical system console */
48 #define VT_PRIMARY      "/dev/tty1"     /* Primary virtual console */
49 #define VT_SECONDARY    "/dev/tty2"     /* Virtual console */
50 #define VT_LOG          "/dev/tty3"     /* Virtual console */
51 #define SERIAL_CON0     "/dev/ttyS0"    /* Primary serial console */
52 #define SERIAL_CON1     "/dev/ttyS1"    /* Serial console */
53 #define SHELL           "/bin/sh"       /* Default shell */
54 #define INITSCRIPT      "/etc/init.d/rcS"       /* Initscript. */
55 #define PATH_DEFAULT    "PATH=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin"
56
57 static char *console = CONSOLE;
58 static char *second_console = VT_SECONDARY;
59 static char *log = VT_LOG;
60
61
62
63 /* try to open up the specified device */
64 int device_open(char *device, int mode)
65 {
66     int m, f, fd = -1;
67
68     m = mode | O_NONBLOCK;
69
70     /* Retry up to 5 times */
71     for (f = 0; f < 5; f++)
72         if ((fd = open(device, m)) >= 0)
73             break;
74     if (fd < 0)
75         return fd;
76     /* Set original flags. */
77     if (m != mode)
78         fcntl(fd, F_SETFL, mode);
79     return fd;
80 }
81
82 /* print a message to the specified device */
83 void message(char *device, char *fmt, ...)
84 {
85     int fd;
86     va_list arguments;
87
88     if ((fd = device_open(device, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
89         va_start(arguments, fmt);
90         vdprintf(fd, fmt, arguments);
91         va_end(arguments);
92         close(fd);
93     } else {
94         fprintf(stderr, "Bummer, can't print: ");
95         va_start(arguments, fmt);
96         vfprintf(stderr, fmt, arguments);
97         fflush(stderr);
98         va_end(arguments);
99     }
100 }
101
102 /* Set terminal settings to reasonable defaults */
103 void set_term( int fd)
104 {
105     struct termios tty;
106     static const char control_characters[] = {
107         '\003', '\034', '\177', '\025', '\004', '\0',
108         '\1', '\0', '\021', '\023', '\032', '\0', '\022',
109         '\017', '\027', '\026', '\0'
110         };
111
112     tcgetattr(fd, &tty);
113
114     /* input modes */
115     tty.c_iflag = IGNPAR|ICRNL|IXON|IXOFF|IXANY;
116
117     /* use line dicipline 0 */
118     tty.c_line = 0;
119
120     /* output modes */
121     tty.c_oflag = OPOST|ONLCR;
122
123     /* local modes */
124     tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOPRT|ECHOKE|IEXTEN;
125
126     /* control chars */
127     memcpy(tty.c_cc, control_characters, sizeof(control_characters));
128
129     tcsetattr(fd, TCSANOW, &tty);
130 }
131
132 /* How much memory does this machine have? */
133 static int mem_total()
134 {
135     char s[80];
136     char *p = "/proc/meminfo";
137     FILE *f;
138     const char pattern[] = "MemTotal:";
139
140     if ((f = fopen(p, "r")) < 0) {
141         message(log, "Error opening %s: %s\n", p, strerror( errno));
142         return -1;
143     }
144     while (NULL != fgets(s, 79, f)) {
145         p = strstr(s, pattern);
146         if (NULL != p) {
147             fclose(f);
148             return (atoi(p + strlen(pattern)));
149         }
150     }
151     return -1;
152 }
153
154 static void console_init()
155 {
156     int fd;
157     int tried_devcons = 0;
158     int tried_vtprimary = 0;
159     char *s;
160
161     if ((s = getenv("CONSOLE")) != NULL) {
162         console = s;
163 /* Apparently the sparc does wierd things... */
164 #if defined (__sparc__)
165         if (strncmp( s, "/dev/tty", 8 )==0) {
166             switch( s[8]) {
167                 case 'a':
168                     s=SERIAL_CON0;
169                     break;
170                 case 'b':
171                     s=SERIAL_CON1;
172             }
173         }
174 #endif
175     } else {
176         console = CONSOLE;
177         tried_devcons++;
178     }
179
180     while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
181         /* Can't open selected console -- try /dev/console */
182         if (!tried_devcons) {
183             tried_devcons++;
184             console = CONSOLE;
185             continue;
186         }
187         /* Can't open selected console -- try vt1 */
188         if (!tried_vtprimary) {
189             tried_vtprimary++;
190             console = VT_PRIMARY;
191             continue;
192         }
193         break;
194     }
195     if (fd < 0)
196         /* Perhaps we should panic here? */
197         console = "/dev/null";
198     else
199         close(fd);
200     message(log, "console=%s\n", console );
201 }
202
203 static int waitfor(int pid)
204 {
205     int status, wpid;
206
207     message(log, "Waiting for process %d.\n", pid);
208     while ((wpid = wait(&status)) != pid) {
209         if (wpid > 0)
210             message(log, "pid %d exited, status=%x.\n", wpid, status);
211     }
212     return wpid;
213 }
214
215
216 static pid_t run(const char * const* command, 
217         char *terminal, int get_enter)
218 {
219     int fd;
220     pid_t pid;
221     const char * const* cmd = command+1;
222     static const char press_enter[] =
223         "\nPlease press Enter to activate this console. ";
224
225     if ((pid = fork()) == 0) {
226         /* Clean up */
227         close(0);
228         close(1);
229         close(2);
230         setsid();
231
232         /* Reset signal handlers set for parent process */
233         signal(SIGUSR1, SIG_DFL);
234         signal(SIGUSR2, SIG_DFL);
235         signal(SIGINT, SIG_DFL);
236         signal(SIGTERM, SIG_DFL);
237
238         if ((fd = device_open(terminal, O_RDWR)) < 0) {
239             message(log, "Bummer, can't open %s\r\n", terminal);
240             exit(-1);
241         }
242         dup(fd);
243         dup(fd);
244         tcsetpgrp(0, getpgrp());
245         set_term(0);
246
247         if (get_enter==TRUE) {
248             /*
249              * Save memory by not exec-ing anything large (like a shell)
250              * before the user wants it. This is critical if swap is not
251              * enabled and the system has low memory. Generally this will
252              * be run on the second virtual console, and the first will
253              * be allowed to start a shell or whatever an init script 
254              * specifies.
255              */
256             char c;
257             write(1, press_enter, sizeof(press_enter) - 1);
258             read(0, &c, 1);
259         }
260
261         /* Log the process name and args */
262         message(log, "Starting pid(%d): '", getpid());
263         while ( *cmd) message(log, "%s ", *cmd++);
264         message(log, "'\r\n");
265         
266         /* Now run it.  The new program will take over this PID, 
267          * so nothing further in init.c should be run. */
268         execvp(*command, (char**)command+1);
269
270         message(log, "Bummer, could not run '%s'\n", command);
271         exit(-1);
272     }
273     return pid;
274 }
275
276 /* Make sure there is enough memory to do something useful. *
277  * Calls swapon if needed so be sure /proc is mounted. */
278 static void check_memory()
279 {
280     struct stat statbuf;
281     const char* const swap_on_cmd[] = 
282             { "/bin/swapon", "swapon", "-a", 0};
283     const char *no_memory =
284             "Sorry, your computer does not have enough memory.\r\n";
285
286     if (mem_total() > 3500)
287         return;
288
289     if (stat("/etc/fstab", &statbuf) == 0) {
290         /* Try to turn on swap */
291         waitfor(run(swap_on_cmd, log, FALSE));
292         if (mem_total() < 3500)
293             goto goodnight;
294     } else
295         goto goodnight;
296     return;
297
298 goodnight:
299         message(console, "%s", no_memory);
300         while (1) sleep(1);
301 }
302
303 static void shutdown_system(void)
304 {
305     const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
306     const char* const umount_cmd[] = { "umount", "umount", "-a", "-n", 0};
307
308     message(console, "The system is going down NOW !!\r\n");
309     sync();
310 #ifndef DEBUG_INIT
311     /* Allow Ctrl-Alt-Del to reboot system. */
312     reboot(RB_ENABLE_CAD);
313 #endif
314     /* Send signals to every process _except_ pid 1 */
315     message(console, "Sending SIGHUP to all processes.\r\n");
316 #ifndef DEBUG_INIT
317     kill(-1, SIGHUP);
318 #endif
319     sleep(2);
320     sync();
321     message(console, "Sending SIGKILL to all processes.\r\n");
322 #ifndef DEBUG_INIT
323     kill(-1, SIGKILL);
324 #endif
325     sleep(1);
326     waitfor(run( swap_off_cmd, log, FALSE));
327     waitfor(run( umount_cmd, log, FALSE));
328     sync();
329     if (get_kernel_revision() <= 2 * 65536 + 2 * 256 + 11) {
330         /* Removed  bdflush call, kupdate in kernels >2.2.11 */
331         bdflush(1, 0);
332         sync();
333     }
334 }
335
336 static void halt_signal(int sig)
337 {
338     shutdown_system();
339     message(console,
340             "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
341 #ifndef DEBUG_INIT
342     reboot(RB_POWER_OFF);
343 #endif
344     exit(0);
345 }
346
347 static void reboot_signal(int sig)
348 {
349     shutdown_system();
350     message(console, "Please stand by while rebooting the system.\r\n");
351 #ifndef DEBUG_INIT
352     reboot(RB_AUTOBOOT);
353 #endif
354     exit(0);
355 }
356
357 extern int init_main(int argc, char **argv)
358 {
359     int run_rc = TRUE;
360     int wait_for_enter = TRUE;
361     pid_t pid1 = 0;
362     pid_t pid2 = 0;
363     struct stat statbuf;
364     const char* const init_commands[] = { INITSCRIPT, INITSCRIPT, 0};
365     const char* const shell_commands[] = { SHELL, "-" SHELL, 0};
366     const char* const* tty0_commands = shell_commands;
367     const char* const* tty1_commands = shell_commands;
368 #ifdef DEBUG_INIT
369     char *hello_msg_format =
370         "init(%d) started:  BusyBox v%s (%s) multi-call binary\r\n";
371 #else
372     char *hello_msg_format =
373         "init started:  BusyBox v%s (%s) multi-call binary\r\n";
374 #endif
375
376     
377     /* Check if we are supposed to be in single user mode */
378     if ( argc > 1 && (!strcmp(argv[1], "single") || 
379                 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
380         run_rc = FALSE;
381     }
382
383     
384     /* Set up sig handlers  -- be sure to
385      * clear all of these in run() */
386     signal(SIGUSR1, halt_signal);
387     signal(SIGUSR2, reboot_signal);
388     signal(SIGINT, reboot_signal);
389     signal(SIGTERM, reboot_signal);
390
391     /* Turn off rebooting via CTL-ALT-DEL -- we get a 
392      * SIGINT on CAD so we can shut things down gracefully... */
393 #ifndef DEBUG_INIT
394     reboot(RB_DISABLE_CAD);
395 #endif 
396
397     /* Figure out where the default console should be */
398     console_init();
399
400     /* Close whatever files are open, and reset the console. */
401     close(0);
402     close(1);
403     close(2);
404     set_term(0);
405     setsid();
406
407     /* Make sure PATH is set to something sane */
408     putenv(PATH_DEFAULT);
409
410    
411     /* Hello world */
412 #ifndef DEBUG_INIT
413     message(log, hello_msg_format, BB_VER, BB_BT);
414     message(console, hello_msg_format, BB_VER, BB_BT);
415 #else
416     message(log, hello_msg_format, getpid(), BB_VER, BB_BT);
417     message(console, hello_msg_format, getpid(), BB_VER, BB_BT);
418 #endif
419
420     
421     /* Mount /proc */
422     if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
423         message(log, "Mounting /proc: done.\n");
424         message(console, "Mounting /proc: done.\n");
425     } else {
426         message(log, "Mounting /proc: failed!\n");
427         message(console, "Mounting /proc: failed!\n");
428     }
429
430     /* Make sure there is enough memory to do something useful. */
431     check_memory();
432
433
434     /* Make sure an init script exists before trying to run it */
435     if (run_rc == TRUE && stat(INITSCRIPT, &statbuf)==0) {
436         wait_for_enter = FALSE;
437         tty0_commands = init_commands;
438     }
439
440
441     /* Ok, now launch the rc script and/or prepare to 
442      * start up some VTs if somebody hits enter... 
443      */
444     for (;;) {
445         pid_t wpid;
446         int status;
447
448         if (pid1 == 0 && tty0_commands) {
449             pid1 = run(tty0_commands, console, wait_for_enter);
450         }
451         if (pid2 == 0 && tty1_commands) {
452             pid2 = run(tty1_commands, second_console, TRUE);
453         }
454         wpid = wait(&status);
455         if (wpid > 0 ) {
456             message(log, "pid %d exited, status=%x.\n", wpid, status);
457         }
458         if (wpid == pid1) {
459             pid1 = 0;
460             if (run_rc == TRUE) {
461                 /* Don't respawn init script if it exits. */
462                 run_rc=FALSE;
463                 wait_for_enter=TRUE;
464                 tty0_commands=shell_commands;
465             }
466         }
467         if (wpid == pid2) {
468             pid2 = 0;
469         }
470         sleep(1);
471     }
472 }