View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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      // The question that is actually written to the wire. This differs from question in case when 0x20 case
72      // randomization is used.
73      private final DnsQuestion wireQuestion;
74      // true if the response must echo the name of wireQuestion with exactly the same case.
75      private final boolean exactCaseMatch;
76      private final DnsRecord[] additionals;
77      private final DnsRecord optResource;
78      private final DnsQueryProtection protection;
79      // null if no cookie is sent with the query.
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                 // Only add the extra OPT record if there is not already one. This is required as only one is allowed
126                 // as per RFC:
127                 //  - https://datatracker.ietf.org/doc/html/rfc6891#section-6.1.1
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                     // We may want to remove this in the future and let the user just specify the opt record in
136                     // the query.
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      * Returns {@code true} if the query was completed already.
158      *
159      * @return {@code true} if done.
160      */
161     final boolean isDone() {
162         return promise.isDone();
163     }
164 
165     /**
166      * Returns the {@link DnsQuestion} that will be written as part of the {@link DnsQuery}.
167      *
168      * @return the question.
169      */
170     final DnsQuestion question() {
171         return question;
172     }
173 
174     /**
175      * Returns the {@link DnsQuestion} that is written to the wire. This may differ in case from
176      * {@link #question()}.
177      *
178      * @return the question.
179      */
180     final DnsQuestion wireQuestion() {
181         return wireQuestion;
182     }
183 
184     /**
185      * Creates and returns a new {@link DnsQuery}.
186      *
187      * @param id                the transaction id to use.
188      * @param nameServerAddr    the nameserver to which the query will be send.
189      * @return                  the new query.
190      */
191     protected abstract DnsQuery newQuery(int id, InetSocketAddress nameServerAddr);
192 
193     /**
194      * Returns the protocol that is used for the query.
195      *
196      * @return  the protocol.
197      */
198     protected abstract String protocol();
199 
200     /**
201      * Write the query and return the {@link ChannelFuture} that is completed once the write completes.
202      *
203      * @param flush                 {@code true} if {@link Channel#flush()} should be called as well.
204      * @return                      the {@link ChannelFuture} that is notified once once the write completes.
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             // We did exhaust the id space, fail the query
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         // Ensure we remove the id from the QueryContextManager once the query completes.
218         promise.addListener(new FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
219             @Override
220             public void operationComplete(Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> future) {
221                 // Cancel the timeout task.
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                     // This query was failed due a timeout or cancellation. Let's delay the removal of the id to reduce
231                     // the risk of reusing the same id again while the remote nameserver might send the response after
232                     // the timeout.
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                     // Remove the id from the manager as soon as the query completes. This may be because of success,
241                     // failure or cancellation
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         // Schedule a query timeout task if necessary.
304         if (queryTimeoutMillis > 0) {
305             timeoutFuture = channel.eventLoop().schedule(new Runnable() {
306                 @Override
307                 public void run() {
308                     if (promise.isDone()) {
309                         // Received a response before the query times out.
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      * Notifies the original {@link Promise} that the response for the query was received.
322      * This method takes ownership of passed {@link AddressedEnvelope}.
323      */
324     void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope, boolean truncated) {
325         finishSuccess(envelope, truncated, true);
326     }
327 
328     /**
329      * @param validateCookie    {@code false} if the response was received via a different, already authenticated,
330      *                          transport (like TCP) and so does not carry a cookie that belongs to this query.
331      */
332     private void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope,
333                                boolean truncated, boolean validateCookie) {
334         // Check if the response was not truncated or if a fallback to TCP is possible.
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; // Ownership transferred, don't release
348             }
349             envelope.release();
350         }
351     }
352 
353     private boolean matchesQuestion(Object responseQuestion) {
354         // Use AbstractDnsRecord.equals(...) for the type and class. It ignores the case of the name, which is
355         // what we want unless 0x20 case randomization is used. In this case the name must be echoed exactly as it was
356         // written, as otherwise the case would not add any entropy.
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                 // A nameserver that supports cookies must echo the client cookie. Once we have seen this, a
373                 // response without one must not be trusted.
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      * Notifies the original {@link Promise} that the query completes because of an failure.
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             // This was caused by a timeout so use DnsNameResolverTimeoutException to allow the user to
408             // handle it special (like retry the query).
409             e = new DnsNameResolverTimeoutException(nameServerAddr, question, buf.toString());
410             if (retryWithTcpOnTimeout && retryWithTcp(e)) {
411                 // We did successfully retry with TCP.
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      * Retry the original query with TCP if possible.
422      *
423      * @param originalResult    the result of the original {@link DnsQueryContext}.
424      * @return                  {@code true} if retry via TCP is supported and so the ownership of
425      *                          {@code originalResult} was transferred, {@code false} otherwise.
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                     // TCP fallback failed, just use the truncated response or error.
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                                     // The cookie only protects the UDP response, the TCP connection is
502                                     // authenticated by itself.
503                                     finishSuccess(future.getNow(), false, false);
504                                     // Release the original result.
505                                     ReferenceCountUtil.release(originalResult);
506                                 } else {
507                                     // TCP fallback failed, just use the truncated response or error.
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 }