@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.ext import io.ktor.client.HttpClient import io.ktor.client.engine.darwin.Darwin import io.ktor.client.request.prepareGet import io.ktor.client.statement.bodyAsChannel import io.ktor.http.isSuccess import io.ktor.utils.io.readAvailable import okio.Buffer import okio.FileSystem import okio.HashingSource import okio.Path import okio.Path.Companion.toPath import okio.buffer import okio.openZip import platform.Foundation.NSURL /** Installs only the architecture-independent server JAR; iOS JVM binaries stay build-provisioned. */ class IosExtensionServerInstaller private constructor( installRoot: String, private val bundledJvmPath: String, private val fileSystem: FileSystem, private val archiveDownloader: (suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit)?, private val trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String, ) { constructor( installRoot: String, bundledJvmPath: String, ) : this( installRoot = installRoot, bundledJvmPath = bundledJvmPath, fileSystem = FileSystem.SYSTEM, archiveDownloader = null, trustedDigest = { release, asset -> release.trustedSha256(asset) }, ) private val installRoot = installRoot.toPath(normalize = true) suspend fun install( release: ExtensionServerRelease, asset: ExtensionServerReleaseAsset, onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> }, ): InstalledExtensionServerBundle { if (!asset.name.endsWith(".zip", ignoreCase = true)) { throw ExtensionServerException("UNSUPPORTED_ARCHIVE", "Only ZIP bundles are supported") } val expectedDigest = trustedDigest(release, asset) fileSystem.createDirectories(installRoot) val archive = installRoot / ".download-${release.version}.zip" val staging = installRoot / ".install-${release.version}" val destination = installRoot / release.version try { fileSystem.delete(archive, mustExist = false) fileSystem.deleteRecursively(staging, mustExist = false) download(asset, archive, onProgress) verifyIosExtensionServerArchiveSha256(fileSystem, archive, expectedDigest) fileSystem.createDirectories(staging) extractIosExtensionServerJar(fileSystem, archive, staging) fileSystem.deleteRecursively(destination, mustExist = false) fileSystem.atomicMove(staging, destination) return resolveBundle(destination, release.version) } finally { fileSystem.delete(archive, mustExist = false) fileSystem.deleteRecursively(staging, mustExist = false) } } fun importJar(sourcePath: String): InstalledExtensionServerBundle { val source = sourcePath.removePrefix("file://").toPath(normalize = true) if (source.name.substringAfterLast('.', "").lowercase() != "jar" || fileSystem.metadataOrNull(source) == null) { throw ExtensionServerException("MISSING_JAR", "Selected extension server JAR does not exist: $source") } val destinationDirectory = installRoot / "manual" val destination = destinationDirectory / source.name val staging = destinationDirectory / ".${source.name}.import" fileSystem.createDirectories(destinationDirectory) fileSystem.delete(staging, mustExist = false) try { copy(source, staging) fileSystem.delete(destination, mustExist = false) fileSystem.atomicMove(staging, destination) } finally { fileSystem.delete(staging, mustExist = false) } return InstalledExtensionServerBundle( version = versionFromPath(destination), rootPath = destinationDirectory.toString(), jvmPath = bundledJvmPath, serverJarPath = destination.toString(), ) } private suspend fun download( asset: ExtensionServerReleaseAsset, target: Path, onProgress: (Long, Long) -> Unit, ) { archiveDownloader?.let { downloader -> downloader(asset, target, onProgress) return } NSURL.URLWithString(asset.downloadUrl) ?: throw ExtensionServerException("INVALID_DOWNLOAD_URL", "Invalid bundle URL: ${asset.downloadUrl}") val client = HttpClient(Darwin) try { client.prepareGet(asset.downloadUrl).execute { response -> if (!response.status.isSuccess()) { throw ExtensionServerException( "DOWNLOAD_HTTP_ERROR", "Bundle download failed with HTTP ${response.status.value}", ) } val channel = response.bodyAsChannel() val expected = response.headers["Content-Length"]?.toLongOrNull() ?: asset.size val output = fileSystem.sink(target).buffer() val buffer = ByteArray(8_192) var downloaded = 0L try { while (true) { val count = channel.readAvailable(buffer) if (count < 0) break if (count == 0) continue output.write(buffer, 0, count) downloaded += count onProgress(downloaded, expected) } } finally { output.close() } } } finally { client.close() } } private fun resolveBundle(directory: Path, version: String): InstalledExtensionServerBundle { val jar = fileSystem.listRecursively(directory) .firstOrNull { path -> val name = path.name.lowercase() name.endsWith(".jar") && "extensionserver" in name && fileSystem.metadata(path).isRegularFile } ?: throw ExtensionServerException("BUNDLE_INVALID", "Installed bundle has no extension server JAR") return InstalledExtensionServerBundle( version = version, rootPath = directory.toString(), jvmPath = bundledJvmPath, serverJarPath = jar.toString(), ) } private fun copy(source: Path, destination: Path) = copy(fileSystem, source, destination) private fun copy(sourceFileSystem: FileSystem, source: Path, destination: Path) { val input = sourceFileSystem.source(source).buffer() val output = fileSystem.sink(destination).buffer() try { output.writeAll(input) } finally { output.close() input.close() } } companion object { internal fun createForTesting( installRoot: String, bundledJvmPath: String, fileSystem: FileSystem, archiveDownloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit, trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String, ): IosExtensionServerInstaller = IosExtensionServerInstaller( installRoot = installRoot, bundledJvmPath = bundledJvmPath, fileSystem = fileSystem, archiveDownloader = archiveDownloader, trustedDigest = trustedDigest, ) } private fun versionFromPath(path: Path): String = Regex("""v?(\d+\.\d+\.\d+)""").find(path.name)?.groupValues?.getOrNull(1) ?: "manual" } internal fun verifyIosExtensionServerArchiveSha256( fileSystem: FileSystem, path: Path, expected: String?, ) { if (expected == null) { throw ExtensionServerException("MISSING_DIGEST", "Release asset has no trusted SHA-256 digest") } val hashingSource = HashingSource.sha256(fileSystem.source(path)) val buffer = Buffer() try { while (hashingSource.read(buffer, 8_192) != -1L) buffer.clear() } finally { hashingSource.close() } val actual = hashingSource.hash.hex() if (!actual.equals(expected, ignoreCase = true)) { throw ExtensionServerException( "CHECKSUM_MISMATCH", "Bundle checksum mismatch: expected $expected, received $actual", ) } } internal fun extractIosExtensionServerJar( fileSystem: FileSystem, archive: Path, destination: Path, ): Path { val zip = fileSystem.openZip(archive) val jar = zip.listRecursively("/".toPath()) .firstOrNull { path -> val name = path.name.lowercase() name.endsWith(".jar") && "extensionserver" in name && zip.metadata(path).isRegularFile } ?: throw ExtensionServerException("BUNDLE_INVALID", "Downloaded bundle has no extension server JAR") val extracted = destination / jar.name val input = zip.source(jar).buffer() val output = fileSystem.sink(extracted).buffer() try { output.writeAll(input) } finally { output.close() input.close() } return extracted }