1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.resolver.dns;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.channel.AddressedEnvelope;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.ChannelFutureListener;
23 import io.netty.channel.ChannelHandlerContext;
24 import io.netty.channel.ChannelInboundHandlerAdapter;
25 import io.netty.channel.ChannelPromise;
26 import io.netty.handler.codec.dns.AbstractDnsOptPseudoRrRecord;
27 import io.netty.handler.codec.dns.DefaultDnsOptCookieRecord;
28 import io.netty.handler.codec.dns.DnsQuery;
29 import io.netty.handler.codec.dns.DnsQuestion;
30 import io.netty.handler.codec.dns.DnsRecord;
31 import io.netty.handler.codec.dns.DnsRecordType;
32 import io.netty.handler.codec.dns.DnsResponse;
33 import io.netty.handler.codec.dns.DnsSection;
34 import io.netty.handler.codec.dns.TcpDnsQueryEncoder;
35 import io.netty.handler.codec.dns.TcpDnsResponseDecoder;
36 import io.netty.util.ReferenceCountUtil;
37 import io.netty.util.concurrent.Future;
38 import io.netty.util.concurrent.FutureListener;
39 import io.netty.util.concurrent.Promise;
40 import io.netty.util.internal.SystemPropertyUtil;
41 import io.netty.util.internal.ThrowableUtil;
42 import io.netty.util.internal.logging.InternalLogger;
43 import io.netty.util.internal.logging.InternalLoggerFactory;
44
45 import java.net.InetSocketAddress;
46 import java.net.SocketAddress;
47 import java.util.concurrent.CancellationException;
48 import java.util.concurrent.TimeUnit;
49
50 import static io.netty.util.internal.ObjectUtil.checkNotNull;
51
52 abstract class DnsQueryContext {
53
54 private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsQueryContext.class);
55 private static final long ID_REUSE_ON_TIMEOUT_DELAY_MILLIS;
56
57 static {
58 ID_REUSE_ON_TIMEOUT_DELAY_MILLIS =
59 SystemPropertyUtil.getLong("io.netty.resolver.dns.idReuseOnTimeoutDelayMillis", 10000);
60 logger.debug("-Dio.netty.resolver.dns.idReuseOnTimeoutDelayMillis: {}", ID_REUSE_ON_TIMEOUT_DELAY_MILLIS);
61 }
62
63 private static final TcpDnsQueryEncoder TCP_ENCODER = new TcpDnsQueryEncoder();
64
65 private final Channel channel;
66 private final InetSocketAddress nameServerAddr;
67 private final DnsQueryContextManager queryContextManager;
68 private final Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise;
69
70 private final DnsQuestion question;
71
72
73 private final DnsQuestion wireQuestion;
74
75 private final boolean exactCaseMatch;
76 private final DnsRecord[] additionals;
77 private final DnsRecord optResource;
78 private final DnsQueryProtection protection;
79
80 private final byte[] clientCookie;
81
82 private final boolean recursionDesired;
83
84 private final Bootstrap socketBootstrap;
85
86 private final boolean retryWithTcpOnTimeout;
87 private final long queryTimeoutMillis;
88
89 private volatile Future<?> timeoutFuture;
90
91 private int id = Integer.MIN_VALUE;
92
93 DnsQueryContext(Channel channel,
94 InetSocketAddress nameServerAddr,
95 DnsQueryContextManager queryContextManager,
96 int maxPayLoadSize,
97 boolean recursionDesired,
98 long queryTimeoutMillis,
99 DnsQuestion question,
100 DnsQuestion wireQuestion,
101 DnsRecord[] additionals,
102 Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise,
103 Bootstrap socketBootstrap,
104 boolean retryWithTcpOnTimeout,
105 DnsQueryProtection protection) {
106 this.channel = checkNotNull(channel, "channel");
107 this.queryContextManager = checkNotNull(queryContextManager, "queryContextManager");
108 this.nameServerAddr = checkNotNull(nameServerAddr, "nameServerAddr");
109 this.question = checkNotNull(question, "question");
110 this.protection = protection;
111 DnsQuestion wireQ = wireQuestion;
112 if (wireQ == null && protection != null && protection.isCaseRandomizationEnabled()) {
113 wireQ = protection.randomizeCase(question);
114 }
115 this.exactCaseMatch = wireQ != null;
116 this.wireQuestion = wireQ != null ? wireQ : question;
117 this.additionals = checkNotNull(additionals, "additionals");
118 this.promise = checkNotNull(promise, "promise");
119 this.recursionDesired = recursionDesired;
120 this.queryTimeoutMillis = queryTimeoutMillis;
121 this.socketBootstrap = socketBootstrap;
122 this.retryWithTcpOnTimeout = retryWithTcpOnTimeout;
123
124 if (maxPayLoadSize > 0 &&
125
126
127
128 !hasOptRecord(additionals)) {
129 if (protection != null && protection.isCookiesEnabled()) {
130 clientCookie = protection.newClientCookie();
131 optResource = new DefaultDnsOptCookieRecord(maxPayLoadSize, clientCookie);
132 } else {
133 clientCookie = null;
134 optResource = new AbstractDnsOptPseudoRrRecord(maxPayLoadSize, 0, 0) {
135
136
137 };
138 }
139 } else {
140 clientCookie = null;
141 optResource = null;
142 }
143 }
144
145 private static boolean hasOptRecord(DnsRecord[] additionals) {
146 if (additionals != null && additionals.length > 0) {
147 for (DnsRecord additional: additionals) {
148 if (additional.type() == DnsRecordType.OPT) {
149 return true;
150 }
151 }
152 }
153 return false;
154 }
155
156
157
158
159
160
161 final boolean isDone() {
162 return promise.isDone();
163 }
164
165
166
167
168
169
170 final DnsQuestion question() {
171 return question;
172 }
173
174
175
176
177
178
179
180 final DnsQuestion wireQuestion() {
181 return wireQuestion;
182 }
183
184
185
186
187
188
189
190
191 protected abstract DnsQuery newQuery(int id, InetSocketAddress nameServerAddr);
192
193
194
195
196
197
198 protected abstract String protocol();
199
200
201
202
203
204
205
206 final ChannelFuture writeQuery(boolean flush) {
207 assert id == Integer.MIN_VALUE : this.getClass().getSimpleName() +
208 ".writeQuery(...) can only be executed once.";
209
210 if ((id = queryContextManager.add(nameServerAddr, this)) == -1) {
211
212 IllegalStateException e = new IllegalStateException("query ID space exhausted: " + question());
213 finishFailure("failed to send a query via " + protocol(), e, false);
214 return channel.newFailedFuture(e);
215 }
216
217
218 promise.addListener(new FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
219 @Override
220 public void operationComplete(Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> future) {
221
222 Future<?> timeoutFuture = DnsQueryContext.this.timeoutFuture;
223 if (timeoutFuture != null) {
224 DnsQueryContext.this.timeoutFuture = null;
225 timeoutFuture.cancel(false);
226 }
227
228 Throwable cause = future.cause();
229 if (cause instanceof DnsNameResolverTimeoutException || cause instanceof CancellationException) {
230
231
232
233 channel.eventLoop().schedule(new Runnable() {
234 @Override
235 public void run() {
236 removeFromContextManager(nameServerAddr);
237 }
238 }, ID_REUSE_ON_TIMEOUT_DELAY_MILLIS, TimeUnit.MILLISECONDS);
239 } else {
240
241
242 removeFromContextManager(nameServerAddr);
243 }
244 }
245 });
246 final DnsQuery query = newQuery(id, nameServerAddr);
247
248 query.setRecursionDesired(recursionDesired);
249
250 query.addRecord(DnsSection.QUESTION, wireQuestion);
251
252 for (DnsRecord record: additionals) {
253 query.addRecord(DnsSection.ADDITIONAL, record);
254 }
255
256 if (optResource != null) {
257 query.addRecord(DnsSection.ADDITIONAL, optResource);
258 }
259
260 if (logger.isDebugEnabled()) {
261 logger.debug("{} WRITE: {}, [{}: {}], {}",
262 channel, protocol(), id, nameServerAddr, wireQuestion);
263 }
264
265 return sendQuery(query, flush);
266 }
267
268 private void removeFromContextManager(InetSocketAddress nameServerAddr) {
269 DnsQueryContext self = queryContextManager.remove(nameServerAddr, id);
270
271 assert self == this : "Removed DnsQueryContext is not the correct instance";
272 }
273
274 private ChannelFuture sendQuery(final DnsQuery query, final boolean flush) {
275 final ChannelPromise writePromise = channel.newPromise();
276 writeQuery(query, flush, writePromise);
277 return writePromise;
278 }
279
280 private void writeQuery(final DnsQuery query,
281 final boolean flush, ChannelPromise promise) {
282 final ChannelFuture writeFuture = flush ? channel.writeAndFlush(query, promise) :
283 channel.write(query, promise);
284 if (writeFuture.isDone()) {
285 onQueryWriteCompletion(queryTimeoutMillis, writeFuture);
286 } else {
287 writeFuture.addListener(new ChannelFutureListener() {
288 @Override
289 public void operationComplete(ChannelFuture future) {
290 onQueryWriteCompletion(queryTimeoutMillis, writeFuture);
291 }
292 });
293 }
294 }
295
296 private void onQueryWriteCompletion(final long queryTimeoutMillis,
297 ChannelFuture writeFuture) {
298 if (!writeFuture.isSuccess()) {
299 finishFailure("failed to send a query '" + id + "' via " + protocol(), writeFuture.cause(), false);
300 return;
301 }
302
303
304 if (queryTimeoutMillis > 0) {
305 timeoutFuture = channel.eventLoop().schedule(new Runnable() {
306 @Override
307 public void run() {
308 if (promise.isDone()) {
309
310 return;
311 }
312
313 finishFailure("query '" + id + "' via " + protocol() + " timed out after " +
314 queryTimeoutMillis + " milliseconds", null, true);
315 }
316 }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
317 }
318 }
319
320
321
322
323
324 void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope, boolean truncated) {
325 finishSuccess(envelope, truncated, true);
326 }
327
328
329
330
331
332 private void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope,
333 boolean truncated, boolean validateCookie) {
334
335 if (!truncated || !retryWithTcp(envelope)) {
336 final DnsResponse res = envelope.content();
337 if (res.count(DnsSection.QUESTION) != 1) {
338 logger.warn("{} Received a DNS response with invalid number of questions. Expected: 1, found: {}",
339 channel, envelope);
340 } else if (!matchesQuestion(res.recordAt(DnsSection.QUESTION))) {
341 logger.warn("{} Received a mismatching DNS response. Expected: [{}], found: {}",
342 channel, wireQuestion, envelope);
343 } else if (validateCookie && !validateCookie(res)) {
344 logger.warn("{} Received a DNS response with a missing or invalid cookie: {}",
345 channel, envelope);
346 } else if (trySuccess(envelope)) {
347 return;
348 }
349 envelope.release();
350 }
351 }
352
353 private boolean matchesQuestion(Object responseQuestion) {
354
355
356
357 if (!question.equals(responseQuestion)) {
358 return false;
359 }
360 return !exactCaseMatch || wireQuestion.name().equals(((DnsRecord) responseQuestion).name());
361 }
362
363 private boolean validateCookie(DnsResponse res) {
364 if (clientCookie == null) {
365 return true;
366 }
367 switch (DnsQueryProtection.checkCookie(res, clientCookie)) {
368 case VALID:
369 protection.cookieReceived(nameServerAddr);
370 return true;
371 case ABSENT:
372
373
374 return !protection.isCookieExpected(nameServerAddr);
375 default:
376 return false;
377 }
378 }
379
380 @SuppressWarnings("unchecked")
381 private boolean trySuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
382 return promise.trySuccess((AddressedEnvelope<DnsResponse, InetSocketAddress>) envelope);
383 }
384
385
386
387
388 final boolean finishFailure(String message, Throwable cause, boolean timeout) {
389 if (promise.isDone()) {
390 return false;
391 }
392 final DnsQuestion question = question();
393
394 final StringBuilder buf = new StringBuilder(message.length() + 128);
395 buf.append('[')
396 .append(id)
397 .append(": ")
398 .append(nameServerAddr)
399 .append("] ")
400 .append(question)
401 .append(' ')
402 .append(message)
403 .append(" (no stack trace available)");
404
405 final DnsNameResolverException e;
406 if (timeout) {
407
408
409 e = new DnsNameResolverTimeoutException(nameServerAddr, question, buf.toString());
410 if (retryWithTcpOnTimeout && retryWithTcp(e)) {
411
412 return false;
413 }
414 } else {
415 e = new DnsNameResolverException(nameServerAddr, question, buf.toString(), cause);
416 }
417 return promise.tryFailure(e);
418 }
419
420
421
422
423
424
425
426
427 private boolean retryWithTcp(final Object originalResult) {
428 if (socketBootstrap == null) {
429 return false;
430 }
431
432 socketBootstrap.connect(nameServerAddr).addListener(new ChannelFutureListener() {
433 @Override
434 public void operationComplete(ChannelFuture future) {
435 if (!future.isSuccess()) {
436 logger.debug("{} Unable to fallback to TCP [{}: {}]",
437 future.channel(), id, nameServerAddr, future.cause());
438
439
440 finishOriginal(originalResult, future);
441 return;
442 }
443 final Channel tcpCh = future.channel();
444 Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise =
445 tcpCh.eventLoop().newPromise();
446 final TcpDnsQueryContext tcpCtx = new TcpDnsQueryContext(tcpCh,
447 (InetSocketAddress) tcpCh.remoteAddress(), queryContextManager, 0,
448 recursionDesired, queryTimeoutMillis, question(), exactCaseMatch ? wireQuestion : null,
449 additionals, promise);
450 tcpCh.pipeline().addLast(TCP_ENCODER);
451 tcpCh.pipeline().addLast(new TcpDnsResponseDecoder());
452 tcpCh.pipeline().addLast(new ChannelInboundHandlerAdapter() {
453 @Override
454 public void channelRead(ChannelHandlerContext ctx, Object msg) {
455 Channel tcpCh = ctx.channel();
456 DnsResponse response = (DnsResponse) msg;
457 int queryId = response.id();
458
459 if (logger.isDebugEnabled()) {
460 logger.debug("{} RECEIVED: TCP [{}: {}], {}", tcpCh, queryId,
461 tcpCh.remoteAddress(), response);
462 }
463
464 DnsQueryContext foundCtx = queryContextManager.get(nameServerAddr, queryId);
465 if (foundCtx != null && foundCtx.isDone()) {
466 logger.debug("{} Received a DNS response for a query that was timed out or cancelled " +
467 ": TCP [{}: {}]", tcpCh, queryId, nameServerAddr);
468 response.release();
469 } else if (foundCtx == tcpCtx) {
470 tcpCtx.finishSuccess(new AddressedEnvelopeAdapter(
471 (InetSocketAddress) ctx.channel().remoteAddress(),
472 (InetSocketAddress) ctx.channel().localAddress(),
473 response), false);
474 } else {
475 response.release();
476 tcpCtx.finishFailure("Received TCP DNS response with unexpected ID", null, false);
477 if (logger.isDebugEnabled()) {
478 logger.debug("{} Received a DNS response with an unexpected ID: TCP [{}: {}]",
479 tcpCh, queryId, tcpCh.remoteAddress());
480 }
481 }
482 }
483
484 @Override
485 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
486 if (tcpCtx.finishFailure(
487 "TCP fallback error", cause, false) && logger.isDebugEnabled()) {
488 logger.debug("{} Error during processing response: TCP [{}: {}]",
489 ctx.channel(), id,
490 ctx.channel().remoteAddress(), cause);
491 }
492 }
493 });
494
495 promise.addListener(
496 new FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
497 @Override
498 public void operationComplete(
499 Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> future) {
500 if (future.isSuccess()) {
501
502
503 finishSuccess(future.getNow(), false, false);
504
505 ReferenceCountUtil.release(originalResult);
506 } else {
507
508 finishOriginal(originalResult, future);
509 }
510 tcpCh.close();
511 }
512 });
513 tcpCtx.writeQuery(true);
514 }
515 });
516 return true;
517 }
518
519 @SuppressWarnings("unchecked")
520 private void finishOriginal(Object originalResult, Future<?> future) {
521 if (originalResult instanceof Throwable) {
522 Throwable error = (Throwable) originalResult;
523 ThrowableUtil.addSuppressed(error, future.cause());
524 promise.tryFailure(error);
525 } else {
526 finishSuccess((AddressedEnvelope<? extends DnsResponse, InetSocketAddress>) originalResult, false);
527 }
528 }
529
530 private static final class AddressedEnvelopeAdapter implements AddressedEnvelope<DnsResponse, InetSocketAddress> {
531 private final InetSocketAddress sender;
532 private final InetSocketAddress recipient;
533 private final DnsResponse response;
534
535 AddressedEnvelopeAdapter(InetSocketAddress sender, InetSocketAddress recipient, DnsResponse response) {
536 this.sender = sender;
537 this.recipient = recipient;
538 this.response = response;
539 }
540
541 @Override
542 public DnsResponse content() {
543 return response;
544 }
545
546 @Override
547 public InetSocketAddress sender() {
548 return sender;
549 }
550
551 @Override
552 public InetSocketAddress recipient() {
553 return recipient;
554 }
555
556 @Override
557 public AddressedEnvelope<DnsResponse, InetSocketAddress> retain() {
558 response.retain();
559 return this;
560 }
561
562 @Override
563 public AddressedEnvelope<DnsResponse, InetSocketAddress> retain(int increment) {
564 response.retain(increment);
565 return this;
566 }
567
568 @Override
569 public AddressedEnvelope<DnsResponse, InetSocketAddress> touch() {
570 response.touch();
571 return this;
572 }
573
574 @Override
575 public AddressedEnvelope<DnsResponse, InetSocketAddress> touch(Object hint) {
576 response.touch(hint);
577 return this;
578 }
579
580 @Override
581 public int refCnt() {
582 return response.refCnt();
583 }
584
585 @Override
586 public boolean release() {
587 return response.release();
588 }
589
590 @Override
591 public boolean release(int decrement) {
592 return response.release(decrement);
593 }
594
595 @Override
596 public boolean equals(Object obj) {
597 if (this == obj) {
598 return true;
599 }
600
601 if (!(obj instanceof AddressedEnvelope)) {
602 return false;
603 }
604
605 @SuppressWarnings("unchecked")
606 final AddressedEnvelope<?, SocketAddress> that = (AddressedEnvelope<?, SocketAddress>) obj;
607 if (sender() == null) {
608 if (that.sender() != null) {
609 return false;
610 }
611 } else if (!sender().equals(that.sender())) {
612 return false;
613 }
614
615 if (recipient() == null) {
616 if (that.recipient() != null) {
617 return false;
618 }
619 } else if (!recipient().equals(that.recipient())) {
620 return false;
621 }
622
623 return response.equals(obj);
624 }
625
626 @Override
627 public int hashCode() {
628 int hashCode = response.hashCode();
629 if (sender() != null) {
630 hashCode = hashCode * 31 + sender().hashCode();
631 }
632 if (recipient() != null) {
633 hashCode = hashCode * 31 + recipient().hashCode();
634 }
635 return hashCode;
636 }
637 }
638 }