View Javadoc
1   /*
2    * Copyright 2015 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    *   http://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.AddressedEnvelope;
20  import io.netty.channel.ChannelHandler;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.socket.DatagramPacket;
23  import io.netty.handler.codec.MessageToMessageEncoder;
24  import io.netty.util.internal.UnstableApi;
25  
26  import java.net.InetSocketAddress;
27  import java.util.List;
28  
29  import static io.netty.util.internal.ObjectUtil.checkNotNull;
30  
31  /**
32   * Encodes a {@link DatagramDnsResponse} (or an {@link AddressedEnvelope} of {@link DnsResponse}} into a
33   * {@link DatagramPacket}.
34   */
35  @UnstableApi
36  @ChannelHandler.Sharable
37  public class DatagramDnsResponseEncoder
38      extends MessageToMessageEncoder<AddressedEnvelope<DnsResponse, InetSocketAddress>> {
39  
40      private final DnsRecordEncoder recordEncoder;
41  
42      /**
43       * Creates a new encoder with {@linkplain DnsRecordEncoder#DEFAULT the default record encoder}.
44       */
45      public DatagramDnsResponseEncoder() {
46          this(DnsRecordEncoder.DEFAULT);
47      }
48  
49      /**
50       * Creates a new encoder with the specified {@code recordEncoder}.
51       */
52      public DatagramDnsResponseEncoder(DnsRecordEncoder recordEncoder) {
53          this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
54      }
55  
56      @Override
57      protected void encode(ChannelHandlerContext ctx,
58                            AddressedEnvelope<DnsResponse, InetSocketAddress> in, List<Object> out) throws Exception {
59  
60          final InetSocketAddress recipient = in.recipient();
61          final DnsResponse response = in.content();
62          final ByteBuf buf = allocateBuffer(ctx, in);
63  
64          boolean success = false;
65          try {
66              encodeHeader(response, buf);
67              encodeQuestions(response, buf);
68              encodeRecords(response, DnsSection.ANSWER, buf);
69              encodeRecords(response, DnsSection.AUTHORITY, buf);
70              encodeRecords(response, DnsSection.ADDITIONAL, buf);
71              success = true;
72          } finally {
73              if (!success) {
74                  buf.release();
75              }
76          }
77  
78          out.add(new DatagramPacket(buf, recipient, null));
79      }
80  
81      /**
82       * Allocate a {@link ByteBuf} which will be used for constructing a datagram packet.
83       * Sub-classes may override this method to return a {@link ByteBuf} with a perfect matching initial capacity.
84       */
85      protected ByteBuf allocateBuffer(
86          ChannelHandlerContext ctx,
87          @SuppressWarnings("unused") AddressedEnvelope<DnsResponse, InetSocketAddress> msg) throws Exception {
88          return ctx.alloc().ioBuffer(1024);
89      }
90  
91      /**
92       * Encodes the header that is always 12 bytes long.
93       *
94       * @param response the response header being encoded
95       * @param buf      the buffer the encoded data should be written to
96       */
97      private static void encodeHeader(DnsResponse response, ByteBuf buf) {
98          buf.writeShort(response.id());
99          int flags = 32768;
100         flags |= (response.opCode().byteValue() & 0xFF) << 11;
101         if (response.isAuthoritativeAnswer()) {
102             flags |= 1 << 10;
103         }
104         if (response.isTruncated()) {
105             flags |= 1 << 9;
106         }
107         if (response.isRecursionDesired()) {
108             flags |= 1 << 8;
109         }
110         if (response.isRecursionAvailable()) {
111             flags |= 1 << 7;
112         }
113         flags |= response.z() << 4;
114         flags |= response.code().intValue();
115         buf.writeShort(flags);
116         buf.writeShort(response.count(DnsSection.QUESTION));
117         buf.writeShort(response.count(DnsSection.ANSWER));
118         buf.writeShort(response.count(DnsSection.AUTHORITY));
119         buf.writeShort(response.count(DnsSection.ADDITIONAL));
120     }
121 
122     private void encodeQuestions(DnsResponse response, ByteBuf buf) throws Exception {
123         final int count = response.count(DnsSection.QUESTION);
124         for (int i = 0; i < count; i++) {
125             recordEncoder.encodeQuestion((DnsQuestion) response.recordAt(DnsSection.QUESTION, i), buf);
126         }
127     }
128 
129     private void encodeRecords(DnsResponse response, DnsSection section, ByteBuf buf) throws Exception {
130         final int count = response.count(section);
131         for (int i = 0; i < count; i++) {
132             recordEncoder.encodeRecord(response.recordAt(section, i), buf);
133         }
134     }
135 }