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.channel.ChannelHandlerContext;
19 import io.netty5.channel.socket.DatagramPacket;
20 import io.netty5.handler.codec.CorruptedFrameException;
21 import io.netty5.handler.codec.MessageToMessageDecoder;
22 import io.netty5.util.internal.UnstableApi;
23
24 import java.net.InetSocketAddress;
25
26
27
28
29 @UnstableApi
30 public class DatagramDnsResponseDecoder extends MessageToMessageDecoder<DatagramPacket> {
31
32 private final DnsResponseDecoder<InetSocketAddress> responseDecoder;
33
34
35
36
37 public DatagramDnsResponseDecoder() {
38 this(DnsRecordDecoder.DEFAULT);
39 }
40
41
42
43
44 public DatagramDnsResponseDecoder(DnsRecordDecoder recordDecoder) {
45 responseDecoder = new DnsResponseDecoder<>(recordDecoder) {
46 @Override
47 protected DnsResponse newResponse(InetSocketAddress sender, InetSocketAddress recipient,
48 int id, DnsOpCode opCode, DnsResponseCode responseCode) {
49 return new DatagramDnsResponse(sender, recipient, id, opCode, responseCode);
50 }
51 };
52 }
53
54 @Override
55 public boolean isSharable() {
56 return true;
57 }
58
59 @Override
60 protected void decode(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
61 final DnsResponse response;
62 try {
63 response = decodeResponse(ctx, packet);
64 } catch (IndexOutOfBoundsException e) {
65 throw new CorruptedFrameException("Unable to decode response", e);
66 }
67 ctx.fireChannelRead(response);
68 }
69
70 protected DnsResponse decodeResponse(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
71 return responseDecoder.decode((InetSocketAddress) packet.sender(), (InetSocketAddress) packet.recipient(),
72 ctx.bufferAllocator(), packet.content());
73 }
74 }