1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.handler.codec.dns;
17
18 import io.netty5.buffer.api.Buffer;
19
20 import java.util.Objects;
21
22 final class DnsQueryEncoder {
23
24 private final DnsRecordEncoder recordEncoder;
25
26
27
28
29 DnsQueryEncoder(DnsRecordEncoder recordEncoder) {
30 this.recordEncoder = Objects.requireNonNull(recordEncoder, "recordEncoder");
31 }
32
33
34
35
36 void encode(DnsQuery query, Buffer out) throws Exception {
37 encodeHeader(query, out);
38 encodeQuestions(query, out);
39 encodeRecords(query, DnsSection.ADDITIONAL, out);
40 }
41
42
43
44
45
46
47
48 private static void encodeHeader(DnsQuery query, Buffer buf) {
49 buf.ensureWritable(12);
50 buf.writeShort((short) query.id());
51 short flags = 0;
52 flags |= (query.opCode().byteValue() & 0xFF) << 14;
53 if (query.isRecursionDesired()) {
54 flags |= 1 << 8;
55 }
56 buf.writeShort(flags);
57 buf.writeShort((short) query.count(DnsSection.QUESTION));
58 buf.writeShort((short) 0);
59 buf.writeShort((short) 0);
60 buf.writeShort((short) query.count(DnsSection.ADDITIONAL));
61 }
62
63 private void encodeQuestions(DnsQuery query, Buffer buf) throws Exception {
64 final int count = query.count(DnsSection.QUESTION);
65 for (int i = 0; i < count; i++) {
66 recordEncoder.encodeQuestion(query.recordAt(DnsSection.QUESTION, i), buf);
67 }
68 }
69
70 private void encodeRecords(DnsQuery query, DnsSection section, Buffer buf) throws Exception {
71 final int count = query.count(section);
72 for (int i = 0; i < count; i++) {
73 recordEncoder.encodeRecord(query.recordAt(section, i), buf);
74 }
75 }
76 }