View Javadoc
1   /*
2    * Copyright 2019 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.netty5.handler.codec.dns;
17  
18  import io.netty5.buffer.api.Buffer;
19  import io.netty5.channel.ChannelHandlerContext;
20  import io.netty5.handler.codec.LengthFieldBasedFrameDecoder;
21  import io.netty5.util.internal.UnstableApi;
22  
23  import java.net.SocketAddress;
24  
25  @UnstableApi
26  public final class TcpDnsResponseDecoder extends LengthFieldBasedFrameDecoder {
27  
28      private final DnsResponseDecoder<SocketAddress> responseDecoder;
29  
30      /**
31       * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
32       */
33      public TcpDnsResponseDecoder() {
34          this(DnsRecordDecoder.DEFAULT, 64 * 1024);
35      }
36  
37      /**
38       * Creates a new decoder with the specified {@code recordDecoder} and {@code maxFrameLength}
39       */
40      public TcpDnsResponseDecoder(DnsRecordDecoder recordDecoder, int maxFrameLength) {
41          // Length is two octets as defined by RFC-7766
42          // See https://tools.ietf.org/html/rfc7766#section-8
43          super(maxFrameLength, 0, 2, 0, 2);
44  
45          this.responseDecoder = new DnsResponseDecoder<>(recordDecoder) {
46              @Override
47              protected DnsResponse newResponse(SocketAddress sender, SocketAddress recipient,
48                                                int id, DnsOpCode opCode, DnsResponseCode responseCode) {
49                  return new DefaultDnsResponse(id, opCode, responseCode);
50              }
51          };
52      }
53  
54      @Override
55      protected Object decode0(ChannelHandlerContext ctx, Buffer in) throws Exception {
56          try (Buffer frame = (Buffer) super.decode0(ctx, in)) {
57              if (frame == null) {
58                  return null;
59              }
60              SocketAddress sender = ctx.channel().remoteAddress();
61              SocketAddress recipient = ctx.channel().localAddress();
62              return responseDecoder.decode(sender, recipient, ctx.bufferAllocator(), frame.split());
63          }
64      }
65  }