author | aefimov |
Thu, 14 Nov 2019 23:16:40 +0000 | |
branch | aefimov-dns-client-branch |
changeset 59101 | 258033faefc9 |
parent 58971 | 465a15dd6bed |
permissions | -rw-r--r-- |
58870 | 1 |
/* |
2 |
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. |
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Oracle designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Oracle in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
24 |
*/ |
|
25 |
||
26 |
package jdk.dns.client.internal; |
|
27 |
||
28 |
import jdk.dns.client.ex.DnsCommunicationException; |
|
29 |
import jdk.dns.client.ex.DnsNameNotFoundException; |
|
30 |
import jdk.dns.client.ex.DnsResolverException; |
|
31 |
||
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
32 |
import java.io.BufferedInputStream; |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
33 |
import java.io.BufferedOutputStream; |
58870 | 34 |
import java.io.IOException; |
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
35 |
import java.io.InputStream; |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
36 |
import java.io.OutputStream; |
58870 | 37 |
import java.net.DatagramPacket; |
38 |
import java.net.InetAddress; |
|
39 |
import java.net.InetSocketAddress; |
|
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
40 |
import java.net.PortUnreachableException; |
58870 | 41 |
import java.net.Socket; |
42 |
import java.net.SocketTimeoutException; |
|
43 |
import java.net.UnknownHostException; |
|
44 |
import java.nio.channels.DatagramChannel; |
|
45 |
import java.security.AccessController; |
|
46 |
import java.security.PrivilegedAction; |
|
47 |
import java.security.SecureRandom; |
|
48 |
import java.util.ArrayList; |
|
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
49 |
import java.util.Arrays; |
58870 | 50 |
import java.util.Collections; |
51 |
import java.util.HashMap; |
|
52 |
import java.util.List; |
|
53 |
import java.util.Map; |
|
54 |
import java.util.concurrent.locks.ReentrantLock; |
|
55 |
||
56 |
import sun.net.util.IPAddressUtil; |
|
57 |
import sun.security.jca.JCAUtil; |
|
58 |
||
59 |
// Some of this code began life as part of sun.javaos.net.DnsClient |
|
60 |
// originally by sritchie@eng 1/96. It was first hacked up for JNDI |
|
61 |
// use by caveh@eng 6/97. |
|
62 |
||
63 |
||
64 |
/** |
|
65 |
* The DnsClient class performs DNS client operations in support of DnsContext. |
|
66 |
*/ |
|
67 |
||
68 |
public class DnsClient { |
|
69 |
||
70 |
// DNS packet header field offsets |
|
71 |
private static final int IDENT_OFFSET = 0; |
|
72 |
private static final int FLAGS_OFFSET = 2; |
|
73 |
private static final int NUMQ_OFFSET = 4; |
|
74 |
private static final int NUMANS_OFFSET = 6; |
|
75 |
private static final int NUMAUTH_OFFSET = 8; |
|
76 |
private static final int NUMADD_OFFSET = 10; |
|
77 |
private static final int DNS_HDR_SIZE = 12; |
|
78 |
||
79 |
// DNS response codes |
|
80 |
private static final int NO_ERROR = 0; |
|
81 |
private static final int FORMAT_ERROR = 1; |
|
82 |
private static final int SERVER_FAILURE = 2; |
|
83 |
private static final int NAME_ERROR = 3; |
|
84 |
private static final int NOT_IMPL = 4; |
|
85 |
private static final int REFUSED = 5; |
|
86 |
||
87 |
private static final String[] rcodeDescription = { |
|
88 |
"No error", |
|
89 |
"DNS format error", |
|
90 |
"DNS server failure", |
|
91 |
"DNS name not found", |
|
92 |
"DNS operation not supported", |
|
93 |
"DNS service refused" |
|
94 |
}; |
|
95 |
||
96 |
private static final int DEFAULT_PORT = 53; |
|
97 |
private static final int TRANSACTION_ID_BOUND = 0x10000; |
|
98 |
private List<InetAddress> servers; |
|
99 |
private List<Integer> serverPorts; |
|
100 |
private int timeout; // initial timeout on UDP and TCP queries in ms |
|
101 |
private int retries; // number of UDP retries |
|
102 |
||
103 |
private static final SecureRandom random; |
|
104 |
||
105 |
static { |
|
106 |
var pa = (PrivilegedAction<SecureRandom>) () -> JCAUtil.getSecureRandom(); |
|
107 |
random = System.getSecurityManager() == null ? pa.run() |
|
108 |
: AccessController.doPrivileged(pa); |
|
109 |
} |
|
110 |
||
111 |
private static final DnsDatagramChannelFactory factory = |
|
112 |
new DnsDatagramChannelFactory(random); |
|
113 |
||
114 |
// Requests sent |
|
115 |
private Map<Integer, ResourceRecord> reqs; |
|
116 |
||
117 |
// Responses received |
|
118 |
private Map<Integer, byte[]> resps; |
|
119 |
||
120 |
//------------------------------------------------------------------------- |
|
121 |
||
122 |
/* |
|
123 |
* Each server is of the form "server[:port]". IPv6 literal host names |
|
124 |
* include delimiting brackets. |
|
125 |
* "timeout" is the initial timeout interval (in ms) for queries, |
|
126 |
* and "retries" gives the number of retries per server. |
|
127 |
*/ |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
128 |
public DnsClient(List<String> servers, int timeout, int retries) { |
58870 | 129 |
this.timeout = timeout; |
130 |
this.retries = retries; |
|
131 |
var serversList = new ArrayList<InetAddress>(); |
|
132 |
var serverPortsList = new ArrayList<Integer>(); |
|
133 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
134 |
if (DEBUG) { |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
135 |
System.err.println("DNS Client: servers list:" + servers); |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
136 |
} |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
137 |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
138 |
for (String serverString : servers) { |
58870 | 139 |
|
140 |
// Is optional port given? |
|
141 |
int colon = serverString.indexOf(':', |
|
142 |
serverString.indexOf(']') + 1); |
|
143 |
||
144 |
int serverPort = (colon < 0) ? DEFAULT_PORT |
|
145 |
: Integer.parseInt(serverString.substring(colon + 1)); |
|
146 |
String server = (colon < 0) |
|
147 |
? serverString |
|
148 |
: serverString.substring(0, colon); |
|
149 |
||
150 |
var pa = (PrivilegedAction<byte[]>) () -> { |
|
151 |
if (IPAddressUtil.isIPv4LiteralAddress(server)) { |
|
152 |
return IPAddressUtil.textToNumericFormatV4(server); |
|
153 |
} else if (IPAddressUtil.isIPv6LiteralAddress(server)) { |
|
154 |
return IPAddressUtil.textToNumericFormatV6(server); |
|
155 |
} |
|
156 |
return null; |
|
157 |
}; |
|
158 |
byte[] addr = System.getSecurityManager() == null ? |
|
159 |
pa.run() : AccessController.doPrivileged(pa); |
|
160 |
if (addr != null) { |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
161 |
try { |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
162 |
serversList.add(InetAddress.getByAddress(server, addr)); |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
163 |
serverPortsList.add(serverPort); |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
164 |
} catch (UnknownHostException e) { |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
165 |
// Malformed IP address is specified - will ignore it |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
166 |
} |
58870 | 167 |
} |
168 |
} |
|
169 |
this.servers = Collections.unmodifiableList(serversList); |
|
170 |
this.serverPorts = Collections.unmodifiableList(serverPortsList); |
|
171 |
reqs = Collections.synchronizedMap( |
|
172 |
new HashMap<>()); |
|
173 |
resps = Collections.synchronizedMap(new HashMap<>()); |
|
174 |
} |
|
175 |
||
176 |
DatagramChannel getDatagramChannel() throws DnsResolverException { |
|
177 |
try { |
|
178 |
return factory.open(); |
|
179 |
} catch (java.net.SocketException e) { |
|
180 |
throw new DnsResolverException("Can't create datagram channel", e); |
|
181 |
} |
|
182 |
} |
|
183 |
||
184 |
@SuppressWarnings("deprecation") |
|
185 |
protected void finalize() { |
|
186 |
close(); |
|
187 |
} |
|
188 |
||
189 |
// A lock to access the request and response queues in tandem. |
|
190 |
private ReentrantLock queuesLock = new ReentrantLock(); |
|
191 |
||
192 |
public void close() { |
|
193 |
queuesLock.lock(); |
|
194 |
try { |
|
195 |
reqs.clear(); |
|
196 |
resps.clear(); |
|
197 |
} finally { |
|
198 |
queuesLock.unlock(); |
|
199 |
} |
|
200 |
} |
|
201 |
||
202 |
/* |
|
203 |
* If recursion is true, recursion is requested on the query. |
|
204 |
* If auth is true, only authoritative responses are accepted; other |
|
205 |
* responses throw NameNotFoundException. |
|
206 |
*/ |
|
207 |
ResourceRecords query(DnsName fqdn, int qclass, int qtype, |
|
208 |
boolean recursion, boolean auth) |
|
209 |
throws DnsResolverException { |
|
210 |
||
211 |
int xid; |
|
212 |
Packet pkt; |
|
213 |
ResourceRecord collision; |
|
214 |
||
215 |
do { |
|
216 |
// Generate a random transaction ID |
|
217 |
xid = random.nextInt(TRANSACTION_ID_BOUND); |
|
218 |
pkt = makeQueryPacket(fqdn, xid, qclass, qtype, recursion); |
|
219 |
||
220 |
// enqueue the outstanding request |
|
221 |
collision = reqs.putIfAbsent(xid, new ResourceRecord(pkt.getData(), |
|
222 |
pkt.length(), Header.HEADER_SIZE, true, false)); |
|
223 |
||
224 |
} while (collision != null); |
|
225 |
||
226 |
Exception caughtException = null; |
|
227 |
boolean[] doNotRetry = new boolean[servers.size()]; |
|
228 |
||
229 |
try { |
|
230 |
// |
|
231 |
// The UDP retry strategy is to try the 1st server, and then |
|
232 |
// each server in order. If no answer, double the timeout |
|
233 |
// and try each server again. |
|
234 |
// |
|
235 |
for (int retry = 0; retry < retries; retry++) { |
|
236 |
||
237 |
// Try each name server. |
|
238 |
for (int i = 0; i < servers.size(); i++) { |
|
239 |
if (doNotRetry[i]) { |
|
240 |
continue; |
|
241 |
} |
|
242 |
||
243 |
// send the request packet and wait for a response. |
|
244 |
try { |
|
245 |
if (DEBUG) { |
|
246 |
dprint("SEND ID (" + (retry + 1) + "): " + xid); |
|
247 |
} |
|
248 |
||
249 |
byte[] msg = doUdpQuery(pkt, servers.get(i), serverPorts.get(i), retry, xid); |
|
250 |
// |
|
251 |
// If the matching response is not got within the |
|
252 |
// given timeout, check if the response was enqueued |
|
253 |
// by some other thread, if not proceed with the next |
|
254 |
// server or retry. |
|
255 |
// |
|
256 |
if (msg == null) { |
|
257 |
if (resps.size() > 0) { |
|
258 |
msg = lookupResponse(xid); |
|
259 |
} |
|
260 |
if (msg == null) { // try next server or retry |
|
261 |
continue; |
|
262 |
} |
|
263 |
} |
|
264 |
Header hdr = new Header(msg, msg.length); |
|
265 |
||
266 |
if (auth && !hdr.authoritative) { |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
267 |
caughtException = new DnsResolverException("DNS response not authoritative"); |
58870 | 268 |
doNotRetry[i] = true; |
269 |
continue; |
|
270 |
} |
|
271 |
if (hdr.truncated) { // message is truncated -- try TCP |
|
272 |
||
273 |
// Try each server, starting with the one that just |
|
274 |
// provided the truncated message. |
|
275 |
int retryTimeout = (timeout * (1 << retry)); |
|
276 |
for (int j = 0; j < servers.size(); j++) { |
|
277 |
int ij = (i + j) % servers.size(); |
|
278 |
if (doNotRetry[ij]) { |
|
279 |
continue; |
|
280 |
} |
|
281 |
try { |
|
282 |
Tcp tcp = |
|
283 |
new Tcp(servers.get(ij), serverPorts.get(ij), retryTimeout); |
|
284 |
byte[] msg2; |
|
285 |
try { |
|
286 |
msg2 = doTcpQuery(tcp, pkt); |
|
287 |
} finally { |
|
288 |
tcp.close(); |
|
289 |
} |
|
290 |
Header hdr2 = new Header(msg2, msg2.length); |
|
291 |
if (hdr2.query) { |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
292 |
throw new DnsResolverException( |
58870 | 293 |
"DNS error: expecting response"); |
294 |
} |
|
295 |
checkResponseCode(hdr2); |
|
296 |
||
297 |
if (!auth || hdr2.authoritative) { |
|
298 |
// Got a valid response |
|
299 |
hdr = hdr2; |
|
300 |
msg = msg2; |
|
301 |
break; |
|
302 |
} else { |
|
303 |
doNotRetry[ij] = true; |
|
304 |
} |
|
305 |
} catch (Exception e) { |
|
306 |
// Try next server, or use UDP response |
|
307 |
} |
|
308 |
} // servers |
|
309 |
} |
|
310 |
return new ResourceRecords(msg, msg.length, hdr, false); |
|
311 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
312 |
} catch (PortUnreachableException e) { |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
313 |
if (caughtException == null) { |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
314 |
caughtException = e; |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
315 |
} |
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
316 |
doNotRetry[i] = true; |
58870 | 317 |
} catch (IOException e) { |
318 |
if (DEBUG) { |
|
319 |
dprint("Caught IOException:" + e); |
|
320 |
} |
|
321 |
if (caughtException == null) { |
|
322 |
caughtException = e; |
|
323 |
} |
|
324 |
} catch (DnsNameNotFoundException e) { |
|
325 |
// This is authoritative, so return immediately |
|
326 |
throw e; |
|
327 |
} catch (DnsCommunicationException e) { |
|
328 |
if (caughtException == null) { |
|
329 |
caughtException = e; |
|
330 |
} |
|
331 |
} catch (DnsResolverException e) { |
|
332 |
if (caughtException == null) { |
|
333 |
caughtException = e; |
|
334 |
} |
|
335 |
doNotRetry[i] = true; |
|
336 |
} |
|
337 |
} // servers |
|
338 |
} // retries |
|
339 |
||
340 |
} finally { |
|
341 |
reqs.remove(xid); // cleanup |
|
342 |
} |
|
343 |
||
344 |
if (caughtException instanceof DnsResolverException) { |
|
345 |
throw (DnsResolverException) caughtException; |
|
346 |
} |
|
347 |
// A network timeout or other error occurred. |
|
348 |
throw new DnsResolverException("DNS error", caughtException); |
|
349 |
} |
|
350 |
||
351 |
/** |
|
352 |
* Tries to retrieve a UDP packet matching the given xid |
|
353 |
* received within the timeout. |
|
354 |
* If a packet with different xid is received, the received packet |
|
355 |
* is enqueued with the corresponding xid in 'resps'. |
|
356 |
*/ |
|
357 |
private byte[] doUdpQuery(Packet pkt, InetAddress server, |
|
358 |
int port, int retry, int xid) |
|
359 |
throws IOException, DnsResolverException { |
|
360 |
||
361 |
int minTimeout = 50; // msec after which there are no retries. |
|
362 |
||
363 |
||
364 |
try (DatagramChannel dc = getDatagramChannel()) { |
|
365 |
DatagramPacket opkt = new DatagramPacket(pkt.getData(), pkt.length(), server, port); |
|
366 |
DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000); |
|
367 |
// Packets may only be sent to or received from this server address |
|
368 |
// TODO: Revisit |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
369 |
var pa = (PrivilegedAction<Void>) () -> { |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
370 |
dc.socket().connect(server, port); |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
371 |
return null; |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
372 |
}; |
58870 | 373 |
if (System.getSecurityManager() == null) { |
374 |
pa.run(); |
|
375 |
} else { |
|
376 |
AccessController.doPrivileged(pa); |
|
377 |
} |
|
378 |
||
379 |
||
380 |
int pktTimeout = (timeout * (1 << retry)); |
|
381 |
try { |
|
382 |
dc.socket().send(opkt); |
|
383 |
||
384 |
// timeout remaining after successive 'receive()' |
|
385 |
int timeoutLeft = pktTimeout; |
|
386 |
int cnt = 0; |
|
387 |
do { |
|
388 |
if (DEBUG) { |
|
389 |
cnt++; |
|
390 |
dprint("Trying RECEIVE(" + |
|
391 |
cnt + ") retry(" + (retry + 1) + |
|
392 |
") for:" + xid + " sock-timeout:" + |
|
393 |
timeoutLeft + " ms."); |
|
394 |
} |
|
395 |
dc.socket().setSoTimeout(timeoutLeft); |
|
396 |
long start = System.currentTimeMillis(); |
|
397 |
||
398 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
399 |
dc.socket().receive(ipkt); |
58870 | 400 |
byte[] data = ipkt.getData(); |
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
401 |
int length = ipkt.getLength(); |
58870 | 402 |
long end = System.currentTimeMillis(); |
403 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
404 |
if (isMatchResponse(data, length, xid)) { |
58870 | 405 |
return data; |
406 |
} |
|
407 |
timeoutLeft = pktTimeout - ((int) (end - start)); |
|
408 |
} while (timeoutLeft > minTimeout); |
|
409 |
||
410 |
} finally { |
|
411 |
dc.disconnect(); |
|
412 |
} |
|
413 |
return null; // no matching packet received within the timeout |
|
414 |
} |
|
415 |
} |
|
416 |
||
417 |
/* |
|
418 |
* Sends a TCP query, and returns the first DNS message in the response. |
|
419 |
*/ |
|
420 |
private byte[] doTcpQuery(Tcp tcp, Packet pkt) throws IOException { |
|
421 |
||
422 |
int len = pkt.length(); |
|
423 |
// Send 2-byte message length, then send message. |
|
424 |
tcp.out.write(len >> 8); |
|
425 |
tcp.out.write(len); |
|
426 |
tcp.out.write(pkt.getData(), 0, len); |
|
427 |
tcp.out.flush(); |
|
428 |
||
429 |
byte[] msg = continueTcpQuery(tcp); |
|
430 |
if (msg == null) { |
|
431 |
throw new IOException("DNS error: no response"); |
|
432 |
} |
|
433 |
return msg; |
|
434 |
} |
|
435 |
||
436 |
/* |
|
437 |
* Returns the next DNS message from the TCP socket, or null on EOF. |
|
438 |
*/ |
|
439 |
private byte[] continueTcpQuery(Tcp tcp) throws IOException { |
|
440 |
||
441 |
int lenHi = tcp.read(); // high-order byte of response length |
|
442 |
if (lenHi == -1) { |
|
443 |
return null; // EOF |
|
444 |
} |
|
445 |
int lenLo = tcp.read(); // low-order byte of response length |
|
446 |
if (lenLo == -1) { |
|
447 |
throw new IOException("Corrupted DNS response: bad length"); |
|
448 |
} |
|
449 |
int len = (lenHi << 8) | lenLo; |
|
450 |
byte[] msg = new byte[len]; |
|
451 |
int pos = 0; // next unfilled position in msg |
|
452 |
while (len > 0) { |
|
453 |
int n = tcp.read(msg, pos, len); |
|
454 |
if (n == -1) { |
|
455 |
throw new IOException( |
|
456 |
"Corrupted DNS response: too little data"); |
|
457 |
} |
|
458 |
len -= n; |
|
459 |
pos += n; |
|
460 |
} |
|
461 |
return msg; |
|
462 |
} |
|
463 |
||
464 |
private Packet makeQueryPacket(DnsName fqdn, int xid, |
|
465 |
int qclass, int qtype, boolean recursion) { |
|
466 |
int qnameLen = fqdn.getOctets(); |
|
467 |
int pktLen = DNS_HDR_SIZE + qnameLen + 4; |
|
468 |
Packet pkt = new Packet(pktLen); |
|
469 |
||
470 |
short flags = recursion ? Header.RD_BIT : 0; |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
471 |
// flags = (short) (flags | Header.CD_BIT | Header.AD_BIT); |
58870 | 472 |
|
473 |
pkt.putShort(xid, IDENT_OFFSET); |
|
474 |
pkt.putShort(flags, FLAGS_OFFSET); |
|
475 |
pkt.putShort(1, NUMQ_OFFSET); |
|
476 |
pkt.putShort(0, NUMANS_OFFSET); |
|
477 |
pkt.putInt(0, NUMAUTH_OFFSET); |
|
478 |
||
479 |
makeQueryName(fqdn, pkt, DNS_HDR_SIZE); |
|
480 |
pkt.putShort(qtype, DNS_HDR_SIZE + qnameLen); |
|
481 |
pkt.putShort(qclass, DNS_HDR_SIZE + qnameLen + 2); |
|
482 |
||
483 |
return pkt; |
|
484 |
} |
|
485 |
||
486 |
// Builds a query name in pkt according to the RFC spec. |
|
487 |
private void makeQueryName(DnsName fqdn, Packet pkt, int off) { |
|
488 |
||
489 |
// Loop through labels, least-significant first. |
|
490 |
for (int i = fqdn.size() - 1; i >= 0; i--) { |
|
491 |
String label = fqdn.get(i); |
|
492 |
int len = label.length(); |
|
493 |
||
494 |
pkt.putByte(len, off++); |
|
495 |
for (int j = 0; j < len; j++) { |
|
496 |
pkt.putByte(label.charAt(j), off++); |
|
497 |
} |
|
498 |
} |
|
499 |
if (!fqdn.hasRootLabel()) { |
|
500 |
pkt.putByte(0, off); |
|
501 |
} |
|
502 |
} |
|
503 |
||
504 |
//------------------------------------------------------------------------- |
|
505 |
||
506 |
private byte[] lookupResponse(Integer xid) throws DnsResolverException { |
|
507 |
// |
|
508 |
// Check the queued responses: some other thread in between |
|
509 |
// received the response for this request. |
|
510 |
// |
|
511 |
if (DEBUG) { |
|
512 |
dprint("LOOKUP for: " + xid + |
|
513 |
"\tResponse Q:" + resps); |
|
514 |
} |
|
515 |
byte[] pkt; |
|
516 |
if ((pkt = resps.get(xid)) != null) { |
|
517 |
checkResponseCode(new Header(pkt, pkt.length)); |
|
518 |
queuesLock.lock(); |
|
519 |
try { |
|
520 |
resps.remove(xid); |
|
521 |
reqs.remove(xid); |
|
522 |
} finally { |
|
523 |
queuesLock.unlock(); |
|
524 |
} |
|
525 |
||
526 |
if (DEBUG) { |
|
527 |
dprint("FOUND (" + Thread.currentThread() + |
|
528 |
") for:" + xid); |
|
529 |
} |
|
530 |
} |
|
531 |
return pkt; |
|
532 |
} |
|
533 |
||
534 |
/* |
|
535 |
* Checks the header of an incoming DNS response. |
|
536 |
* Returns true if it matches the given xid and throws a naming |
|
537 |
* exception, if appropriate, based on the response code. |
|
538 |
* |
|
539 |
* Also checks that the domain name, type and class in the response |
|
540 |
* match those in the original query. |
|
541 |
*/ |
|
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
542 |
private boolean isMatchResponse(byte[] pkt, int length, int xid) |
58870 | 543 |
throws DnsResolverException { |
544 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
545 |
Header hdr = new Header(pkt, length); |
58870 | 546 |
if (hdr.query) { |
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
547 |
throw new DnsResolverException("DNS error: expecting response"); |
58870 | 548 |
} |
549 |
||
550 |
if (!reqs.containsKey(xid)) { // already received, ignore the response |
|
551 |
return false; |
|
552 |
} |
|
553 |
||
554 |
// common case- the request sent matches the subsequent response read |
|
555 |
if (hdr.xid == xid) { |
|
556 |
if (DEBUG) { |
|
557 |
dprint("XID MATCH:" + xid); |
|
558 |
} |
|
559 |
checkResponseCode(hdr); |
|
560 |
if (!hdr.query && hdr.numQuestions == 1) { |
|
561 |
||
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
562 |
ResourceRecord rr = new ResourceRecord(pkt, length, |
58870 | 563 |
Header.HEADER_SIZE, true, false); |
564 |
||
565 |
// Retrieve the original query |
|
566 |
ResourceRecord query = reqs.get(xid); |
|
567 |
int qtype = query.getType(); |
|
568 |
int qclass = query.getRrclass(); |
|
569 |
DnsName qname = query.getName(); |
|
570 |
||
571 |
// Check that the type/class/name in the query section of the |
|
572 |
// response match those in the original query |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
573 |
if ((qtype == ResourceRecord.TYPE_ANY || |
58870 | 574 |
qtype == rr.getType()) && |
575 |
(qclass == ResourceRecord.QCLASS_STAR || |
|
576 |
qclass == rr.getRrclass()) && |
|
577 |
qname.equals(rr.getName())) { |
|
578 |
||
579 |
if (DEBUG) { |
|
580 |
dprint("MATCH NAME:" + qname + " QTYPE:" + qtype + |
|
581 |
" QCLASS:" + qclass); |
|
582 |
} |
|
583 |
||
584 |
// Remove the response for the xid if received by some other |
|
585 |
// thread. |
|
586 |
queuesLock.lock(); |
|
587 |
try { |
|
588 |
resps.remove(xid); |
|
589 |
reqs.remove(xid); |
|
590 |
} finally { |
|
591 |
queuesLock.unlock(); |
|
592 |
} |
|
593 |
return true; |
|
594 |
||
595 |
} else { |
|
596 |
if (DEBUG) { |
|
597 |
dprint("NO-MATCH NAME:" + qname + " QTYPE:" + qtype + |
|
598 |
" QCLASS:" + qclass); |
|
599 |
} |
|
600 |
} |
|
601 |
} |
|
602 |
return false; |
|
603 |
} |
|
604 |
||
605 |
// |
|
606 |
// xid mis-match: enqueue the response, it may belong to some other |
|
607 |
// thread that has not yet had a chance to read its response. |
|
608 |
// enqueue only the first response, responses for retries are ignored. |
|
609 |
// |
|
610 |
queuesLock.lock(); |
|
611 |
try { |
|
612 |
if (reqs.containsKey(hdr.xid)) { // enqueue only the first response |
|
59101
258033faefc9
aefimov-dns-client-branch: Fix timeouts, add platform specific file locations
aefimov
parents:
58971
diff
changeset
|
613 |
resps.put(hdr.xid, Arrays.copyOf(pkt, length)); |
58870 | 614 |
} |
615 |
} finally { |
|
616 |
queuesLock.unlock(); |
|
617 |
} |
|
618 |
||
619 |
if (DEBUG) { |
|
620 |
dprint("NO-MATCH SEND ID:" + |
|
621 |
xid + " RECVD ID:" + hdr.xid + |
|
622 |
" Response Q:" + resps + |
|
623 |
" Reqs size:" + reqs.size()); |
|
624 |
} |
|
625 |
return false; |
|
626 |
} |
|
627 |
||
628 |
/* |
|
629 |
* Throws an exception if appropriate for the response code of a |
|
630 |
* given header. |
|
631 |
*/ |
|
632 |
private void checkResponseCode(Header hdr) throws DnsResolverException { |
|
633 |
||
634 |
int rcode = hdr.rcode; |
|
635 |
if (rcode == NO_ERROR) { |
|
636 |
return; |
|
637 |
} |
|
638 |
String msg = (rcode < rcodeDescription.length) |
|
639 |
? rcodeDescription[rcode] |
|
640 |
: "DNS error"; |
|
641 |
||
642 |
msg += " [response code " + rcode + "]"; |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
643 |
throw new DnsResolverException(msg); |
58870 | 644 |
} |
645 |
||
646 |
//------------------------------------------------------------------------- |
|
647 |
||
648 |
private static final boolean DEBUG = java.security.AccessController.doPrivileged( |
|
649 |
(PrivilegedAction<Boolean>) () -> Boolean.getBoolean("jdk.dns.client.debug")); |
|
650 |
||
651 |
private static void dprint(String mess) { |
|
652 |
if (DEBUG) { |
|
653 |
System.err.println("DNS: " + mess); |
|
654 |
} |
|
655 |
} |
|
656 |
||
657 |
} |
|
658 |
||
659 |
class Tcp { |
|
660 |
||
661 |
private final Socket sock; |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
662 |
private final InputStream in; |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
663 |
final OutputStream out; |
58870 | 664 |
private int timeoutLeft; |
665 |
||
666 |
Tcp(InetAddress server, int port, int timeout) throws IOException { |
|
667 |
sock = new Socket(); |
|
668 |
try { |
|
669 |
long start = System.currentTimeMillis(); |
|
670 |
sock.connect(new InetSocketAddress(server, port), timeout); |
|
671 |
timeoutLeft = (int) (timeout - (System.currentTimeMillis() - start)); |
|
672 |
if (timeoutLeft <= 0) |
|
673 |
throw new SocketTimeoutException(); |
|
674 |
||
675 |
sock.setTcpNoDelay(true); |
|
58971
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
676 |
out = new BufferedOutputStream(sock.getOutputStream()); |
465a15dd6bed
aefimov-dns-client-branch: Cleanup and address ANY type failures
aefimov
parents:
58870
diff
changeset
|
677 |
in = new BufferedInputStream(sock.getInputStream()); |
58870 | 678 |
} catch (Exception e) { |
679 |
try { |
|
680 |
sock.close(); |
|
681 |
} catch (IOException ex) { |
|
682 |
e.addSuppressed(ex); |
|
683 |
} |
|
684 |
throw e; |
|
685 |
} |
|
686 |
} |
|
687 |
||
688 |
void close() throws IOException { |
|
689 |
sock.close(); |
|
690 |
} |
|
691 |
||
692 |
private interface SocketReadOp { |
|
693 |
int read() throws IOException; |
|
694 |
} |
|
695 |
||
696 |
private int readWithTimeout(SocketReadOp reader) throws IOException { |
|
697 |
if (timeoutLeft <= 0) |
|
698 |
throw new SocketTimeoutException(); |
|
699 |
||
700 |
sock.setSoTimeout(timeoutLeft); |
|
701 |
long start = System.currentTimeMillis(); |
|
702 |
try { |
|
703 |
return reader.read(); |
|
704 |
} finally { |
|
705 |
timeoutLeft -= System.currentTimeMillis() - start; |
|
706 |
} |
|
707 |
} |
|
708 |
||
709 |
int read() throws IOException { |
|
710 |
return readWithTimeout(in::read); |
|
711 |
} |
|
712 |
||
713 |
int read(byte b[], int off, int len) throws IOException { |
|
714 |
return readWithTimeout(() -> in.read(b, off, len)); |
|
715 |
} |
|
716 |
} |
|
717 |
||
718 |
/* |
|
719 |
* javaos emulation -cj |
|
720 |
*/ |
|
721 |
class Packet { |
|
722 |
byte[] buf; |
|
723 |
||
724 |
Packet(int len) { |
|
725 |
buf = new byte[len]; |
|
726 |
} |
|
727 |
||
728 |
Packet(byte data[], int len) { |
|
729 |
buf = new byte[len]; |
|
730 |
System.arraycopy(data, 0, buf, 0, len); |
|
731 |
} |
|
732 |
||
733 |
void putInt(int x, int off) { |
|
734 |
buf[off] = (byte) (x >> 24); |
|
735 |
buf[off + 1] = (byte) (x >> 16); |
|
736 |
buf[off + 2] = (byte) (x >> 8); |
|
737 |
buf[off + 3] = (byte) x; |
|
738 |
} |
|
739 |
||
740 |
void putShort(int x, int off) { |
|
741 |
buf[off] = (byte) (x >> 8); |
|
742 |
buf[off + 1] = (byte) x; |
|
743 |
} |
|
744 |
||
745 |
void putByte(int x, int off) { |
|
746 |
buf[off] = (byte) x; |
|
747 |
} |
|
748 |
||
749 |
void putBytes(byte src[], int src_offset, int dst_offset, int len) { |
|
750 |
System.arraycopy(src, src_offset, buf, dst_offset, len); |
|
751 |
} |
|
752 |
||
753 |
int length() { |
|
754 |
return buf.length; |
|
755 |
} |
|
756 |
||
757 |
byte[] getData() { |
|
758 |
return buf; |
|
759 |
} |
|
760 |
} |