package example.arkfor.updates import android.content.Context import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.math.BigInteger import java.net.HttpURLConnection import java.net.URI import java.security.MessageDigest import java.util.concurrent.TimeUnit import javax.net.ssl.HttpsURLConnection import org.json.JSONException import org.json.JSONObject /** * Android reference client for the public latest.json contract. * Call downloadIfNewer from a worker thread. It returns a verified file in the * app-private cache, or null when no update should be downloaded. It never * installs or executes the returned package. */ object ArkforAndroidUpdateClient { data class VerifiedUpdate( val version: String, val filename: String, val sha256: String, val file: File, ) private data class Manifest( val appId: String, val channel: String, val platform: String, val version: String, val downloadUrl: String, val filename: String, val sizeBytes: Long, val sha256: String, ) private data class SemVer( val major: BigInteger, val minor: BigInteger, val patch: BigInteger, val prerelease: String, ) private const val MAX_MANIFEST_BYTES = 1L shl 20 private const val DEFAULT_MAX_ARTIFACT_BYTES = 1L shl 30 private const val TOTAL_TIMEOUT_MILLIS = 15L * 60L * 1000L private const val SOCKET_TIMEOUT_MILLIS = 15_000 private const val MAX_REDIRECTS = 5 private val identifierPattern = Regex("^[a-z0-9][a-z0-9_-]{1,62}$") // Mirrors the server rule: Unicode letters/numbers are allowed (Chinese release // filenames), while separators, spaces, a leading dot and >200 UTF-8 bytes are not. private val filenamePattern = Regex("^[\\p{L}\\p{N}][\\p{L}\\p{N}._+-]{0,127}$") private val sha256Pattern = Regex("^[A-Fa-f0-9]{64}$") private val semVerPattern = Regex( "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z.-]+))?(?:\\+([0-9A-Za-z.-]+))?$", ) private val maxUint64 = BigInteger("18446744073709551615") /** * Checks one manifest and downloads only a strictly newer matching build. * The caller supplies the platform identifier used by its published app; * it is compared exactly with the manifest and is not inferred from device * hardware, which may support multiple ABIs. */ fun downloadIfNewer( context: Context, manifestUrl: String, expectedAppId: String, expectedChannel: String, expectedPlatform: String, installedVersion: String, allowPrerelease: Boolean = false, maxArtifactBytes: Long = DEFAULT_MAX_ARTIFACT_BYTES, ): VerifiedUpdate? { require(identifierPattern.matches(expectedAppId)) { "expected app ID is invalid" } require(identifierPattern.matches(expectedChannel)) { "expected channel is invalid" } require(identifierPattern.matches(expectedPlatform)) { "expected platform is invalid" } require(maxArtifactBytes > 0) { "maximum artifact size must be positive" } val installed = parseSemVer(installedVersion) val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(TOTAL_TIMEOUT_MILLIS) val manifestConnection = openHttps(manifestUrl, deadline) val manifest = try { if (contentLength(manifestConnection) > MAX_MANIFEST_BYTES) { throw IOException("manifest is too large") } val bytes = readAtMost(manifestConnection, MAX_MANIFEST_BYTES, deadline) parseManifest(bytes, maxArtifactBytes) } finally { manifestConnection.disconnect() } if (manifest.appId != expectedAppId || manifest.channel != expectedChannel || manifest.platform != expectedPlatform ) { throw IOException("manifest app, channel, or platform does not match the requested target") } val latest = parseSemVer(manifest.version) if (compareSemVer(latest, installed) <= 0) return null if (latest.prerelease.isNotEmpty() && !allowPrerelease) return null return downloadArtifact( context.applicationContext.cacheDir, manifest, maxArtifactBytes, deadline, ) } private fun parseManifest(bytes: ByteArray, maxArtifactBytes: Long): Manifest { val json = try { JSONObject(bytes.toString(Charsets.UTF_8)) } catch (error: JSONException) { throw IOException("manifest JSON is invalid", error) } if (requiredLong(json, "schemaVersion") != 1L) { throw IOException("manifest schema is unsupported") } val appId = requiredString(json, "appId") val channel = requiredString(json, "channel") val platform = requiredString(json, "platform") if (!identifierPattern.matches(appId) || !identifierPattern.matches(channel) || !identifierPattern.matches(platform) ) { throw IOException("manifest target is invalid") } val version = requiredString(json, "version") parseSemVer(version) val filename = requiredString(json, "filename") if (filename.toByteArray(Charsets.UTF_8).size > 200 || !filenamePattern.matches(filename)) { throw IOException("manifest filename is invalid") } val sizeBytes = requiredLong(json, "sizeBytes") if (sizeBytes <= 0 || sizeBytes > maxArtifactBytes || sizeBytes == Long.MAX_VALUE) { throw IOException("artifact size is outside the configured limit") } val sha256 = requiredString(json, "sha256") if (!sha256Pattern.matches(sha256)) throw IOException("manifest SHA-256 is invalid") val downloadUrl = requiredString(json, "downloadUrl") requireHttpsUri(downloadUrl) return Manifest(appId, channel, platform, version, downloadUrl, filename, sizeBytes, sha256) } private fun requiredString(json: JSONObject, name: String): String = try { json.get(name) as? String ?: throw IOException("manifest field $name is invalid") } catch (error: JSONException) { throw IOException("manifest field $name is missing", error) } private fun requiredLong(json: JSONObject, name: String): Long = try { when (val value = json.get(name)) { is Int -> value.toLong() is Long -> value else -> throw IOException("manifest field $name is invalid") } } catch (error: JSONException) { throw IOException("manifest field $name is missing", error) } private fun downloadArtifact( cacheDirectory: File, manifest: Manifest, maxArtifactBytes: Long, deadline: Long, ): VerifiedUpdate { if (manifest.sizeBytes > maxArtifactBytes) throw IOException("artifact exceeds the configured limit") val connection = openHttps(manifest.downloadUrl, deadline) val responseLength = contentLength(connection) if (responseLength >= 0 && responseLength != manifest.sizeBytes) { connection.disconnect() throw IOException("artifact Content-Length does not match the manifest") } val temporary = try { File.createTempFile("arkfor-update-", ".artifact", cacheDirectory) } catch (error: IOException) { connection.disconnect() throw error } var keepFile = false try { val digest = MessageDigest.getInstance("SHA-256") var total = 0L FileOutputStream(temporary).use { output -> connection.inputStream.use { input -> val buffer = ByteArray(16 * 1024) while (true) { connection.readTimeout = remainingTimeoutMillis(deadline) val count = input.read(buffer) if (count < 0) break val countBytes = count.toLong() if (countBytes > manifest.sizeBytes - total || countBytes > maxArtifactBytes - total) { throw IOException("artifact is larger than the manifest or configured limit") } total += countBytes digest.update(buffer, 0, count) output.write(buffer, 0, count) } } output.fd.sync() } if (total != manifest.sizeBytes) throw IOException("artifact size does not match the manifest") val actualSha256 = digest.digest().joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) } if (!actualSha256.equals(manifest.sha256, ignoreCase = true)) { throw IOException("artifact SHA-256 does not match the manifest") } keepFile = true return VerifiedUpdate(manifest.version, manifest.filename, actualSha256, temporary) } finally { connection.disconnect() if (!keepFile) temporary.delete() } } private fun readAtMost(connection: HttpsURLConnection, limit: Long, deadline: Long): ByteArray { val output = ByteArrayOutputStream() connection.inputStream.use { input -> val buffer = ByteArray(8 * 1024) var total = 0L while (true) { connection.readTimeout = remainingTimeoutMillis(deadline) val count = input.read(buffer) if (count < 0) break total += count if (total > limit) throw IOException("response exceeds the configured limit") output.write(buffer, 0, count) } } return output.toByteArray() } private fun openHttps(rawUrl: String, deadline: Long): HttpsURLConnection { var target = requireHttpsUri(rawUrl) for (redirectCount in 0..MAX_REDIRECTS) { val connection = (target.toURL().openConnection() as? HttpsURLConnection) ?: throw IOException("HTTPS connection is unavailable") connection.instanceFollowRedirects = false connection.connectTimeout = remainingTimeoutMillis(deadline) connection.readTimeout = remainingTimeoutMillis(deadline) connection.requestMethod = "GET" connection.setRequestProperty("Accept-Encoding", "identity") connection.setRequestProperty("Cache-Control", "no-cache") val status = try { connection.responseCode } catch (error: IOException) { connection.disconnect() throw IOException("HTTPS request failed", error) } if (status in REDIRECT_STATUSES) { val location = connection.getHeaderField("Location") connection.disconnect() if (redirectCount == MAX_REDIRECTS || location.isNullOrBlank()) { throw IOException("HTTPS redirect could not be followed") } target = requireHttpsUri(target.resolve(location).toString()) continue } if (status != HttpURLConnection.HTTP_OK) { connection.disconnect() throw IOException("HTTPS server returned HTTP $status") } return connection } throw IOException("too many HTTPS redirects") } private fun contentLength(connection: HttpsURLConnection): Long = connection.getHeaderField("Content-Length")?.toLongOrNull() ?: -1L private fun requireHttpsUri(value: String): URI { val uri = try { URI(value) } catch (error: Exception) { throw IOException("URL is invalid", error) } if (!uri.scheme.orEmpty().equals("https", ignoreCase = true) || uri.host.isNullOrBlank() || uri.port !in -1..65535 || uri.userInfo != null || uri.rawFragment != null ) { throw IOException("URL must use HTTPS without credentials or fragments") } return uri } private fun parseSemVer(value: String): SemVer { val match = semVerPattern.matchEntire(value) ?: throw IOException("semantic version is invalid") val majorText = match.groupValues[1] val minorText = match.groupValues[2] val patchText = match.groupValues[3] val prereleaseText = match.groupValues[4] val buildText = match.groupValues[5] validatePrerelease(prereleaseText) validateBuild(buildText) if (majorText.length > 20 || minorText.length > 20 || patchText.length > 20) { throw IOException("semantic version component is too large") } val major = BigInteger(majorText) val minor = BigInteger(minorText) val patch = BigInteger(patchText) if (major > maxUint64 || minor > maxUint64 || patch > maxUint64) { throw IOException("semantic version component is too large") } return SemVer(major, minor, patch, prereleaseText) } private fun compareSemVer(a: SemVer, b: SemVer): Int { a.major.compareTo(b.major).takeIf { it != 0 }?.let { return it } a.minor.compareTo(b.minor).takeIf { it != 0 }?.let { return it } a.patch.compareTo(b.patch).takeIf { it != 0 }?.let { return it } if (a.prerelease.isEmpty()) return if (b.prerelease.isEmpty()) 0 else 1 if (b.prerelease.isEmpty()) return -1 return comparePrerelease(a.prerelease, b.prerelease) } private fun validatePrerelease(value: String) { if (value.isEmpty()) return if (value.hasEmptyDotIdentifier()) throw IOException("semantic version prerelease is invalid") var start = 0 while (start < value.length) { val end = identifierEnd(value, start) if (isNumericIdentifier(value, start, end) && end - start > 1 && value[start] == '0') { throw IOException("semantic version prerelease is invalid") } start = end + 1 } } private fun validateBuild(value: String) { if (value.isNotEmpty() && value.hasEmptyDotIdentifier()) { throw IOException("semantic version build metadata is invalid") } } private fun comparePrerelease(a: String, b: String): Int { var aStart = 0 var bStart = 0 while (true) { val aEnd = identifierEnd(a, aStart) val bEnd = identifierEnd(b, bStart) val comparison = compareIdentifier(a, aStart, aEnd, b, bStart, bEnd) if (comparison != 0) return comparison val aFinished = aEnd == a.length val bFinished = bEnd == b.length if (aFinished || bFinished) { return when { aFinished && bFinished -> 0 aFinished -> -1 else -> 1 } } aStart = aEnd + 1 bStart = bEnd + 1 } } private fun compareIdentifier(a: String, aStart: Int, aEnd: Int, b: String, bStart: Int, bEnd: Int): Int { val aNumeric = isNumericIdentifier(a, aStart, aEnd) val bNumeric = isNumericIdentifier(b, bStart, bEnd) if (aNumeric && bNumeric) { val aLength = aEnd - aStart val bLength = bEnd - bStart if (aLength != bLength) return aLength.compareTo(bLength) } else { if (aNumeric) return -1 if (bNumeric) return 1 } val sharedLength = minOf(aEnd - aStart, bEnd - bStart) for (index in 0 until sharedLength) { val comparison = a[aStart + index].compareTo(b[bStart + index]) if (comparison != 0) return comparison } return (aEnd - aStart).compareTo(bEnd - bStart) } private fun identifierEnd(value: String, start: Int): Int { val separator = value.indexOf('.', start) return if (separator < 0) value.length else separator } private fun isNumericIdentifier(value: String, start: Int, end: Int): Boolean { if (start >= end) return false for (index in start until end) if (value[index] !in '0'..'9') return false return true } private fun String.hasEmptyDotIdentifier(): Boolean = startsWith('.') || endsWith('.') || contains("..") private fun remainingTimeoutMillis(deadline: Long): Int { if (Thread.currentThread().isInterrupted) throw IOException("update request was interrupted") val remainingNanos = deadline - System.nanoTime() if (remainingNanos <= 0) throw IOException("update request timed out") val remainingMillis = TimeUnit.NANOSECONDS.toMillis(remainingNanos).coerceAtLeast(1L) return minOf(SOCKET_TIMEOUT_MILLIS.toLong(), remainingMillis).toInt() } private val REDIRECT_STATUSES = setOf( HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_SEE_OTHER, 307, 308, ) }