1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.dns;
17
18 import io.netty.buffer.ByteBuf;
19
20
21
22
23
24
25 public class DefaultDnsRecordDecoder implements DnsRecordDecoder {
26
27 static final String ROOT = ".";
28
29
30
31
32 protected DefaultDnsRecordDecoder() { }
33
34 @Override
35 public final DnsQuestion decodeQuestion(ByteBuf in) throws Exception {
36 String name = decodeName(in);
37 DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
38 int qClass = in.readUnsignedShort();
39 return new DefaultDnsQuestion(name, type, qClass);
40 }
41
42 @Override
43 public final <T extends DnsRecord> T decodeRecord(ByteBuf in) throws Exception {
44 final int startOffset = in.readerIndex();
45 final String name = decodeName(in);
46
47 final int endOffset = in.writerIndex();
48 if (endOffset - in.readerIndex() < 10) {
49
50 in.readerIndex(startOffset);
51 return null;
52 }
53
54 final DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
55 final int aClass = in.readUnsignedShort();
56 final long ttl = in.readUnsignedInt();
57 final int length = in.readUnsignedShort();
58 final int offset = in.readerIndex();
59
60 if (endOffset - offset < length) {
61
62 in.readerIndex(startOffset);
63 return null;
64 }
65
66 @SuppressWarnings("unchecked")
67 T record = (T) decodeRecord(name, type, aClass, ttl, in, offset, length);
68 in.readerIndex(offset + length);
69 return record;
70 }
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85 protected DnsRecord decodeRecord(
86 String name, DnsRecordType type, int dnsClass, long timeToLive,
87 ByteBuf in, int offset, int length) throws Exception {
88
89
90
91
92
93 if (type == DnsRecordType.PTR) {
94 return new DefaultDnsPtrRecord(
95 name, dnsClass, timeToLive, decodeName0(in.duplicate().setIndex(offset, offset + length)));
96 }
97 if (type == DnsRecordType.CNAME || type == DnsRecordType.NS) {
98 return new DefaultDnsRawRecord(name, type, dnsClass, timeToLive,
99 DnsCodecUtil.decompressDomainName(
100 in.duplicate().setIndex(offset, offset + length)));
101 }
102 return new DefaultDnsRawRecord(
103 name, type, dnsClass, timeToLive, in.retainedDuplicate().setIndex(offset, offset + length));
104 }
105
106
107
108
109
110
111
112
113
114 protected String decodeName0(ByteBuf in) {
115 return decodeName(in);
116 }
117
118
119
120
121
122
123
124
125
126 public static String decodeName(ByteBuf in) {
127 return DnsCodecUtil.decodeDomainName(in);
128 }
129 }