-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.c
130 lines (106 loc) · 2.56 KB
/
init.c
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
static const char *MV_ENV_VARS[] = {"MV_INIT", "MV_HOSTNAME", "MV_DEBUG",
"MV_TTY", NULL};
static const char *BIN_SH = "/bin/sh";
static void pr_debug(const char *fmt, ...) {
if (strcmp(getenv("MV_DEBUG"), "1") != 0) {
return;
}
printf("init: ");
va_list arg;
va_start(arg, fmt);
vprintf(fmt, arg);
va_end(arg);
printf("\n");
}
static void cleanup_env() {
const char **env_var = MV_ENV_VARS;
while (*env_var != NULL) {
unsetenv(*env_var);
env_var++;
}
}
int main(int argc, char *argv[]) {
if (mkdir("/proc", 0555) != 0 && errno != EEXIST) {
perror("mkdir: /proc");
return 1;
}
if (mount("proc", "/proc", "proc", 0, NULL) != 0) {
perror("mount: /proc");
return 1;
}
if (mkdir("/dev", 0755) != 0 && errno != EEXIST) {
perror("mkdir: /dev/pts");
return 1;
}
if (mkdir("/dev/pts", 0620) != 0 && errno != EEXIST) {
perror("mkdir: /dev/pts");
return 1;
}
if (mount("devpts", "/dev/pts", "devpts", MS_NOSUID | MS_NOEXEC, NULL) != 0) {
perror("mount: /dev/pts");
return 1;
}
if (mkdir("/dev/shm", 0777) != 0 && errno != EEXIST) {
perror("mkdir: /dev/shm");
return 1;
}
if (mount("shm", "/dev/shm", "tmpfs", MS_NOSUID | MS_NOEXEC | MS_NODEV,
NULL) != 0) {
perror("mount: /dev/shm");
return 1;
}
char *hostname = getenv("MV_HOSTNAME");
if (hostname) {
pr_debug("sethostname: %s", hostname);
sethostname(hostname, strlen(hostname));
}
char *init = getenv("MV_INIT");
if (!init) {
init = (char *)BIN_SH;
}
argv[0] = init;
pr_debug("execvp: argc=%d argv0=%s", argc, argv[0]);
if (strcmp(getenv("MV_TTY"), "1") == 0) {
setsid();
int fd = open("/dev/hvc0", O_RDWR);
if (fd < 0) {
perror("open: /dev/hvc0");
return 1;
}
if (!isatty(fd)) {
perror("isatty: /dev/hvc0");
return 1;
}
dup2(fd, 0);
dup2(fd, 1);
dup2(fd, 2);
while (fd > 2) {
close(fd--);
}
// This should fix the following error:
//
// /bin/sh: can't access tty; job control turned off
//
ioctl(0, TIOCSCTTY, 1);
} else {
// Disable ECHO
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ECHO;
tcsetattr(0, 0, &term);
printf("init: ready\n");
}
cleanup_env();
return execvp(argv[0], argv);
}