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 DnsQueryLifecycleObserver queryLifecycleObserver;
69      private final Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise;
70  
71      private final DnsQuestion question;
72      // The question that is actually written to the wire. This differs from question in case when 0x20 case
73      // randomization is used.
74      private final DnsQuestion wireQuestion;
75      // true if the response must echo the name of wireQuestion with exactly the same case.
76      private final boolean exactCaseMatch;
77      private final DnsRecord[] additionals;
78      private final DnsRecord optResource;
79      private final DnsQueryProtection protection;
80      // null if no cookie is sent with the query.
81      private final byte[] clientCookie;
82  
83      private final boolean recursionDesired;
84  
85      private final Bootstrap socketBootstrap;
86  
87      private final boolean retryWithTcpOnTimeout;
88      private final long queryTimeoutMillis;
89  
90      private volatile Future<?> timeoutFuture;
91  
92      private int id = Integer.MIN_VALUE;
93  
94      DnsQueryContext(Channel channel,
95                      InetSocketAddress nameServerAddr,
96                      DnsQueryContextManager queryContextManager,
97                      DnsQueryLifecycleObserver queryLifecycleObserver,
98                      int maxPayLoadSize,
99                      boolean recursionDesired,
100                     long queryTimeoutMillis,
101                     DnsQuestion question,
102                     DnsQuestion wireQuestion,
103                     DnsRecord[] additionals,
104                     Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise,
105                     Bootstrap socketBootstrap,
106                     boolean retryWithTcpOnTimeout,
107                     DnsQueryProtection protection) {
108         this.channel = checkNotNull(channel, "channel");
109         this.queryContextManager = checkNotNull(queryContextManager, "queryContextManager");
110         this.queryLifecycleObserver = checkNotNull(queryLifecycleObserver, "queryLifecycleObserver");
111         this.nameServerAddr = checkNotNull(nameServerAddr, "nameServerAddr");
112         this.question = checkNotNull(question, "question");
113         this.protection = protection;
114         DnsQuestion wireQ = wireQuestion;
115         if (wireQ == null && protection != null && protection.isCaseRandomizationEnabled()) {
116             wireQ = protection.randomizeCase(question);
117         }
118         this.exactCaseMatch = wireQ != null;
119         this.wireQuestion = wireQ != null ? wireQ : question;
120         this.additionals = checkNotNull(additionals, "additionals");
121         this.promise = checkNotNull(promise, "promise");
122         this.recursionDesired = recursionDesired;
123         this.queryTimeoutMillis = queryTimeoutMillis;
124         this.socketBootstrap = socketBootstrap;
125         this.retryWithTcpOnTimeout = retryWithTcpOnTimeout;
126 
127         if (maxPayLoadSize > 0 &&
128                 // Only add the extra OPT record if there is not already one. This is required as only one is allowed
129                 // as per RFC:
130                 //  - https://datatracker.ietf.org/doc/html/rfc6891#section-6.1.1
131                 !hasOptRecord(additionals)) {
132             if (protection != null && protection.isCookiesEnabled()) {
133                 clientCookie = protection.newClientCookie();
134                 optResource = new DefaultDnsOptCookieRecord(maxPayLoadSize, clientCookie);
135             } else {
136                 clientCookie = null;
137                 optResource = new AbstractDnsOptPseudoRrRecord(maxPayLoadSize, 0, 0) {
138                     // We may want to remove this in the future and let the user just specify the opt record in
139                     // the query.
140                 };
141             }
142         } else {
143             clientCookie = null;
144             optResource = null;
145         }
146     }
147 
148     private static boolean hasOptRecord(DnsRecord[] additionals) {
149         if (additionals != null && additionals.length > 0) {
150             for (DnsRecord additional: additionals) {
151                 if (additional.type() == DnsRecordType.OPT) {
152                     return true;
153                 }
154             }
155         }
156         return false;
157     }
158 
159     /**
160      * Returns {@code true} if the query was completed already.
161      *
162      * @return {@code true} if done.
163      */
164     final boolean isDone() {
165         return promise.isDone();
166     }
167 
168     /**
169      * Returns the {@link DnsQuestion} that will be written as part of the {@link DnsQuery}.
170      *
171      * @return the question.
172      */
173     final DnsQuestion question() {
174         return question;
175     }
176 
177     /**
178      * Returns the {@link DnsQuestion} that is written to the wire. This may differ in case from
179      * {@link #question()}.
180      *
181      * @return the question.
182      */
183     final DnsQuestion wireQuestion() {
184         return wireQuestion;
185     }
186 
187     /**
188      * Creates and returns a new {@link DnsQuery}.
189      *
190      * @param id                the transaction id to use.
191      * @param nameServerAddr    the nameserver to which the query will be send.
192      * @return                  the new query.
193      */
194     protected abstract DnsQuery newQuery(int id, InetSocketAddress nameServerAddr);
195 
196     /**
197      * Returns the protocol that is used for the query.
198      *
199      * @return  the protocol.
200      */
201     protected abstract String protocol();
202 
203     /**
204      * Write the query and return the {@link ChannelFuture} that is completed once the write completes.
205      *
206      * @param flush                 {@code true} if {@link Channel#flush()} should be called as well.
207      */
208     final void writeQuery(boolean flush) {
209         assert id == Integer.MIN_VALUE : this.getClass().getSimpleName() +
210                 ".writeQuery(...) can only be executed once.";
211 
212         if ((id = queryContextManager.add(nameServerAddr, this)) == -1) {
213             // We did exhaust the id space, fail the query
214             IllegalStateException e = new IllegalStateException("query ID space exhausted: " + question());
215             finishFailure("failed to send a query via " + protocol(), e, false);
216             queryLifecycleObserver.queryWritten(nameServerAddr, channel.newFailedFuture(e));
217             return;
218         }
219 
220         // Ensure we remove the id from the QueryContextManager once the query completes.
221         promise.addListener((FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>) future -> {
222             // Cancel the timeout task.
223             Future<?> timeoutFuture = DnsQueryContext.this.timeoutFuture;
224             if (timeoutFuture != null) {
225                 DnsQueryContext.this.timeoutFuture = null;
226                 timeoutFuture.cancel(false);
227             }
228 
229             Throwable cause = future.cause();
230             if (cause instanceof DnsNameResolverTimeoutException || cause instanceof CancellationException) {
231                 // This query was failed due a timeout or cancellation. Let's delay the removal of the id to reduce
232                 // the risk of reusing the same id again while the remote nameserver might send the response after
233                 // the timeout.
234                 channel.eventLoop().schedule(new Runnable() {
235                     @Override
236                     public void run() {
237                         removeFromContextManager(nameServerAddr);
238                     }
239                 }, ID_REUSE_ON_TIMEOUT_DELAY_MILLIS, TimeUnit.MILLISECONDS);
240             } else {
241                 // Remove the id from the manager as soon as the query completes. This may be because of success,
242                 // failure or cancellation
243                 removeFromContextManager(nameServerAddr);
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         ChannelFuture f = sendQuery(query, flush);
266         queryLifecycleObserver.queryWritten(nameServerAddr, f);
267     }
268 
269     private void removeFromContextManager(InetSocketAddress nameServerAddr) {
270         DnsQueryContext self = queryContextManager.remove(nameServerAddr, id);
271 
272         assert self == this : "Removed DnsQueryContext is not the correct instance";
273     }
274 
275     private ChannelFuture sendQuery(final DnsQuery query, final boolean flush) {
276         final ChannelPromise writePromise = channel.newPromise();
277         writeQuery(query, flush, writePromise);
278         return writePromise;
279     }
280 
281     private void writeQuery(final DnsQuery query,
282                             final boolean flush, ChannelPromise promise) {
283         final ChannelFuture writeFuture = flush ? channel.writeAndFlush(query, promise) :
284                 channel.write(query, promise);
285         if (writeFuture.isDone()) {
286             onQueryWriteCompletion(queryTimeoutMillis, writeFuture);
287         } else {
288             writeFuture.addListener((ChannelFutureListener) future ->
289                     onQueryWriteCompletion(queryTimeoutMillis, future));
290         }
291     }
292 
293     private void onQueryWriteCompletion(final long queryTimeoutMillis,
294                                         ChannelFuture writeFuture) {
295         if (!writeFuture.isSuccess()) {
296             finishFailure("failed to send a query '" + id + "' via " + protocol(), writeFuture.cause(), false);
297             return;
298         }
299 
300         // Schedule a query timeout task if necessary.
301         if (queryTimeoutMillis > 0) {
302             timeoutFuture = channel.eventLoop().schedule(new Runnable() {
303                 @Override
304                 public void run() {
305                     if (promise.isDone()) {
306                         // Received a response before the query times out.
307                         return;
308                     }
309 
310                     finishFailure("query '" + id + "' via " + protocol() + " timed out after " +
311                             queryTimeoutMillis + " milliseconds", null, true);
312                 }
313             }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
314         }
315     }
316 
317     /**
318      * Notifies the original {@link Promise} that the response for the query was received.
319      * This method takes ownership of passed {@link AddressedEnvelope}.
320      */
321     void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope, boolean truncated) {
322         finishSuccess(envelope, truncated, true);
323     }
324 
325     /**
326      * @param validateCookie    {@code false} if the response was received via a different, already authenticated,
327      *                          transport (like TCP) and so does not carry a cookie that belongs to this query.
328      */
329     private void finishSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope,
330                                boolean truncated, boolean validateCookie) {
331         // Check if the response was not truncated or if a fallback to TCP is possible.
332         if (!truncated || !retryWithTcp(envelope)) {
333             final DnsResponse res = envelope.content();
334             if (res.count(DnsSection.QUESTION) != 1) {
335                 logger.warn("{} Received a DNS response with invalid number of questions. Expected: 1, found: {}",
336                         channel, envelope);
337             } else if (!matchesQuestion(res.recordAt(DnsSection.QUESTION))) {
338                 logger.warn("{} Received a mismatching DNS response. Expected: [{}], found: {}",
339                         channel, wireQuestion, envelope);
340             } else if (validateCookie && !validateCookie(res)) {
341                 logger.warn("{} Received a DNS response with a missing or invalid cookie: {}",
342                         channel, envelope);
343             } else if (trySuccess(envelope)) {
344                 return; // Ownership transferred, don't release
345             }
346             envelope.release();
347         }
348     }
349 
350     private boolean matchesQuestion(Object responseQuestion) {
351         // Use AbstractDnsRecord.equals(...) for the type and class. It ignores the case of the name, which is
352         // what we want unless 0x20 case randomization is used. In this case the name must be echoed exactly as it was
353         // written, as otherwise the case would not add any entropy.
354         if (!question.equals(responseQuestion)) {
355             return false;
356         }
357         return !exactCaseMatch || wireQuestion.name().equals(((DnsRecord) responseQuestion).name());
358     }
359 
360     private boolean validateCookie(DnsResponse res) {
361         if (clientCookie == null) {
362             return true;
363         }
364         switch (DnsQueryProtection.checkCookie(res, clientCookie)) {
365             case VALID:
366                 protection.cookieReceived(nameServerAddr);
367                 return true;
368             case ABSENT:
369                 // A nameserver that supports cookies must echo the client cookie. Once we have seen this, a
370                 // response without one must not be trusted.
371                 return !protection.isCookieExpected(nameServerAddr);
372             default:
373                 return false;
374         }
375     }
376 
377     @SuppressWarnings("unchecked")
378     private boolean trySuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
379         return promise.trySuccess((AddressedEnvelope<DnsResponse, InetSocketAddress>) envelope);
380     }
381 
382     /**
383      * Notifies the original {@link Promise} that the query completes because of an failure.
384      */
385     final boolean finishFailure(String message, Throwable cause, boolean timeout) {
386         if (promise.isDone()) {
387             return false;
388         }
389         final DnsQuestion question = question();
390 
391         final StringBuilder buf = new StringBuilder(message.length() + 128);
392         buf.append('[')
393            .append(id)
394            .append(": ")
395            .append(nameServerAddr)
396            .append("] ")
397            .append(question)
398            .append(' ')
399            .append(message)
400            .append(" (no stack trace available)");
401 
402         final DnsNameResolverException e;
403         if (timeout) {
404             // This was caused by a timeout so use DnsNameResolverTimeoutException to allow the user to
405             // handle it special (like retry the query).
406             e = new DnsNameResolverTimeoutException(nameServerAddr, question, buf.toString());
407             if (retryWithTcpOnTimeout && retryWithTcp(e)) {
408                 // We did successfully retry with TCP.
409                 return false;
410             }
411         } else {
412             e = new DnsNameResolverException(nameServerAddr, question, buf.toString(), cause);
413         }
414         return promise.tryFailure(e);
415     }
416 
417     /**
418      * Retry the original query with TCP if possible.
419      *
420      * @param originalResult    the result of the original {@link DnsQueryContext}.
421      * @return                  {@code true} if retry via TCP is supported and so the ownership of
422      *                          {@code originalResult} was transferred, {@code false} otherwise.
423      */
424     private boolean retryWithTcp(final Object originalResult) {
425         if (socketBootstrap == null) {
426             return false;
427         }
428 
429         socketBootstrap.connect(nameServerAddr).addListener((ChannelFutureListener) future -> {
430             if (!future.isSuccess()) {
431                 logger.debug("{} Unable to fallback to TCP [{}: {}]",
432                         future.channel(), id, nameServerAddr, future.cause());
433                 // TCP fallback failed, just use the truncated response or error.
434                 finishOriginal(originalResult, future);
435                 return;
436             }
437             final Channel tcpCh = future.channel();
438             Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise =
439                     tcpCh.eventLoop().newPromise();
440             final TcpDnsQueryContext tcpCtx = new TcpDnsQueryContext(tcpCh,
441                     (InetSocketAddress) tcpCh.remoteAddress(), queryContextManager, queryLifecycleObserver, 0,
442                     recursionDesired, queryTimeoutMillis, question(), exactCaseMatch ? wireQuestion : null,
443                     additionals, promise);
444             tcpCh.pipeline().addLast(TCP_ENCODER);
445             tcpCh.pipeline().addLast(new TcpDnsResponseDecoder());
446             tcpCh.pipeline().addLast(new ChannelInboundHandlerAdapter() {
447                 @Override
448                 public void channelRead(ChannelHandlerContext ctx, Object msg) {
449                     Channel tcpCh = ctx.channel();
450                     DnsResponse response = (DnsResponse) msg;
451                     int queryId = response.id();
452 
453                     if (logger.isDebugEnabled()) {
454                         logger.debug("{} RECEIVED: TCP [{}: {}], {}", tcpCh, queryId,
455                                 tcpCh.remoteAddress(), response);
456                     }
457 
458                     DnsQueryContext foundCtx = queryContextManager.get(nameServerAddr, queryId);
459                     if (foundCtx != null && foundCtx.isDone()) {
460                         logger.debug("{} Received a DNS response for a query that was timed out or cancelled " +
461                                 ": TCP [{}: {}]", tcpCh, queryId, nameServerAddr);
462                         response.release();
463                     } else if (foundCtx == tcpCtx) {
464                         tcpCtx.finishSuccess(new AddressedEnvelopeAdapter(
465                                 (InetSocketAddress) ctx.channel().remoteAddress(),
466                                 (InetSocketAddress) ctx.channel().localAddress(),
467                                 response), false);
468                     } else {
469                         response.release();
470                         tcpCtx.finishFailure("Received TCP DNS response with unexpected ID", null, false);
471                         if (logger.isDebugEnabled()) {
472                             logger.debug("{} Received a DNS response with an unexpected ID: TCP [{}: {}]",
473                                     tcpCh, queryId, tcpCh.remoteAddress());
474                         }
475                     }
476                 }
477 
478                 @Override
479                 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
480                     if (tcpCtx.finishFailure(
481                             "TCP fallback error", cause, false) && logger.isDebugEnabled()) {
482                         logger.debug("{} Error during processing response: TCP [{}: {}]",
483                                 ctx.channel(), id,
484                                 ctx.channel().remoteAddress(), cause);
485                     }
486                 }
487             });
488 
489             promise.addListener(
490                     (FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>) future1 -> {
491                         if (future1.isSuccess()) {
492                             // The cookie only protects the UDP response, the TCP connection is authenticated by itself.
493                             finishSuccess(future1.getNow(), false, false);
494                             // Release the original result.
495                             ReferenceCountUtil.release(originalResult);
496                         } else {
497                             // TCP fallback failed, just use the truncated response or error.
498                             finishOriginal(originalResult, future1);
499                         }
500                         tcpCh.close();
501                     });
502             tcpCtx.writeQuery(true);
503         });
504         return true;
505     }
506 
507     @SuppressWarnings("unchecked")
508     private void finishOriginal(Object originalResult, Future<?> future) {
509         if (originalResult instanceof Throwable) {
510             Throwable error = (Throwable) originalResult;
511             ThrowableUtil.addSuppressed(error, future.cause());
512             promise.tryFailure(error);
513         } else {
514             finishSuccess((AddressedEnvelope<? extends DnsResponse, InetSocketAddress>) originalResult, false);
515         }
516     }
517 
518     private static final class AddressedEnvelopeAdapter implements AddressedEnvelope<DnsResponse, InetSocketAddress> {
519         private final InetSocketAddress sender;
520         private final InetSocketAddress recipient;
521         private final DnsResponse response;
522 
523         AddressedEnvelopeAdapter(InetSocketAddress sender, InetSocketAddress recipient, DnsResponse response) {
524             this.sender = sender;
525             this.recipient = recipient;
526             this.response = response;
527         }
528 
529         @Override
530         public DnsResponse content() {
531             return response;
532         }
533 
534         @Override
535         public InetSocketAddress sender() {
536             return sender;
537         }
538 
539         @Override
540         public InetSocketAddress recipient() {
541             return recipient;
542         }
543 
544         @Override
545         public AddressedEnvelope<DnsResponse, InetSocketAddress> retain() {
546             response.retain();
547             return this;
548         }
549 
550         @Override
551         public AddressedEnvelope<DnsResponse, InetSocketAddress> retain(int increment) {
552             response.retain(increment);
553             return this;
554         }
555 
556         @Override
557         public AddressedEnvelope<DnsResponse, InetSocketAddress> touch() {
558             response.touch();
559             return this;
560         }
561 
562         @Override
563         public AddressedEnvelope<DnsResponse, InetSocketAddress> touch(Object hint) {
564             response.touch(hint);
565             return this;
566         }
567 
568         @Override
569         public int refCnt() {
570             return response.refCnt();
571         }
572 
573         @Override
574         public boolean release() {
575             return response.release();
576         }
577 
578         @Override
579         public boolean release(int decrement) {
580             return response.release(decrement);
581         }
582 
583         @Override
584         public boolean equals(Object obj) {
585             if (this == obj) {
586                 return true;
587             }
588 
589             if (!(obj instanceof AddressedEnvelope)) {
590                 return false;
591             }
592 
593             @SuppressWarnings("unchecked")
594             final AddressedEnvelope<?, SocketAddress> that = (AddressedEnvelope<?, SocketAddress>) obj;
595             if (sender() == null) {
596                 if (that.sender() != null) {
597                     return false;
598                 }
599             } else if (!sender().equals(that.sender())) {
600                 return false;
601             }
602 
603             if (recipient() == null) {
604                 if (that.recipient() != null) {
605                     return false;
606                 }
607             } else if (!recipient().equals(that.recipient())) {
608                 return false;
609             }
610 
611             return response.equals(obj);
612         }
613 
614         @Override
615         public int hashCode() {
616             int hashCode = response.hashCode();
617             if (sender() != null) {
618                 hashCode = hashCode * 31 + sender().hashCode();
619             }
620             if (recipient() != null) {
621                 hashCode = hashCode * 31 + recipient().hashCode();
622             }
623             return hashCode;
624         }
625     }
626 }