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    *   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.socket.InternetProtocolFamily;
20  import io.netty.handler.codec.UnsupportedMessageTypeException;
21  
22  /**
23   * The default {@link DnsRecordEncoder} implementation.
24   *
25   * @see DefaultDnsRecordDecoder
26   */
27  public class DefaultDnsRecordEncoder implements DnsRecordEncoder {
28      private static final int PREFIX_MASK = Byte.SIZE - 1;
29  
30      /**
31       * Creates a new instance.
32       */
33      protected DefaultDnsRecordEncoder() { }
34  
35      @Override
36      public final void encodeQuestion(DnsQuestion question, ByteBuf out) throws Exception {
37          encodeName(question.name(), out);
38          out.writeShort(question.type().intValue());
39          out.writeShort(question.dnsClass());
40      }
41  
42      private static final Class<?>[] SUPPORTED_MESSAGES = new Class<?>[] {
43              DnsQuestion.class, DnsPtrRecord.class,
44              DnsOptEcsRecord.class, DnsOptCookieRecord.class, DnsOptPseudoRecord.class, DnsRawRecord.class };
45  
46      @Override
47      public void encodeRecord(DnsRecord record, ByteBuf out) throws Exception {
48          if (record instanceof DnsQuestion) {
49              encodeQuestion((DnsQuestion) record, out);
50          } else if (record instanceof DnsPtrRecord) {
51              encodePtrRecord((DnsPtrRecord) record, out);
52          } else if (record instanceof DnsOptEcsRecord) {
53              encodeOptEcsRecord((DnsOptEcsRecord) record, out);
54          } else if (record instanceof DnsOptCookieRecord) {
55              encodeOptCookieRecord((DnsOptCookieRecord) record, out);
56          } else if (record instanceof DnsOptPseudoRecord) {
57              encodeOptPseudoRecord((DnsOptPseudoRecord) record, out);
58          } else if (record instanceof DnsRawRecord) {
59              encodeRawRecord((DnsRawRecord) record, out);
60          } else {
61              throw new UnsupportedMessageTypeException(record, SUPPORTED_MESSAGES);
62          }
63      }
64  
65      private void encodeRecord0(DnsRecord record, ByteBuf out) throws Exception {
66          encodeName(record.name(), out);
67          out.writeShort(record.type().intValue());
68          out.writeShort(record.dnsClass());
69          out.writeInt((int) record.timeToLive());
70      }
71  
72      private void encodePtrRecord(DnsPtrRecord record, ByteBuf out) throws Exception {
73          encodeRecord0(record, out);
74          int writerIndex = out.writerIndex();
75          // Skip 2 bytes as these will be used to encode the rdataLen after we know how many bytes were written.
76          // See https://www.rfc-editor.org/rfc/rfc1035.html#section-3.2.1
77          out.writerIndex(writerIndex + 2);
78          encodeName(record.hostname(), out);
79          int rdLength = out.writerIndex() - (writerIndex + 2);
80          out.setShort(writerIndex, rdLength);
81      }
82  
83      private void encodeOptPseudoRecord(DnsOptPseudoRecord record, ByteBuf out) throws Exception {
84          encodeRecord0(record, out);
85          out.writeShort(0);
86      }
87  
88      private void encodeOptCookieRecord(DnsOptCookieRecord record, ByteBuf out) throws Exception {
89          byte[] clientCookie = record.clientCookie();
90          if (clientCookie.length != DnsOptCookieRecord.CLIENT_COOKIE_LENGTH) {
91              throw new IllegalArgumentException("clientCookie.length: " + clientCookie.length +
92                      " (expected: " + DnsOptCookieRecord.CLIENT_COOKIE_LENGTH + ')');
93          }
94          encodeRecord0(record, out);
95  
96          out.writeShort(2 + // OPTION-CODE
97                  2 + // OPTION-LENGTH
98                  clientCookie.length); // RDLENGTH
99          out.writeShort(DnsOptCookieRecord.OPTION_CODE);
100         out.writeShort(clientCookie.length);
101         out.writeBytes(clientCookie);
102     }
103 
104     private void encodeOptEcsRecord(DnsOptEcsRecord record, ByteBuf out) throws Exception {
105         encodeRecord0(record, out);
106 
107         int sourcePrefixLength = record.sourcePrefixLength();
108         int scopePrefixLength = record.scopePrefixLength();
109         int lowOrderBitsToPreserve = sourcePrefixLength & PREFIX_MASK;
110 
111         byte[] bytes = record.address();
112         int addressBits = bytes.length << 3;
113         if (addressBits < sourcePrefixLength || sourcePrefixLength < 0) {
114             throw new IllegalArgumentException(sourcePrefixLength + ": " +
115                     sourcePrefixLength + " (expected: 0 >= " + addressBits + ')');
116         }
117 
118         // See https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xhtml
119         final short addressNumber = (short) (bytes.length == 4 ?
120                 InternetProtocolFamily.IPv4.addressNumber() : InternetProtocolFamily.IPv6.addressNumber());
121         int payloadLength = calculateEcsAddressLength(sourcePrefixLength, lowOrderBitsToPreserve);
122 
123         int fullPayloadLength = 2 + // OPTION-CODE
124                 2 + // OPTION-LENGTH
125                 2 + // FAMILY
126                 1 + // SOURCE PREFIX-LENGTH
127                 1 + // SCOPE PREFIX-LENGTH
128                 payloadLength; //  ADDRESS...
129 
130         out.writeShort(fullPayloadLength);
131         out.writeShort(8); // This is the defined type for ECS.
132 
133         out.writeShort(fullPayloadLength - 4); // Not include OPTION-CODE and OPTION-LENGTH
134         out.writeShort(addressNumber);
135         out.writeByte(sourcePrefixLength);
136         out.writeByte(scopePrefixLength); // Must be 0 in queries.
137 
138         if (lowOrderBitsToPreserve > 0) {
139             int bytesLength = payloadLength - 1;
140             out.writeBytes(bytes, 0, bytesLength);
141 
142             // Pad the leftover of the last byte with zeros.
143             out.writeByte(padWithZeros(bytes[bytesLength], lowOrderBitsToPreserve));
144         } else {
145             // The sourcePrefixLength align with Byte so just copy in the bytes directly.
146             out.writeBytes(bytes, 0, payloadLength);
147         }
148     }
149 
150     // Package-Private for testing
151     static int calculateEcsAddressLength(int sourcePrefixLength, int lowOrderBitsToPreserve) {
152         return (sourcePrefixLength >>> 3) + (lowOrderBitsToPreserve != 0 ? 1 : 0);
153     }
154 
155     private void encodeRawRecord(DnsRawRecord record, ByteBuf out) throws Exception {
156         encodeRecord0(record, out);
157 
158         ByteBuf content = record.content();
159         int contentLen = content.readableBytes();
160 
161         out.writeShort(contentLen);
162         out.writeBytes(content, content.readerIndex(), contentLen);
163     }
164 
165     protected void encodeName(String name, ByteBuf buf) throws Exception {
166         DnsCodecUtil.encodeDomainName(name, buf);
167     }
168 
169     private static byte padWithZeros(byte b, int lowOrderBitsToPreserve) {
170         switch (lowOrderBitsToPreserve) {
171         case 0:
172             return 0;
173         case 1:
174             return (byte) (0x80 & b);
175         case 2:
176             return (byte) (0xC0 & b);
177         case 3:
178             return (byte) (0xE0 & b);
179         case 4:
180             return (byte) (0xF0 & b);
181         case 5:
182             return (byte) (0xF8 & b);
183         case 6:
184             return (byte) (0xFC & b);
185         case 7:
186             return (byte) (0xFE & b);
187         case 8:
188             return b;
189         default:
190             throw new IllegalArgumentException("lowOrderBitsToPreserve: " + lowOrderBitsToPreserve);
191         }
192     }
193 }