55c5c7318effa9821d11aedd76636cfa126fbb75
[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 VT_CONSOLE      "/dev/console"  /* Logical system console */
45 #define VT_PRIMARY      "/dev/tty1"     /* Primary virtual console */
46 #define VT_SECONDARY    "/dev/tty2"     /* Virtual console */
47 #define VT_LOG          "/dev/tty3"     /* Virtual console */
48 #define SERIAL_CON0     "/dev/ttyS0"    /* Primary serial console */
49 #define SERIAL_CON1     "/dev/ttyS1"    /* Serial console */
50 #define SHELL           "/bin/sh"       /* Default shell */
51 #define INITSCRIPT      "/etc/init.d/rcS"       /* Initscript. */
52 #define PATH_DEFAULT    "PATH=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin"
53
54 #define LOG             0x1
55 #define CONSOLE         0x2
56 static char *console = VT_CONSOLE;
57 static char *second_console = VT_SECONDARY;
58 static char *log = VT_LOG;
59
60
61
62 /* try to open up the specified device */
63 int device_open(char *device, int mode)
64 {
65     int m, f, fd = -1;
66
67     m = mode | O_NONBLOCK;
68
69     /* Retry up to 5 times */
70     for (f = 0; f < 5; f++)
71         if ((fd = open(device, m)) >= 0)
72             break;
73     if (fd < 0)
74         return fd;
75     /* Reset original flags. */
76     if (m != mode)
77         fcntl(fd, F_SETFL, mode);
78     return fd;
79 }
80
81 /* print a message to the specified device:
82  * device may be bitwise-or'd from LOG | CONSOLE */
83 void message(int device, char *fmt, ...)
84 {
85     int fd;
86     static int log_fd=-1;
87     va_list arguments;
88
89     /* Take full control of the log tty, and never close it.
90      * It's mine, all mine!  Muhahahaha! */
91     if (log_fd==-1) {
92         if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
93             log_fd=-1;
94             fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
95             fflush(stderr);
96             return;
97         }
98     }
99
100     if ( (device & LOG) && (log_fd != -1) ) {
101         va_start(arguments, fmt);
102         vdprintf(log_fd, fmt, arguments);
103         va_end(arguments);
104     }
105     if (device & CONSOLE) {
106         if ((fd = device_open(console, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
107             va_start(arguments, fmt);
108             vdprintf(fd, fmt, arguments);
109             va_end(arguments);
110             close(fd);
111         } else {
112             fprintf(stderr, "Bummer, can't print: ");
113             va_start(arguments, fmt);
114             vfprintf(stderr, fmt, arguments);
115             fflush(stderr);
116             va_end(arguments);
117         }
118     }
119 }
120
121
122 /* Set terminal settings to reasonable defaults */
123 void set_term( int fd)
124 {
125     struct termios tty;
126 #if 0
127     static const char control_characters[] = {
128         '\003', '\034', '\177', '\025', '\004', '\0',
129         '\1', '\0', '\021', '\023', '\032', '\0', '\022',
130         '\017', '\027', '\026', '\0'
131         };
132 #endif
133     static const char control_characters[] = {
134         '\003', '\034', '\177', '\030', '\004', '\0',
135         '\1', '\0', '\021', '\023', '\032', '\0', '\022',
136         '\017', '\027', '\026', '\0'
137         };
138
139     tcgetattr(fd, &tty);
140
141     /* Make it be sane */
142     tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
143     tty.c_cflag |= HUPCL|CLOCAL;
144
145     /* input modes */
146     tty.c_iflag = IGNPAR|ICRNL|IXON|IXOFF|IXANY;
147
148     /* use line dicipline 0 */
149     tty.c_line = 0;
150
151     /* output modes */
152     tty.c_oflag = OPOST|ONLCR;
153
154     /* local modes */
155     tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOPRT|ECHOKE|IEXTEN;
156
157     /* control chars */
158     memcpy(tty.c_cc, control_characters, sizeof(control_characters));
159
160     tcsetattr(fd, TCSANOW, &tty);
161 }
162
163 /* Set terminal settings to reasonable defaults */
164 void set_term_old( int fd)
165 {
166     struct termios tty;
167
168     ioctl(fd, TCGETA, &tty);
169
170     tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
171     tty.c_cflag |= HUPCL|CLOCAL;
172
173     tty.c_cc[VINTR]    = 3;
174     tty.c_cc[VQUIT]    = 28;
175     tty.c_cc[VERASE]   = 127;
176     //tty.c_cc[VKILL]    = 21;
177     tty.c_cc[VKILL]    = 24;
178     tty.c_cc[VEOF]     = 4;
179     tty.c_cc[VTIME]    = 0;
180     tty.c_cc[VMIN]     = 1;
181     tty.c_cc[VSWTC]    = 0;
182     tty.c_cc[VSTART]   = 17;
183     tty.c_cc[VSTOP]    = 19;
184     tty.c_cc[VSUSP]    = 26;
185     tty.c_cc[VEOL]     = 0;
186     tty.c_cc[VREPRINT] = 18;
187     tty.c_cc[VDISCARD] = 15;
188     tty.c_cc[VWERASE]  = 23;
189     tty.c_cc[VLNEXT]   = 22;
190     tty.c_cc[VEOL2]    = 0;
191     
192
193     tty.c_line  = 0;
194     tty.c_iflag = IGNPAR|ICRNL|IXON|IXOFF|IXANY;
195     tty.c_oflag = OPOST|ONLCR;
196     tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOPRT|ECHOKE|IEXTEN;
197
198     ioctl(fd, TCSETA, &tty);
199 }
200
201 /* How much memory does this machine have? */
202 static int mem_total()
203 {
204     char s[80];
205     char *p = "/proc/meminfo";
206     FILE *f;
207     const char pattern[] = "MemTotal:";
208
209     if ((f = fopen(p, "r")) < 0) {
210         message(LOG, "Error opening %s: %s\n", p, strerror( errno));
211         return -1;
212     }
213     while (NULL != fgets(s, 79, f)) {
214         p = strstr(s, pattern);
215         if (NULL != p) {
216             fclose(f);
217             return (atoi(p + strlen(pattern)));
218         }
219     }
220     return -1;
221 }
222
223 static void console_init()
224 {
225     int fd;
226     int tried_devcons = 0;
227     int tried_vtprimary = 0;
228     char *s;
229
230     if ((s = getenv("CONSOLE")) != NULL) {
231         console = s;
232 /* Apparently the sparc does wierd things... */
233 #if defined (__sparc__)
234         if (strncmp( s, "/dev/tty", 8 )==0) {
235             switch( s[8]) {
236                 case 'a':
237                     s=SERIAL_CON0;
238                     break;
239                 case 'b':
240                     s=SERIAL_CON1;
241             }
242         }
243 #endif
244     } else {
245         console = VT_CONSOLE;
246         tried_devcons++;
247     }
248
249     while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
250         /* Can't open selected console -- try /dev/console */
251         if (!tried_devcons) {
252             tried_devcons++;
253             console = VT_CONSOLE;
254             continue;
255         }
256         /* Can't open selected console -- try vt1 */
257         if (!tried_vtprimary) {
258             tried_vtprimary++;
259             console = VT_PRIMARY;
260             continue;
261         }
262         break;
263     }
264     if (fd < 0)
265         /* Perhaps we should panic here? */
266         console = "/dev/null";
267     else
268         close(fd);
269     message(LOG, "console=%s\n", console );
270 }
271
272 static int waitfor(int pid)
273 {
274     int status, wpid;
275
276     message(LOG, "Waiting for process %d.\n", pid);
277     while ((wpid = wait(&status)) != pid) {
278         if (wpid > 0)
279             message(LOG, "pid %d exited, status=0x%x.\n", wpid, status);
280     }
281     return wpid;
282 }
283
284
285 static pid_t run(const char * const* command, 
286         char *terminal, int get_enter)
287 {
288     int fd;
289     pid_t pid;
290     const char * const* cmd = command+1;
291     static const char press_enter[] =
292         "\nPlease press Enter to activate this console. ";
293
294     if ((pid = fork()) == 0) {
295         /* Clean up */
296         close(0);
297         close(1);
298         close(2);
299         setsid();
300
301         /* Reset signal handlers set for parent process */
302         signal(SIGUSR1, SIG_DFL);
303         signal(SIGUSR2, SIG_DFL);
304         signal(SIGINT, SIG_DFL);
305         signal(SIGTERM, SIG_DFL);
306
307         if ((fd = device_open(terminal, O_RDWR)) < 0) {
308             message(LOG, "Bummer, can't open %s\r\n", terminal);
309             exit(-1);
310         }
311         dup(fd);
312         dup(fd);
313         tcsetpgrp(0, getpgrp());
314         set_term(0);
315
316         if (get_enter==TRUE) {
317             /*
318              * Save memory by not exec-ing anything large (like a shell)
319              * before the user wants it. This is critical if swap is not
320              * enabled and the system has low memory. Generally this will
321              * be run on the second virtual console, and the first will
322              * be allowed to start a shell or whatever an init script 
323              * specifies.
324              */
325             char c;
326             message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n", 
327                     *cmd, getpid(), terminal );
328             write(1, press_enter, sizeof(press_enter) - 1);
329             read(0, &c, 1);
330         }
331
332         /* Log the process name and args */
333         message(LOG, "Starting pid %d, console %s: '", getpid(), terminal);
334         while ( *cmd) message(LOG, "%s ", *cmd++);
335         message(LOG, "'\r\n");
336         
337         /* Now run it.  The new program will take over this PID, 
338          * so nothing further in init.c should be run. */
339         execvp(*command, (char**)command+1);
340
341         message(LOG, "Bummer, could not run '%s'\n", command);
342         exit(-1);
343     }
344     return pid;
345 }
346
347 /* Make sure there is enough memory to do something useful. *
348  * Calls swapon if needed so be sure /proc is mounted. */
349 static void check_memory()
350 {
351     struct stat statbuf;
352     const char* const swap_on_cmd[] = 
353             { "/bin/swapon", "swapon", "-a", 0};
354
355     if (mem_total() > 3500)
356         return;
357
358     if (stat("/etc/fstab", &statbuf) == 0) {
359         /* Try to turn on swap */
360         waitfor(run(swap_on_cmd, log, FALSE));
361         if (mem_total() < 3500)
362             goto goodnight;
363     } else
364         goto goodnight;
365     return;
366
367 goodnight:
368         message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
369         while (1) sleep(1);
370 }
371
372 static void shutdown_system(void)
373 {
374     const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
375     const char* const umount_cmd[] = { "umount", "umount", "-a", "-n", 0};
376
377 #ifndef DEBUG_INIT
378     /* Allow Ctrl-Alt-Del to reboot system. */
379     reboot(RB_ENABLE_CAD);
380 #endif
381     message(CONSOLE, "The system is going down NOW !!\r\n");
382     sync();
383     /* Send signals to every process _except_ pid 1 */
384     message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
385 #ifndef DEBUG_INIT
386     kill(-1, SIGHUP);
387 #endif
388     sleep(2);
389     sync();
390     message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
391 #ifndef DEBUG_INIT
392     kill(-1, SIGKILL);
393 #endif
394     sleep(1);
395     waitfor(run( swap_off_cmd, console, FALSE));
396     waitfor(run( umount_cmd, console, FALSE));
397     sync();
398     bdflush(1, 0);
399 }
400
401 static void halt_signal(int sig)
402 {
403     shutdown_system();
404     message(CONSOLE,
405             "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
406     sync();
407 #ifndef DEBUG_INIT
408     reboot(RB_HALT_SYSTEM);
409     //reboot(RB_POWER_OFF);
410 #endif
411     exit(0);
412 }
413
414 static void reboot_signal(int sig)
415 {
416     shutdown_system();
417     message(CONSOLE, "Please stand by while rebooting the system.\r\n");
418     sync();
419 #ifndef DEBUG_INIT
420     reboot(RB_AUTOBOOT);
421 #endif
422     exit(0);
423 }
424
425 extern int init_main(int argc, char **argv)
426 {
427     int run_rc = TRUE;
428     int wait_for_enter = TRUE;
429     pid_t pid1 = 0;
430     pid_t pid2 = 0;
431     struct stat statbuf;
432     const char* const init_commands[] = { INITSCRIPT, INITSCRIPT, 0};
433     const char* const shell_commands[] = { SHELL, "-" SHELL, 0};
434     const char* const* tty0_commands = shell_commands;
435     const char* const* tty1_commands = shell_commands;
436 #ifdef DEBUG_INIT
437     char *hello_msg_format =
438         "init(%d) started:  BusyBox v%s (%s) multi-call binary\r\n";
439 #else
440     char *hello_msg_format =
441         "init started:  BusyBox v%s (%s) multi-call binary\r\n";
442 #endif
443
444     
445     /* Check if we are supposed to be in single user mode */
446     if ( argc > 1 && (!strcmp(argv[1], "single") || 
447                 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
448         run_rc = FALSE;
449     }
450
451     
452     /* Set up sig handlers  -- be sure to
453      * clear all of these in run() */
454     signal(SIGUSR1, halt_signal);
455     signal(SIGUSR2, reboot_signal);
456     signal(SIGINT, reboot_signal);
457     signal(SIGTERM, reboot_signal);
458
459     /* Turn off rebooting via CTL-ALT-DEL -- we get a 
460      * SIGINT on CAD so we can shut things down gracefully... */
461 #ifndef DEBUG_INIT
462     reboot(RB_DISABLE_CAD);
463 #endif 
464
465     /* Figure out where the default console should be */
466     console_init();
467
468     /* Close whatever files are open, and reset the console. */
469     close(0);
470     close(1);
471     close(2);
472     set_term(0);
473     setsid();
474
475     /* Make sure PATH is set to something sane */
476     putenv(PATH_DEFAULT);
477
478    
479     /* Hello world */
480 #ifndef DEBUG_INIT
481     message(CONSOLE|LOG, hello_msg_format, BB_VER, BB_BT);
482 #else
483     message(CONSOLE|LOG, hello_msg_format, getpid(), BB_VER, BB_BT);
484 #endif
485
486     
487     /* Mount /proc */
488     if (mount ("proc", "/proc", "proc", 0, 0) == 0)
489         message(CONSOLE|LOG, "Mounting /proc: done.\n");
490     else
491         message(CONSOLE|LOG, "Mounting /proc: failed!\n");
492
493     /* Make sure there is enough memory to do something useful. */
494     check_memory();
495
496
497     /* Make sure an init script exists before trying to run it */
498     if (run_rc == TRUE && stat(INITSCRIPT, &statbuf)==0) {
499         wait_for_enter = FALSE;
500         tty0_commands = init_commands;
501     }
502
503
504     /* Ok, now launch the rc script and/or prepare to 
505      * start up some VTs if somebody hits enter... 
506      */
507     for (;;) {
508         pid_t wpid;
509         int status;
510
511         if (pid1 == 0 && tty0_commands) {
512             pid1 = run(tty0_commands, console, wait_for_enter);
513         }
514         if (pid2 == 0 && tty1_commands) {
515             pid2 = run(tty1_commands, second_console, TRUE);
516         }
517         wpid = wait(&status);
518         if (wpid > 0 ) {
519             message(LOG, "pid %d exited, status=%x.\n", wpid, status);
520         }
521         if (wpid == pid1) {
522             pid1 = 0;
523             if (run_rc == TRUE) {
524                 /* Don't respawn init script if it exits,
525                  * Start a shell instead. */
526                 run_rc=FALSE;
527                 wait_for_enter=TRUE;
528                 tty0_commands=shell_commands;
529             }
530         }
531         if (wpid == pid2) {
532             pid2 = 0;
533         }
534         sleep(1);
535     }
536 }