package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.database.DatabaseJson import java.io.File import java.net.NetworkInterface import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible import kotlinx.serialization.json.* actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions = runInterruptible(Dispatchers.IO) { when { System.getProperty("os.name").contains("win", true) -> decodeWindowsUpdateConditions(conditionCommand( listOf("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "\$ReadPower = ${if (needPower) "\$true" else "\$false"};\n$WindowsConditionScript"))) System.getProperty("os.name").contains("mac", true) -> { val route = conditionCommand(listOf("/sbin/route", "-n", "get", "default")) val hardware = conditionCommand(listOf("/usr/sbin/networksetup", "-listallhardwareports")) val power = if (needPower) conditionCommand(listOf("/usr/bin/pmset", "-g", "batt")) else null decodeMacUpdateConditions(route, hardware, power) } else -> readLinuxUpdateConditions(needPower) } } /** Fixed read-only commands, bounded runtime/output, no shell or user-controlled arguments. */ internal fun conditionCommand(command: List, timeoutMillis: Long = 2_000, maximumBytes: Int = 8_192): String? { val process = try { ProcessBuilder(command).redirectErrorStream(true).apply { environment()["LC_ALL"] = "C" }.start() } catch (_: Exception) { return null } return try { if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS) || process.exitValue() != 0) null else { val available = process.inputStream.available() if (available > maximumBytes) null else process.inputStream.readNBytes(available).toString(Charsets.UTF_8) } } finally { if (process.isAlive) { process.descendants().use { descendants -> descendants.forEach { it.destroyForcibly() } } process.destroyForcibly() } process.inputStream.close() process.errorStream.close() process.outputStream.close() } } internal fun decodeMacUpdateConditions(route: String?, hardware: String?, power: String?): UpdateDeviceConditions { val active = route?.lineSequence()?.firstOrNull { it.trim().startsWith("interface:") }?.substringAfter(':')?.trim() var port: String? = null val wifiInterfaces = mutableSetOf() val knownInterfaces = mutableSetOf() hardware?.lineSequence()?.forEach { line -> when { line.startsWith("Hardware Port:") -> port = line.substringAfter(':').trim() line.startsWith("Device:") -> { val name = line.substringAfter(':').trim() knownInterfaces += name if (port in setOf("Wi-Fi", "AirPort")) wifiInterfaces += name } } } val connected = if (route == null) null else active?.isNotEmpty() == true val wifi = if (connected == false) false else if (active == null || hardware == null || active !in knownInterfaces) null else active in wifiInterfaces val external = when { power?.lineSequence()?.firstOrNull()?.contains("'AC Power'") == true -> true power?.lineSequence()?.firstOrNull()?.contains("'Battery Power'") == true -> false else -> null } // macOS does not expose a reliable cost flag through these read-only command interfaces. return UpdateDeviceConditions(connected, wifi, if (connected == false) false else null, external) } internal fun decodeWindowsUpdateConditions(json: String?): UpdateDeviceConditions { if (json == null) return UpdateDeviceConditions() return runCatching { val obj = DatabaseJson.parseToJsonElement(json.trim().removePrefix("\uFEFF")) as? JsonObject ?: return@runCatching UpdateDeviceConditions() if (obj.keys.any { it !in setOf("connected", "wifi", "unmetered", "externalPower") } || obj.values.any { it != JsonNull && (it !is JsonPrimitive || it.isString || it.booleanOrNull == null) }) return@runCatching UpdateDeviceConditions() DatabaseJson.decodeFromJsonElement(obj) }.getOrElse { UpdateDeviceConditions() } } private fun boundedText(path: String, maximum: Int = 65_536): String? = runCatching { File(path).inputStream().use { input -> input.readNBytes(maximum + 1).takeIf { it.size <= maximum }?.toString(Charsets.UTF_8) } }.getOrNull() private fun readLinuxUpdateConditions(needPower: Boolean): UpdateDeviceConditions { val up = runCatching { NetworkInterface.getNetworkInterfaces().asSequence().filter { it.isUp && !it.isLoopback } .take(128).map { it.name }.toSet() }.getOrDefault(emptySet()) val ipv4 = boundedText("/proc/net/route") val ipv6 = boundedText("/proc/net/ipv6_route") val active = linuxDefaultInterface(ipv4, ipv6, up) val connected = if (ipv4 == null && ipv6 == null) null else active != null val safeInterface = active?.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,64}")) } val wifi = if (connected == false) false else safeInterface?.let { File("/sys/class/net/$it/wireless").isDirectory || File("/sys/class/net/$it/phy80211").exists() } val metered = safeInterface?.let { conditionCommand(listOf("nmcli", "-t", "-g", "GENERAL.METERED", "device", "show", it)) } val supplies = (if (needPower) File("/sys/class/power_supply").listFiles().orEmpty().toList() else emptyList()).take(128).map { supply -> boundedText("${supply.path}/type", 128)?.trim().orEmpty() to boundedText("${supply.path}/online", 32)?.trim() } return UpdateDeviceConditions(connected, wifi, if (connected == false) false else decodeLinuxUnmetered(metered), decodeLinuxExternalPower(supplies)) } internal fun linuxDefaultInterface(ipv4: String?, ipv6: String?, up: Set): String? { ipv4?.lineSequence()?.drop(1)?.forEach { line -> val fields = line.trim().split(Regex("\\s+")) if (fields.size >= 8 && fields[1] == "00000000" && fields[7] == "00000000" && fields[3].toIntOrNull(16)?.and(1) == 1 && fields[0] in up) return fields[0] } ipv6?.lineSequence()?.forEach { line -> val fields = line.trim().split(Regex("\\s+")) 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() } return null } internal fun decodeLinuxUnmetered(value: String?): Boolean? = when (value?.trim()?.lowercase()) { "no" -> true "yes", "yes (guessed)", "guess-yes" -> false else -> null // A guess of free data is not affirmative evidence of an unmetered connection. } internal fun decodeLinuxExternalPower(supplies: List>): Boolean? { val external = supplies.filter { (type, _) -> type == "Mains" || type.startsWith("USB") || type == "Wireless" } .mapNotNull { (_, online) -> when (online) { "1" -> true; "0" -> false; else -> null } } return when { true in external -> true; external.isNotEmpty() -> false; else -> null } } private val WindowsConditionScript = """ ${'$'}ErrorActionPreference = 'Stop' ${'$'}connected = ${'$'}null; ${'$'}wifi = ${'$'}null; ${'$'}unmetered = ${'$'}null; ${'$'}externalPower = ${'$'}null if (${'$'}ReadPower) { try { Add-Type -AssemblyName System.Windows.Forms ${'$'}line = [System.Windows.Forms.SystemInformation]::PowerStatus.PowerLineStatus.ToString() if (${'$'}line -eq 'Online') { ${'$'}externalPower = ${'$'}true } elseif (${'$'}line -eq 'Offline') { ${'$'}externalPower = ${'$'}false } } catch {} } try { ${'$'}profile = [Windows.Networking.Connectivity.NetworkInformation, Windows.Networking.Connectivity, ContentType=WindowsRuntime]::GetInternetConnectionProfile() if (${'$'}null -eq ${'$'}profile) { ${'$'}connected = ${'$'}false; ${'$'}wifi = ${'$'}false; ${'$'}unmetered = ${'$'}false } else { ${'$'}connected = ${'$'}profile.GetNetworkConnectivityLevel().ToString() -eq 'InternetAccess' ${'$'}wifi = ${'$'}connected -and ${'$'}profile.IsWlanConnectionProfile ${'$'}cost = ${'$'}profile.GetConnectionCost() ${'$'}kind = ${'$'}cost.NetworkCostType.ToString() if (${'$'}kind -ne 'Unknown') { ${'$'}unmetered = ${'$'}connected -and (${'$'}kind -eq 'Unrestricted') -and -not ${'$'}cost.Roaming -and -not ${'$'}cost.OverDataLimit } } } catch {} @{connected=${'$'}connected; wifi=${'$'}wifi; unmetered=${'$'}unmetered; externalPower=${'$'}externalPower} | ConvertTo-Json -Compress """.trimIndent()