Yokan / rebuild
Course 1 8624561

UpdateDeviceConditions.desktop.kt

composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.desktop.kt

implementation152 lines
1package eu.friedcutlet.yokan.services.scheduling23import eu.friedcutlet.yokan.database.DatabaseJson4import java.io.File5import java.net.NetworkInterface6import java.util.concurrent.TimeUnit7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.runInterruptible9import kotlinx.serialization.json.*1011actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions = runInterruptible(Dispatchers.IO) {12    when {13        System.getProperty("os.name").contains("win", true) -> decodeWindowsUpdateConditions(conditionCommand(14            listOf("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",15                "\$ReadPower = ${if (needPower) "\$true" else "\$false"};\n$WindowsConditionScript")))16        System.getProperty("os.name").contains("mac", true) -> {17            val route = conditionCommand(listOf("/sbin/route", "-n", "get", "default"))18            val hardware = conditionCommand(listOf("/usr/sbin/networksetup", "-listallhardwareports"))19            val power = if (needPower) conditionCommand(listOf("/usr/bin/pmset", "-g", "batt")) else null20            decodeMacUpdateConditions(route, hardware, power)21        }22        else -> readLinuxUpdateConditions(needPower)23    }24}2526/** Fixed read-only commands, bounded runtime/output, no shell or user-controlled arguments. */27internal fun conditionCommand(command: List<String>, timeoutMillis: Long = 2_000, maximumBytes: Int = 8_192): String? {28    val process = try { ProcessBuilder(command).redirectErrorStream(true).apply { environment()["LC_ALL"] = "C" }.start() }29        catch (_: Exception) { return null }30    return try {31        if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS) || process.exitValue() != 0) null32        else {33            val available = process.inputStream.available()34            if (available > maximumBytes) null else process.inputStream.readNBytes(available).toString(Charsets.UTF_8)35        }36    } finally {37        if (process.isAlive) {38            process.descendants().use { descendants -> descendants.forEach { it.destroyForcibly() } }39            process.destroyForcibly()40        }41        process.inputStream.close()42        process.errorStream.close()43        process.outputStream.close()44    }45}4647internal fun decodeMacUpdateConditions(route: String?, hardware: String?, power: String?): UpdateDeviceConditions {48    val active = route?.lineSequence()?.firstOrNull { it.trim().startsWith("interface:") }?.substringAfter(':')?.trim()49    var port: String? = null50    val wifiInterfaces = mutableSetOf<String>()51    val knownInterfaces = mutableSetOf<String>()52    hardware?.lineSequence()?.forEach { line ->53        when {54            line.startsWith("Hardware Port:") -> port = line.substringAfter(':').trim()55            line.startsWith("Device:") -> {56                val name = line.substringAfter(':').trim()57                knownInterfaces += name58                if (port in setOf("Wi-Fi", "AirPort")) wifiInterfaces += name59            }60        }61    }62    val connected = if (route == null) null else active?.isNotEmpty() == true63    val wifi = if (connected == false) false else if (active == null || hardware == null || active !in knownInterfaces) null else active in wifiInterfaces64    val external = when {65        power?.lineSequence()?.firstOrNull()?.contains("'AC Power'") == true -> true66        power?.lineSequence()?.firstOrNull()?.contains("'Battery Power'") == true -> false67        else -> null68    }69    // macOS does not expose a reliable cost flag through these read-only command interfaces.70    return UpdateDeviceConditions(connected, wifi, if (connected == false) false else null, external)71}7273internal fun decodeWindowsUpdateConditions(json: String?): UpdateDeviceConditions {74    if (json == null) return UpdateDeviceConditions()75    return runCatching {76        val obj = DatabaseJson.parseToJsonElement(json.trim().removePrefix("\uFEFF")) as? JsonObject ?: return@runCatching UpdateDeviceConditions()77        if (obj.keys.any { it !in setOf("connected", "wifi", "unmetered", "externalPower") } || obj.values.any {78            it != JsonNull && (it !is JsonPrimitive || it.isString || it.booleanOrNull == null)79        }) return@runCatching UpdateDeviceConditions()80        DatabaseJson.decodeFromJsonElement<UpdateDeviceConditions>(obj)81    }.getOrElse { UpdateDeviceConditions() }82}8384private fun boundedText(path: String, maximum: Int = 65_536): String? = runCatching {85    File(path).inputStream().use { input -> input.readNBytes(maximum + 1).takeIf { it.size <= maximum }?.toString(Charsets.UTF_8) }86}.getOrNull()8788private fun readLinuxUpdateConditions(needPower: Boolean): UpdateDeviceConditions {89    val up = runCatching { NetworkInterface.getNetworkInterfaces().asSequence().filter { it.isUp && !it.isLoopback }90        .take(128).map { it.name }.toSet() }.getOrDefault(emptySet())91    val ipv4 = boundedText("/proc/net/route")92    val ipv6 = boundedText("/proc/net/ipv6_route")93    val active = linuxDefaultInterface(ipv4, ipv6, up)94    val connected = if (ipv4 == null && ipv6 == null) null else active != null95    val safeInterface = active?.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,64}")) }96    val wifi = if (connected == false) false else safeInterface?.let {97        File("/sys/class/net/$it/wireless").isDirectory || File("/sys/class/net/$it/phy80211").exists()98    }99    val metered = safeInterface?.let { conditionCommand(listOf("nmcli", "-t", "-g", "GENERAL.METERED", "device", "show", it)) }100    val supplies = (if (needPower) File("/sys/class/power_supply").listFiles().orEmpty().toList() else emptyList()).take(128).map { supply ->101        boundedText("${supply.path}/type", 128)?.trim().orEmpty() to boundedText("${supply.path}/online", 32)?.trim()102    }103    return UpdateDeviceConditions(connected, wifi,104        if (connected == false) false else decodeLinuxUnmetered(metered), decodeLinuxExternalPower(supplies))105}106107internal fun linuxDefaultInterface(ipv4: String?, ipv6: String?, up: Set<String>): String? {108    ipv4?.lineSequence()?.drop(1)?.forEach { line ->109        val fields = line.trim().split(Regex("\\s+"))110        if (fields.size >= 8 && fields[1] == "00000000" && fields[7] == "00000000" && fields[3].toIntOrNull(16)?.and(1) == 1 && fields[0] in up) return fields[0]111    }112    ipv6?.lineSequence()?.forEach { line ->113        val fields = line.trim().split(Regex("\\s+"))114        if (fields.size >= 10 && fields[0] == "0".repeat(32) && fields[1] == "00" && fields[8].toLongOrNull(16)?.and(1L) == 1L && fields.last() in up) return fields.last()115    }116    return null117}118119internal fun decodeLinuxUnmetered(value: String?): Boolean? = when (value?.trim()?.lowercase()) {120    "no" -> true121    "yes", "yes (guessed)", "guess-yes" -> false122    else -> null // A guess of free data is not affirmative evidence of an unmetered connection.123}124125internal fun decodeLinuxExternalPower(supplies: List<Pair<String, String?>>): Boolean? {126    val external = supplies.filter { (type, _) -> type == "Mains" || type.startsWith("USB") || type == "Wireless" }127        .mapNotNull { (_, online) -> when (online) { "1" -> true; "0" -> false; else -> null } }128    return when { true in external -> true; external.isNotEmpty() -> false; else -> null }129}130131private val WindowsConditionScript = """132    ${'$'}ErrorActionPreference = 'Stop'133    ${'$'}connected = ${'$'}null; ${'$'}wifi = ${'$'}null; ${'$'}unmetered = ${'$'}null; ${'$'}externalPower = ${'$'}null134    if (${'$'}ReadPower) { try {135        Add-Type -AssemblyName System.Windows.Forms136        ${'$'}line = [System.Windows.Forms.SystemInformation]::PowerStatus.PowerLineStatus.ToString()137        if (${'$'}line -eq 'Online') { ${'$'}externalPower = ${'$'}true }138        elseif (${'$'}line -eq 'Offline') { ${'$'}externalPower = ${'$'}false }139    } catch {} }140    try {141        ${'$'}profile = [Windows.Networking.Connectivity.NetworkInformation, Windows.Networking.Connectivity, ContentType=WindowsRuntime]::GetInternetConnectionProfile()142        if (${'$'}null -eq ${'$'}profile) { ${'$'}connected = ${'$'}false; ${'$'}wifi = ${'$'}false; ${'$'}unmetered = ${'$'}false }143        else {144            ${'$'}connected = ${'$'}profile.GetNetworkConnectivityLevel().ToString() -eq 'InternetAccess'145            ${'$'}wifi = ${'$'}connected -and ${'$'}profile.IsWlanConnectionProfile146            ${'$'}cost = ${'$'}profile.GetConnectionCost()147            ${'$'}kind = ${'$'}cost.NetworkCostType.ToString()148            if (${'$'}kind -ne 'Unknown') { ${'$'}unmetered = ${'$'}connected -and (${'$'}kind -eq 'Unrestricted') -and -not ${'$'}cost.Roaming -and -not ${'$'}cost.OverDataLimit }149        }150    } catch {}151    @{connected=${'$'}connected; wifi=${'$'}wifi; unmetered=${'$'}unmetered; externalPower=${'$'}externalPower} | ConvertTo-Json -Compress152""".trimIndent()153

Search chapters, reference and source filenames.