-
Notifications
You must be signed in to change notification settings - Fork 975
/
TcpServerSocketChannel.cs
291 lines (248 loc) · 10.6 KB
/
TcpServerSocketChannel.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels.Sockets
{
using System;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Sockets;
using DotNetty.Common.Internal.Logging;
/// <summary>
/// A <see cref="IServerSocketChannel" /> implementation which uses Socket-based implementation to accept new
/// connections.
/// </summary>
public class TcpServerSocketChannel : AbstractSocketChannel, IServerSocketChannel
{
static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<TcpServerSocketChannel>();
static readonly ChannelMetadata METADATA = new ChannelMetadata(false);
static readonly Action<object, object> ReadCompletedSyncCallback = OnReadCompletedSync;
readonly IServerSocketChannelConfiguration config;
SocketChannelAsyncOperation acceptOperation;
/// <summary>
/// Create a new instance
/// </summary>
public TcpServerSocketChannel()
: this(new Socket(SocketType.Stream, ProtocolType.Tcp))
{
}
/// <summary>
/// Create a new instance
/// </summary>
public TcpServerSocketChannel(AddressFamily addressFamily)
: this(new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
{
}
/// <summary>
/// Create a new instance using the given <see cref="Socket"/>.
/// </summary>
public TcpServerSocketChannel(Socket socket)
: base(null, socket)
{
this.config = new TcpServerSocketChannelConfig(this, socket);
}
public override IChannelConfiguration Configuration => this.config;
public override bool Active => this.Socket.IsBound;
public override ChannelMetadata Metadata => METADATA;
protected override EndPoint RemoteAddressInternal => null;
protected override EndPoint LocalAddressInternal => this.Socket.LocalEndPoint;
SocketChannelAsyncOperation AcceptOperation => this.acceptOperation ?? (this.acceptOperation = new SocketChannelAsyncOperation(this, false));
protected override IChannelUnsafe NewUnsafe() => new TcpServerSocketChannelUnsafe(this);
protected override void DoBind(EndPoint localAddress)
{
this.Socket.Bind(localAddress);
this.Socket.Listen(this.config.Backlog);
this.SetState(StateFlags.Active);
this.CacheLocalAddress();
}
protected override void DoClose()
{
if (this.TryResetState(StateFlags.Open | StateFlags.Active))
{
this.Socket.Dispose();
}
}
protected override void ScheduleSocketRead()
{
bool closed = false;
SocketChannelAsyncOperation operation = this.AcceptOperation;
while (!closed)
{
try
{
bool pending = this.Socket.AcceptAsync(operation);
if (!pending)
{
this.EventLoop.Execute(ReadCompletedSyncCallback, this.Unsafe, operation);
}
return;
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.OperationAborted || ex.SocketErrorCode == SocketError.InvalidArgument)
{
closed = true;
}
catch (SocketException ex)
{
// socket exceptions here are internal to channel's operation and should not go through the pipeline
// especially as they have no effect on overall channel's operation
Logger.Info("Exception on accept.", ex);
}
catch (ObjectDisposedException)
{
closed = true;
}
catch (Exception ex)
{
this.Pipeline.FireExceptionCaught(ex);
closed = true;
}
}
if (closed && this.Open)
{
this.Unsafe.CloseSafe();
}
}
static void OnReadCompletedSync(object u, object p) => ((ISocketChannelUnsafe)u).FinishRead((SocketChannelAsyncOperation)p);
protected override bool DoConnect(EndPoint remoteAddress, EndPoint localAddress)
{
throw new NotSupportedException();
}
protected override void DoFinishConnect(SocketChannelAsyncOperation operation)
{
throw new NotSupportedException();
}
protected override void DoDisconnect()
{
throw new NotSupportedException();
}
protected override void DoWrite(ChannelOutboundBuffer input)
{
throw new NotSupportedException();
}
protected sealed override object FilterOutboundMessage(object msg)
{
throw new NotSupportedException();
}
sealed class TcpServerSocketChannelUnsafe : AbstractSocketUnsafe
{
public TcpServerSocketChannelUnsafe(TcpServerSocketChannel channel)
: base(channel)
{
}
new TcpServerSocketChannel Channel => (TcpServerSocketChannel)this.channel;
public override void FinishRead(SocketChannelAsyncOperation operation)
{
Contract.Assert(this.channel.EventLoop.InEventLoop);
TcpServerSocketChannel ch = this.Channel;
if ((ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active) == 0)
{
return; // read was signaled as a result of channel closure
}
IChannelConfiguration config = ch.Configuration;
IChannelPipeline pipeline = ch.Pipeline;
IRecvByteBufAllocatorHandle allocHandle = this.Channel.Unsafe.RecvBufAllocHandle;
allocHandle.Reset(config);
bool closed = false;
Exception exception = null;
try
{
Socket connectedSocket = null;
try
{
connectedSocket = operation.AcceptSocket;
operation.AcceptSocket = null;
operation.Validate();
var message = this.PrepareChannel(connectedSocket);
connectedSocket = null;
ch.ReadPending = false;
pipeline.FireChannelRead(message);
allocHandle.IncMessagesRead(1);
if (!config.AutoRead && !ch.ReadPending)
{
// ChannelConfig.setAutoRead(false) was called in the meantime.
// Completed Accept has to be processed though.
return;
}
while (allocHandle.ContinueReading())
{
connectedSocket = ch.Socket.Accept();
message = this.PrepareChannel(connectedSocket);
connectedSocket = null;
ch.ReadPending = false;
pipeline.FireChannelRead(message);
allocHandle.IncMessagesRead(1);
}
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.OperationAborted || ex.SocketErrorCode == SocketError.InvalidArgument)
{
closed = true;
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.WouldBlock)
{
}
catch (SocketException ex)
{
// socket exceptions here are internal to channel's operation and should not go through the pipeline
// especially as they have no effect on overall channel's operation
Logger.Info("Exception on accept.", ex);
}
catch (ObjectDisposedException)
{
closed = true;
}
catch (Exception ex)
{
exception = ex;
}
allocHandle.ReadComplete();
pipeline.FireChannelReadComplete();
if (exception != null)
{
// ServerChannel should not be closed even on SocketException because it can often continue
// accepting incoming connections. (e.g. too many open files)
pipeline.FireExceptionCaught(exception);
}
if (closed && ch.Open)
{
this.CloseSafe();
}
}
finally
{
// Check if there is a readPending which was not processed yet.
if (!closed && (ch.ReadPending || config.AutoRead))
{
ch.DoBeginRead();
}
}
}
TcpSocketChannel PrepareChannel(Socket socket)
{
try
{
return new TcpSocketChannel(this.channel, socket, true);
}
catch (Exception ex)
{
Logger.Warn("Failed to create a new channel from accepted socket.", ex);
try
{
socket.Dispose();
}
catch (Exception ex2)
{
Logger.Warn("Failed to close a socket cleanly.", ex2);
}
throw;
}
}
}
sealed class TcpServerSocketChannelConfig : DefaultServerSocketChannelConfig
{
public TcpServerSocketChannelConfig(TcpServerSocketChannel channel, Socket javaSocket)
: base(channel, javaSocket)
{
}
protected override void AutoReadCleared() => ((TcpServerSocketChannel)this.Channel).ReadPending = false;
}
}
}