package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.services.files.IosZipArchive import eu.friedcutlet.yokan.services.files.buildStoredZip import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.addressOf import kotlinx.cinterop.alloc import kotlinx.cinterop.memScoped import kotlinx.cinterop.ptr import kotlinx.cinterop.reinterpret import kotlinx.cinterop.usePinned import platform.zlib.Z_BUF_ERROR import platform.zlib.Z_DEFAULT_STRATEGY import platform.zlib.Z_DEFLATED import platform.zlib.Z_FINISH import platform.zlib.Z_NO_FLUSH import platform.zlib.Z_OK import platform.zlib.Z_STREAM_END import platform.zlib.deflate import platform.zlib.deflateBound import platform.zlib.deflateEnd import platform.zlib.deflateInit2 import platform.zlib.inflate import platform.zlib.inflateEnd import platform.zlib.inflateInit2 import platform.zlib.z_stream actual fun createPlatformBackupCompression(): BackupCompression = IosBackupCompression /** * zlib-backed compression for backups. ZIP reading reuses [IosZipArchive] * (the same reader CBZ/EPUB support uses), so Mangayomi `.backup` archives * restore on iOS like they do on the JVM platforms. ZIP writing emits a * stored archive via [buildStoredZip]; the old Flutter app inflates entries * regardless of method, so skipping deflate only costs file size. */ @OptIn(ExperimentalForeignApi::class) private object IosBackupCompression : BackupCompression { // ponytail: single-shot gzip on whole byte arrays; stream if backups outgrow memory. override fun compress(data: ByteArray, level: Int): ByteArray = gzipDeflate(data, level) ?: error("gzip compression failed.") override fun decompress(data: ByteArray): ByteArray = gzipInflate(data) ?: error("Backup is not valid gzip data.") override fun unzipFirstEntry(data: ByteArray): ByteArray? { val archive = IosZipArchive.open(data) ?: return null return archive.entryNames.firstOrNull { !it.endsWith("/") }?.let(archive::read) } override fun unzipEntries(data: ByteArray): Map? { val archive = IosZipArchive.open(data) ?: return null return buildMap { archive.entryNames.forEach { name -> if (!name.endsWith("/")) archive.read(name)?.let { put(name, it) } } } } override fun zipSingleEntry(entryName: String, data: ByteArray, level: Int): ByteArray = buildStoredZip(listOf(entryName to data)) } /** windowBits 15 + 16 selects the gzip wrapper in zlib. */ private const val GZIP_WINDOW_BITS = 15 + 16 @OptIn(ExperimentalForeignApi::class) private fun gzipDeflate(data: ByteArray, level: Int): ByteArray? = memScoped { val stream = alloc() val clamped = level.coerceIn(0, 9) if (deflateInit2(stream.ptr, clamped, Z_DEFLATED, GZIP_WINDOW_BITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) return null try { val bound = deflateBound(stream.ptr, data.size.toULong()).toInt() val output = ByteArray(bound.coerceAtLeast(32)) val input = if (data.isEmpty()) ByteArray(1) else data input.usePinned { pinnedIn -> output.usePinned { pinnedOut -> stream.next_in = pinnedIn.addressOf(0).reinterpret() stream.avail_in = data.size.toUInt() stream.next_out = pinnedOut.addressOf(0).reinterpret() stream.avail_out = output.size.toUInt() if (deflate(stream.ptr, Z_FINISH) != Z_STREAM_END) return null } } output.copyOf(stream.total_out.toInt()) } finally { deflateEnd(stream.ptr) } } /** Deflate expands at most ~1032:1, so a trailer claiming more than that is a lie. */ private const val MAX_DEFLATE_RATIO = 1032L /** The trailer size only sizes the first buffer, capped here; the buffer doubles if the data needs more. */ private const val MAX_INITIAL_INFLATE_BYTES = 64L * 1024 * 1024 @OptIn(ExperimentalForeignApi::class) private fun gzipInflate(data: ByteArray): ByteArray? { if (data.size < 18) return null // gzip trailer stores the uncompressed size (mod 2^32) in the last 4 bytes; corrupt or hostile files // can claim anything, so it is a starting capacity, never an allocation we trust. val trailer = data.size - 4 val isize = (data[trailer].toLong() and 0xFF) or ((data[trailer + 1].toLong() and 0xFF) shl 8) or ((data[trailer + 2].toLong() and 0xFF) shl 16) or ((data[trailer + 3].toLong() and 0xFF) shl 24) var output = ByteArray(isize.coerceIn(1L, minOf(data.size * MAX_DEFLATE_RATIO, MAX_INITIAL_INFLATE_BYTES)).toInt()) return data.usePinned { pinnedIn -> memScoped { val stream = alloc() stream.next_in = pinnedIn.addressOf(0).reinterpret() stream.avail_in = data.size.toUInt() if (inflateInit2(stream.ptr, GZIP_WINDOW_BITS) != Z_OK) return@memScoped null try { while (true) { val produced = stream.total_out.toInt() if (produced == output.size) { if (output.size == Int.MAX_VALUE) return@memScoped null output = output.copyOf(minOf(output.size * 2L, Int.MAX_VALUE.toLong()).toInt()) } val status = output.usePinned { pinnedOut -> stream.next_out = pinnedOut.addressOf(produced).reinterpret() stream.avail_out = (output.size - produced).toUInt() inflate(stream.ptr, Z_NO_FLUSH) } if (status == Z_STREAM_END) break // Output space left after Z_OK/Z_BUF_ERROR means the input ended before the stream did. if ((status != Z_OK && status != Z_BUF_ERROR) || stream.avail_out != 0u) return@memScoped null } val produced = stream.total_out.toInt() if (produced == output.size) output else output.copyOf(produced) } finally { inflateEnd(stream.ptr) } } } }