Yokan / rebuild
Course 1 8624561

IosZipArchive.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosZipArchive.ios.kt

implementation333 lines
1package eu.friedcutlet.yokan.services.files23import kotlinx.cinterop.ExperimentalForeignApi4import kotlinx.cinterop.addressOf5import kotlinx.cinterop.alloc6import kotlinx.cinterop.memScoped7import kotlinx.cinterop.ptr8import kotlinx.cinterop.reinterpret9import kotlinx.cinterop.usePinned10import platform.posix.SEEK_END11import platform.posix.SEEK_SET12import platform.posix.fclose13import platform.posix.fopen14import platform.posix.fread15import platform.posix.fseek16import platform.posix.ftell17import platform.posix.fwrite18import platform.posix.remove19import platform.posix.rename20import platform.zlib.Z_FINISH21import platform.zlib.Z_OK22import platform.zlib.Z_STREAM_END23import platform.zlib.inflate24import platform.zlib.inflateEnd25import platform.zlib.inflateInit226import platform.zlib.z_stream2728private data class IosZipEntry(29    val compressionMethod: Int,30    val crc: Int,31    val compressedSize: Int,32    val uncompressedSize: Int,33    val localHeaderOffset: Int,34)3536/**37 * Minimal ZIP reader (stored + deflate) on the platform zlib binding, shared by CBZ/EPUB support38 * ([openFile]: positioned reads of the central directory, then one entry at a time) and backup39 * restore ([open]: bytes already in memory). Retains only the entry table.40 *41 * Sizes and offsets are 32-bit and read as Int, so archives over 2 GiB and ZIP64 are unsupported.42 */43internal class IosZipArchive private constructor(44    private val readAt: (offset: Long, length: Int) -> ByteArray?,45    private val entries: Map<String, IosZipEntry>,46) {47    val entryNames: List<String> get() = entries.keys.toList()4849    fun read(path: String): ByteArray? = readEntry(path, maxBytes = null)5051    fun readImage(path: String, maxBytes: Long): ByteArray? = readEntry(path, maxBytes)5253    private fun readEntry(path: String, maxBytes: Long?): ByteArray? {54        val normalized = normalizeArchivePath(path, decodePercentSpaces = false).takeIf(String::isNotEmpty) ?: return null55        val entry = entries[normalized]56            ?: entries.entries.firstOrNull { it.key.endsWith(normalized) }?.value57            ?: return null58        if (maxBytes != null && (entry.uncompressedSize <= 0 || entry.compressedSize < 0 ||59                entry.uncompressedSize.toLong() > maxBytes || entry.compressedSize.toLong() > maxBytes)60        ) return null61        val offset = entry.localHeaderOffset.toLong()62        val header = readAt(offset, LOCAL_HEADER_SIZE) ?: return null63        if (header.u32(0) != LOCAL_FILE_HEADER) return null64        val dataStart = offset + LOCAL_HEADER_SIZE + header.u16(26) + header.u16(28)65        val compressed = readAt(dataStart, entry.compressedSize) ?: return null66        val data = when (entry.compressionMethod) {67            0 -> compressed68            8 -> inflateRaw(compressed, entry.uncompressedSize)69            else -> null70        } ?: return null71        return data.takeIf { it.size == entry.uncompressedSize && crc32Of(it) == entry.crc }72    }7374    companion object {75        private const val END_OF_CENTRAL_DIRECTORY = 0x06054B5076        private const val CENTRAL_DIRECTORY_HEADER = 0x02014B5077        private const val LOCAL_FILE_HEADER = 0x04034B5078        private const val LOCAL_HEADER_SIZE = 3079        private const val END_RECORD_SIZE = 228081        /** The end record plus the longest ZIP comment. */82        private const val MAX_END_RECORD_SEARCH = END_RECORD_SIZE + 65_535L8384        fun open(bytes: ByteArray): IosZipArchive? = parse(bytes.size.toLong()) { offset, length ->85            bytes.copyOfRange(offset.toInt(), (offset + length).toInt())86        }8788        /** Reads [path] with positioned file reads; callers hold any security scope around each call. */89        fun openFile(path: String, strict: Boolean = false): IosZipArchive? {90            val size = fileLength(path) ?: return null91            return parse(size, strict) { offset, length -> readFileRange(path, offset, length) }92        }9394        /** [readRange] only sees in-bounds ranges, so a corrupt size never allocates past the archive. */95        private fun parse(96            size: Long,97            strict: Boolean = false,98            readRange: (offset: Long, length: Int) -> ByteArray?,99        ): IosZipArchive? {100            val readAt = { offset: Long, length: Int ->101                if (offset < 0 || length < 0 || offset + length > size) null else readRange(offset, length)102            }103            if (size < END_RECORD_SIZE) return null104            val tailLength = minOf(size, MAX_END_RECORD_SEARCH).toInt()105            val tail = readAt(size - tailLength, tailLength) ?: return null106            val eocd = (tail.size - END_RECORD_SIZE downTo 0)107                .firstOrNull { tail.u32(it) == END_OF_CENTRAL_DIRECTORY }108                ?: return null109            val diskNumber = tail.u16(eocd + 4)110            val directoryDiskNumber = tail.u16(eocd + 6)111            val entriesOnDisk = tail.u16(eocd + 8)112            val entryCount = tail.u16(eocd + 10)113            val directoryOffset = tail.u32(eocd + 16)114            val directorySize = tail.u32(eocd + 12)115            val commentLength = tail.u16(eocd + 20)116            val eocdAbsoluteOffset = size - tailLength + eocd117            if (strict) {118                if (diskNumber != 0 || directoryDiskNumber != 0 || entriesOnDisk != entryCount ||119                    entryCount < 0 || entryCount == 0xffff || directoryOffset < 0 || directoryOffset == -1 ||120                    directorySize < 0 || directorySize == -1 || commentLength < 0 ||121                    eocd + END_RECORD_SIZE + commentLength != tail.size ||122                    directoryOffset.toLong() + directorySize.toLong() != eocdAbsoluteOffset123                ) return null124            }125            val directory = readAt(directoryOffset.toLong(), directorySize) ?: return null126            var cursor = 0127            val entries = LinkedHashMap<String, IosZipEntry>(entryCount)128            repeat(entryCount) {129                if (cursor < 0 || cursor + 46 > directory.size || directory.u32(cursor) != CENTRAL_DIRECTORY_HEADER) {130                    if (strict) return null131                    return@repeat132                }133                val method = directory.u16(cursor + 10)134                val compressedSize = directory.u32(cursor + 20)135                val uncompressedSize = directory.u32(cursor + 24)136                val nameLength = directory.u16(cursor + 28)137                val extraLength = directory.u16(cursor + 30)138                val commentLength = directory.u16(cursor + 32)139                val localOffset = directory.u32(cursor + 42)140                val nameStart = cursor + 46141                val nameEnd = nameStart + nameLength142                val recordEnd = nameEnd + extraLength + commentLength143                if (nameLength <= 0 || extraLength < 0 || commentLength < 0 || recordEnd < nameEnd || recordEnd > directory.size) {144                    if (strict) return null145                    return@repeat146                }147                val name = runCatching { directory.copyOfRange(nameStart, nameEnd).decodeToString() }.getOrNull()148                if (name.isNullOrBlank()) {149                    if (strict) return null150                } else {151                    if (strict && (compressedSize < 0 || uncompressedSize < 0 || localOffset < 0)) return null152                    entries[normalizeArchivePath(name, decodePercentSpaces = false)] = IosZipEntry(153                        compressionMethod = method,154                        crc = directory.u32(cursor + 16),155                        compressedSize = compressedSize,156                        uncompressedSize = uncompressedSize,157                        localHeaderOffset = localOffset,158                    )159                }160                cursor = recordEnd161            }162            if (strict && (entries.size != entryCount || cursor != directory.size)) return null163            return IosZipArchive(readAt, entries).takeIf { entries.isNotEmpty() }164        }165    }166}167168@OptIn(ExperimentalForeignApi::class)169private fun fileLength(path: String): Long? {170    val file = fopen(path, "rb") ?: return null171    return try {172        if (fseek(file, 0, SEEK_END) == 0) ftell(file).takeIf { it >= 0 } else null173    } finally {174        fclose(file)175    }176}177178@OptIn(ExperimentalForeignApi::class)179private fun readFileRange(path: String, offset: Long, length: Int): ByteArray? {180    if (length == 0) return ByteArray(0)181    val file = fopen(path, "rb") ?: return null182    return try {183        if (fseek(file, offset, SEEK_SET) != 0) return null184        val buffer = ByteArray(length)185        val read = buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, length.toULong(), file) }186        buffer.takeIf { read == length.toULong() }187    } finally {188        fclose(file)189    }190}191192/** Builds a stored (method 0) ZIP in memory; backups use it for their single entry. */193internal fun buildStoredZip(entries: List<Pair<String, ByteArray>>): ByteArray {194    val chunks = mutableListOf<ByteArray>()195    check(writeStoredZip(entries.asSequence()) { chunk -> chunks += chunk; true })196    val result = ByteArray(chunks.sumOf { it.size })197    var cursor = 0198    chunks.forEach { chunk ->199        chunk.copyInto(result, cursor)200        cursor += chunk.size201    }202    return result203}204205/**206 * Streams a stored ZIP of [entries] into [targetPath], holding one entry in memory at a time. Writes207 * `<target>.part` first so a failed write never looks complete; false when writing failed.208 */209@OptIn(ExperimentalForeignApi::class)210internal fun writeStoredZipFile(targetPath: String, entries: Sequence<Pair<String, ByteArray>>): Boolean {211    val partial = "$targetPath.part"212    val file = fopen(partial, "wb") ?: return false213    var written = false214    try {215        written = writeStoredZip(entries) { chunk ->216            chunk.isEmpty() || chunk.usePinned { pinned ->217                fwrite(pinned.addressOf(0), 1uL, chunk.size.toULong(), file) == chunk.size.toULong()218            }219        }220    } finally {221        if (fclose(file) != 0) written = false222    }223    if (written && rename(partial, targetPath) == 0) return true224    remove(partial)225    return false226}227228private class StoredZipEntry(val name: ByteArray, val crc: Int, val size: Int, val headerOffset: Int)229230/**231 * Emits a stored (method 0) ZIP of [entries] chunk by chunk through [emit], so archive creation needs232 * no deflate encoder. False when [emit] fails or the archive outgrows the offsets [IosZipArchive] reads.233 */234private fun writeStoredZip(entries: Sequence<Pair<String, ByteArray>>, emit: (ByteArray) -> Boolean): Boolean {235    var offset = 0L236    fun put(bytes: ByteArray): Boolean {237        offset += bytes.size238        return offset <= Int.MAX_VALUE && emit(bytes)239    }240    val central = mutableListOf<StoredZipEntry>()241    for ((name, data) in entries) {242        val entry = StoredZipEntry(name.encodeToByteArray(), crc32Of(data), data.size, offset.toInt())243        val header = ByteArray(30)244        header.putU32(0, 0x04034B50)245        header.putU16(4, 20) // version needed246        header.putU16(8, 0) // method: stored247        header.putU32(14, entry.crc)248        header.putU32(18, entry.size)249        header.putU32(22, entry.size)250        header.putU16(26, entry.name.size)251        if (!put(header) || !put(entry.name) || !put(data)) return false252        central += entry253    }254    val centralStart = offset.toInt()255    for (entry in central) {256        val record = ByteArray(46)257        record.putU32(0, 0x02014B50)258        record.putU16(4, 20) // version made by259        record.putU16(6, 20) // version needed260        record.putU16(10, 0) // method: stored261        record.putU32(16, entry.crc)262        record.putU32(20, entry.size)263        record.putU32(24, entry.size)264        record.putU16(28, entry.name.size)265        record.putU32(42, entry.headerOffset)266        if (!put(record) || !put(entry.name)) return false267    }268    val centralSize = offset.toInt() - centralStart269    val eocd = ByteArray(22)270    eocd.putU32(0, 0x06054B50)271    eocd.putU16(8, central.size)272    eocd.putU16(10, central.size)273    eocd.putU32(12, centralSize)274    eocd.putU32(16, centralStart)275    return put(eocd)276}277278private fun ByteArray.putU16(offset: Int, value: Int) {279    this[offset] = (value and 0xFF).toByte()280    this[offset + 1] = ((value ushr 8) and 0xFF).toByte()281}282283private fun ByteArray.putU32(offset: Int, value: Int) {284    this[offset] = (value and 0xFF).toByte()285    this[offset + 1] = ((value ushr 8) and 0xFF).toByte()286    this[offset + 2] = ((value ushr 16) and 0xFF).toByte()287    this[offset + 3] = ((value ushr 24) and 0xFF).toByte()288}289290@OptIn(ExperimentalForeignApi::class)291private fun crc32Of(data: ByteArray): Int {292    if (data.isEmpty()) return 0293    return data.usePinned { pinned ->294        platform.zlib.crc32(0uL, pinned.addressOf(0).reinterpret(), data.size.toUInt()).toInt()295    }296}297298private fun ByteArray.u16(offset: Int): Int {299    if (offset < 0 || offset + 2 > size) return -1300    return (this[offset].toInt() and 0xFF) or ((this[offset + 1].toInt() and 0xFF) shl 8)301}302303private fun ByteArray.u32(offset: Int): Int {304    if (offset < 0 || offset + 4 > size) return -1305    return (this[offset].toInt() and 0xFF) or306        ((this[offset + 1].toInt() and 0xFF) shl 8) or307        ((this[offset + 2].toInt() and 0xFF) shl 16) or308        ((this[offset + 3].toInt() and 0xFF) shl 24)309}310311@OptIn(ExperimentalForeignApi::class)312private fun inflateRaw(compressed: ByteArray, expectedSize: Int): ByteArray? {313    if (expectedSize < 0) return null314    if (expectedSize == 0) return ByteArray(0)315    val output = ByteArray(expectedSize)316    return compressed.usePinned { inputPinned ->317        output.usePinned { outputPinned ->318            memScoped {319                val stream = alloc<z_stream>()320                stream.next_in = inputPinned.addressOf(0).reinterpret()321                stream.avail_in = compressed.size.toUInt()322                stream.next_out = outputPinned.addressOf(0).reinterpret()323                stream.avail_out = output.size.toUInt()324                if (inflateInit2(stream.ptr, -15) != Z_OK) return@memScoped null325                try {326                    output.takeIf { inflate(stream.ptr, Z_FINISH) == Z_STREAM_END }327                } finally {328                    inflateEnd(stream.ptr)329                }330            }331        }332    }333}334

Search chapters, reference and source filenames.