package run.webup.platform; import java.util.*; import javax.naming.directory.*; import org.springframework.stereotype.Component; @Component public class DomainResolver { public List records(String hostname, String type) { Hashtable env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "1"); DirContext context = null; try { context = new InitialDirContext(env); var values = context.getAttributes(hostname, new String[] {type}).get(type); List result = new ArrayList<>(); if (values != null) for (int i = 0; i < values.size() && i < 100; i++) result.add(values.get(i).toString()); return result; } catch (javax.naming.NameNotFoundException e) { return List.of(); } catch (Exception e) { throw new ApiError.Failure(502, "DNS 查询失败,请稍后重试或检查解析服务器"); } finally { if (context != null) try { context.close(); } catch (Exception ignored) { } } } public boolean proof(String hostname, String token) { return records("_webup-challenge." + hostname, "TXT").stream() .anyMatch(value -> value.replace("\"", "").replace(" ", "").equals(token)); } public boolean pointsTo(String hostname, String expected) { String current = hostname; for (int depth = 0; depth < 8; depth++) { var values = records(current, "CNAME"); if (values.isEmpty()) break; current = DomainNames.hostname(values.getFirst()); if (current.equals(expected)) return true; } Set target = new HashSet<>(records(expected, "A")); target.addAll(records(expected, "AAAA")); if (target.isEmpty()) return false; List addresses = new ArrayList<>(records(hostname, "A")); addresses.addAll(records(hostname, "AAAA")); return !addresses.isEmpty() && target.containsAll(addresses); } }