Stuff
[oweals/busybox.git] / 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 #define CONSOLE         "/dev/console"  /* Logical system console */
45 #define VT_PRIMARY      "/dev/tty0"     /* Virtual console master */
46 #define VT_SECONDARY    "/dev/tty1"     /* Virtual console master */
47 #define VT_LOG          "/dev/tty2"     /* Virtual console master */
48 #define SHELL           "/bin/sh"       /* Default shell */
49 #define INITSCRIPT      "/etc/init.d/rcS"       /* Initscript. */
50 #define PATH_DEFAULT    "PATH=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin"
51
52 static char *console = CONSOLE;
53 //static char *first_terminal = "/dev/tty1";
54 static char *second_terminal = "/dev/tty2";
55 static char *log = "/dev/tty3";
56
57
58
59 /* try to open up the specified device */
60 int device_open(char *device, int mode)
61 {
62     int m, f, fd = -1;
63
64     mode = m | O_NONBLOCK;
65
66     /* Retry up to 5 times */
67     for (f = 0; f < 5; f++)
68         if ((fd = open(device, m)) >= 0)
69             break;
70     if (fd < 0)
71         return fd;
72     /* Set original flags. */
73     if (m != mode)
74         fcntl(fd, F_SETFL, mode);
75     return fd;
76 }
77
78 /* print a message to the specified device */
79 void message(char *device, char *fmt, ...)
80 {
81     int fd;
82     va_list arguments;
83
84     if ((fd = device_open(device, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
85         va_start(arguments, fmt);
86         vdprintf(fd, fmt, arguments);
87         va_end(arguments);
88         close(fd);
89     } else {
90         fprintf(stderr, "Bummer, can't print: ");
91         va_start(arguments, fmt);
92         vfprintf(stderr, fmt, arguments);
93         fflush(stderr);
94         va_end(arguments);
95     }
96 }
97
98 /* Set terminal settings to reasonable defaults */
99 void set_term( int fd)
100 {
101     struct termios tty;
102
103     tcgetattr(fd, &tty);
104     tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
105     tty.c_cflag |= HUPCL|CLOCAL;
106
107     tty.c_cc[VINTR] = 3;
108     tty.c_cc[VQUIT] = 28;
109     tty.c_cc[VERASE] = 127;
110     tty.c_cc[VKILL] = 24;
111     tty.c_cc[VEOF] = 4;
112     tty.c_cc[VTIME] = 0;
113     tty.c_cc[VMIN] = 1;
114     tty.c_cc[VSTART] = 17;
115     tty.c_cc[VSTOP] = 19;
116     tty.c_cc[VSUSP] = 26;
117
118     tty.c_iflag = IGNPAR|ICRNL|IXON|IXANY;
119     tty.c_oflag = OPOST|ONLCR;
120     tty.c_lflag = ISIG|ICANON|ECHO|ECHOCTL|ECHOPRT|ECHOKE;
121
122     tcsetattr(fd, TCSANOW, &tty);
123 }
124
125 static int mem_total()
126 {
127     char s[80];
128     char *p;
129     FILE *f;
130     const char pattern[] = "MemTotal:";
131
132     f = fopen("/proc/meminfo", "r");
133     while (NULL != fgets(s, 79, f)) {
134         p = strstr(s, pattern);
135         if (NULL != p) {
136             fclose(f);
137             return (atoi(p + strlen(pattern)));
138         }
139     }
140     return -1;
141 }
142
143 static void set_free_pages()
144 {
145     char s[80];
146     FILE *f;
147
148     f = fopen("/proc/sys/vm/freepages", "r");
149     fgets(s, 79, f);
150     if (atoi(s) < 32) {
151         fclose(f);
152         f = fopen("/proc/sys/vm/freepages", "w");
153         fprintf(f, "30\t40\t50\n");
154         printf("\nIncreased /proc/sys/vm/freepages values to 30/40/50\n");
155     }
156     fclose(f);
157 }
158
159
160 static void console_init()
161 {
162     int fd;
163     struct stat statbuf;
164     int tried_devcons = 0;
165     int tried_vtmaster = 0;
166     char *s;
167
168     fprintf(stderr, "entering console_init()\n");
169     if ((s = getenv("CONSOLE")) != NULL)
170         console = s;
171     else {
172         console = CONSOLE;
173         tried_devcons++;
174     }
175
176     if ( stat(CONSOLE, &statbuf) && S_ISLNK(statbuf.st_mode)) {
177         fprintf(stderr, "Yikes! /dev/console does not exist or is a symlink.\n");
178     }
179     while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
180         if (!tried_devcons) {
181             tried_devcons++;
182             console = CONSOLE;
183             continue;
184         }
185         if (!tried_vtmaster) {
186             tried_vtmaster++;
187             console = VT_PRIMARY;
188             continue;
189         }
190         break;
191     }
192     if (fd < 0)
193         console = "/dev/null";
194     else
195         close(fd);
196     fprintf(stderr, "console=%s\n", console);
197 }
198
199 static int waitfor(int pid)
200 {
201     int status, wpid;
202
203     message(log, "Waiting for process %d.\n", pid);
204     while ((wpid = wait(&status)) != pid) {
205         if (wpid > 0)
206             message(log, "pid %d exited, status=%x.\n", wpid, status);
207     }
208     return wpid;
209 }
210
211
212 static pid_t run(const char * const* command, 
213         char *terminal, int get_enter)
214 {
215     int i;
216     pid_t pid;
217     static const char press_enter[] =
218         "\nPlease press Enter to activate this console. ";
219
220     if ((pid = fork()) == 0) {
221         /* Clean up */
222         close(0);
223         close(1);
224         close(2);
225         setsid();
226
227         open(terminal, O_RDWR);
228         dup(0);
229         dup(0);
230         tcsetpgrp(0, getpgrp());
231         set_term(0);
232
233         if (get_enter) {
234             /*
235              * Save memory by not exec-ing anything large (like a shell)
236              * before the user wants it. This is critical if swap is not
237              * enabled and the system has low memory. Generally this will
238              * be run on the second virtual console, and the first will
239              * be allowed to start a shell or whatever an init script 
240              * specifies.
241              */
242             char c;
243             write(0, press_enter, sizeof(press_enter) - 1);
244             read(0, &c, 1);
245         }
246
247         /* Log the process name and args */
248
249         /* Now run it.  The new program will take over this PID, 
250          * so nothing further in init.c should be run. */
251         message(log, "Executing '%s', pid(%d)\r\n", *command, getpid());
252         execvp(*command, (char**)command+1);
253
254         message(log, "Hmm.  Trying as a script.\r\n");
255         /* If shell scripts are not executed, force the issue */
256         if (errno == ENOEXEC) {
257             char * args[16];
258             args[0] = SHELL;
259             args[1] = "-c";
260             args[2] = "exec";
261             for( i=0 ; i<16 && command[i]; i++)
262                 args[3+i] = (char*)command[i];
263             args[i] = NULL;
264             execvp(*args, (char**)args+1);
265         }
266         message(log, "Could not execute '%s'\n", command);
267         exit(-1);
268     }
269     return pid;
270 }
271
272
273 static void shutdown_system(void)
274 {
275     const char* const swap_off_cmd[] = { "/bin/swapoff", "-a", 0};
276     const char* const umount_cmd[] = { "/bin/umount", "-a", "-n", 0};
277
278     message(console, "The system is going down NOW !!\r\n");
279     sync();
280     /* Allow Ctrl-Alt-Del to reboot system. */
281     reboot(RB_ENABLE_CAD);
282
283     /* Send signals to every process _except_ pid 1 */
284     message(console, "Sending SIGHUP to all processes.\r\n");
285     kill(-1, SIGHUP);
286     sleep(2);
287     sync();
288     message(console, "Sending SIGKILL to all processes.\r\n");
289     kill(-1, SIGKILL);
290     sleep(1);
291     waitfor(run( swap_off_cmd, console, 0));
292     waitfor(run( umount_cmd, console, 0));
293     sync();
294     if (get_kernel_revision() <= 2 * 65536 + 2 * 256 + 11) {
295         /* Removed  bdflush call, kupdate in kernels >2.2.11 */
296         bdflush(1, 0);
297         sync();
298     }
299 }
300
301 static void halt_signal(int sig)
302 {
303     shutdown_system();
304     message(console,
305             "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
306     reboot(RB_POWER_OFF);
307     exit(0);
308 }
309
310 static void reboot_signal(int sig)
311 {
312     shutdown_system();
313     message(console, "Please stand by while rebooting the system.\r\n");
314     reboot(RB_AUTOBOOT);
315     exit(0);
316 }
317
318 extern int init_main(int argc, char **argv)
319 {
320     int run_rc = TRUE;
321     pid_t pid1 = 0;
322     pid_t pid2 = 0;
323     struct stat statbuf;
324     const char* const swap_on_cmd[] = { "/bin/swapon", " -a ", 0};
325     const char* const init_commands[] = { SHELL, " -c", " exec ", INITSCRIPT, 0};
326     const char* const shell_commands[] = { SHELL, " -", 0};
327     const char* const* tty0_commands = init_commands;
328     const char* const* tty1_commands = shell_commands;
329     char *hello_msg_format =
330         "init started:  BusyBox v%s (%s) multi-call binary\r\n";
331     const char *no_memory =
332         "Sorry, your computer does not have enough memory.\r\n";
333
334     /* Set up sig handlers */
335     signal(SIGUSR1, halt_signal);
336     signal(SIGSEGV, halt_signal);
337     signal(SIGPWR, halt_signal);
338     signal(SIGALRM, halt_signal);
339     signal(SIGHUP, halt_signal);
340     signal(SIGUSR2, reboot_signal);
341     signal(SIGINT, reboot_signal);
342     signal(SIGTERM, reboot_signal);
343
344     /* Turn off rebooting via CTL-ALT-DEL -- we get a 
345      * SIGINT on CAD so we can shut things down gracefully... */
346     reboot(RB_DISABLE_CAD);
347     
348     /* Figure out where the default console should be */
349     console_init();
350
351     /* Close whatever files are open, and reset the console. */
352     close(0);
353     close(1);
354     close(2);
355     //set_term(0);
356     setsid();
357
358     /* Make sure PATH is set to something sane */
359     if (getenv("PATH") == NULL)
360         putenv(PATH_DEFAULT);
361
362     /* Hello world */
363     message(log, hello_msg_format, BB_VER, BB_BT);
364     fprintf(stderr, hello_msg_format, BB_VER, BB_BT);
365
366     
367     /* Mount /proc */
368     if (mount("/proc", "/proc", "proc", 0, 0) == 0) {
369         fprintf(stderr, "Mounting /proc: done.\n");
370         message(log, "Mounting /proc: done.\n");
371     } else {
372         fprintf(stderr, "Mounting /proc: failed!\n");
373         message(log, "Mounting /proc: failed!\n");
374     }
375
376     /* Make sure there is enough memory to do something useful */
377     set_free_pages();
378     if (mem_total() < 3500) {
379         int retval;
380         retval = stat("/etc/fstab", &statbuf);
381         if (retval) {
382             fprintf(stderr, "%s", no_memory);
383             while (1) {
384                 sleep(1);
385             }
386         } else {
387             /* Try to turn on swap */
388             waitfor(run(swap_on_cmd, console, 0));
389             if (mem_total() < 2000) {
390                 fprintf(stderr, "%s", no_memory);
391                 while (1) {
392                     sleep(1);
393                 }
394             }
395         }
396     }
397
398     /* Check if we are supposed to be in single user mode */
399     if ( argc > 1 && (!strcmp(argv[1], "single") || 
400                 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
401         run_rc = FALSE;
402         tty0_commands = shell_commands;
403         tty1_commands = shell_commands;
404     }
405
406     /* Make sure an init script exists before trying to run it */
407     if (run_rc == TRUE && stat(INITSCRIPT, &statbuf)) {
408         tty0_commands = shell_commands;
409         tty1_commands = shell_commands;
410     }
411
412     /* Ok, now launch the rc script and/or prepare to 
413      * start up some VTs if somebody hits enter... 
414      */
415     for (;;) {
416         pid_t wpid;
417         int status;
418
419         if (pid1 == 0 && tty0_commands) {
420             pid1 = run(tty0_commands, console, 1);
421         }
422         if (pid2 == 0 && tty1_commands) {
423             pid2 = run(tty1_commands, second_terminal, 1);
424         }
425         wpid = wait(&status);
426         if (wpid > 0 ) {
427             message(log, "pid %d exited, status=%x.\n", wpid, status);
428         }
429         /* Don't respawn an init script if it exits */
430         if (run_rc == FALSE && wpid == pid1) {
431             pid1 = 0;
432         }
433         if (wpid == pid2) {
434             pid2 = 0;
435         }
436         sleep(1);
437     }
438 }