forked from shadowsocks/shadowsocks-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPRelay.cs
601 lines (524 loc) · 19.6 KB
/
TCPRelay.cs
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
using Splat;
using Shadowsocks.Net.Crypto;
using Shadowsocks.Net.Crypto.AEAD;
using Shadowsocks.Net.Proxy;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Shadowsocks.Net.Crypto.CryptoBase;
using Shadowsocks.Models;
namespace Shadowsocks.Net
{
public class TCPRelay : StreamService, IEnableLogger
{
public event EventHandler<SSTCPConnectedEventArgs> OnConnected;
public event EventHandler<SSTransmitEventArgs> OnInbound;
public event EventHandler<SSTransmitEventArgs> OnOutbound;
public event EventHandler<SSRelayEventArgs> OnFailed;
private Server _server;
private DateTime _lastSweepTime;
public ISet<TCPHandler> Handlers { get; set; }
public TCPRelay(Server server)
{
_server = server;
Handlers = new HashSet<TCPHandler>();
_lastSweepTime = DateTime.Now;
}
public override bool Handle(CachedNetworkStream stream, object state)
{
byte[] fp = new byte[256];
int len = stream.ReadFirstBlock(fp);
var socket = stream.Socket;
if (socket.ProtocolType != ProtocolType.Tcp
|| (len < 2 || fp[0] != 5))
return false;
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
TCPHandler handler = new TCPHandler(_server, socket);
IList<TCPHandler> handlersToClose = new List<TCPHandler>();
lock (Handlers)
{
Handlers.Add(handler);
DateTime now = DateTime.Now;
if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
{
_lastSweepTime = now;
foreach (TCPHandler handler1 in Handlers)
if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
handlersToClose.Add(handler1);
}
}
foreach (TCPHandler handler1 in handlersToClose)
{
this.Log().Debug("Closing timed out TCP connection.");
handler1.Close();
}
/*
* Start after we put it into Handlers set. Otherwise if it failed in handler.Start()
* then it will call handler.Close() before we add it into the set.
* Then the handler will never release until the next Handle call. Sometimes it will
* cause odd problems (especially during memory profiling).
*/
// handler.Start(fp, len);
_ = handler.StartAsync(fp, len);
return true;
// return Handle(fp, len, stream.Socket, state);
}
[Obsolete]
public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
{
if (socket.ProtocolType != ProtocolType.Tcp
|| (length < 2 || firstPacket[0] != 5))
{
return false;
}
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
TCPHandler handler = new TCPHandler(_server, socket);
handler.OnConnected += OnConnected;
handler.OnInbound += OnInbound;
handler.OnOutbound += OnOutbound;
handler.OnFailed += OnFailed;
handler.OnClosed += (h, arg) =>
{
lock (Handlers)
{
Handlers.Remove(handler);
}
};
IList<TCPHandler> handlersToClose = new List<TCPHandler>();
lock (Handlers)
{
Handlers.Add(handler);
DateTime now = DateTime.Now;
if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
{
_lastSweepTime = now;
foreach (TCPHandler handler1 in Handlers)
{
if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
{
handlersToClose.Add(handler1);
}
}
}
}
foreach (TCPHandler handler1 in handlersToClose)
{
this.Log().Debug("Closing timed out TCP connection.");
handler1.Close();
}
/*
* Start after we put it into Handlers set. Otherwise if it failed in handler.Start()
* then it will call handler.Close() before we add it into the set.
* Then the handler will never release until the next Handle call. Sometimes it will
* cause odd problems (especially during memory profiling).
*/
// handler.Start(firstPacket, length);
_ = handler.StartAsync(firstPacket, length);
return true;
}
public override void Stop()
{
List<TCPHandler> handlersToClose = new List<TCPHandler>();
lock (Handlers)
{
handlersToClose.AddRange(Handlers);
}
handlersToClose.ForEach(h => h.Close());
}
}
public class SSRelayEventArgs : EventArgs
{
public readonly Server server;
public SSRelayEventArgs(Server server)
{
this.server = server;
}
}
public class SSTransmitEventArgs : SSRelayEventArgs
{
public readonly long length;
public SSTransmitEventArgs(Server server, long length) : base(server)
{
this.length = length;
}
}
public class SSTCPConnectedEventArgs : SSRelayEventArgs
{
public readonly TimeSpan latency;
public SSTCPConnectedEventArgs(Server server, TimeSpan latency) : base(server)
{
this.latency = latency;
}
}
public class TCPHandler : IEnableLogger
{
public event EventHandler<SSTCPConnectedEventArgs> OnConnected;
public event EventHandler<SSTransmitEventArgs> OnInbound;
public event EventHandler<SSTransmitEventArgs> OnOutbound;
public event EventHandler<SSRelayEventArgs> OnClosed;
public event EventHandler<SSRelayEventArgs> OnFailed;
private readonly int _serverTimeout;
private readonly int _proxyTimeout;
private readonly MemoryPool<byte> pool = MemoryPool<byte>.Shared;
// each recv size.
public const int RecvSize = 16384;
// overhead of one chunk, reserved for AEAD ciphers
public const int ChunkOverheadSize = 100;//16 * 2 /* two tags */ + AEADEncryptor.ChunkLengthBytes;
// In general, the ciphertext length, we should take overhead into account
public const int SendSize = 32768;
public DateTime lastActivity;
// TODO: forward proxy
//private readonly ForwardProxyConfig _config;
private readonly Server _server;
private readonly Socket _connection;
private IProxy _remote;
private ICrypto encryptor;
// workaround
private ICrypto decryptor;
private byte[] _firstPacket;
private int _firstPacketLength;
private const int CMD_CONNECT = 0x01;
private const int CMD_BIND = 0x02;
private const int CMD_UDP_ASSOC = 0x03;
private bool _closed = false;
// instance-based lock without static
private readonly object _encryptionLock = new object();
private readonly object _decryptionLock = new object();
private readonly object _closeConnLock = new object();
// TODO: decouple controller
public TCPHandler(Server server, Socket socket)
{
_server = server;
_connection = socket;
_proxyTimeout = 5000;
_serverTimeout = 5000;
lastActivity = DateTime.Now;
}
public void CreateRemote(EndPoint destination)
{
if (_server == null || _server.Host == "")
{
throw new ArgumentException("No server configured");
}
encryptor = CryptoFactory.GetEncryptor(_server.Method, _server.Password);
decryptor = CryptoFactory.GetEncryptor(_server.Method, _server.Password);
}
public async Task StartAsync(byte[] firstPacket, int length)
{
_firstPacket = firstPacket;
_firstPacketLength = length;
(int cmd, EndPoint dst) = await Socks5Handshake();
if (cmd == CMD_CONNECT)
{
await ConnectRemote(dst);
await SendAddress(dst);
await Forward();
}
else if (cmd == CMD_UDP_ASSOC)
{
await DrainConnection();
}
}
private void ErrorClose(Exception e)
{
this.Log().Error(e, "");
Close();
}
public void Close()
{
lock (_closeConnLock)
{
if (_closed)
{
return;
}
_closed = true;
}
OnClosed?.Invoke(this, new SSRelayEventArgs(_server));
try
{
_connection.Shutdown(SocketShutdown.Both);
_connection.Close();
encryptor?.Dispose();
decryptor?.Dispose();
}
catch (Exception e)
{
this.Log().Error(e, "");
}
}
async Task<(int cmd, EndPoint destination)> Socks5Handshake()
{
// not so strict here
// 5 2 1 2 should return 5 255
// 5 1 0 5 / 1 0 1 127 0 0 1 0 80 will cause handshake fail
int bytesRead = _firstPacketLength;
if (bytesRead <= 1)
{
Close();
return (0, default);
}
byte[] response = { 5, 0 };
if (_firstPacket[0] != 5)
{
// reject socks 4
response = new byte[] { 0, 91 };
this.Log().Error("socks5 protocol error");
}
await _connection.SendAsync(response, SocketFlags.None);
using var bufOwner = pool.Rent(512);
var buf = bufOwner.Memory;
if (await _connection.ReceiveAsync(buf.Slice(0, 5), SocketFlags.None) != 5)
{
Close();
return (0, default);
}
var cmd = buf.Span[1];
EndPoint dst = default;
switch (cmd)
{
case CMD_CONNECT:
await _connection.SendAsync(new byte[] { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, SocketFlags.None);
dst = await ReadAddress(buf);
// start forward
break;
case CMD_UDP_ASSOC:
dst = await ReadAddress(buf);
await SendUdpAssociate();
// drain
break;
default:
Close();
break;
}
return (cmd, dst);
}
async Task DrainConnection()
{
if (_closed)
{
return;
}
using var b = pool.Rent(512);
try
{
int l;
do
{
l = await _connection.ReceiveAsync(b.Memory, SocketFlags.None);
}
while (l > 0);
Close();
}
catch (Exception e)
{
ErrorClose(e);
}
}
private async Task<EndPoint> ReadAddress(Memory<byte> buf)
{
var atyp = buf.Span[3];
var maybeDomainLength = buf.Span[4];
buf.Span[0] = atyp;
buf.Span[1] = maybeDomainLength;
int toRead = atyp switch
{
ATYP_IPv4 => 4,
ATYP_IPv6 => 16,
ATYP_DOMAIN => maybeDomainLength + 1,
_ => throw new NotSupportedException(),
} + 2 - 1;
await _connection.ReceiveAsync(buf.Slice(2, toRead), SocketFlags.None);
return GetSocks5EndPoint(buf.ToArray());
}
private int ReadPort(byte[] arr, long offset)
{
return (arr[offset] << 8) + arr[offset + 1];
}
private EndPoint GetSocks5EndPoint(byte[] buf)
{
int maybeDomainLength = buf[1] + 2;
return (buf[0]) switch
{
ATYP_IPv4 => new IPEndPoint(new IPAddress(buf[1..5]), ReadPort(buf, 5)),
ATYP_IPv6 => new IPEndPoint(new IPAddress(buf[1..17]), ReadPort(buf, 17)),
ATYP_DOMAIN => new DnsEndPoint(Encoding.ASCII.GetString(buf[2..maybeDomainLength]), ReadPort(buf, maybeDomainLength)),
_ => throw new NotSupportedException(),
};
}
private async Task SendUdpAssociate()
{
IPEndPoint endPoint = (IPEndPoint)_connection.LocalEndPoint;
byte[] address = endPoint.Address.GetAddressBytes();
int port = endPoint.Port;
byte[] response = new byte[4 + address.Length + ADDR_PORT_LEN];
response[0] = 5;
switch (endPoint.AddressFamily)
{
case AddressFamily.InterNetwork:
response[3] = ATYP_IPv4;
break;
case AddressFamily.InterNetworkV6:
response[3] = ATYP_IPv6;
break;
}
address.CopyTo(response, 4);
response[^1] = (byte)(port & 0xFF);
response[^2] = (byte)((port >> 8) & 0xFF);
await _connection.SendAsync(response, SocketFlags.None);
}
private async Task ConnectRemote(EndPoint destination)
{
CreateRemote(destination);
IProxy remote;
EndPoint proxyEP = null;
EndPoint serverEP = new DnsEndPoint(_server.Host, _server.Port);
EndPoint pluginEP = null; // TODO: plugin local end point
remote = new DirectConnect(); // TODO: forward proxy
NetworkCredential auth = null;
/*if (_config.useAuth)
{
auth = new NetworkCredential(_config.authUser, _config.authPwd);
}
if (pluginEP != null)
{
serverEP = pluginEP;
remote = new DirectConnect();
}
else if (_config.useProxy)
{
remote = _config.proxyType switch
{
ForwardProxyConfig.PROXY_SOCKS5 => new Socks5Proxy(),
ForwardProxyConfig.PROXY_HTTP => new HttpProxy(),
_ => throw new NotSupportedException("Unknown forward proxy."),
};
proxyEP = new DnsEndPoint(_config.proxyServer, _config.proxyPort);
}
else
{
remote = new DirectConnect();
}*/
CancellationTokenSource cancelProxy = new CancellationTokenSource(_proxyTimeout * 1000);
await remote.ConnectProxyAsync(proxyEP, auth, cancelProxy.Token);
_remote = remote;
if (!(remote is DirectConnect))
{
this.Log().Debug($"Socket connected to proxy {remote.ProxyEndPoint}");
}
var _startConnectTime = DateTime.Now;
CancellationTokenSource cancelServer = new CancellationTokenSource(_serverTimeout * 1000);
await remote.ConnectRemoteAsync(serverEP, cancelServer.Token);
this.Log().Debug($"Socket connected to ss server: {_server}");
TimeSpan latency = DateTime.Now - _startConnectTime;
OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency));
}
private async Task SendAddress(EndPoint dest)
{
byte[] dstByte = GetSocks5EndPointByte(dest);
using var t = pool.Rent(512);
try
{
int addrlen = encryptor.Encrypt(dstByte, t.Memory.Span);
await _remote.SendAsync(t.Memory.Slice(0, addrlen));
}
catch (Exception e)
{
ErrorClose(e);
}
}
private byte[] GetSocks5EndPointByte(EndPoint dest)
{
if (dest is DnsEndPoint d)
{
byte[] r = new byte[d.Host.Length + 4];
r[0] = 3;
r[1] = (byte)d.Host.Length;
Encoding.ASCII.GetBytes(d.Host, r.AsSpan(2));
r[^2] = (byte)(d.Port / 256);
r[^1] = (byte)(d.Port % 256);
return r;
}
else if (dest is IPEndPoint i)
{
if (i.AddressFamily == AddressFamily.InterNetwork)
{
byte[] r = new byte[7];
r[0] = 1;
i.Address.GetAddressBytes().CopyTo(r, 1);
r[^2] = (byte)(i.Port / 256);
r[^1] = (byte)(i.Port % 256);
return r;
}
else if (i.AddressFamily == AddressFamily.InterNetworkV6)
{
byte[] r = new byte[19];
r[0] = 1;
i.Address.GetAddressBytes().CopyTo(r, 1);
r[^2] = (byte)(i.Port / 256);
r[^1] = (byte)(i.Port % 256);
return r;
}
}
throw new NotImplementedException();
}
private async Task Forward()
{
try
{
await Task.WhenAll(ForwardInbound(), ForwardOutbound());
Close();
}
catch (Exception e)
{
ErrorClose(e);
}
}
private async Task ForwardInbound()
{
using var cipherOwner = pool.Rent(RecvSize);
using var plainOwner = pool.Rent(SendSize);
var plain = plainOwner.Memory;
var cipher = cipherOwner.Memory;
try
{
while (true)
{
int len = await _remote.ReceiveAsync(cipher);
if (len == 0) break;
int plen = decryptor.Decrypt(plain.Span, cipher.Span.Slice(0, len));
if (plen == 0) continue;
int len2 = await _connection.SendAsync(plain.Slice(0, plen), SocketFlags.None);
if (len2 == 0) break;
OnInbound?.Invoke(this, new SSTransmitEventArgs(_server, plen));
}
}
catch (Exception e)
{
ErrorClose(e);
}
}
private async Task ForwardOutbound()
{
using var plainOwner = pool.Rent(RecvSize);
using var cipherOwner = pool.Rent(SendSize);
var plain = plainOwner.Memory;
var cipher = cipherOwner.Memory;
while (true)
{
int len = await _connection.ReceiveAsync(plain, SocketFlags.None);
if (len == 0) break;
int clen = encryptor.Encrypt(plain.Span.Slice(0, len), cipher.Span);
int len2 = await _remote.SendAsync(cipher.Slice(0, clen));
if (len2 == 0) break;
OnOutbound?.Invoke(this, new SSTransmitEventArgs(_server, len));
}
_remote.Shutdown(SocketShutdown.Send);
}
}
}