-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.c
128 lines (106 loc) · 2.43 KB
/
tunnel.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <poll.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <linux/if_packet.h>
#include "tunnel.h"
struct tunnel *
tcp_tunnel_accept(int listen_fd) {
struct tunnel *t;
int client_fd;
struct sockaddr_in client_sin;
socklen_t sin_len = sizeof(client_sin);
if((client_fd = accept(listen_fd, (struct sockaddr *)&client_sin, &sin_len)) < 0) {
perror("accept");
return NULL;
}
if(sin_len <= 0) {
perror("wtf");
return NULL;
}
t = malloc(sizeof(*t));
if(!t)
return NULL;
t->fd = client_fd;
return t;
}
static void
free_tunnel(struct tunnel *t) {
free(t);
}
struct tunnel *
connect_tunnel(const char *host, const char *port, enum protocol proto) {
int sock;
struct tunnel *t;
struct addrinfo hint = {0}, *res;
hint.ai_family = PF_INET;
hint.ai_socktype = proto == PROTO_TCP ? SOCK_STREAM : SOCK_DGRAM;
if(getaddrinfo(host, port, &hint, &res) < 0) {
perror("getaddrinfo");
return NULL;
}
if((sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) {
perror("socket");
return NULL;
}
if(connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
perror("connect");
return NULL;
}
t = malloc(sizeof(*t));
if(!t)
return NULL;
t->fd = sock;
t->proto = proto;
printf("tunnel connection done\n");
return t;
}
void
tunnel_disconnected(struct tunnel *t) {
printf("tunnel disconnected\n");
free_tunnel(t);
}
int
tunnel_listen(int port) {
int sock;
int yes = 1;
struct sockaddr_in sin;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return -1;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
perror("setsockopt");
return -1;
}
if(bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("bind");
return -1;
}
if(listen(sock, 5) < 0) {
perror("listen");
return -1;
}
return sock;
}
ssize_t
tcp_tunnel_write(struct tunnel *t, unsigned char *buf, size_t n) {
return write(t->fd, buf, n);
}
ssize_t
tcp_tunnel_read(struct tunnel *t, unsigned char *buf, size_t n) {
return read(t->fd, buf, n);
}