Yokan / rebuild
Course 1 8624561

EnhancedHttpService.kt

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

implementation357 lines
1package eu.friedcutlet.yokan.services.http23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.services.logging.AppLogger6import eu.friedcutlet.yokan.services.logging.Diagnostics7import eu.friedcutlet.yokan.services.http.cookies.CookieJar8import eu.friedcutlet.yokan.services.http.cookies.parseHost9import kotlin.concurrent.Volatile10import kotlinx.coroutines.CancellationException11import kotlinx.coroutines.delay12import kotlinx.coroutines.sync.Mutex13import kotlinx.coroutines.sync.withLock14import kotlinx.serialization.json.Json15import kotlinx.serialization.json.JsonArray16import kotlinx.serialization.json.JsonObject17import kotlinx.serialization.json.JsonPrimitive18import kotlinx.serialization.json.buildJsonObject19import kotlinx.serialization.json.contentOrNull20import kotlinx.serialization.json.jsonArray21import kotlinx.serialization.json.jsonObject22import kotlinx.serialization.json.jsonPrimitive23import kotlinx.serialization.json.put2425/**26 * Decorator around the platform [HttpService] that adds:27 *   - default `User-Agent` (`DbSettings.userAgent`).28 *   - automatic Cookie injection + Set-Cookie persistence via the shared29 *     [CookieJar].30 *   - request/response logging through [AppLogger].31 *   - automatic Cloudflare challenge solving for GET requests and streams: a32 *     FlareSolverr-compatible proxy first, then the platform WebView33 *     (Mangayomi's `m_client` retry policy), single-flight per host.34 */35class EnhancedHttpService(36    private val delegate: HttpService,37    private val database: YokanDatabase,38    private val cookieJar: CookieJar,39) : HttpService {40    /** Set once the platform WebView service exists (see ServiceRegistry). */41    var cloudflareSolver: (suspend (url: String, headers: Map<String, String>) -> HttpResponse?)? = null4243    // ponytail: one gate per host ever challenged, never evicted; such hosts are few.44    private val solveGatesLock = Mutex()45    private val solveGates = HashMap<String, CloudflareGate>()4647    override suspend fun request(request: HttpRequest): HttpResponse {48        request.skipMarked()?.let { return performRequest(it, allowCloudflareSolve = false) }49        return performRequest(request, allowCloudflareSolve = true)50    }5152    override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {53        val skipped = request.skipMarked()54        if (skipped != null || !request.method.equals("GET", ignoreCase = true)) {55            return performStream(skipped ?: request, onChunk)56        }57        val seen = solveGeneration(request.url)58        val response = performStream(request, onChunk)59        if (!response.isCloudflareChallenge()) return response60        clearCloudflare(request.url, enrichedHeaders(request, database.settings()), seen) ?: return response61        AppLogger.info("[net] Retrying stream ${request.url} with the fresh Cloudflare clearance")62        return performStream(request, onChunk)63    }6465    private suspend fun performStream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {66        val settings = database.settings()67        val headers = enrichedHeaders(request, settings)68        val startMs = eu.friedcutlet.yokan.util.nowMillis()69        var received = 0L70        AppLogger.info("[net] ${request.method} ${request.url} (stream)")71        val response = try {72            delegate.stream(request.copy(headers = headers)) { chunk ->73                throttleBytes(chunk.size.toLong(), settings.networkDownloadSpeedLimitKib)74                received += chunk.size75                onChunk(chunk)76            }77        } catch (t: Throwable) {78            val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs79            AppLogger.error("[net] ${request.method} ${request.url} -> ${t::class.simpleName}: ${t.message.orEmpty()} (${elapsed}ms)")80            Diagnostics.recordRequestFailure()81            throw t82        }83        cookieJar.setFromResponse(request.url, response.setCookies)84        val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs85        Diagnostics.recordResponse(response.statusCode, received)86        val log: (String) -> Unit = if (response.statusCode in 200..399) AppLogger::info else AppLogger::warn87        log("[net] ${request.method} ${request.url} -> ${response.statusCode} (${elapsed}ms, ${received}B streamed)")88        return response89    }9091    /** Without the skip marker and the caller's Cookie (the jar's fresh clearance replaces it); null when unmarked. */92    private fun HttpRequest.skipMarked(): HttpRequest? {93        if (headers.keys.none { it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true) }) return null94        return copy(headers = headers.filterKeys {95            !it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true) && !it.equals("Cookie", ignoreCase = true)96        })97    }9899    private suspend fun performRequest(request: HttpRequest, allowCloudflareSolve: Boolean): HttpResponse {100        val settings = database.settings()101        val solvable = allowCloudflareSolve && request.method.equals("GET", ignoreCase = true)102        val seen = if (solvable) solveGeneration(request.url) else 0103        val forceCloudflareSolve = request.headers.keys.any {104            it.equals(RESOLVE_CLOUDFLARE_HEADER, ignoreCase = true)105        }106        val headers = enrichedHeaders(request, settings)107        // Network log: method + URL on entry, status + duration on success, error class108        // + message on failure. Goes through AppLogger (stdout + opt-in file).109        val startMs = eu.friedcutlet.yokan.util.nowMillis()110        AppLogger.info("[net] ${request.method} ${request.url}")111        val uploadBytes = request.bodyBytes?.size?.toLong()112            ?: request.body?.encodeToByteArray()?.size?.toLong()113            ?: 0L114        throttleBytes(uploadBytes, settings.networkUploadSpeedLimitKib)115        val response = try {116            delegate.request(request.copy(headers = headers))117        } catch (t: Throwable) {118            val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs119            val cause = t.message.orEmpty().ifBlank { t::class.simpleName.orEmpty() }120            AppLogger.error("[net] ${request.method} ${request.url} -> ${t::class.simpleName}: $cause (${elapsed}ms)")121            Diagnostics.recordRequestFailure()122            throw t123        }124        val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs125        Diagnostics.recordResponse(response.statusCode, response.bodyBytes.size.toLong())126        val level: (String) -> Unit = if (response.statusCode in 200..399) AppLogger::info else AppLogger::warn127        level("[net] ${request.method} ${request.url} -> ${response.statusCode} (${elapsed}ms, ${response.bodyBytes.size}B)")128        throttleBytes(response.bodyBytes.size.toLong(), settings.networkDownloadSpeedLimitKib)129        cookieJar.setFromResponse(request.url, response.setCookies)130        if (solvable && (forceCloudflareSolve || response.isCloudflareChallenge())) {131            val clearance = clearCloudflare(request.url, headers, seen) ?: return response132            clearance.webViewResponse?.let { return it }133            val retried = performRequest(request, allowCloudflareSolve = false)134            if (!retried.isCloudflareChallenge()) return retried135            AppLogger.warn("[net] Cloudflare challenge NOT cleared after proxy retry for ${request.url}")136            val fallback = clearCloudflare(request.url, headers, solveGeneration(request.url), useProxy = false)137            return fallback?.webViewResponse ?: retried138        }139        return response140    }141142    /**143     * Clears the Cloudflare challenge on [url]'s host, one solve at a time per host: a caller that144     * waited out another caller's attempt ([seenGeneration] is stale) reuses its outcome instead of145     * solving again, so N parallel page downloads trigger one solve. Null when nothing cleared it.146     */147    private suspend fun clearCloudflare(148        url: String,149        headers: Map<String, String>,150        seenGeneration: Int,151        useProxy: Boolean = true,152    ): CloudflareClearance? {153        val gate = solveGate(url)154        return gate.mutex.withLock {155            if (gate.generation != seenGeneration) return@withLock gate.lastClearance156            solveCloudflare(url, headers, useProxy).also { cleared ->157                // Waiters retry on the cookies themselves; the WebView's response answered only this caller.158                gate.lastClearance = if (cleared != null) CloudflareClearance(webViewResponse = null) else null159                gate.generation += 1160            }161        }162    }163164    /** The FlareSolverr-compatible proxy when configured, then the WebView. Never re-enters itself. */165    private suspend fun solveCloudflare(url: String, headers: Map<String, String>, useProxy: Boolean): CloudflareClearance? {166        val proxyUrl = database.settings().cloudflareBypassProxyUrl.trim()167        if (useProxy && proxyUrl.isNotEmpty()) {168            AppLogger.info("[net] Cloudflare challenge detected for $url; solving via proxy ($proxyUrl)")169            if (solveWithCfProxy(proxyUrl, url)) {170                AppLogger.info("[net] Cloudflare challenge solved via proxy for $url; retrying")171                return CloudflareClearance(webViewResponse = null)172            }173        }174        val solver = cloudflareSolver ?: return null175        AppLogger.info("[net] Cloudflare challenge detected for $url; solving via WebView")176        // ponytail: the platform solvers re-fetch [url] through request() to verify, which buffers the177        // body; fine for pages, a video stream is held in memory once. Upgrade: a verify-less solve.178        val solved = catchingNonCancellation {179            solver(url, headers + (SKIP_CLOUDFLARE_HEADER to "1"))180        }.getOrNull()181        if (solved != null && !solved.isCloudflareChallenge()) {182            AppLogger.info("[net] Cloudflare challenge cleared for $url")183            return CloudflareClearance(webViewResponse = solved)184        }185        AppLogger.warn("[net] Cloudflare challenge NOT cleared for $url")186        return null187    }188189    private suspend fun solveGate(url: String): CloudflareGate =190        solveGatesLock.withLock { solveGates.getOrPut(parseHost(url).orEmpty()) { CloudflareGate() } }191192    /** Read before sending, so a solve that finishes while this call is in flight is reused, not repeated. */193    private suspend fun solveGeneration(url: String): Int =194        solveGatesLock.withLock { solveGates[parseHost(url).orEmpty()]?.generation ?: 0 }195196    private suspend fun solveWithCfProxy(proxyUrl: String, targetUrl: String): Boolean {197        return try {198            val payload = buildJsonObject {199                put("cmd", "request.get")200                put("url", targetUrl)201                put("maxTimeout", 60000)202                // Only cookies + userAgent are read; FlareSolverr >= 3.1 and Byparr skip the page body.203                put("returnOnlyCookies", true)204            }.toString()205            val proxyResponse = delegate.request(206                HttpRequest(207                    url = cloudflareProxyEndpoint(proxyUrl),208                    method = "POST",209                    headers = mapOf(210                        "Content-Type" to "application/json",211                        SKIP_CLOUDFLARE_HEADER to "1",212                    ),213                    body = payload,214                ),215            )216            if (proxyResponse.statusCode != 200) {217                AppLogger.warn("[net] Cloudflare proxy returned HTTP ${proxyResponse.statusCode}")218                return false219            }220            val root = CfProxyJson.parseToJsonElement(proxyResponse.body) as? JsonObject ?: return false221            val status = root["status"]?.jsonPrimitive?.contentOrNull222            if (status != "ok") {223                val message = root["message"]?.jsonPrimitive?.contentOrNull224                AppLogger.warn("[net] Cloudflare proxy status: $status ($message)")225                return false226            }227            val solution = root["solution"]?.jsonObject ?: return false228            val cookiesArray = solution["cookies"]?.jsonArray ?: JsonArray(emptyList())229            val cookies = cookiesArray.mapNotNull { item ->230                val obj = item as? JsonObject ?: return@mapNotNull null231                val name = obj["name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null232                val value = obj["value"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null233                val domain = obj["domain"]?.jsonPrimitive?.contentOrNull?.trimStart('.')234                Triple(name, value, domain)235            }236            if (cookies.isEmpty()) {237                AppLogger.warn("[net] Cloudflare proxy returned no cookies in solution")238                return false239            }240            // Each cookie goes to its own domain; the target host additionally gets the cookies241            // whose domain covers it, so a `.example.com` clearance still reaches `www.example.com`.242            val targetHost = parseHost(targetUrl)243            cookies.groupBy { it.third?.takeIf(String::isNotBlank) ?: targetHost }244                .forEach { (domain, group) -> if (domain != null) cookieJar.put(domain, group.cookieHeader()) }245            if (targetHost != null) {246                val covering = cookies.filter { (_, _, domain) ->247                    !domain.isNullOrBlank() && domain != targetHost && targetHost.endsWith(".$domain")248                }249                if (covering.isNotEmpty()) cookieJar.put(targetHost, covering.cookieHeader())250            }251            val ua = solution["userAgent"]?.jsonPrimitive?.contentOrNull252            if (!ua.isNullOrBlank()) {253                cookieJar.rememberUserAgent(targetUrl, ua)254            }255            true256        } catch (cancelled: CancellationException) {257            throw cancelled258        } catch (t: Throwable) {259            AppLogger.warn("[net] Cloudflare proxy solve failed: ${t.message}")260            false261        }262    }263264    private fun enrichedHeaders(request: HttpRequest, settings: eu.friedcutlet.yokan.database.DbSettings): MutableMap<String, String> {265        val headers = request.headers266            .filterKeys {267                !it.equals(RESOLVE_CLOUDFLARE_HEADER, ignoreCase = true) &&268                    !it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true)269            }270            .toMutableMap()271        val sessionUserAgent = cookieJar.userAgent(request.url)272        if (sessionUserAgent != null) {273            headers.keys.filter { it.equals("User-Agent", ignoreCase = true) }.forEach(headers::remove)274            headers["User-Agent"] = sessionUserAgent275        } else if (headers.keys.none { it.equals("User-Agent", ignoreCase = true) }) {276            headers["User-Agent"] = settings.userAgent277        }278        if (headers.keys.none { it.equals("Cookie", ignoreCase = true) }) {279            cookieJar.cookieHeader(request.url)?.let { headers["Cookie"] = it }280        }281        return headers282    }283284    private suspend fun throttleBytes(bytes: Long, kibPerSecond: Int) {285        if (bytes <= 0L || kibPerSecond <= 0) return286        val bytesPerSecond = kibPerSecond.toLong().coerceAtLeast(1L) * 1024L287        val delayMs = (bytes * 1_000L) / bytesPerSecond288        if (delayMs > 0L) delay(delayMs)289    }290}291292private const val SKIP_CLOUDFLARE_HEADER = "X-Yokan-Skip-Cloudflare"293private const val RESOLVE_CLOUDFLARE_HEADER = "X-Yokan-Resolve-Cloudflare"294private val CfProxyJson = Json { ignoreUnknownKeys = true }295private val CloudflareChallengeTitle =296    Regex("<title[^>]*>\\s*(?:Just a moment|Attention Required)", RegexOption.IGNORE_CASE)297298/** `name=value; name2=value2` for (name, value, domain) triples. */299private fun List<Triple<String, String, String?>>.cookieHeader(): String =300    joinToString("; ") { "${it.first}=${it.second}" }301302internal fun isCloudflareChallengePageTitle(title: String): Boolean {303    val normalized = title.trim().lowercase()304    return normalized.contains("just a moment") ||305        normalized.contains("attention required") ||306        normalized.contains("verification required") ||307        normalized.contains("security verification")308}309310internal fun HttpResponse.isCloudflareChallenge(): Boolean {311    val challengeStatus = statusCode == 403 || statusCode == 429 || statusCode == 503312    // Challenge pages are HTML: don't decode image/video bodies to text just to scan them.313    val contentType = headers.header("content-type")314    if (!challengeStatus && contentType != null && !contentType.contains("html", ignoreCase = true)) return false315    if (hasChallengeMarkers(body)) return true316    if (!challengeStatus) return false317    val server = headers.header("server").orEmpty()318    return server.contains("cloudflare", ignoreCase = true) ||319        server.contains("ddos-guard", ignoreCase = true)320}321322/**323 * Stricter than the request check: an image host's plain 403 (hotlink/auth) must not trigger a solve, so a324 * stream needs Cloudflare's own `cf-mitigated: challenge`, or a Cloudflare HTML page carrying the markers.325 */326private fun HttpStreamResponse.isCloudflareChallenge(): Boolean {327    if (statusCode != 403 && statusCode != 429 && statusCode != 503) return false328    if (headers.header("cf-mitigated")?.equals("challenge", ignoreCase = true) == true) return true329    return headers.header("server")?.contains("cloudflare", ignoreCase = true) == true &&330        headers.header("content-type")?.contains("html", ignoreCase = true) == true &&331        hasChallengeMarkers(body.decodeToString())332}333334private fun hasChallengeMarkers(body: String): Boolean =335    body.contains(CloudflareChallengeTitle) ||336        body.contains("cf-browser-verification", ignoreCase = true) ||337        body.contains("cf-chl-widget", ignoreCase = true)338339/** A cleared challenge; [webViewResponse] is the WebView solver's verified retry, null when the caller must retry. */340private class CloudflareClearance(val webViewResponse: HttpResponse?)341342/** Single-flight state for one host; [generation] counts finished solve attempts, mutated under [mutex]. */343private class CloudflareGate {344    val mutex = Mutex()345    @Volatile var generation = 0346    var lastClearance: CloudflareClearance? = null347}348349/**350 * The FlareSolverr/Byparr endpoint for the configured proxy: a bare `host:port` (no path) gets `/v1`,351 * a missing scheme gets `http://`; an explicit path is used as typed.352 */353internal fun cloudflareProxyEndpoint(proxyUrl: String): String {354    val url = proxyUrl.trim().let { if ("://" in it) it else "http://$it" }355    val path = url.substringAfter("://").substringBefore('?').substringBefore('#').substringAfter('/', "")356    return if (path.isEmpty()) url.trimEnd('/') + "/v1" else url357}358

Search chapters, reference and source filenames.