package eu.friedcutlet.yokan.services.files 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.posix.SEEK_END import platform.posix.SEEK_SET import platform.posix.fclose import platform.posix.fopen import platform.posix.fread import platform.posix.fseek import platform.posix.ftell import platform.posix.fwrite import platform.posix.remove import platform.posix.rename import platform.zlib.Z_FINISH import platform.zlib.Z_OK import platform.zlib.Z_STREAM_END import platform.zlib.inflate import platform.zlib.inflateEnd import platform.zlib.inflateInit2 import platform.zlib.z_stream private data class IosZipEntry( val compressionMethod: Int, val crc: Int, val compressedSize: Int, val uncompressedSize: Int, val localHeaderOffset: Int, ) /** * Minimal ZIP reader (stored + deflate) on the platform zlib binding, shared by CBZ/EPUB support * ([openFile]: positioned reads of the central directory, then one entry at a time) and backup * restore ([open]: bytes already in memory). Retains only the entry table. * * Sizes and offsets are 32-bit and read as Int, so archives over 2 GiB and ZIP64 are unsupported. */ internal class IosZipArchive private constructor( private val readAt: (offset: Long, length: Int) -> ByteArray?, private val entries: Map, ) { val entryNames: List get() = entries.keys.toList() fun read(path: String): ByteArray? = readEntry(path, maxBytes = null) fun readImage(path: String, maxBytes: Long): ByteArray? = readEntry(path, maxBytes) private fun readEntry(path: String, maxBytes: Long?): ByteArray? { val normalized = normalizeArchivePath(path, decodePercentSpaces = false).takeIf(String::isNotEmpty) ?: return null val entry = entries[normalized] ?: entries.entries.firstOrNull { it.key.endsWith(normalized) }?.value ?: return null if (maxBytes != null && (entry.uncompressedSize <= 0 || entry.compressedSize < 0 || entry.uncompressedSize.toLong() > maxBytes || entry.compressedSize.toLong() > maxBytes) ) return null val offset = entry.localHeaderOffset.toLong() val header = readAt(offset, LOCAL_HEADER_SIZE) ?: return null if (header.u32(0) != LOCAL_FILE_HEADER) return null val dataStart = offset + LOCAL_HEADER_SIZE + header.u16(26) + header.u16(28) val compressed = readAt(dataStart, entry.compressedSize) ?: return null val data = when (entry.compressionMethod) { 0 -> compressed 8 -> inflateRaw(compressed, entry.uncompressedSize) else -> null } ?: return null return data.takeIf { it.size == entry.uncompressedSize && crc32Of(it) == entry.crc } } companion object { private const val END_OF_CENTRAL_DIRECTORY = 0x06054B50 private const val CENTRAL_DIRECTORY_HEADER = 0x02014B50 private const val LOCAL_FILE_HEADER = 0x04034B50 private const val LOCAL_HEADER_SIZE = 30 private const val END_RECORD_SIZE = 22 /** The end record plus the longest ZIP comment. */ private const val MAX_END_RECORD_SEARCH = END_RECORD_SIZE + 65_535L fun open(bytes: ByteArray): IosZipArchive? = parse(bytes.size.toLong()) { offset, length -> bytes.copyOfRange(offset.toInt(), (offset + length).toInt()) } /** Reads [path] with positioned file reads; callers hold any security scope around each call. */ fun openFile(path: String, strict: Boolean = false): IosZipArchive? { val size = fileLength(path) ?: return null return parse(size, strict) { offset, length -> readFileRange(path, offset, length) } } /** [readRange] only sees in-bounds ranges, so a corrupt size never allocates past the archive. */ private fun parse( size: Long, strict: Boolean = false, readRange: (offset: Long, length: Int) -> ByteArray?, ): IosZipArchive? { val readAt = { offset: Long, length: Int -> if (offset < 0 || length < 0 || offset + length > size) null else readRange(offset, length) } if (size < END_RECORD_SIZE) return null val tailLength = minOf(size, MAX_END_RECORD_SEARCH).toInt() val tail = readAt(size - tailLength, tailLength) ?: return null val eocd = (tail.size - END_RECORD_SIZE downTo 0) .firstOrNull { tail.u32(it) == END_OF_CENTRAL_DIRECTORY } ?: return null val diskNumber = tail.u16(eocd + 4) val directoryDiskNumber = tail.u16(eocd + 6) val entriesOnDisk = tail.u16(eocd + 8) val entryCount = tail.u16(eocd + 10) val directoryOffset = tail.u32(eocd + 16) val directorySize = tail.u32(eocd + 12) val commentLength = tail.u16(eocd + 20) val eocdAbsoluteOffset = size - tailLength + eocd if (strict) { if (diskNumber != 0 || directoryDiskNumber != 0 || entriesOnDisk != entryCount || entryCount < 0 || entryCount == 0xffff || directoryOffset < 0 || directoryOffset == -1 || directorySize < 0 || directorySize == -1 || commentLength < 0 || eocd + END_RECORD_SIZE + commentLength != tail.size || directoryOffset.toLong() + directorySize.toLong() != eocdAbsoluteOffset ) return null } val directory = readAt(directoryOffset.toLong(), directorySize) ?: return null var cursor = 0 val entries = LinkedHashMap(entryCount) repeat(entryCount) { if (cursor < 0 || cursor + 46 > directory.size || directory.u32(cursor) != CENTRAL_DIRECTORY_HEADER) { if (strict) return null return@repeat } val method = directory.u16(cursor + 10) val compressedSize = directory.u32(cursor + 20) val uncompressedSize = directory.u32(cursor + 24) val nameLength = directory.u16(cursor + 28) val extraLength = directory.u16(cursor + 30) val commentLength = directory.u16(cursor + 32) val localOffset = directory.u32(cursor + 42) val nameStart = cursor + 46 val nameEnd = nameStart + nameLength val recordEnd = nameEnd + extraLength + commentLength if (nameLength <= 0 || extraLength < 0 || commentLength < 0 || recordEnd < nameEnd || recordEnd > directory.size) { if (strict) return null return@repeat } val name = runCatching { directory.copyOfRange(nameStart, nameEnd).decodeToString() }.getOrNull() if (name.isNullOrBlank()) { if (strict) return null } else { if (strict && (compressedSize < 0 || uncompressedSize < 0 || localOffset < 0)) return null entries[normalizeArchivePath(name, decodePercentSpaces = false)] = IosZipEntry( compressionMethod = method, crc = directory.u32(cursor + 16), compressedSize = compressedSize, uncompressedSize = uncompressedSize, localHeaderOffset = localOffset, ) } cursor = recordEnd } if (strict && (entries.size != entryCount || cursor != directory.size)) return null return IosZipArchive(readAt, entries).takeIf { entries.isNotEmpty() } } } } @OptIn(ExperimentalForeignApi::class) private fun fileLength(path: String): Long? { val file = fopen(path, "rb") ?: return null return try { if (fseek(file, 0, SEEK_END) == 0) ftell(file).takeIf { it >= 0 } else null } finally { fclose(file) } } @OptIn(ExperimentalForeignApi::class) private fun readFileRange(path: String, offset: Long, length: Int): ByteArray? { if (length == 0) return ByteArray(0) val file = fopen(path, "rb") ?: return null return try { if (fseek(file, offset, SEEK_SET) != 0) return null val buffer = ByteArray(length) val read = buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, length.toULong(), file) } buffer.takeIf { read == length.toULong() } } finally { fclose(file) } } /** Builds a stored (method 0) ZIP in memory; backups use it for their single entry. */ internal fun buildStoredZip(entries: List>): ByteArray { val chunks = mutableListOf() check(writeStoredZip(entries.asSequence()) { chunk -> chunks += chunk; true }) val result = ByteArray(chunks.sumOf { it.size }) var cursor = 0 chunks.forEach { chunk -> chunk.copyInto(result, cursor) cursor += chunk.size } return result } /** * Streams a stored ZIP of [entries] into [targetPath], holding one entry in memory at a time. Writes * `.part` first so a failed write never looks complete; false when writing failed. */ @OptIn(ExperimentalForeignApi::class) internal fun writeStoredZipFile(targetPath: String, entries: Sequence>): Boolean { val partial = "$targetPath.part" val file = fopen(partial, "wb") ?: return false var written = false try { written = writeStoredZip(entries) { chunk -> chunk.isEmpty() || chunk.usePinned { pinned -> fwrite(pinned.addressOf(0), 1uL, chunk.size.toULong(), file) == chunk.size.toULong() } } } finally { if (fclose(file) != 0) written = false } if (written && rename(partial, targetPath) == 0) return true remove(partial) return false } private class StoredZipEntry(val name: ByteArray, val crc: Int, val size: Int, val headerOffset: Int) /** * Emits a stored (method 0) ZIP of [entries] chunk by chunk through [emit], so archive creation needs * no deflate encoder. False when [emit] fails or the archive outgrows the offsets [IosZipArchive] reads. */ private fun writeStoredZip(entries: Sequence>, emit: (ByteArray) -> Boolean): Boolean { var offset = 0L fun put(bytes: ByteArray): Boolean { offset += bytes.size return offset <= Int.MAX_VALUE && emit(bytes) } val central = mutableListOf() for ((name, data) in entries) { val entry = StoredZipEntry(name.encodeToByteArray(), crc32Of(data), data.size, offset.toInt()) val header = ByteArray(30) header.putU32(0, 0x04034B50) header.putU16(4, 20) // version needed header.putU16(8, 0) // method: stored header.putU32(14, entry.crc) header.putU32(18, entry.size) header.putU32(22, entry.size) header.putU16(26, entry.name.size) if (!put(header) || !put(entry.name) || !put(data)) return false central += entry } val centralStart = offset.toInt() for (entry in central) { val record = ByteArray(46) record.putU32(0, 0x02014B50) record.putU16(4, 20) // version made by record.putU16(6, 20) // version needed record.putU16(10, 0) // method: stored record.putU32(16, entry.crc) record.putU32(20, entry.size) record.putU32(24, entry.size) record.putU16(28, entry.name.size) record.putU32(42, entry.headerOffset) if (!put(record) || !put(entry.name)) return false } val centralSize = offset.toInt() - centralStart val eocd = ByteArray(22) eocd.putU32(0, 0x06054B50) eocd.putU16(8, central.size) eocd.putU16(10, central.size) eocd.putU32(12, centralSize) eocd.putU32(16, centralStart) return put(eocd) } private fun ByteArray.putU16(offset: Int, value: Int) { this[offset] = (value and 0xFF).toByte() this[offset + 1] = ((value ushr 8) and 0xFF).toByte() } private fun ByteArray.putU32(offset: Int, value: Int) { this[offset] = (value and 0xFF).toByte() this[offset + 1] = ((value ushr 8) and 0xFF).toByte() this[offset + 2] = ((value ushr 16) and 0xFF).toByte() this[offset + 3] = ((value ushr 24) and 0xFF).toByte() } @OptIn(ExperimentalForeignApi::class) private fun crc32Of(data: ByteArray): Int { if (data.isEmpty()) return 0 return data.usePinned { pinned -> platform.zlib.crc32(0uL, pinned.addressOf(0).reinterpret(), data.size.toUInt()).toInt() } } private fun ByteArray.u16(offset: Int): Int { if (offset < 0 || offset + 2 > size) return -1 return (this[offset].toInt() and 0xFF) or ((this[offset + 1].toInt() and 0xFF) shl 8) } private fun ByteArray.u32(offset: Int): Int { if (offset < 0 || offset + 4 > size) return -1 return (this[offset].toInt() and 0xFF) or ((this[offset + 1].toInt() and 0xFF) shl 8) or ((this[offset + 2].toInt() and 0xFF) shl 16) or ((this[offset + 3].toInt() and 0xFF) shl 24) } @OptIn(ExperimentalForeignApi::class) private fun inflateRaw(compressed: ByteArray, expectedSize: Int): ByteArray? { if (expectedSize < 0) return null if (expectedSize == 0) return ByteArray(0) val output = ByteArray(expectedSize) return compressed.usePinned { inputPinned -> output.usePinned { outputPinned -> memScoped { val stream = alloc() stream.next_in = inputPinned.addressOf(0).reinterpret() stream.avail_in = compressed.size.toUInt() stream.next_out = outputPinned.addressOf(0).reinterpret() stream.avail_out = output.size.toUInt() if (inflateInit2(stream.ptr, -15) != Z_OK) return@memScoped null try { output.takeIf { inflate(stream.ptr, Z_FINISH) == Z_STREAM_END } } finally { inflateEnd(stream.ptr) } } } } }