package com.qft.optical import java.net.URI /** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */ object EndpointRouting { /** * A dedicated QFT Wi-Fi must never reuse QR/LAN adapter addresses. Its only * direct candidates are gateways supplied by Android for that exact Network. * Current-LAN fallback mode may additionally use advertised same-subnet IPs. */ fun afterConnection( dedicatedWifi: Boolean, gatewayEndpoints: List, routedAdvertisedEndpoints: List, ): List = if (dedicatedWifi) { gatewayEndpoints.distinct() } else { (gatewayEndpoints + routedAdvertisedEndpoints).distinct() } /** Same isolation rule for retry/recovery after the first gateway probe. */ fun forRecovery( dedicatedWifi: Boolean, discoveredEndpoint: String?, gatewayEndpoints: List, advertisedEndpoints: List, ): List { val candidates = listOfNotNull(discoveredEndpoint) + gatewayEndpoints return (candidates + if (dedicatedWifi) emptyList() else advertisedEndpoints).distinct() } fun onAnySubnet( endpoints: List, expectedPort: Int, localLinks: List>, ): List { val subnets = localLinks.mapNotNull { (address, prefix) -> ipv4(address)?.let { it to prefix.coerceIn(0, 32) } } if (subnets.isEmpty()) return emptyList() return endpoints.filter { endpoint -> val uri = try { URI(endpoint) } catch (_: Exception) { return@filter false } if (uri.scheme != "http" || uri.port != expectedPort) return@filter false val candidate = ipv4(uri.host ?: return@filter false) ?: return@filter false subnets.any { (local, prefix) -> sameSubnet(local, candidate, prefix) } }.distinct() } private fun sameSubnet(a: Long, b: Long, prefix: Int): Boolean { if (prefix == 0) return true val mask = (0xFFFF_FFFFL shl (32 - prefix)) and 0xFFFF_FFFFL return (a and mask) == (b and mask) } private fun ipv4(value: String): Long? { val parts = value.split('.') if (parts.size != 4) return null var result = 0L for (part in parts) { val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null result = (result shl 8) or octet.toLong() } return result } }