-
Notifications
You must be signed in to change notification settings - Fork 0
/
socks5_server.cpp
370 lines (325 loc) · 12 KB
/
socks5_server.cpp
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// client:
// (local resolve)
// curl -v http://www.baidu.com/ --proxy socks5://127.0.0.1:1080
// (remote resolve)
// curl -v http://www.baidu.com/ --proxy socks5h://127.0.0.1:1080
#include "uvio/core.hpp"
#include "uvio/net.hpp"
#include "uvio/net/endian.hpp"
#include <array>
#include <sstream>
#define PORT 1080
#define BUFSIZE (static_cast<size_t>(16 * 1024))
namespace socks5 {
using namespace uvio;
using namespace uvio::net;
// with buf
using BufferedReader = TcpReader;
using BufferedWriter = TcpWriter;
// no buf
using Reader = io::OwnedReadHalf<TcpStream>;
using Writer = io::OwnedWriteHalf<TcpStream>;
// class Socks5Codec : public Codec<Socks5Codec> {};
// https://datatracker.ietf.org/doc/html/rfc1928
class Socks5Framed {
public:
// CMD
// o CONNECT X'01'
// o BIND X'02'
// o UDP ASSOCIATE X'03'
enum class Cmd {
CONNECT,
BIND,
UDP_ASSOCIATE,
};
struct Request {
Cmd cmd{};
std::string addr;
int port{};
};
public:
explicit Socks5Framed(TcpStream &&stream) {
auto [reader, writer] = std::move(stream).into_split();
buffered_reader_ = BufferedReader{std::move(reader), BUFSIZE};
buffered_writer_ = BufferedWriter{std::move(writer), BUFSIZE};
}
public:
[[REMEMBER_CO_AWAIT]]
auto auth_methods() -> Task<Result<void>> {
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
std::array<char, 2> bytes2{};
co_await buffered_reader_.read_exact(bytes2);
if (bytes2[0] != 0x05) {
co_return uvio::unexpected{make_uvio_error(Error::Unclassified)};
}
auto n_methods = bytes2[1];
std::vector<char> methods(n_methods);
co_await buffered_reader_.read_exact(methods);
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
// method selection message
bytes2[0] = 0x05;
// o X'00' NO AUTHENTICATION REQUIRED
// o X'01' GSSAPI
// o X'02' USERNAME/PASSWORD
// o X'03' to X'7F' IANA ASSIGNED
// o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
// o X'FF' NO ACCEPTABLE METHODS
bytes2[1] = 0x00;
co_await buffered_writer_.write(bytes2);
co_await buffered_writer_.flush();
co_return Result<void>{};
}
[[REMEMBER_CO_AWAIT]]
auto read_request() -> Task<Result<Request>> {
Request request;
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// Where:
//
// o VER protocol version: X'05'
// o CMD
// o CONNECT X'01'
// o BIND X'02'
// o UDP ASSOCIATE X'03'
// o RSV RESERVED
// o ATYP address type of following address
// o IP V4 address: X'01'
// o DOMAINNAME: X'03'
// o IP V6 address: X'04'
// o DST.ADDR desired destination address
// o DST.PORT desired destination port in network octet
// order
std::array<char, 2> bytes2{};
std::array<char, 4> bytes4{};
co_await buffered_reader_.read_exact(bytes4);
if (bytes4[0] != 0x05) {
co_return uvio::unexpected{make_uvio_error(Error::Unclassified)};
}
if (bytes4[1] == 0x01) {
// connect
request.cmd = Cmd::CONNECT;
} else if (bytes4[1] == 0x02) {
// bind
request.cmd = Cmd::BIND;
} else if (bytes4[1] == 0x03) {
// udp associate
request.cmd = Cmd::UDP_ASSOCIATE;
} else {
co_return uvio::unexpected{make_uvio_error(Error::Unclassified)};
}
ASSERT(bytes4[2] == 0x00);
if (bytes4[3] == 0x01) {
// ipv4
co_await buffered_reader_.read_exact(bytes4);
request.addr = ip_to_string(bytes4);
co_await buffered_reader_.read_exact(bytes2);
uint16_t port = bytes2[0] | bytes2[1] << 8;
request.port = net::byteorder::ntoh16(port);
} else if (bytes4[3] == 0x03) {
// domain name
std::array<char, 1> byte{};
co_await buffered_reader_.read_exact(byte);
std::vector<char> buf(byte[0]);
co_await buffered_reader_.read_exact(buf);
request.addr = std::string{buf.data(), buf.size()};
// LOG_DEBUG("request.addr: {}", request.addr);
co_await buffered_reader_.read_exact(bytes2);
uint16_t port = bytes2[0] | bytes2[1] << 8;
request.port = net::byteorder::ntoh16(port);
// LOG_DEBUG("request.port: {}", request.port);
} else if (bytes4[3] == 0x04) {
// ipv6
std::vector<char> buf(16);
co_await buffered_reader_.read_exact(buf);
// TODO(x)
// request.addr =
co_await buffered_reader_.read_exact(bytes2);
uint16_t port = bytes2[0] | bytes2[1] << 8;
request.port = net::byteorder::ntoh16(port);
} else {
co_return uvio::unexpected{make_uvio_error(Error::Unclassified)};
}
co_return request;
}
[[REMEMBER_CO_AWAIT]]
auto write_reply() -> Task<Result<void>> {
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// Where:
//
// o VER protocol version: X'05'
// o REP Reply field:
// o X'00' succeeded
// o X'01' general SOCKS server failure
// o X'02' connection not allowed by ruleset
// o X'03' Network unreachable
// o X'04' Host unreachable
// o X'05' Connection refused
// o X'06' TTL expired
// o X'07' Command not supported
// o X'08' Address type not supported
// o X'09' to X'FF' unassigned
// o RSV RESERVED
// o ATYP address type of following address
// o IP V4 address: X'01'
// o DOMAINNAME: X'03'
// o IP V6 address: X'04'
// o BND.ADDR server bound address
// o BND.PORT server bound port in network octet order
// Fields marked RESERVED (RSV) must be set to X'00'.
std::array<char, 2> bytes2{};
std::array<char, 4> bytes4{};
// version
bytes4[0] = 0x05;
// reply
bytes4[1] = 0x00;
// reserved
bytes4[2] = 0x00;
// address type
bytes4[3] = 0x01;
co_await buffered_writer_.write(bytes4);
// 这个地址似乎并没有什么用, 客户端早就已经知道代理服务地址了
bytes4[0] = 127;
bytes4[1] = 0;
bytes4[2] = 0;
bytes4[3] = 1;
// host address -> network address
co_await buffered_writer_.write(bytes4);
// TODO(x)
// auto port = net::byteorder::hton16(PORT);
// 端口不设置测试好像也没问题
auto port = net::byteorder::hton16(0);
bytes2[0] = static_cast<char>(port & 0xFF);
bytes2[1] = static_cast<char>((port >> 8) & 0xFF);
co_await buffered_writer_.write(bytes2);
co_await buffered_writer_.flush();
co_return Result<void>{};
}
[[REMEMBER_CO_AWAIT]]
auto connect(Request req) -> Task<Result<void>> {
// TODO(x): do resolve if domain name?
auto ok = co_await DNS::resolve(req.addr, std::to_string(req.port));
if (!ok) {
co_return uvio::unexpected{ok.error()};
}
auto remote = co_await TcpStream::connect(ok.value(), req.port);
if (!remote) {
LOG_ERROR("Connect {}:{} failed", req.addr, req.port);
co_return uvio::unexpected{remote.error()};
}
auto local
= reunite(buffered_reader_.inner(), buffered_writer_.inner());
if (!local) {
co_return uvio::unexpected{local.error()};
}
auto [l_reader, l_writer] = local->into_split();
auto [r_reader, r_writer] = remote->into_split();
// local -> remote
// remote -> local
spawn(forward(std::move(l_reader), std::move(r_writer))); // outbound
spawn(forward(std::move(r_reader), std::move(l_writer))); // inbound
co_return Result<void>{};
}
private:
auto forward(Reader reader, Writer writer) -> Task<> {
// std::array<char, 1024> buf{};
std::vector<char> buf(static_cast<size_t>(BUFSIZE));
while (true) {
auto rret = co_await reader.read(buf);
if (!rret) {
LOG_ERROR("{}", rret.error().message());
co_return;
}
// LOG_DEBUG("{}", std::string_view{buf.data(), rret.value()});
// LOG_DEBUG("rret: {}", rret.value());
auto wret = co_await writer.write({buf.data(), rret.value()});
if (!wret) {
LOG_ERROR("{}", wret.error().message());
co_return;
}
ASSERT(rret.value() == wret.value());
}
}
auto ip_to_string(const std::array<char, 4> &ipv4) -> std::string {
std::stringstream ss;
ss << static_cast<int>(static_cast<unsigned char>(ipv4[0])) << '.'
<< static_cast<int>(static_cast<unsigned char>(ipv4[1])) << '.'
<< static_cast<int>(static_cast<unsigned char>(ipv4[2])) << '.'
<< static_cast<int>(static_cast<unsigned char>(ipv4[3]));
return ss.str();
}
private:
BufferedReader buffered_reader_;
BufferedWriter buffered_writer_;
};
class Socks5Server {
public:
Socks5Server(std::string_view host, int port)
: host_{host}
, port_{port} {}
public:
auto run() {
block_on([this]() -> Task<> {
auto listener = TcpListener();
listener.bind(this->host_, this->port_);
console.info("Listening on {}:{} ...", this->host_, this->port_);
while (true) {
auto stream = (co_await listener.accept()).value();
spawn(this->handle_proxy(std::move(stream)));
}
}());
}
private:
auto handle_proxy(TcpStream stream) -> Task<> {
Socks5Framed socks5_framed{std::move(stream)};
if (auto ok = co_await socks5_framed.auth_methods(); !ok) {
LOG_ERROR("{}", ok.error().message());
co_return;
}
auto has_req = co_await socks5_framed.read_request();
if (!has_req) {
LOG_ERROR("{}", has_req.error().message());
co_return;
}
auto req = std::move(has_req.value());
if (auto ok = co_await socks5_framed.write_reply(); !ok) {
LOG_ERROR("{}", ok.error().message());
co_return;
}
switch (req.cmd) {
case Socks5Framed::Cmd::CONNECT:
co_await socks5_framed.connect(req);
break;
case Socks5Framed::Cmd::BIND:
// TODO(x)
case Socks5Framed::Cmd::UDP_ASSOCIATE:
// TODO(x)
break;
}
}
private:
std::string host_;
int port_;
};
} // namespace socks5
auto main() -> int {
#if !defined(_WIN32)
signal(SIGPIPE, SIG_IGN); // uv_signal_start(signal, callback, signum)
#endif
socks5::Socks5Server proxy{"0.0.0.0", PORT};
proxy.run();
}