bind the console to /dev/null if the real console fails to come up
[project/procd.git] / early.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <sys/mount.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22
23 #include "procd.h"
24
25 static void early_mounts(void)
26 {
27         mount("proc", "/proc", "proc", MS_NOATIME, 0);
28         mount("sysfs", "/sys", "sysfs", MS_NOATIME, 0);
29
30         mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOATIME, NULL);
31         mkdir("/tmp/run", 0777);
32         mkdir("/tmp/lock", 0777);
33         mkdir("/tmp/state", 0777);
34         symlink("/tmp", "/var");
35
36         mount("tmpfs", "/dev", "tmpfs", MS_NOATIME, "mode=0755,size=512K");
37         mkdir("/dev/shm", 0755);
38         mkdir("/dev/pts", 0755);
39         mount("devpts", "/dev/pts", "devpts", MS_NOATIME, "mode=600");
40 }
41
42 static void early_dev(void)
43 {
44         mkdev("*", 0600);
45         mknod("/dev/null", 0666, makedev(1, 3));
46 }
47
48 static void early_console(const char *dev)
49 {
50         struct stat s;
51         int dd;
52
53         if (stat(dev, &s)) {
54                 ERROR("Failed to stat %s\n", dev);
55                 return;
56         }
57
58         dd = open(dev, O_RDWR);
59         if (dd < 0)
60                 dd = open("/dev/null", O_RDWR);
61
62         dup2(dd, STDIN_FILENO);
63         dup2(dd, STDOUT_FILENO);
64         dup2(dd, STDERR_FILENO);
65
66         if (dd != STDIN_FILENO &&
67             dd != STDOUT_FILENO &&
68             dd != STDERR_FILENO)
69                 close(dd);
70 }
71
72 static void early_env(void)
73 {
74         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin", 1);
75 }
76
77 void procd_early(void)
78 {
79         if (getpid() != 1)
80                 return;
81
82         early_mounts();
83         early_dev();
84         early_env();
85         early_console("/dev/console");
86
87         LOG("Console is alive\n");
88 }