-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathNioUdpClient.java
More file actions
258 lines (229 loc) · 7.95 KB
/
Copy pathNioUdpClient.java
File metadata and controls
258 lines (229 loc) · 7.95 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
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.xbill.DNS.io.UdpIoClient;
@Slf4j
final class NioUdpClient extends NioClient implements UdpIoClient {
private final int ephemeralStart;
private final int ephemeralRange;
private final SecureRandom prng;
private final Queue<Transaction> registrationQueue = new ConcurrentLinkedQueue<>();
private final Queue<Transaction> pendingTransactions = new ConcurrentLinkedQueue<>();
NioUdpClient() {
// https://datatracker.ietf.org/doc/html/rfc6335#section-6
int ephemeralStartDefault = 49152;
int ephemeralEndDefault = 65535;
// Linux usually uses 32768-60999
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
ephemeralStartDefault = 32768;
ephemeralEndDefault = 60999;
}
ephemeralStart = Integer.getInteger("dnsjava.udp.ephemeral.start", ephemeralStartDefault);
int ephemeralEnd = Integer.getInteger("dnsjava.udp.ephemeral.end", ephemeralEndDefault);
ephemeralRange = ephemeralEnd - ephemeralStart;
if (Boolean.getBoolean("dnsjava.udp.ephemeral.use_ephemeral_port")) {
prng = null;
} else {
prng = new SecureRandom();
}
setRegistrationsTask(this::processPendingRegistrations, false);
setTimeoutTask(this::checkTransactionTimeouts, false);
setCloseTask(this::closeUdp, false);
}
private void processPendingRegistrations(Selector selector) {
while (!registrationQueue.isEmpty()) {
Transaction t = registrationQueue.poll();
if (t == null) {
continue;
}
try {
log.trace("Registering OP_READ for transaction with id {}", t.id);
t.channel.register(selector, SelectionKey.OP_READ, t);
t.send();
} catch (IOException e) {
t.completeExceptionally(e);
}
}
}
private void checkTransactionTimeouts() {
for (Iterator<Transaction> it = pendingTransactions.iterator(); it.hasNext(); ) {
Transaction t = it.next();
if (t.endTime - System.nanoTime() < 0) {
t.completeExceptionally(new SocketTimeoutException("Query timed out"));
it.remove();
}
}
}
@RequiredArgsConstructor
private final class Transaction implements KeyProcessor {
private final int id;
private final byte[] data;
private final int max;
private final long endTime;
private final DatagramChannel channel;
private final CompletableFuture<byte[]> f;
void send() throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(data);
verboseLog(
"UDP write: transaction id=" + id,
channel.socket().getLocalSocketAddress(),
channel.socket().getRemoteSocketAddress(),
data);
int n = channel.send(buffer, channel.socket().getRemoteSocketAddress());
if (n == 0) {
throw new EOFException(
"Insufficient room for the datagram in the underlying output buffer for transaction "
+ id);
} else if (n < data.length) {
throw new EOFException("Could not send all data for transaction " + id);
}
}
@Override
public void processReadyKey(SelectionKey key) {
if (!key.isValid()) {
completeExceptionally(new EOFException("Key for transaction " + id + " is invalid"));
pendingTransactions.remove(this);
return;
}
if (!key.isReadable()) {
completeExceptionally(new EOFException("Key for transaction " + id + " is not readable"));
pendingTransactions.remove(this);
key.cancel();
return;
}
DatagramChannel keyChannel = (DatagramChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(max);
int read;
try {
read = keyChannel.read(buffer);
if (read <= 0) {
throw new EOFException("Could not read expected data for transaction " + id);
}
} catch (IOException | NotYetConnectedException e) {
completeExceptionally(e);
pendingTransactions.remove(this);
key.cancel();
return;
}
buffer.flip();
byte[] resultingData = new byte[read];
System.arraycopy(buffer.array(), 0, resultingData, 0, read);
verboseLog(
"UDP read: transaction id=" + id,
keyChannel.socket().getLocalSocketAddress(),
keyChannel.socket().getRemoteSocketAddress(),
resultingData);
key.cancel();
silentDisconnectAndCloseChannel();
f.complete(resultingData);
pendingTransactions.remove(this);
}
private void completeExceptionally(Exception e) {
silentDisconnectAndCloseChannel();
f.completeExceptionally(e);
}
private void silentDisconnectAndCloseChannel() {
try {
channel.disconnect();
} catch (IOException e) {
// ignore, we either already have everything we need or can't do anything
} finally {
NioUdpClient.silentCloseChannel(channel);
}
}
}
@Override
public CompletableFuture<byte[]> sendAndReceiveUdp(
InetSocketAddress local,
InetSocketAddress remote,
Message query,
byte[] data,
int max,
Duration timeout) {
long endTime = System.nanoTime() + timeout.toNanos();
CompletableFuture<byte[]> f = new CompletableFuture<>();
DatagramChannel channel = null;
try {
final Selector selector = selector();
channel = DatagramChannel.open();
channel.configureBlocking(false);
Transaction t = new Transaction(query.getHeader().getID(), data, max, endTime, channel, f);
if (local == null || local.getPort() == 0) {
boolean bound = false;
for (int i = 0; i < 1024 && !bound; i++) {
bound = tryBindToSocket(local, channel);
}
if (!bound) {
t.completeExceptionally(new IOException("No available source port found"));
return f;
}
}
channel.connect(remote);
pendingTransactions.add(t);
registrationQueue.add(t);
selector.wakeup();
} catch (IOException e) {
silentCloseChannel(channel);
f.completeExceptionally(e);
} catch (Throwable e) {
// Make sure to close the channel, no matter what, but only handle the declared IOException
silentCloseChannel(channel);
throw e;
}
return f;
}
private boolean tryBindToSocket(InetSocketAddress local, DatagramChannel channel)
throws IOException {
try {
InetSocketAddress address = null;
if (local == null) {
if (prng != null) {
address = new InetSocketAddress(prng.nextInt(ephemeralRange) + ephemeralStart);
}
} else {
int port = local.getPort();
if (port == 0 && prng != null) {
port = prng.nextInt(ephemeralRange) + ephemeralStart;
}
address = new InetSocketAddress(local.getAddress(), port);
}
channel.bind(address);
return true;
} catch (SocketException e) {
// ignore, we'll try another random port
}
return false;
}
private static void silentCloseChannel(DatagramChannel channel) {
if (channel != null) {
try {
channel.close();
} catch (IOException ioe) {
// ignore
}
}
}
private void closeUdp() {
registrationQueue.clear();
EOFException closing = new EOFException("Client is closing");
pendingTransactions.forEach(t -> t.completeExceptionally(closing));
pendingTransactions.clear();
}
}