|
| 1 | +package io.github.hectorvent.floci.core.common.dns; |
| 2 | + |
| 3 | +import io.github.hectorvent.floci.config.EmulatorConfig; |
| 4 | +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; |
| 5 | +import io.vertx.core.Vertx; |
| 6 | +import io.vertx.core.buffer.Buffer; |
| 7 | +import io.vertx.core.datagram.DatagramSocket; |
| 8 | +import io.vertx.core.datagram.DatagramSocketOptions; |
| 9 | +import jakarta.enterprise.context.ApplicationScoped; |
| 10 | +import jakarta.inject.Inject; |
| 11 | +import org.jboss.logging.Logger; |
| 12 | + |
| 13 | +import java.net.DatagramPacket; |
| 14 | +import java.net.InetAddress; |
| 15 | +import java.nio.ByteBuffer; |
| 16 | +import java.nio.file.Files; |
| 17 | +import java.nio.file.Path; |
| 18 | +import java.util.ArrayList; |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Optional; |
| 22 | + |
| 23 | +/** |
| 24 | + * Embedded UDP/53 DNS server that runs inside the Floci container and is injected |
| 25 | + * into every spawned container (Lambda, RDS, ElastiCache) as their DNS resolver. |
| 26 | + * |
| 27 | + * Resolves *.{floci.hostname} (and any configured extra-suffixes) to Floci's own |
| 28 | + * Docker network IP so virtual-hosted S3 URLs (my-bucket.floci:4566) work from |
| 29 | + * inside Lambda containers without requiring wildcard Docker aliases. |
| 30 | + * |
| 31 | + * All other queries are forwarded transparently to the upstream resolver read from |
| 32 | + * /etc/resolv.conf (Docker's embedded DNS at 127.0.0.11). |
| 33 | + * |
| 34 | + * Only starts when Floci detects it is running inside Docker. No-op on the host. |
| 35 | + */ |
| 36 | +@ApplicationScoped |
| 37 | +public class EmbeddedDnsServer { |
| 38 | + |
| 39 | + private static final Logger LOG = Logger.getLogger(EmbeddedDnsServer.class); |
| 40 | + private static final int DNS_PORT = 53; |
| 41 | + private static final int TTL = 60; |
| 42 | + private static final String FALLBACK_UPSTREAM = "127.0.0.11"; |
| 43 | + |
| 44 | + private volatile String serverIp; |
| 45 | + private final List<String> suffixes = new ArrayList<>(); |
| 46 | + private String upstreamDns; |
| 47 | + |
| 48 | + EmbeddedDnsServer(List<String> suffixes) { |
| 49 | + this.suffixes.addAll(suffixes); |
| 50 | + } |
| 51 | + |
| 52 | + @Inject |
| 53 | + public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx) { |
| 54 | + if (!containerDetector.isRunningInContainer()) { |
| 55 | + return; |
| 56 | + } |
| 57 | + try { |
| 58 | + String myIp = InetAddress.getLocalHost().getHostAddress(); |
| 59 | + upstreamDns = readUpstreamDns(); |
| 60 | + |
| 61 | + config.hostname().ifPresent(suffixes::add); |
| 62 | + config.dns().extraSuffixes().ifPresent(suffixes::addAll); |
| 63 | + |
| 64 | + DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); |
| 65 | + socket.listen(DNS_PORT, "0.0.0.0", ar -> { |
| 66 | + if (ar.succeeded()) { |
| 67 | + serverIp = myIp; |
| 68 | + LOG.infov("Embedded DNS server started on {0}:53, resolving {1} → {0}", myIp, suffixes); |
| 69 | + socket.handler(packet -> handleQuery( |
| 70 | + vertx, socket, packet.data().getBytes(), |
| 71 | + packet.sender().host(), packet.sender().port(), myIp)); |
| 72 | + } else { |
| 73 | + LOG.warnv("Embedded DNS server failed to bind on port 53: {0}", ar.cause().getMessage()); |
| 74 | + } |
| 75 | + }); |
| 76 | + } catch (Exception e) { |
| 77 | + LOG.warnv("Failed to initialize embedded DNS server: {0}", e.getMessage()); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + public Optional<String> getServerIp() { |
| 82 | + return Optional.ofNullable(serverIp); |
| 83 | + } |
| 84 | + |
| 85 | + // ── packet handling ─────────────────────────────────────────────────────── |
| 86 | + |
| 87 | + private void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data, |
| 88 | + String senderHost, int senderPort, String myIp) { |
| 89 | + try { |
| 90 | + ByteBuffer buf = ByteBuffer.wrap(data); |
| 91 | + short txId = buf.getShort(); |
| 92 | + short flags = buf.getShort(); |
| 93 | + short qdCount = buf.getShort(); |
| 94 | + buf.getShort(); // ancount |
| 95 | + buf.getShort(); // nscount |
| 96 | + buf.getShort(); // arcount |
| 97 | + |
| 98 | + if ((flags & 0x8000) != 0 || qdCount < 1) { |
| 99 | + return; // not a standard query |
| 100 | + } |
| 101 | + |
| 102 | + int questionOffset = buf.position(); // always 12 for a standard query |
| 103 | + String qname = readName(buf, data); |
| 104 | + short qtype = buf.getShort(); |
| 105 | + buf.getShort(); // qclass |
| 106 | + int questionEnd = buf.position(); |
| 107 | + |
| 108 | + if (qtype == 1 && matchesSuffix(qname)) { |
| 109 | + byte[] response = buildAResponse(data, txId, questionOffset, questionEnd, myIp); |
| 110 | + socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}); |
| 111 | + } else { |
| 112 | + forwardAsync(vertx, socket, data, senderHost, senderPort); |
| 113 | + } |
| 114 | + } catch (Exception e) { |
| 115 | + LOG.debugv("DNS packet error: {0}", e.getMessage()); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + // ── helpers ─────────────────────────────────────────────────────────────── |
| 120 | + |
| 121 | + boolean matchesSuffix(String name) { |
| 122 | + if (name == null || name.isEmpty()) { |
| 123 | + return false; |
| 124 | + } |
| 125 | + String lower = name.toLowerCase(); |
| 126 | + for (String suffix : suffixes) { |
| 127 | + String s = suffix.toLowerCase(); |
| 128 | + if (lower.equals(s) || lower.endsWith("." + s)) { |
| 129 | + return true; |
| 130 | + } |
| 131 | + } |
| 132 | + return false; |
| 133 | + } |
| 134 | + |
| 135 | + String readName(ByteBuffer buf, byte[] data) { |
| 136 | + StringBuilder sb = new StringBuilder(); |
| 137 | + int safety = 0; |
| 138 | + while (buf.hasRemaining() && safety++ < 128) { |
| 139 | + int len = buf.get() & 0xFF; |
| 140 | + if (len == 0) { |
| 141 | + break; |
| 142 | + } |
| 143 | + if ((len & 0xC0) == 0xC0) { |
| 144 | + // compression pointer |
| 145 | + int offset = ((len & 0x3F) << 8) | (buf.get() & 0xFF); |
| 146 | + ByteBuffer ptr = ByteBuffer.wrap(data); |
| 147 | + ptr.position(offset); |
| 148 | + if (sb.length() > 0) { |
| 149 | + sb.append('.'); |
| 150 | + } |
| 151 | + sb.append(readName(ptr, data)); |
| 152 | + return sb.toString(); |
| 153 | + } |
| 154 | + if (sb.length() > 0) { |
| 155 | + sb.append('.'); |
| 156 | + } |
| 157 | + byte[] label = new byte[len]; |
| 158 | + buf.get(label); |
| 159 | + sb.append(new String(label)); |
| 160 | + } |
| 161 | + return sb.toString(); |
| 162 | + } |
| 163 | + |
| 164 | + byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, String ip) { |
| 165 | + int questionLength = questionEnd - questionOffset; |
| 166 | + // header(12) + question + answer(name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) + rdata(4)) |
| 167 | + ByteBuffer resp = ByteBuffer.allocate(12 + questionLength + 16); |
| 168 | + |
| 169 | + // header |
| 170 | + resp.putShort(txId); |
| 171 | + resp.putShort((short) 0x8180); // QR=1, AA=1, RD=1, RCODE=0 |
| 172 | + resp.putShort((short) 1); // qdcount |
| 173 | + resp.putShort((short) 1); // ancount |
| 174 | + resp.putShort((short) 0); // nscount |
| 175 | + resp.putShort((short) 0); // arcount |
| 176 | + |
| 177 | + // question (copied verbatim from query) |
| 178 | + resp.put(query, questionOffset, questionLength); |
| 179 | + |
| 180 | + // answer |
| 181 | + resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name) |
| 182 | + resp.putShort((short) 1); // type A |
| 183 | + resp.putShort((short) 1); // class IN |
| 184 | + resp.putInt(TTL); |
| 185 | + resp.putShort((short) 4); // rdlength |
| 186 | + |
| 187 | + for (String octet : ip.split("\\.")) { |
| 188 | + resp.put((byte) Integer.parseInt(octet)); |
| 189 | + } |
| 190 | + |
| 191 | + return resp.array(); |
| 192 | + } |
| 193 | + |
| 194 | + private void forwardAsync(Vertx vertx, DatagramSocket socket, byte[] query, |
| 195 | + String senderHost, int senderPort) { |
| 196 | + String upstream = upstreamDns; |
| 197 | + if (upstream == null) { |
| 198 | + return; |
| 199 | + } |
| 200 | + vertx.executeBlocking(() -> { |
| 201 | + try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) { |
| 202 | + fwd.setSoTimeout(2000); |
| 203 | + InetAddress addr = InetAddress.getByName(upstream); |
| 204 | + fwd.send(new DatagramPacket(query, query.length, addr, DNS_PORT)); |
| 205 | + byte[] buf = new byte[512]; |
| 206 | + DatagramPacket resp = new DatagramPacket(buf, buf.length); |
| 207 | + fwd.receive(resp); |
| 208 | + return Arrays.copyOf(resp.getData(), resp.getLength()); |
| 209 | + } |
| 210 | + }).onSuccess(response -> |
| 211 | + socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}) |
| 212 | + ).onFailure(e -> |
| 213 | + LOG.debugv("DNS forwarding to {0} failed: {1}", upstream, e.getMessage()) |
| 214 | + ); |
| 215 | + } |
| 216 | + |
| 217 | + private String readUpstreamDns() { |
| 218 | + try { |
| 219 | + for (String line : Files.readAllLines(Path.of("/etc/resolv.conf"))) { |
| 220 | + line = line.trim(); |
| 221 | + if (line.startsWith("nameserver ")) { |
| 222 | + String server = line.substring("nameserver ".length()).trim(); |
| 223 | + if (!server.equals("127.0.0.1")) { |
| 224 | + return server; |
| 225 | + } |
| 226 | + } |
| 227 | + } |
| 228 | + } catch (Exception e) { |
| 229 | + LOG.debugv("Could not read /etc/resolv.conf: {0}", e.getMessage()); |
| 230 | + } |
| 231 | + return FALLBACK_UPSTREAM; |
| 232 | + } |
| 233 | +} |
0 commit comments