Yokan / rebuild
Course 1 8624561

BackupCompression.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.wasm.kt

implementation278 lines
1package eu.friedcutlet.yokan.services.backup23import kotlinx.coroutines.suspendCancellableCoroutine4import kotlin.io.encoding.Base645import kotlin.io.encoding.ExperimentalEncodingApi6import kotlin.js.ExperimentalWasmJsInterop7import kotlin.js.JsAny8import kotlin.js.Promise9import kotlin.coroutines.resume10import kotlin.coroutines.resumeWithException1112actual fun createPlatformBackupCompression(): BackupCompression = WasmBackupCompression1314/**15 * The browser's CompressionStream API is async-only and this contract is16 * synchronous, so web backups export uncompressed — other platforms sniff17 * the gzip magic bytes and treat non-gzipped payloads as raw. Importing a18 * gzipped backup on the web fails with a clear error instead of corrupting.19 */20private object WasmBackupCompression : BackupCompression {21    override fun compress(data: ByteArray, level: Int): ByteArray = data2223    override fun decompress(data: ByteArray): ByteArray {24        if (looksGzipped(data)) {25            throw UnsupportedOperationException(26                "Gzipped backups cannot be imported in the browser; export an uncompressed backup instead.",27            )28        }29        return data30    }3132    override suspend fun unzipFirstEntryAsync(data: ByteArray): ByteArray? =33        parseZip(data).firstOrNull { !it.name.endsWith('/') }?.let { readEntry(data, it, 0L) }3435    override suspend fun unzipEntriesAsync(data: ByteArray): Map<String, ByteArray> = buildMap {36        var totalOutput = 0L37        parseZip(data).forEach { entry ->38            if (!entry.name.endsWith('/')) {39                val decoded = readEntry(data, entry, totalOutput)40                totalOutput += decoded.size.toLong()41                put(entry.name, decoded)42            }43        }44    }4546    private suspend fun readEntry(data: ByteArray, entry: ZipEntry, totalOutput: Long): ByteArray {47        requireZip(entry.uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit")48        requireZip(totalOutput <= MaxArchiveOutputBytes - entry.uncompressedSize, "archive output exceeds the 64 MiB browser limit")4950        val localOffset = entry.localHeaderOffset51        requireZip(localOffset < entry.centralDirectoryOffset, "local file header overlaps the central directory")52        requireRange(data, localOffset, 30L, "local file header is truncated")53        requireZip(u32(data, localOffset.toInt()) == LocalFileHeader, "local file header signature is invalid")54        val local = localOffset.toInt()55        val localVersionNeeded = u16(data, local + 4)56        val localFlags = u16(data, local + 6)57        val localMethod = u16(data, local + 8)58        val localCrc = u32(data, local + 14)59        val localCompressedSize = u32(data, local + 18)60        val localUncompressedSize = u32(data, local + 22)61        val nameLength = u16(data, local + 26)62        val extraLength = u16(data, local + 28)63        requireUnsupported(localVersionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported")64        requireZip(localFlags == entry.flags, "local and central flags differ for ${entry.name}")65        requireZip(localMethod == entry.method, "local and central methods differ for ${entry.name}")66        requireZip(localCrc != Zip32Sentinel && localCompressedSize != Zip32Sentinel && localUncompressedSize != Zip32Sentinel, "ZIP64 local entries are not supported in the browser")67        val contentStart = localOffset + 30L + nameLength + extraLength68        val contentEnd = contentStart + entry.compressedSize69        requireZip(contentEnd <= entry.centralDirectoryOffset, "entry data overlaps the central directory")70        requireRange(data, contentStart, entry.compressedSize, "entry data is truncated")71        val localNameEnd = localOffset + 30L + nameLength72        requireRange(data, localOffset + 30L, nameLength, "local entry name is truncated")73        val localName = data.copyOfRange((localOffset + 30L).toInt(), localNameEnd.toInt()).decodeToString()74        requireZip(localName == entry.name, "local and central names differ")75        requireZip(76            localCrc == entry.crc32 &&77                localCompressedSize == entry.compressedSize &&78                localUncompressedSize == entry.uncompressedSize,79            "local and central metadata differ for ${entry.name}",80        )81        val compressed = data.copyOfRange(contentStart.toInt(), contentEnd.toInt())82        return when (entry.method) {83            Stored -> {84                requireZip(entry.compressedSize == entry.uncompressedSize, "stored entry sizes differ for ${entry.name}")85                compressed86            }87            Deflated -> inflateRaw(compressed, entry.name, entry.uncompressedSize.toInt())88            else -> error("Unsupported ZIP backup: compression method ${entry.method} is not supported for ${entry.name}")89        }.also { decoded ->90            requireZip(decoded.size.toLong() == entry.uncompressedSize, "decoded size differs from central metadata for ${entry.name}")91            requireZip(crc32(decoded) == entry.crc32, "CRC-32 mismatch for ${entry.name}")92        }93    }94}9596private data class ZipEntry(97    val name: String,98    val flags: Long,99    val method: Long,100    val crc32: Long,101    val compressedSize: Long,102    val uncompressedSize: Long,103    val localHeaderOffset: Long,104    val centralDirectoryOffset: Long,105)106107private const val EndOfCentralDirectory = 0x06054B50L108private const val CentralDirectoryHeader = 0x02014B50L109private const val LocalFileHeader = 0x04034B50L110private const val Stored = 0L111private const val Deflated = 8L112private const val Zip32Sentinel = 0xFFFF_FFFFL113private const val Zip16Sentinel = 0xFFFFL114private const val Utf8Flag = 0x800L115private const val SupportedFlags = Utf8Flag116private const val MaxArchiveOutputBytes = 64L * 1024L * 1024L117118private fun parseZip(data: ByteArray): List<ZipEntry> {119    requireZip(data.size >= 22, "end-of-central-directory record is missing")120    val eocd = (data.size - 22 downTo (data.size - 65_557).coerceAtLeast(0))121        .firstOrNull { candidate ->122            u32(data, candidate) == EndOfCentralDirectory &&123                candidate.toLong() + 22L + u16(data, candidate + 20) == data.size.toLong()124        }125        ?: error("Invalid ZIP backup: end-of-central-directory record is missing")126    val entryCount = u16(data, eocd + 10)127    val centralSize = u32(data, eocd + 12)128    val centralOffset = u32(data, eocd + 16)129    val diskNumber = u16(data, eocd + 4)130    val centralDisk = u16(data, eocd + 6)131    val entriesOnDisk = u16(data, eocd + 8)132    requireUnsupported(diskNumber == 0L && centralDisk == 0L && entriesOnDisk == entryCount, "multi-disk ZIP archives are not supported in the browser")133    requireUnsupported(134        entryCount != Zip16Sentinel && centralSize != Zip32Sentinel && centralOffset != Zip32Sentinel,135        "ZIP64 archives are not supported in the browser",136    )137    val centralEnd = centralOffset + centralSize138    requireZip(entryCount <= centralSize / 46L, "central directory entry count is invalid")139    requireZip(centralOffset <= data.size.toLong() && centralSize <= data.size.toLong() - centralOffset && centralEnd <= eocd.toLong(), "central directory is truncated")140141    val entries = ArrayList<ZipEntry>(entryCount.toInt())142    var cursor = centralOffset143    repeat(entryCount.toInt()) {144        requireRange(data, cursor, 46L, "central directory entry is truncated")145        requireZip(u32(data, cursor.toInt()) == CentralDirectoryHeader, "central directory entry is invalid")146        val versionNeeded = u16(data, cursor.toInt() + 6)147        val flags = u16(data, cursor.toInt() + 8)148        val method = u16(data, cursor.toInt() + 10)149        val crc32 = u32(data, cursor.toInt() + 16)150        val compressedSize = u32(data, cursor.toInt() + 20)151        val uncompressedSize = u32(data, cursor.toInt() + 24)152        val nameLength = u16(data, cursor.toInt() + 28)153        val extraLength = u16(data, cursor.toInt() + 30)154        val commentLength = u16(data, cursor.toInt() + 32)155        val diskStart = u16(data, cursor.toInt() + 34)156        val localHeaderOffset = u32(data, cursor.toInt() + 42)157        requireUnsupported(versionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported")158        requireUnsupported(flags and 1L == 0L, "encrypted ZIP entries are not supported in the browser")159        requireUnsupported(flags and SupportedFlags.inv() == 0L, "unsupported ZIP entry flags")160        requireUnsupported(161            diskStart == 0L && compressedSize != Zip32Sentinel && uncompressedSize != Zip32Sentinel && localHeaderOffset != Zip32Sentinel,162            "ZIP64 or multi-disk entries are not supported in the browser",163        )164        requireUnsupported(method == Stored || method == Deflated, "compression method $method is not supported in the browser")165        requireZip(uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit")166        val nameStart = cursor + 46L167        val next = nameStart + nameLength + extraLength + commentLength168        requireZip(next >= nameStart && next <= centralEnd, "central directory entry is truncated")169        val name = data.copyOfRange(nameStart.toInt(), (nameStart + nameLength).toInt()).decodeToString()170        requireZip(name.isNotEmpty() && '\u0000' !in name, "ZIP entry name is invalid")171        entries += ZipEntry(name, flags, method, crc32, compressedSize, uncompressedSize, localHeaderOffset, centralOffset)172        cursor = next173    }174    requireZip(cursor == centralEnd, "central directory size does not match its entries")175    return entries176}177178private fun u16(data: ByteArray, offset: Int): Long =179    (data[offset].toLong() and 0xFFL) or ((data[offset + 1].toLong() and 0xFFL) shl 8)180181private fun u32(data: ByteArray, offset: Int): Long =182    (data[offset].toLong() and 0xFFL) or183        ((data[offset + 1].toLong() and 0xFFL) shl 8) or184        ((data[offset + 2].toLong() and 0xFFL) shl 16) or185        ((data[offset + 3].toLong() and 0xFFL) shl 24)186187private fun requireZip(condition: Boolean, message: String) {188    if (!condition) error("Invalid ZIP backup: $message")189}190191private fun requireUnsupported(condition: Boolean, message: String) {192    if (!condition) error("Unsupported ZIP backup: $message")193}194195private fun requireRange(data: ByteArray, offset: Long, length: Long, message: String) {196    requireZip(offset >= 0L && length >= 0L && offset <= data.size.toLong() && length <= data.size.toLong() - offset, message)197}198199private fun crc32(data: ByteArray): Long {200    var crc = 0xFFFF_FFFFL201    data.forEach { byte ->202        crc = (crc ushr 8) xor Crc32Table[((crc xor (byte.toLong() and 0xFFL)) and 0xFFL).toInt()]203    }204    return crc xor 0xFFFF_FFFFL205}206207private val Crc32Table = LongArray(256) { index ->208    var value = index.toLong()209    repeat(8) { value = if (value and 1L != 0L) (value ushr 1) xor 0xEDB88320L else value ushr 1 }210    value211}212213@OptIn(ExperimentalEncodingApi::class, ExperimentalWasmJsInterop::class)214private suspend fun inflateRaw(data: ByteArray, entryName: String, maxOutputBytes: Int): ByteArray {215    return try {216        suspendCancellableCoroutine { continuation ->217            inflateRawJs(Base64.encode(data), maxOutputBytes).then(218                onFulfilled = { value ->219                    if (value == null) {220                        continuation.resumeWithException(IllegalStateException("DecompressionStream returned no data"))221                    } else {222                        runCatching { Base64.decode(jsString(value)) }223                            .fold(continuation::resume, continuation::resumeWithException)224                    }225                    null226                },227                onRejected = { error ->228                    continuation.resumeWithException(IllegalStateException(jsString(error)))229                    null230                },231            )232        }233    } catch (error: Throwable) {234        throw IllegalArgumentException(235            "Browser could not deflate ZIP entry $entryName: ${error.message.orEmpty().ifBlank { "DecompressionStream('deflate-raw') is unavailable or the entry is corrupt" }}",236            error,237        )238    }239}240241@OptIn(ExperimentalWasmJsInterop::class)242private fun inflateRawJs(base64: String, maxOutputBytes: Int): Promise<JsAny?> = js(243    """244    (async () => {245        const binary = atob(base64);246        const input = new Uint8Array(binary.length);247        for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i);248        const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('deflate-raw'));249        const reader = stream.getReader();250        const chunks = [];251        let outputLength = 0;252        while (true) {253            const result = await reader.read();254            if (result.done) break;255            outputLength += result.value.byteLength;256            if (outputLength > maxOutputBytes) {257                await reader.cancel();258                throw new Error('decompressed ZIP entry exceeds its declared or browser output limit');259            }260            chunks.push(result.value);261        }262        const output = new Uint8Array(outputLength);263        let outputOffset = 0;264        for (const chunk of chunks) {265            output.set(chunk, outputOffset);266            outputOffset += chunk.byteLength;267        }268        let binaryOutput = '';269        for (let i = 0; i < output.length; i += 0x8000) {270            binaryOutput += String.fromCharCode(...output.subarray(i, i + 0x8000));271        }272        return btoa(binaryOutput);273    })()274    """,275)276277@OptIn(ExperimentalWasmJsInterop::class)278private fun jsString(value: JsAny): String = js("String(value)")279

Search chapters, reference and source filenames.