a9f6afbe04289a2e5473db7ef7e25db01b8f83ce
[project/procd.git] / initd / 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 #include <stdlib.h>
23
24 #include "../log.h"
25 #include "init.h"
26
27 static void
28 early_mounts(void)
29 {
30         mount("proc", "/proc", "proc", MS_NOATIME, 0);
31         mount("sysfs", "/sys", "sysfs", MS_NOATIME, 0);
32
33         mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV | MS_NOATIME, NULL);
34         mkdir("/tmp/run", 0777);
35         mkdir("/tmp/lock", 0777);
36         mkdir("/tmp/state", 0777);
37         symlink("/tmp", "/var");
38
39         mount("tmpfs", "/dev", "tmpfs", MS_NOATIME, "mode=0755,size=512K");
40         mkdir("/dev/shm", 0755);
41         mkdir("/dev/pts", 0755);
42         mount("devpts", "/dev/pts", "devpts", MS_NOATIME, "mode=600");
43 }
44
45 static void
46 early_dev(void)
47 {
48         mkdev("*", 0600);
49         mknod("/dev/null", 0666, makedev(1, 3));
50 }
51
52 static void
53 early_console(const char *dev)
54 {
55         struct stat s;
56         int dd;
57
58         if (stat(dev, &s)) {
59                 ERROR("Failed to stat %s\n", dev);
60                 return;
61         }
62
63         dd = open(dev, O_RDWR);
64         if (dd < 0)
65                 dd = open("/dev/null", O_RDWR);
66
67         dup2(dd, STDIN_FILENO);
68         dup2(dd, STDOUT_FILENO);
69         dup2(dd, STDERR_FILENO);
70
71         if (dd != STDIN_FILENO &&
72             dd != STDOUT_FILENO &&
73             dd != STDERR_FILENO)
74                 close(dd);
75
76         fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
77 }
78
79 static void
80 early_env(void)
81 {
82         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin", 1);
83 }
84
85 void
86 early(void)
87 {
88         if (getpid() != 1)
89                 return;
90
91         early_mounts();
92         early_dev();
93         early_env();
94         early_console("/dev/console");
95
96         LOG("Console is alive\n");
97 }