package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonPrimitive const val CustomDohProviderId: Int = 999 data class DohProviderOption(val id: Int, val name: String, val url: String) val DohProviders: List = listOf( DohProviderOption(0, "Cloudflare", "https://cloudflare-dns.com/dns-query"), DohProviderOption(1, "Google", "https://dns.google/dns-query"), DohProviderOption(2, "AdGuard", "https://dns-unfiltered.adguard.com/dns-query"), DohProviderOption(3, "Quad9", "https://dns.quad9.net/dns-query"), DohProviderOption(4, "AliDNS", "https://dns.alidns.com/dns-query"), DohProviderOption(5, "DNSPod", "https://doh.pub/dns-query"), DohProviderOption(6, "360 DNS", "https://doh.360.cn/dns-query"), DohProviderOption(7, "Quad101", "https://dns.twnic.tw/dns-query"), DohProviderOption(8, "Mullvad", "https://doh.mullvad.net/dns-query"), DohProviderOption(9, "ControlD", "https://freedns.controld.com/p0"), DohProviderOption(10, "Njalla", "https://dns.njal.la/dns-query"), DohProviderOption(11, "Shecan", "https://free.shecan.ir/dns-query"), ) /** * Minimal DNS-over-HTTPS resolver. When DoH is enabled in settings (read on every lookup) we query * the configured provider's JSON endpoint and return the first IPv4 answer; otherwise null, so the * caller uses the system resolver. [http] must not resolve through this resolver. */ class DohResolver( private val database: YokanDatabase, private val http: HttpService, ) { private val json = Json { ignoreUnknownKeys = true; isLenient = true } // OkHttp resolves from several connection threads at once. private val cacheLock = PlatformLock() private val cache = mutableMapOf() suspend fun resolve(hostname: String): String? { if (hostname.isBlank()) return null val settings = database.settings() if (!settings.dohEnabled) return null val now = eu.friedcutlet.yokan.util.nowMillis() cacheLock.withLock { cache[hostname]?.takeIf { it.expiresAtMillis > now } }?.let { return it.address } val provider = providerFor(settings) ?: return null if (provider.url.isBlank()) return null val separator = if (provider.url.contains("?")) "&" else "?" val response = catchingNonCancellation { http.request( HttpRequest( url = "${provider.url}${separator}name=$hostname&type=A", headers = mapOf("Accept" to "application/dns-json"), ), ) }.getOrNull() ?: return null if (response.statusCode !in 200..299) return null val parsed = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return null val answers = parsed["Answer"] as? JsonArray ?: return null val ip = answers.firstNotNullOfOrNull { entry -> val obj = entry as? JsonObject ?: return@firstNotNullOfOrNull null val type = obj["type"]?.jsonPrimitive?.intOrNull ?: return@firstNotNullOfOrNull null if (type != 1) return@firstNotNullOfOrNull null obj["data"]?.jsonPrimitive?.contentOrNull } ?: return null cacheLock.withLock { cache[hostname] = CachedAnswer(ip, now + ProviderCacheMillis) } return ip } private fun providerFor(settings: eu.friedcutlet.yokan.database.DbSettings): Provider? { if (settings.dohProviderId == CustomDohProviderId) { val custom = settings.customDohUrl.trim() if (custom.isBlank()) return null return Provider("Custom", custom) } val match = DohProviders.firstOrNull { it.id == settings.dohProviderId } ?: DohProviders[0] return Provider(match.name, match.url) } private companion object { const val ProviderCacheMillis = 5L * 60L * 1000L } private data class Provider(val name: String, val url: String) private data class CachedAnswer(val address: String, val expiresAtMillis: Long) }