forked from shadowsocks/shadowsocks-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPListener.cs
176 lines (154 loc) · 5.19 KB
/
TCPListener.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
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Shadowsocks.Net
{
public interface IStreamService
{
[Obsolete]
bool Handle(byte[] firstPacket, int length, Socket socket, object state);
public abstract bool Handle(CachedNetworkStream stream, object state);
void Stop();
}
public abstract class StreamService : IStreamService
{
[Obsolete]
public abstract bool Handle(byte[] firstPacket, int length, Socket socket, object state);
public abstract bool Handle(CachedNetworkStream stream, object state);
public virtual void Stop() { }
}
public class TCPListener : IEnableLogger
{
public class UDPState
{
public UDPState(Socket s)
{
socket = s;
remoteEndPoint = new IPEndPoint(s.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
}
public Socket socket;
public byte[] buffer = new byte[4096];
public EndPoint remoteEndPoint;
}
IPEndPoint _localEndPoint;
Socket _tcpSocket;
IEnumerable<IStreamService> _services;
public TCPListener(IPEndPoint localEndPoint, IEnumerable<IStreamService> services)
{
_localEndPoint = localEndPoint;
_services = services;
}
private bool CheckIfPortInUse(int port)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
return ipProperties.GetActiveTcpListeners().Any(endPoint => endPoint.Port == port);
}
public void Start()
{
if (CheckIfPortInUse(_localEndPoint.Port))
throw new Exception($"Port {_localEndPoint.Port} already in use");
try
{
// Create a TCP/IP socket.
_tcpSocket = new Socket(_localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_tcpSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
// Bind the socket to the local endpoint and listen for incoming connections.
_tcpSocket.Bind(_localEndPoint);
_tcpSocket.Listen(1024);
// Start an asynchronous socket to listen for connections.
this.Log().Info($"Shadowsocks started TCP");
this.Log().Debug(Crypto.CryptoFactory.DumpRegisteredEncryptor());
_tcpSocket.BeginAccept(new AsyncCallback(AcceptCallback), _tcpSocket);
}
catch (SocketException)
{
_tcpSocket.Close();
throw;
}
}
public void Stop()
{
_tcpSocket?.Close();
foreach (IStreamService s in _services)
{
s.Stop();
}
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
try
{
Socket conn = listener.EndAccept(ar);
byte[] buf = new byte[4096];
object[] state = new object[] {
conn,
buf
};
conn.BeginReceive(buf, 0, buf.Length, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
this.Log().Error(e, "");
}
finally
{
try
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
catch (ObjectDisposedException)
{
// do nothing
}
catch (Exception e)
{
this.Log().Error(e, "");
}
}
}
private void ReceiveCallback(IAsyncResult ar)
{
object[] state = (object[])ar.AsyncState;
Socket conn = (Socket)state[0];
byte[] buf = (byte[])state[1];
try
{
int bytesRead = conn.EndReceive(ar);
if (bytesRead <= 0)
{
goto Shutdown;
}
foreach (IStreamService service in _services)
{
if (service.Handle(buf, bytesRead, conn, null))
{
return;
}
}
Shutdown:
// no service found for this
if (conn.ProtocolType == ProtocolType.Tcp)
{
conn.Close();
}
}
catch (Exception e)
{
this.Log().Error(e, "");
conn.Close();
}
}
}
}