Yokan / rebuild
Course 1 8624561

DnsService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/DnsService.kt

implementation92 lines
1package eu.friedcutlet.yokan.services.http23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.util.PlatformLock6import kotlinx.serialization.json.Json7import kotlinx.serialization.json.JsonArray8import kotlinx.serialization.json.JsonObject9import kotlinx.serialization.json.contentOrNull10import kotlinx.serialization.json.intOrNull11import kotlinx.serialization.json.jsonPrimitive1213const val CustomDohProviderId: Int = 9991415data class DohProviderOption(val id: Int, val name: String, val url: String)1617val DohProviders: List<DohProviderOption> = listOf(18    DohProviderOption(0, "Cloudflare", "https://cloudflare-dns.com/dns-query"),19    DohProviderOption(1, "Google", "https://dns.google/dns-query"),20    DohProviderOption(2, "AdGuard", "https://dns-unfiltered.adguard.com/dns-query"),21    DohProviderOption(3, "Quad9", "https://dns.quad9.net/dns-query"),22    DohProviderOption(4, "AliDNS", "https://dns.alidns.com/dns-query"),23    DohProviderOption(5, "DNSPod", "https://doh.pub/dns-query"),24    DohProviderOption(6, "360 DNS", "https://doh.360.cn/dns-query"),25    DohProviderOption(7, "Quad101", "https://dns.twnic.tw/dns-query"),26    DohProviderOption(8, "Mullvad", "https://doh.mullvad.net/dns-query"),27    DohProviderOption(9, "ControlD", "https://freedns.controld.com/p0"),28    DohProviderOption(10, "Njalla", "https://dns.njal.la/dns-query"),29    DohProviderOption(11, "Shecan", "https://free.shecan.ir/dns-query"),30)3132/**33 * Minimal DNS-over-HTTPS resolver. When DoH is enabled in settings (read on every lookup) we query34 * the configured provider's JSON endpoint and return the first IPv4 answer; otherwise null, so the35 * caller uses the system resolver. [http] must not resolve through this resolver.36 */37class DohResolver(38    private val database: YokanDatabase,39    private val http: HttpService,40) {41    private val json = Json { ignoreUnknownKeys = true; isLenient = true }42    // OkHttp resolves from several connection threads at once.43    private val cacheLock = PlatformLock()44    private val cache = mutableMapOf<String, CachedAnswer>()4546    suspend fun resolve(hostname: String): String? {47        if (hostname.isBlank()) return null48        val settings = database.settings()49        if (!settings.dohEnabled) return null50        val now = eu.friedcutlet.yokan.util.nowMillis()51        cacheLock.withLock { cache[hostname]?.takeIf { it.expiresAtMillis > now } }?.let { return it.address }52        val provider = providerFor(settings) ?: return null53        if (provider.url.isBlank()) return null54        val separator = if (provider.url.contains("?")) "&" else "?"55        val response = catchingNonCancellation {56            http.request(57                HttpRequest(58                    url = "${provider.url}${separator}name=$hostname&type=A",59                    headers = mapOf("Accept" to "application/dns-json"),60                ),61            )62        }.getOrNull() ?: return null63        if (response.statusCode !in 200..299) return null64        val parsed = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return null65        val answers = parsed["Answer"] as? JsonArray ?: return null66        val ip = answers.firstNotNullOfOrNull { entry ->67            val obj = entry as? JsonObject ?: return@firstNotNullOfOrNull null68            val type = obj["type"]?.jsonPrimitive?.intOrNull ?: return@firstNotNullOfOrNull null69            if (type != 1) return@firstNotNullOfOrNull null70            obj["data"]?.jsonPrimitive?.contentOrNull71        } ?: return null72        cacheLock.withLock { cache[hostname] = CachedAnswer(ip, now + ProviderCacheMillis) }73        return ip74    }7576    private fun providerFor(settings: eu.friedcutlet.yokan.database.DbSettings): Provider? {77        if (settings.dohProviderId == CustomDohProviderId) {78            val custom = settings.customDohUrl.trim()79            if (custom.isBlank()) return null80            return Provider("Custom", custom)81        }82        val match = DohProviders.firstOrNull { it.id == settings.dohProviderId } ?: DohProviders[0]83        return Provider(match.name, match.url)84    }8586    private companion object {87        const val ProviderCacheMillis = 5L * 60L * 1000L88    }8990    private data class Provider(val name: String, val url: String)91    private data class CachedAnswer(val address: String, val expiresAtMillis: Long)92}93

Search chapters, reference and source filenames.