Classify patch input files with PatchFileClassifier

Add ZipChannel, a zip archive backed by a DataChannel. open() returns
a random access DataChannel of STORED entries, and openStream()
returns a sequential stream of STORED or DEFLATED entries.

Add PatchFileClassifier to inspect the format of input files and
locate the payload to patch: RawFile, BootZip, PayloadBin, or Tar.
Zip archives are inspected with ZipChannel, and nested zips such as
the inner image zip of factory images are transparently inspected
instead. The payload is accessed as either a DataChannel or a
decompressed InputStream based on its type.

MagiskInstaller now relies on PatchFileClassifier to process inputs.
WholeFilePatcher now accepts an InputStream, as whole file formats
are always processed sequentially. ZipExtractor is removed as it is
fully superseded.

Add unit tests for ZipChannel with in-memory zips, and update
existing tests to go through PatchFileClassifier.

Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-07 16:53:36 -07:00
committed by John Wu
parent 5f7b39ac63
commit cefa2730d4
6 changed files with 488 additions and 196 deletions
@@ -35,14 +35,13 @@ import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
interface WholeFilePatcher {
@Throws(IOException::class)
suspend fun start(channel: DataChannel): ExtendedFile
suspend fun start(input: InputStream): ExtendedFile
@Throws(IOException::class)
suspend fun finish(patched: ExtendedFile)
@@ -219,19 +218,23 @@ abstract class MagiskInstallImpl protected constructor(
private suspend fun processInput(input: DataChannel): Boolean {
try {
input.use {
val head = ByteArray(512)
if (input.read(ByteBuffer.wrap(head), 0) != head.size) {
console.add("! Invalid input file")
return false
}
val magic = head.copyOf(4)
val tarMagic = head.copyOfRange(257, 262)
return if (tarMagic.contentEquals("ustar".toByteArray())) {
processWholeFile(input)
} else {
extractAndProcessImage(input, magic)
PatchFileClassifier(input).use { file ->
logs.add("Input type: ${file.type}, payload: ${file.entryPath ?: "<input>"}")
return when (file.type) {
PatchFileClassifier.Type.Tar -> processWholeFile(file.openStream())
PatchFileClassifier.Type.PayloadBin -> extractAndProcessImage { out ->
console.add("- Processing as OTA package")
OtaPayloadExtractor(out, console, logs).extract(file.openChannel())
}
PatchFileClassifier.Type.BootZip -> extractAndProcessImage { out ->
console.add("- Extracting: ${file.entryPath} (${file.size} bytes)")
file.openStream().use { it.copyAndCloseOut(out.newOutputStream()) }
}
PatchFileClassifier.Type.RawFile -> extractAndProcessImage { out ->
console.add("- Copying image to cache")
file.openStream().use { it.copyAndCloseOut(out.newOutputStream()) }
}
}
}
}
} catch (e: IOException) {
@@ -243,7 +246,7 @@ abstract class MagiskInstallImpl protected constructor(
// Patch the boot image in a tar archive, and output a new tar archive
// with all the original entries and the patched boot image
private suspend fun processWholeFile(input: DataChannel): Boolean {
private suspend fun processWholeFile(input: InputStream): Boolean {
val outFile = MediaStoreUtils.getFile("$destName.tar")
val outStream = outFile.uri.outputStream().buffered(1024 * 1024)
val tar = TarProcessor(installDir, outStream, console, logs)
@@ -286,18 +289,11 @@ abstract class MagiskInstallImpl protected constructor(
}
// Extract the boot image from the input, and output the patched boot image
private suspend fun extractAndProcessImage(input: DataChannel, magic: ByteArray): Boolean {
private suspend fun extractAndProcessImage(extract: suspend (ExtendedFile) -> Unit): Boolean {
// Process input file
targetImage = installDir.getChildFile("boot.img")
try {
if (magic.contentEquals("CrAU".toByteArray())) {
OtaPayloadExtractor(targetImage, console, logs).extract(input)
} else if (magic.contentEquals("PK\u0003\u0004".toByteArray())) {
ZipExtractor(targetImage, console, logs).extract(input)
} else {
console.add("- Copying image to cache")
input.stream().use { it.copyAndCloseOut(targetImage.newOutputStream()) }
}
extract(targetImage)
} catch (e: IOException) {
console.add("! Process error")
Timber.e(e)
@@ -0,0 +1,150 @@
package com.topjohnwu.magisk.core.tasks
import com.topjohnwu.magisk.core.utils.DataChannel
import com.topjohnwu.magisk.core.utils.ZipChannel
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
/**
* Inspect the format of a file to be patched, and locate the payload to process.
*
* Zip archives are inspected with [ZipChannel]; nested zips (e.g. the inner image zip
* of factory images) are transparently inspected instead of the outer archive.
*
* Based on [type], the payload can be accessed with:
* - [openChannel]: random access, required for [Type.PayloadBin] and [Type.RawFile].
* Payloads within zip archives must be STORED.
* - [openStream]: sequential access, sufficient for all other types.
* Payloads within zip archives are decompressed transparently.
*
* The classifier does not take ownership of the input channel. Both the input channel
* and the classifier must remain open while using channels or streams of the payload.
*/
class PatchFileClassifier @Throws(IOException::class) constructor(
input: DataChannel
) : Closeable {
enum class Type {
/** A raw image file, e.g. boot.img */
RawFile,
/** A zip archive containing boot images, e.g. factory images */
BootZip,
/** An A/B OTA payload, e.g. payload.bin in OTA packages */
PayloadBin,
/** A tar archive, e.g. Samsung firmware AP tar */
Tar,
}
private val zips = mutableListOf<ZipChannel>()
private val entryNames = mutableListOf<String>()
// The channel containing the payload: either the payload itself when entry is null,
// or the zip archive (the last element of zips) containing the payload entry.
private var channel = input
private var entry: ZipArchiveEntry? = null
val type: Type
init {
try {
type = classify()
} catch (e: Exception) {
close()
throw e
}
}
/** Decompressed size of the payload. */
val size: Long get() = entry?.size ?: channel.size()
/**
* Path of the payload within (nested) zip archives, null if the input itself is the payload.
*/
val entryPath: String? get() = if (entryNames.isEmpty()) null else entryNames.joinToString("/")
/**
* Get a [DataChannel] of the payload. Payloads in zip archives must be STORED.
* The caller is responsible for closing the returned channel.
*/
@Throws(IOException::class)
fun openChannel(): DataChannel {
val entry = entry ?: return channel.slice(0, channel.size())
return zips.last().open(entry)
}
/**
* Get an [InputStream] of the payload, decompressed if required.
* The caller is responsible for closing the returned stream.
*/
@Throws(IOException::class)
fun openStream(): InputStream {
val entry = entry ?: return channel.stream()
return zips.last().openStream(entry)
}
override fun close() {
zips.forEach { runCatching { it.close() } }
zips.clear()
}
private fun classify(): Type {
repeat(MAX_ZIP_DEPTH + 1) {
val head = ByteArray(HEAD_SIZE)
if (channel.read(ByteBuffer.wrap(head), 0) != head.size) {
throw IOException("Invalid input file")
}
when {
head.matches(257, TAR_MAGIC) -> return Type.Tar
head.matches(0, PAYLOAD_MAGIC) -> return Type.PayloadBin
!head.matches(0, ZIP_MAGIC) -> return Type.RawFile
}
val zip = ZipChannel(channel)
zips.add(zip)
zip.getEntry("payload.bin")?.let { return found(it, Type.PayloadBin) }
findBootImage(zip)?.let { return found(it, Type.BootZip) }
// Factory images contain the actual images in an inner zip
val imageZip = zip.find {
val name = it.name.substringAfterLast('/')
name.startsWith("image-") && name.endsWith(".zip")
}
if (imageZip != null) {
entryNames.add(imageZip.name)
channel = zip.open(imageZip)
return@repeat
}
throw IOException("No supported files found in zip")
}
throw IOException("Too many nested zip archives")
}
private fun found(entry: ZipArchiveEntry, type: Type): Type {
this.entry = entry
entryNames.add(entry.name)
return type
}
private fun findBootImage(zip: ZipChannel): ZipArchiveEntry? =
zip.find { it.name.substringAfterLast('/') == "init_boot.img" }
?: zip.find { it.name.substringAfterLast('/') == "boot.img" }
private fun ByteArray.matches(offset: Int, magic: ByteArray): Boolean {
if (offset + magic.size > size) return false
return magic.indices.all { this[offset + it] == magic[it] }
}
companion object {
private const val HEAD_SIZE = 1024
private const val MAX_ZIP_DEPTH = 3
private val TAR_MAGIC = "ustar".toByteArray()
private val PAYLOAD_MAGIC = "CrAU".toByteArray()
private val ZIP_MAGIC = "PK\u0003\u0004".toByteArray()
}
}
@@ -3,7 +3,6 @@ package com.topjohnwu.magisk.core.tasks
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.ktx.copyAll
import com.topjohnwu.magisk.core.utils.DataChannel
import com.topjohnwu.superuser.Shell
import com.topjohnwu.superuser.nio.ExtendedFile
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
@@ -24,7 +23,7 @@ import java.nio.ByteBuffer
* other entries to the output tar. Returns the image to be patched.
* 2. [finish]: write the patched image to the output tar and finalize the archive.
*
* [start] closes the input channel. The caller owns the output stream and is
* [start] closes the input stream. The caller owns the output stream and is
* responsible for closing it.
*/
class TarProcessor(
@@ -44,9 +43,9 @@ class TarProcessor(
private lateinit var target: BootItem
@Throws(IOException::class)
override suspend fun start(channel: DataChannel): ExtendedFile = channel.use {
val tarIn = TarArchiveInputStream(it.stream().buffered(1024 * 1024))
tarIn.use { processEntries(tarIn) }
override suspend fun start(input: InputStream): ExtendedFile {
val tarIn = TarArchiveInputStream(input.buffered(1024 * 1024))
return tarIn.use { processEntries(tarIn) }
}
@Throws(IOException::class)
@@ -1,158 +0,0 @@
package com.topjohnwu.magisk.core.tasks
import com.topjohnwu.magisk.core.utils.DataChannel
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.archivers.zip.ZipMethod
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption
import java.util.zip.Inflater
import java.util.zip.InflaterInputStream
class ZipExtractor(
private val outFile: File,
private val console: MutableList<String>,
private val logs: MutableList<String>,
) : ImageExtractor {
@Throws(IOException::class)
override suspend fun extract(channel: DataChannel) {
ZipFile.builder()
.setSeekableByteChannel(channel)
.setIgnoreLocalFileHeader(true)
.get().use { zipFile ->
val payload = zipFile.getEntry("payload.bin")
if (payload != null) {
console.add("- Processing as OTA package")
zipFile.getEntry("META-INF/com/android/metadata")?.let { entry ->
zipFile.getInputStream(entry).use {
val meta = it.bufferedReader().readText()
logs.add(meta)
console.add("- OTA metadata:")
meta.lines().forEach { line ->
if (line.startsWith("post-")) {
console.add(" ${line.substringAfter('-')}")
}
}
}
}
zipFile.getRawInputStream(payload)
extractFromOTAPackage(payload, channel)
} else {
extractFromFactoryImage(zipFile, channel)
}
}
}
@Throws(IOException::class)
private suspend fun extractFromOTAPackage(
payload: ZipArchiveEntry,
channel: DataChannel,
) {
if (payload.method != ZipMethod.STORED.code) {
throw IOException("payload.bin is compressed, expected STORED method")
}
OtaPayloadExtractor(outFile, console, logs)
.extract(channel.slice(payload.dataOffset, payload.size))
}
@Throws(IOException::class)
private fun extractFromFactoryImage(
zipFile: ZipFile,
channel: DataChannel,
) {
console.add("- Processing as factory image package")
findBootImageZipEntry(zipFile)?.let { entry ->
return extractImageFile(zipFile, entry, channel)
}
val imageZipEntry = zipFile.entries.asSequence().find { entry ->
val fileName = entry.name.substringAfterLast('/')
fileName.startsWith("image-") && fileName.endsWith(".zip")
}
if (imageZipEntry != null) {
zipFile.getRawInputStream(imageZipEntry)
return extractFromInnerImageZip(imageZipEntry, channel)
}
throw IOException("inner image ZIP not found in factory image package")
}
private fun findBootImageZipEntry(zipFile: ZipFile): ZipArchiveEntry? {
return zipFile.entries.asSequence().find {
it.name.substringAfterLast('/') == "init_boot.img"
} ?: zipFile.entries.asSequence().find {
it.name.substringAfterLast('/') == "boot.img"
}
}
@Throws(IOException::class)
private fun extractFromInnerImageZip(
entry: ZipArchiveEntry,
channel: DataChannel,
) {
logs.add("Found inner image ZIP: ${entry.name}")
if (entry.method != ZipMethod.STORED.code) {
throw IOException("image ZIP is compressed, expected STORED method")
}
channel.slice(entry.dataOffset, entry.size).use { innerZipChannel ->
ZipFile.builder()
.setSeekableByteChannel(innerZipChannel)
.setIgnoreLocalFileHeader(true)
.get().use { innerZipFile ->
val targetEntry = findBootImageZipEntry(innerZipFile)
?: throw IOException("boot image not found in inner image ZIP")
return extractImageFile(innerZipFile, targetEntry, innerZipChannel)
}
}
}
@Throws(IOException::class)
private fun extractImageFile(
zipFile: ZipFile,
entry: ZipArchiveEntry,
channel: DataChannel,
) {
console.add("- Found boot image entry: ${entry.name} (${entry.size} bytes)")
console.add("- Downloading")
zipFile.getRawInputStream(entry)
when (entry.method) {
ZipMethod.STORED.code -> {
FileChannel.open(
outFile.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.READ,
StandardOpenOption.TRUNCATE_EXISTING
).use { fileChannel ->
val mapped = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, entry.size)
val sourceChannel = channel.slice(entry.dataOffset, entry.size)
sourceChannel.read(mapped)
}
}
ZipMethod.DEFLATED.code -> {
InflaterInputStream(
channel.stream(entry.dataOffset, entry.size),
Inflater(true),
16 * 1024
).use { input ->
FileOutputStream(outFile).use { out ->
input.copyTo(out)
}
}
}
else -> throw IOException("unsupported method: ${entry.method}")
}
}
}
@@ -0,0 +1,90 @@
package com.topjohnwu.magisk.core.utils
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.archivers.zip.ZipMethod
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.util.zip.Inflater
import java.util.zip.InflaterInputStream
/**
* A zip archive backed by a [DataChannel].
*
* [entries] lists all files in the archive. The content of an entry can be accessed with:
* - [open]: a [DataChannel] supporting random access. Only STORED entries are supported.
* - [openStream]: a sequential [InputStream]. Both STORED and DEFLATED entries are supported.
*
* The archive does not take ownership of the source channel. Both the source channel
* and the archive must remain open while using channels or streams of its entries.
*/
class ZipChannel(private val source: DataChannel) : Closeable {
// Use a slice so that closing the zip file does not close the source channel
private val zip = ZipFile.builder()
.setSeekableByteChannel(source.slice(0, source.size()))
.setIgnoreLocalFileHeader(true)
.get()
/** All files (excluding directories) in the archive. */
val entries: List<ZipArchiveEntry> by lazy {
zip.entries.toList().filter { !it.isDirectory }
}
fun getEntry(name: String): ZipArchiveEntry? = zip.getEntry(name)
fun find(predicate: (ZipArchiveEntry) -> Boolean) = entries.find(predicate)
/**
* Get a [DataChannel] of the content of [entry], which must be STORED.
* The caller is responsible for closing the returned channel.
*/
@Throws(IOException::class)
fun open(entry: ZipArchiveEntry): DataChannel {
if (entry.method != ZipMethod.STORED.code) {
throw IOException("${entry.name} is compressed, expected STORED method")
}
if (entry.size <= 0) {
throw IOException("Empty entry: ${entry.name}")
}
return source.slice(dataOffset(entry), entry.size)
}
/**
* Get an [InputStream] of the decompressed content of [entry].
* The caller is responsible for closing the returned stream.
*/
@Throws(IOException::class)
fun openStream(entry: ZipArchiveEntry): InputStream {
return when (entry.method) {
ZipMethod.STORED.code -> source.stream(dataOffset(entry), entry.size)
ZipMethod.DEFLATED.code -> {
val inflater = Inflater(true)
val raw = source.stream(dataOffset(entry), entry.compressedSize)
object : InflaterInputStream(raw, inflater, BUFFER_SIZE) {
override fun close() {
try {
super.close()
} finally {
inflater.end()
}
}
}
}
else -> throw IOException("Unsupported compression method ${entry.method}: ${entry.name}")
}
}
// Resolve the data offset, which requires parsing the local file header
private fun dataOffset(entry: ZipArchiveEntry): Long {
zip.getRawInputStream(entry).close()
return entry.dataOffset
}
override fun close() = zip.close()
companion object {
private const val BUFFER_SIZE = 64 * 1024
}
}
@@ -3,23 +3,37 @@ package com.topjohnwu.magisk.test
import androidx.annotation.Keep
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.core.tasks.OtaPayloadExtractor
import com.topjohnwu.magisk.core.tasks.PatchFileClassifier
import com.topjohnwu.magisk.core.tasks.TarProcessor
import com.topjohnwu.magisk.core.tasks.ZipExtractor
import com.topjohnwu.magisk.core.utils.DataChannel
import com.topjohnwu.magisk.core.utils.ZipChannel
import com.topjohnwu.superuser.nio.ExtendedFile
import com.topjohnwu.superuser.nio.FileSystemManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.util.zip.CRC32
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.random.Random
private const val FACTORY_IMAGE_URL =
"https://dl.google.com/dl/android/aosp/yogi-cd1a.261005.003.b1-factory-90f36052.zip"
@@ -55,13 +69,22 @@ class AppTest : TestCommon {
tarWorkingDir.deleteRecursively()
}
private fun testZipExtraction(url: String) = runBlocking(Dispatchers.IO) {
// Classify the file at url, and extract the boot image with the extractor
private fun testZipExtraction(
url: String,
expectedType: PatchFileClassifier.Type,
extract: suspend (PatchFileClassifier, MutableList<String>, MutableList<String>) -> Unit,
) = runBlocking(Dispatchers.IO) {
val console = mutableListOf<String>()
val logs = mutableListOf<String>()
try {
val channel = DataChannel.Http(ServiceLocator.okhttp, url)
ZipExtractor(outFile, console, logs).extract(channel)
DataChannel.Http(ServiceLocator.okhttp, url).use { channel ->
PatchFileClassifier(channel).use { file ->
assertEquals("Unexpected file type", expectedType, file.type)
extract(file, console, logs)
}
}
} catch (e: Exception) {
System.err.println("Console:\n" + console.joinToString("\n"))
System.err.println("Logs:\n" + logs.joinToString("\n"))
@@ -76,10 +99,16 @@ class AppTest : TestCommon {
}
@Test
fun testFactoryZipExtraction() = testZipExtraction(FACTORY_IMAGE_URL)
fun testFactoryZipExtraction() =
testZipExtraction(FACTORY_IMAGE_URL, PatchFileClassifier.Type.BootZip) { file, _, _ ->
file.openStream().use { input -> outFile.outputStream().use { input.copyTo(it) } }
}
@Test
fun testOtaZipExtraction() = testZipExtraction(OTA_IMAGE_URL)
fun testOtaZipExtraction() =
testZipExtraction(OTA_IMAGE_URL, PatchFileClassifier.Type.PayloadBin) { file, console, logs ->
OtaPayloadExtractor(outFile, console, logs).extract(file.openChannel())
}
@Test
fun testTarProcessor() = runBlocking(Dispatchers.IO) {
@@ -89,9 +118,13 @@ class AppTest : TestCommon {
try {
FileOutputStream("/dev/null").buffered(1024 * 1024).use { outStream ->
val channel = DataChannel.Http(ServiceLocator.okhttp, TAR_IMAGE_URL)
val tar = TarProcessor(workingDir, outStream, console, logs)
val bootImage = tar.start(channel)
val bootImage = DataChannel.Http(ServiceLocator.okhttp, TAR_IMAGE_URL).use { channel ->
PatchFileClassifier(channel).use { file ->
assertEquals("Unexpected file type", PatchFileClassifier.Type.Tar, file.type)
tar.start(file.openStream())
}
}
assertTrue("Extracted init_boot.img should exist", bootImage.exists())
assertEquals("Extracted file size should be $INIT_BOOT_SIZE bytes", INIT_BOOT_SIZE, bootImage.length())
@@ -108,6 +141,188 @@ class AppTest : TestCommon {
}
}
@Test
fun testZipChannelEntries() {
val zip = buildZip(
ZipItem("dir/", ByteArray(0), ZipEntry.STORED),
ZipItem("dir/boot.img", testData(1000, 1), ZipEntry.STORED),
ZipItem("dir/sub/", ByteArray(0), ZipEntry.STORED),
ZipItem("payload.bin", testData(2000, 2), ZipEntry.DEFLATED),
)
val source = ByteArrayChannel(zip)
ZipChannel(source).use { zc ->
assertEquals(
"Directories should be excluded",
listOf("dir/boot.img", "payload.bin"),
zc.entries.map { it.name }
)
assertNotNull("getEntry should find files", zc.getEntry("payload.bin"))
assertNull("getEntry should return null for missing files", zc.getEntry("missing"))
assertEquals("dir/boot.img", zc.find { it.name.endsWith("boot.img") }?.name)
assertNull(zc.find { it.name.endsWith(".zip") })
}
assertTrue("ZipChannel should not close the source channel", source.isOpen)
}
@Test
fun testZipChannelStored() {
// Larger than all DataChannel cache thresholds
val data = testData(3 * 1024 * 1024 + 123, 3)
val zip = buildZip(
ZipItem("first.txt", "hello".toByteArray(), ZipEntry.DEFLATED),
ZipItem("image.img", data, ZipEntry.STORED),
)
ZipChannel(ByteArrayChannel(zip)).use { zc ->
val entry = zc.getEntry("image.img")!!
// Random access through open()
zc.open(entry).use { ch ->
assertEquals("Channel size mismatch", data.size.toLong(), ch.size())
for (offset in listOf(0, 1, 4095, 16 * 1024, 700 * 1024, data.size - 100)) {
for (len in listOf(1, 100, 64 * 1024, 600 * 1024)) {
val n = minOf(len, data.size - offset)
val buf = ByteBuffer.allocate(n)
assertEquals(n, ch.read(buf, offset.toLong()))
assertArrayEquals(
"Random read mismatch at $offset+$n",
data.copyOfRange(offset, offset + n),
buf.array()
)
}
}
assertEquals("Read beyond EOF", -1, ch.read(ByteBuffer.allocate(1), data.size.toLong()))
ch.stream().use { assertArrayEquals("Channel stream mismatch", data, it.readBytes()) }
ch.slice(1000, 5000).stream().use {
assertArrayEquals("Slice mismatch", data.copyOfRange(1000, 6000), it.readBytes())
}
}
// Sequential access through openStream()
zc.openStream(entry).use { assertArrayEquals("Stream mismatch", data, it.readBytes()) }
}
}
@Test
fun testZipChannelDeflated() {
val random = testData(2 * 1024 * 1024, 4)
val text = "Magisk ".repeat(100000).toByteArray()
val zip = buildZip(
ZipItem("random.bin", random, ZipEntry.DEFLATED),
ZipItem("text.txt", text, ZipEntry.DEFLATED),
)
ZipChannel(ByteArrayChannel(zip)).use { zc ->
for ((name, data) in listOf("random.bin" to random, "text.txt" to text)) {
val entry = zc.getEntry(name)!!
assertEquals("Uncompressed size mismatch", data.size.toLong(), entry.size)
zc.openStream(entry).use {
assertArrayEquals("Decompressed $name mismatch", data, it.readBytes())
}
assertThrows("open() should reject compressed entries", IOException::class.java) {
zc.open(entry)
}
}
// Text compresses well, make sure it is really compressed
assertTrue(zc.getEntry("text.txt")!!.compressedSize < text.size / 10)
}
}
@Test
fun testZipChannelEmptyEntry() {
val zip = buildZip(
ZipItem("empty.stored", ByteArray(0), ZipEntry.STORED),
ZipItem("empty.deflated", ByteArray(0), ZipEntry.DEFLATED),
)
ZipChannel(ByteArrayChannel(zip)).use { zc ->
val stored = zc.getEntry("empty.stored")!!
assertThrows(IOException::class.java) { zc.open(stored) }
zc.openStream(stored).use { assertEquals(0, it.readBytes().size) }
zc.openStream(zc.getEntry("empty.deflated")!!).use { assertEquals(0, it.readBytes().size) }
}
}
@Test
fun testZipChannelNested() {
val boot = testData(512 * 1024, 5)
val payload = testData(256 * 1024, 6)
val inner = buildZip(
ZipItem("init_boot.img", boot, ZipEntry.DEFLATED),
ZipItem("payload.bin", payload, ZipEntry.STORED),
)
val outer = buildZip(
ZipItem("README", "readme".toByteArray(), ZipEntry.DEFLATED),
ZipItem("device/image-device-1234.zip", inner, ZipEntry.STORED),
)
ZipChannel(ByteArrayChannel(outer)).use { zc ->
val innerEntry = zc.find { it.name.endsWith(".zip") }!!
zc.open(innerEntry).use { innerChannel ->
ZipChannel(innerChannel).use { izc ->
assertEquals(listOf("init_boot.img", "payload.bin"), izc.entries.map { it.name })
izc.openStream(izc.getEntry("init_boot.img")!!).use {
assertArrayEquals("Nested deflated entry mismatch", boot, it.readBytes())
}
izc.open(izc.getEntry("payload.bin")!!).use { ch ->
val buf = ByteBuffer.allocate(1000)
ch.read(buf, 5000)
assertArrayEquals(
"Nested stored entry mismatch",
payload.copyOfRange(5000, 6000),
buf.array()
)
}
}
assertTrue("Inner ZipChannel should not close its source", innerChannel.isOpen)
}
}
}
@Test
fun testZipChannelInvalid() {
assertThrows(IOException::class.java) {
ZipChannel(ByteArrayChannel(testData(4096, 7)))
}
}
private class ZipItem(val name: String, val data: ByteArray, val method: Int)
private fun buildZip(vararg items: ZipItem): ByteArray {
val bytes = ByteArrayOutputStream()
ZipOutputStream(bytes).use { zip ->
for (item in items) {
val entry = ZipEntry(item.name)
entry.method = item.method
if (item.method == ZipEntry.STORED) {
// STORED entries require size and CRC to be set beforehand
entry.size = item.data.size.toLong()
entry.compressedSize = item.data.size.toLong()
entry.crc = CRC32().apply { update(item.data) }.value
}
zip.putNextEntry(entry)
zip.write(item.data)
zip.closeEntry()
}
}
return bytes.toByteArray()
}
private fun testData(size: Int, seed: Long) = ByteArray(size).also { Random(seed).nextBytes(it) }
// An in-memory DataChannel
private class ByteArrayChannel(
private val data: ByteArray,
startOffset: Long = 0,
size: Long = data.size.toLong(),
) : DataChannel(startOffset, size) {
override fun slice(offset: Long, sliceSize: Long): DataChannel {
require(offset >= 0 && sliceSize >= 0 && offset + sliceSize <= size)
return ByteArrayChannel(data, startOffset + offset, sliceSize)
}
override fun stream(offset: Long, sliceSize: Long): InputStream {
val len = minOf(offset + sliceSize, size) - offset
return ByteArrayInputStream(data, (startOffset + offset).toInt(), len.toInt())
}
}
private fun calculateSha256(file: File): String =
file.inputStream().use { calculateSha256(it) }