1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
#define _DEFAULT_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void create_vfs(void) {
if (mkdir("/proc", 0755) != 0 && errno != EEXIST) {
perror("proc");
}
if (mkdir("/sys", 0755) != 0 && errno != EEXIST) {
perror("sys");
}
if (mkdir("/dev", 0755) != 0 && errno != EEXIST) {
perror("dev");
}
if (mkdir("/run", 0755) != 0 && errno != EEXIST) {
perror("run");
}
}
void mount_vfs(void) {
if (mount("proc", "/proc", "proc",
MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME, NULL) != 0 &&
errno != EBUSY) {
perror("mount /proc");
}
if (mount("sys", "/sys", "sysfs",
MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME, NULL) != 0 &&
errno != EBUSY) {
perror("mount /sys");
}
if (mount("dev", "/dev", "devtmpfs", MS_NOSUID | MS_RELATIME, "mode=755") !=
0 &&
errno != EBUSY) {
perror("mount /dev");
}
if (mount("run", "/run", "tmpfs", MS_NOSUID | MS_NODEV | MS_RELATIME,
"mode=755") != 0 &&
errno != EBUSY) {
perror("mount /run");
}
mkdir("/dev/pts", 0755);
mkdir("/dev/shm", 1777);
if (mount("devpts", "/dev/pts", "devpts",
MS_NOSUID | MS_NOEXEC | MS_RELATIME, "gid=5,mode=620") != 0 &&
errno != EBUSY) {
perror("mount /dev/pts");
}
if (mount("shm", "/dev/shm", "tmpfs", MS_NOSUID | MS_NODEV | MS_RELATIME,
"mode=1777") != 0 &&
errno != EBUSY) {
perror("mount /dev/shm");
}
}
void set_hostname(void) {
char buf[256];
int fd = open("/etc/hostname", O_RDONLY);
if (fd < 0) {
perror("open /etc/hostname");
return;
}
ssize_t bytes_read = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (bytes_read > 0) {
buf[bytes_read] = '\0';
size_t len = strcspn(buf, "\r\n ");
buf[len] = '\0';
if (sethostname(buf, len) != 0) {
perror("sethostname");
}
}
}
int main(void) {
create_vfs();
mount_vfs();
int fd = open("/dev/console", O_RDWR);
if (fd >= 0) {
dup2(fd, 0);
dup2(fd, 1);
dup2(fd, 2);
if (fd > 2) {
close(fd);
}
} else {
perror("console");
}
set_hostname();
return 0;
}
|