-
-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathDnsTcpMessageHandler.cs
More file actions
465 lines (379 loc) · 16.1 KB
/
Copy pathDnsTcpMessageHandler.cs
File metadata and controls
465 lines (379 loc) · 16.1 KB
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
// Copyright 2024 Michael Conrad.
// Licensed under the Apache License, Version 2.0.
// See LICENSE file for details.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using DnsClient.Internal;
namespace DnsClient
{
internal class DnsTcpMessageHandler : DnsMessageHandler
{
private readonly ConcurrentDictionary<IPEndPoint, ClientPool> _pools = new ConcurrentDictionary<IPEndPoint, ClientPool>();
public override DnsMessageHandleType Type { get; } = DnsMessageHandleType.TCP;
public override DnsResponseMessage Query(IPEndPoint server, DnsRequestMessage request, TimeSpan timeout)
{
CancellationToken cancellationToken = default;
using var cts = timeout.TotalMilliseconds != Timeout.Infinite && timeout.TotalMilliseconds < int.MaxValue ?
new CancellationTokenSource(timeout) : null;
cancellationToken = cts?.Token ?? default;
ClientPool pool;
while (!_pools.TryGetValue(server, out pool))
{
_pools.TryAdd(server, new ClientPool(true, server));
}
cancellationToken.ThrowIfCancellationRequested();
var entry = pool.GetNextClient();
using var cancelCallback = cancellationToken.Register(() =>
{
if (entry == null)
{
return;
}
entry.DisposeClient();
});
try
{
entry.Connect();
var response = QueryInternal(entry.Client, request, cancellationToken);
ValidateResponse(request, response);
pool.Enqueue(entry);
return response;
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.NotSocket)
{
throw new OperationCanceledException(cancellationToken);
}
catch (ObjectDisposedException)
{
throw new OperationCanceledException(cancellationToken);
}
catch
{
entry.DisposeClient();
throw;
}
}
public override async Task<DnsResponseMessage> QueryAsync(
IPEndPoint server,
DnsRequestMessage request,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ClientPool pool;
while (!_pools.TryGetValue(server, out pool))
{
_pools.TryAdd(server, new ClientPool(true, server));
}
var entry = pool.GetNextClient();
using var cancelCallback = cancellationToken.Register(() =>
{
if (entry == null)
{
return;
}
entry.DisposeClient();
});
try
{
await entry.ConnectAsync(cancellationToken).ConfigureAwait(false);
var response = await QueryAsyncInternal(entry.Client, request, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ValidateResponse(request, response);
pool.Enqueue(entry);
return response;
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.NotSocket)
{
throw new OperationCanceledException(cancellationToken);
}
catch (ObjectDisposedException)
{
throw new OperationCanceledException(cancellationToken);
}
catch
{
entry.DisposeClient();
throw;
}
}
private DnsResponseMessage QueryInternal(TcpClient client, DnsRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var stream = client.GetStream();
// use a pooled buffer to writer the data + the length of the data later into the first two bytes
using var memory = new PooledBytes(DnsQueryOptions.MaximumBufferSize);
using (var writer = new DnsDatagramWriter(new ArraySegment<byte>(memory.Buffer, 2, memory.Buffer.Length - 2)))
{
GetRequestData(request, writer);
int dataLength = writer.Index;
memory.Buffer[0] = (byte)((dataLength >> 8) & 0xff);
memory.Buffer[1] = (byte)(dataLength & 0xff);
//await client.Client.SendAsync(new ArraySegment<byte>(memory.Buffer, 0, dataLength + 2), SocketFlags.None).ConfigureAwait(false);
stream.Write(memory.Buffer, 0, dataLength + 2);
stream.Flush();
}
if (!stream.CanRead)
{
// might retry
throw new TimeoutException();
}
cancellationToken.ThrowIfCancellationRequested();
var responses = new List<DnsResponseMessage>();
byte[] buffer = memory.Buffer;
do
{
int bytesReceivedForLen = 0, readForLen;
while ((bytesReceivedForLen += readForLen = stream.Read(buffer, bytesReceivedForLen, 2)) < 2)
{
if (readForLen <= 0)
{
// disconnected, might retry
throw new TimeoutException();
}
}
int length = buffer[0] << 8 | buffer[1];
if (length <= 0)
{
// server signals close/disconnecting, might retry
throw new TimeoutException();
}
if (length > buffer.Length)
{
buffer = new byte[length];
}
int bytesReceived = 0, read;
int readSize = length > 4096 ? 4096 : length;
cancellationToken.ThrowIfCancellationRequested();
while (!cancellationToken.IsCancellationRequested
&& (bytesReceived += read = stream.Read(buffer, bytesReceived, readSize)) < length)
{
if (read <= 0)
{
// disconnected
throw new TimeoutException();
}
if (bytesReceived + readSize > length)
{
readSize = length - bytesReceived;
if (readSize <= 0)
{
break;
}
}
}
DnsResponseMessage response = GetResponseMessage(new ArraySegment<byte>(buffer, 0, bytesReceived));
responses.Add(response);
} while (stream.DataAvailable && !cancellationToken.IsCancellationRequested);
cancellationToken.ThrowIfCancellationRequested();
return DnsResponseMessage.Combine(responses);
}
private async Task<DnsResponseMessage> QueryAsyncInternal(TcpClient client, DnsRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var stream = client.GetStream();
// use a pooled buffer to writer the data + the length of the data later into the first two bytes
using var memory = new PooledBytes(DnsQueryOptions.MaximumBufferSize);
using (var writer = new DnsDatagramWriter(new ArraySegment<byte>(memory.Buffer, 2, memory.Buffer.Length - 2)))
{
GetRequestData(request, writer);
int dataLength = writer.Index;
memory.Buffer[0] = (byte)((dataLength >> 8) & 0xff);
memory.Buffer[1] = (byte)(dataLength & 0xff);
await stream.WriteAsync(memory.Buffer, 0, dataLength + 2, cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
if (!stream.CanRead)
{
// might retry
throw new TimeoutException();
}
cancellationToken.ThrowIfCancellationRequested();
var responses = new List<DnsResponseMessage>();
do
{
int length;
int bytesReceivedForLen = 0, readForLen;
while ((bytesReceivedForLen += (readForLen = await stream.ReadAsync(memory.Buffer, bytesReceivedForLen, 2, cancellationToken).ConfigureAwait(false))) < 2)
{
if (readForLen <= 0)
{
// disconnected, might retry
throw new TimeoutException();
}
}
length = memory.Buffer[0] << 8 | memory.Buffer[1];
if (length <= 0)
{
// server signals close/disconnecting, might retry
throw new TimeoutException();
}
byte[] buffer = memory.Buffer.Length <= length ? new byte[length] : memory.Buffer;
int bytesReceived = 0, read;
int readSize = length > 4096 ? 4096 : length;
cancellationToken.ThrowIfCancellationRequested();
while (!cancellationToken.IsCancellationRequested
&& (bytesReceived += read = await stream.ReadAsync(buffer, bytesReceived, readSize, cancellationToken).ConfigureAwait(false)) < length)
{
if (read <= 0)
{
// disconnected
throw new TimeoutException();
}
if (bytesReceived + readSize > length)
{
readSize = length - bytesReceived;
if (readSize <= 0)
{
break;
}
}
}
DnsResponseMessage response = GetResponseMessage(new ArraySegment<byte>(buffer, 0, bytesReceived));
responses.Add(response);
} while (stream.DataAvailable && !cancellationToken.IsCancellationRequested);
cancellationToken.ThrowIfCancellationRequested();
return DnsResponseMessage.Combine(responses);
}
private class ClientPool : IDisposable
{
private bool _disposedValue;
private readonly bool _enablePool;
private ConcurrentQueue<ClientEntry> _clients = new ConcurrentQueue<ClientEntry>();
private readonly IPEndPoint _endpoint;
public ClientPool(bool enablePool, IPEndPoint endpoint)
{
_enablePool = enablePool;
_endpoint = endpoint;
}
public ClientEntry GetNextClient()
{
if (_disposedValue)
{
throw new ObjectDisposedException(nameof(ClientPool));
}
ClientEntry entry = null;
if (_enablePool)
{
while (entry == null && !TryDequeue(out entry))
{
entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily) { LingerState = new LingerOption(true, 0) }, _endpoint);
}
}
else
{
entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily), _endpoint);
}
return entry;
}
public void Enqueue(ClientEntry entry)
{
if (_disposedValue)
{
throw new ObjectDisposedException(nameof(ClientPool));
}
if (entry == null)
{
throw new ArgumentNullException(nameof(entry));
}
if (entry.Client.Client?.RemoteEndPoint?.Equals(_endpoint) != true)
{
throw new ArgumentException("Invalid endpoint.");
}
// TickCount swap will be fine here as the entry just gets disposed and we'll create a new one starting at 0+ again, totally fine...
if (_enablePool && entry.Client.Connected && entry.StartMillis + entry.MaxLiveTime >= (Environment.TickCount & int.MaxValue))
{
_clients.Enqueue(entry);
}
else
{
// dispose the client and don't keep a reference
entry.DisposeClient();
}
}
public bool TryDequeue(out ClientEntry entry)
{
if (_disposedValue)
{
throw new ObjectDisposedException(nameof(ClientPool));
}
bool result;
while (result = _clients.TryDequeue(out entry))
{
// validate the client before returning it
if (entry.Client.Connected && entry.StartMillis + entry.MaxLiveTime >= (Environment.TickCount & int.MaxValue))
{
break;
}
else
{
entry.DisposeClient();
}
}
return result;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var entry in _clients)
{
entry.DisposeClient();
}
_clients = new ConcurrentQueue<ClientEntry>();
}
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
public class ClientEntry
{
public ClientEntry(TcpClient client, IPEndPoint endpoint)
{
Client = client;
Endpoint = endpoint;
}
public void Connect()
{
if (!Client.Connected)
{
Client.Connect(Endpoint);
}
}
public Task ConnectAsync(CancellationToken cancellationToken)
{
if (!Client.Connected)
{
#if NET6_0_OR_GREATER
return Client.ConnectAsync(Endpoint, cancellationToken).AsTask();
#else
return Client.ConnectAsync(Endpoint.Address, Endpoint.Port);
#endif
}
return Task.CompletedTask;
}
public void DisposeClient()
{
try
{
Client.Dispose();
}
catch { }
}
public TcpClient Client { get; }
public IPEndPoint Endpoint { get; }
public int StartMillis { get; set; } = Environment.TickCount & int.MaxValue;
public int MaxLiveTime { get; set; } = 5000;
}
}
}
}