查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
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.netty.handler.codec.dns;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
21  import io.netty.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<SocketAddress>(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 decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
56          ByteBuf frame = (ByteBuf) super.decode(ctx, in);
57          if (frame == null) {
58              return null;
59          }
60  
61          try {
62              return responseDecoder.decode(ctx.channel().remoteAddress(), ctx.channel().localAddress(), frame.slice());
63          } finally {
64              frame.release();
65          }
66      }
67  
68      @Override
69      protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
70          return buffer.copy(index, length);
71      }
72  }