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
|
#include <sys/socket.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <err.h>
#include "tunnel.h"
#include "macro.h"
static void sighandler(int signo __unused)
{
unlink(TUNNEL_SOCK_PATH);
exit(EXIT_FAILURE);
}
static void tunnel_daemon_loop(int sock)
{
for (;;) {
int fd = accept(sock, NULL, NULL);
if (fd < 0) {
warn("accept");
continue;
}
FILE *fp = fdopen(fd, "w");
if (fp) {
fprintf(fp, "hello from %d", getpid());
fclose(fp);
}
}
}
int tunnel_daemon(int sock)
{
switch (fork()) {
case -1:
warn("fork");
return -1;
case 0:
break;
default:
return 0;
}
if (setsid() < 0)
err(EXIT_FAILURE, "setsid");
chdir("/");
struct sigaction sa = {
.sa_handler = sighandler
};
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
#if 0
int fd = open("/dev/null", O_RDWR);
if (fd < 0)
err(EXIT_FAILURE, "open /dev/null");
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > 2)
close(fd);
#endif
tunnel_daemon_loop(sock);
return 0;
}
|