Yokan / rebuild
Course 1 8624561

BackupCompression.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.ios.kt

implementation137 lines
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.services.files.IosZipArchive4import eu.friedcutlet.yokan.services.files.buildStoredZip5import kotlinx.cinterop.ExperimentalForeignApi6import kotlinx.cinterop.addressOf7import kotlinx.cinterop.alloc8import kotlinx.cinterop.memScoped9import kotlinx.cinterop.ptr10import kotlinx.cinterop.reinterpret11import kotlinx.cinterop.usePinned12import platform.zlib.Z_BUF_ERROR13import platform.zlib.Z_DEFAULT_STRATEGY14import platform.zlib.Z_DEFLATED15import platform.zlib.Z_FINISH16import platform.zlib.Z_NO_FLUSH17import platform.zlib.Z_OK18import platform.zlib.Z_STREAM_END19import platform.zlib.deflate20import platform.zlib.deflateBound21import platform.zlib.deflateEnd22import platform.zlib.deflateInit223import platform.zlib.inflate24import platform.zlib.inflateEnd25import platform.zlib.inflateInit226import platform.zlib.z_stream2728actual fun createPlatformBackupCompression(): BackupCompression = IosBackupCompression2930/**31 * zlib-backed compression for backups. ZIP reading reuses [IosZipArchive]32 * (the same reader CBZ/EPUB support uses), so Mangayomi `.backup` archives33 * restore on iOS like they do on the JVM platforms. ZIP writing emits a34 * stored archive via [buildStoredZip]; the old Flutter app inflates entries35 * regardless of method, so skipping deflate only costs file size.36 */37@OptIn(ExperimentalForeignApi::class)38private object IosBackupCompression : BackupCompression {39    // ponytail: single-shot gzip on whole byte arrays; stream if backups outgrow memory.40    override fun compress(data: ByteArray, level: Int): ByteArray =41        gzipDeflate(data, level) ?: error("gzip compression failed.")4243    override fun decompress(data: ByteArray): ByteArray =44        gzipInflate(data) ?: error("Backup is not valid gzip data.")4546    override fun unzipFirstEntry(data: ByteArray): ByteArray? {47        val archive = IosZipArchive.open(data) ?: return null48        return archive.entryNames.firstOrNull { !it.endsWith("/") }?.let(archive::read)49    }5051    override fun unzipEntries(data: ByteArray): Map<String, ByteArray>? {52        val archive = IosZipArchive.open(data) ?: return null53        return buildMap {54            archive.entryNames.forEach { name ->55                if (!name.endsWith("/")) archive.read(name)?.let { put(name, it) }56            }57        }58    }5960    override fun zipSingleEntry(entryName: String, data: ByteArray, level: Int): ByteArray =61        buildStoredZip(listOf(entryName to data))62}6364/** windowBits 15 + 16 selects the gzip wrapper in zlib. */65private const val GZIP_WINDOW_BITS = 15 + 166667@OptIn(ExperimentalForeignApi::class)68private fun gzipDeflate(data: ByteArray, level: Int): ByteArray? = memScoped {69    val stream = alloc<z_stream>()70    val clamped = level.coerceIn(0, 9)71    if (deflateInit2(stream.ptr, clamped, Z_DEFLATED, GZIP_WINDOW_BITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) return null72    try {73        val bound = deflateBound(stream.ptr, data.size.toULong()).toInt()74        val output = ByteArray(bound.coerceAtLeast(32))75        val input = if (data.isEmpty()) ByteArray(1) else data76        input.usePinned { pinnedIn ->77            output.usePinned { pinnedOut ->78                stream.next_in = pinnedIn.addressOf(0).reinterpret()79                stream.avail_in = data.size.toUInt()80                stream.next_out = pinnedOut.addressOf(0).reinterpret()81                stream.avail_out = output.size.toUInt()82                if (deflate(stream.ptr, Z_FINISH) != Z_STREAM_END) return null83            }84        }85        output.copyOf(stream.total_out.toInt())86    } finally {87        deflateEnd(stream.ptr)88    }89}9091/** Deflate expands at most ~1032:1, so a trailer claiming more than that is a lie. */92private const val MAX_DEFLATE_RATIO = 1032L9394/** The trailer size only sizes the first buffer, capped here; the buffer doubles if the data needs more. */95private const val MAX_INITIAL_INFLATE_BYTES = 64L * 1024 * 10249697@OptIn(ExperimentalForeignApi::class)98private fun gzipInflate(data: ByteArray): ByteArray? {99    if (data.size < 18) return null100    // gzip trailer stores the uncompressed size (mod 2^32) in the last 4 bytes; corrupt or hostile files101    // can claim anything, so it is a starting capacity, never an allocation we trust.102    val trailer = data.size - 4103    val isize = (data[trailer].toLong() and 0xFF) or104        ((data[trailer + 1].toLong() and 0xFF) shl 8) or105        ((data[trailer + 2].toLong() and 0xFF) shl 16) or106        ((data[trailer + 3].toLong() and 0xFF) shl 24)107    var output = ByteArray(isize.coerceIn(1L, minOf(data.size * MAX_DEFLATE_RATIO, MAX_INITIAL_INFLATE_BYTES)).toInt())108    return data.usePinned { pinnedIn ->109        memScoped {110            val stream = alloc<z_stream>()111            stream.next_in = pinnedIn.addressOf(0).reinterpret()112            stream.avail_in = data.size.toUInt()113            if (inflateInit2(stream.ptr, GZIP_WINDOW_BITS) != Z_OK) return@memScoped null114            try {115                while (true) {116                    val produced = stream.total_out.toInt()117                    if (produced == output.size) {118                        if (output.size == Int.MAX_VALUE) return@memScoped null119                        output = output.copyOf(minOf(output.size * 2L, Int.MAX_VALUE.toLong()).toInt())120                    }121                    val status = output.usePinned { pinnedOut ->122                        stream.next_out = pinnedOut.addressOf(produced).reinterpret()123                        stream.avail_out = (output.size - produced).toUInt()124                        inflate(stream.ptr, Z_NO_FLUSH)125                    }126                    if (status == Z_STREAM_END) break127                    // Output space left after Z_OK/Z_BUF_ERROR means the input ended before the stream did.128                    if ((status != Z_OK && status != Z_BUF_ERROR) || stream.avail_out != 0u) return@memScoped null129                }130                val produced = stream.total_out.toInt()131                if (produced == output.size) output else output.copyOf(produced)132            } finally {133                inflateEnd(stream.ptr)134            }135        }136    }137}138

Search chapters, reference and source filenames.