app: refactor DataChannel and extractors

Refactor DataSourceChannel into an abstract DataChannel with nested
DataChannel.File and DataChannel.Http implementations, separating
local file and remote HTTP stream backends.

Additionally:
- Rename Payload to OtaPayloadExtractor and ExtractImage to
  ZipExtractor to better reflect their responsibilities.
- Standardize both extractors with a uniform constructor and a
  consume(channel: DataChannel) method that handles channel lifecycle.
- Make OtaPayloadExtractor stateless by passing channel, manifest,
  and data offsets directly through method arguments.

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-10-06 15:53:42 -07:00
committed by John Wu
parent 3b37599db9
commit 5ebd48ab87
4 changed files with 179 additions and 140 deletions
@@ -15,7 +15,7 @@ import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.core.isRunningAsStub
import com.topjohnwu.magisk.core.ktx.copyAll
import com.topjohnwu.magisk.core.ktx.writeTo
import com.topjohnwu.magisk.core.utils.DataSourceChannel
import com.topjohnwu.magisk.core.utils.DataChannel
import com.topjohnwu.magisk.core.utils.DummyList
import com.topjohnwu.magisk.core.utils.MediaStoreUtils
import com.topjohnwu.magisk.core.utils.MediaStoreUtils.inputStream
@@ -37,7 +37,6 @@ import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStrea
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
@@ -367,11 +366,9 @@ abstract class MagiskInstallImpl protected constructor(
try {
if (magic.contentEquals("CrAU".toByteArray())) {
DataSourceChannel(channel).use { source ->
Payload(source).extract(boot, console, logs)
}
OtaPayloadExtractor(boot, console, logs).consume(DataChannel.File(channel))
} else if (magic.contentEquals("PK\u0003\u0004".toByteArray())) {
ExtractImage(boot, console, logs).consume(DataSourceChannel(channel))
ZipExtractor(boot, console, logs).consume(DataChannel.File(channel))
} else {
console.add("- Copying image to cache")
src.copyAndCloseOut(boot.newOutputStream())
@@ -434,8 +431,8 @@ abstract class MagiskInstallImpl protected constructor(
// Download image from url
try {
srcBoot = installDir.getChildFile("boot.img")
ExtractImage(srcBoot, console, logs)
.consume(DataSourceChannel(ServiceLocator.okhttp, url))
ZipExtractor(srcBoot, console, logs)
.consume(DataChannel.Http(ServiceLocator.okhttp, url))
} catch (e: IOException) {
console.add("! Error: " + e.message)
Timber.e(e)
@@ -3,7 +3,7 @@ package com.topjohnwu.magisk.core.tasks
import chromeos_update_engine.DeltaArchiveManifest
import chromeos_update_engine.InstallOperation
import chromeos_update_engine.PartitionUpdate
import com.topjohnwu.magisk.core.utils.DataSourceChannel
import com.topjohnwu.magisk.core.utils.DataChannel
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
import java.io.File
@@ -14,40 +14,42 @@ import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption
import java.security.MessageDigest
class Payload(private val channel: DataSourceChannel) {
private val manifest: DeltaArchiveManifest
private var dataBase = 0L
class OtaPayloadExtractor(
private val outFile: File,
private val console: MutableList<String>,
private val logs: MutableList<String>,
) {
@Throws(IOException::class)
fun consume(channel: DataChannel) {
channel.use {
val manifest = readPayloadHeader(it)
val dataBase = channel.position()
init {
manifest = readPayloadHeader()
val partition = findPartition(manifest)
console.add("- Found partition ${partition.partition_name}")
val actualHash = extractPartition(it, manifest, dataBase, partition)
val newPartitionInfo = partition.new_partition_info
if (newPartitionInfo?.hash == null) {
logs.add("Hash verification skipped")
return
}
fun toHex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it) }
val expectedHash = newPartitionInfo.hash.toByteArray()
if (!expectedHash.contentEquals(actualHash)) {
throw IOException(
"Hash mismatch, expected ${toHex(expectedHash)}, but got ${toHex(actualHash)}"
)
}
logs.add("Hash verification passed")
}
}
@Throws(IOException::class)
fun extract(outputFile: File, console: MutableList<String>, logger: MutableList<String>) {
val partition = findPartition()
console.add("- Found partition ${partition.partition_name}")
val actualHash = extractPartition(outputFile, partition, console)
val newPartitionInfo = partition.new_partition_info
if (newPartitionInfo?.hash == null) {
logger.add("Hash verification skipped")
return
}
fun toHex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it) }
val expectedHash = newPartitionInfo.hash.toByteArray()
if (!expectedHash.contentEquals(actualHash)) {
throw IOException(
"Hash mismatch, expected ${toHex(expectedHash)}, but got ${toHex(actualHash)}"
)
}
logger.add("Hash verification passed")
}
@Throws(IOException::class)
private fun readPayloadHeader(): DeltaArchiveManifest {
private fun readPayloadHeader(channel: DataChannel): DeltaArchiveManifest {
// Read magic
val magicBuffer = ByteBuffer.allocate(4)
channel.read(magicBuffer)
@@ -93,13 +95,11 @@ class Payload(private val channel: DataSourceChannel) {
// Skip manifest signature
channel.position(channel.position() + manifestSigLen)
dataBase = channel.position()
return manifest
}
@Throws(IOException::class)
private fun findPartition(): PartitionUpdate {
private fun findPartition(manifest: DeltaArchiveManifest): PartitionUpdate {
return manifest.partitions.find { it.partition_name == "init_boot" }
?: manifest.partitions.find { it.partition_name == "boot" }
?: throw IOException("boot partition not found in payload")
@@ -107,12 +107,13 @@ class Payload(private val channel: DataSourceChannel) {
@Throws(IOException::class)
private fun extractPartition(
outputFile: File,
channel: DataChannel,
manifest: DeltaArchiveManifest,
dataBase: Long,
partition: PartitionUpdate,
console: MutableList<String>,
): ByteArray {
FileChannel.open(
outputFile.toPath(),
outFile.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.READ,
@@ -126,7 +127,7 @@ class Payload(private val channel: DataSourceChannel) {
if (index % 5 == 0 || index == count - 1) {
console.add("- Downloading ${index + 1}/$count")
}
processOperation(outChannel, operation)
processOperation(outChannel, operation, channel, dataBase, manifest.block_size ?: 4096)
}
val digest = MessageDigest.getInstance("SHA-256")
@@ -137,7 +138,13 @@ class Payload(private val channel: DataSourceChannel) {
}
@Throws(IOException::class)
private fun processOperation(outChannel: FileChannel, operation: InstallOperation) {
private fun processOperation(
outChannel: FileChannel,
operation: InstallOperation,
channel: DataChannel,
dataBase: Long,
blockSize: Int,
) {
val dataType = operation.type
if (dataType == InstallOperation.Type.ZERO) {
return
@@ -148,7 +155,7 @@ class Payload(private val channel: DataSourceChannel) {
dataBuffer.flip()
val dstExtent = operation.dst_extents[0]
val outOffset = (dstExtent.start_block ?: 0L) * (manifest.block_size ?: 4096)
val outOffset = (dstExtent.start_block ?: 0L) * blockSize
when (dataType) {
InstallOperation.Type.REPLACE -> {
@@ -1,6 +1,6 @@
package com.topjohnwu.magisk.core.tasks
import com.topjohnwu.magisk.core.utils.DataSourceChannel
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
@@ -12,13 +12,13 @@ import java.nio.file.StandardOpenOption
import java.util.zip.Inflater
import java.util.zip.InflaterInputStream
class ExtractImage(
class ZipExtractor(
private val outFile: File,
private val console: MutableList<String>,
private val logs: MutableList<String>,
) {
@Throws(IOException::class)
fun consume(channel: DataSourceChannel) {
fun consume(channel: DataChannel) {
ZipFile.builder()
.setSeekableByteChannel(channel)
.setIgnoreLocalFileHeader(true)
@@ -51,21 +51,20 @@ class ExtractImage(
@Throws(IOException::class)
private fun extractFromOTAPackage(
payload: ZipArchiveEntry,
channel: DataSourceChannel,
channel: DataChannel,
) {
if (payload.method != ZipMethod.STORED.code) {
throw IOException("payload.bin is compressed, expected STORED method")
}
channel.slice(payload.dataOffset, payload.size).use { payloadChannel ->
Payload(payloadChannel).extract(outFile, console, logs)
}
OtaPayloadExtractor(outFile, console, logs)
.consume(channel.slice(payload.dataOffset, payload.size))
}
@Throws(IOException::class)
private fun extractFromFactoryImage(
zipFile: ZipFile,
channel: DataSourceChannel,
channel: DataChannel,
) {
console.add("- Processing as factory image package")
@@ -96,7 +95,7 @@ class ExtractImage(
@Throws(IOException::class)
private fun extractFromInnerImageZip(
entry: ZipArchiveEntry,
channel: DataSourceChannel,
channel: DataChannel,
) {
logs.add("Found inner image ZIP: ${entry.name}")
@@ -120,7 +119,7 @@ class ExtractImage(
private fun extractImageFile(
zipFile: ZipFile,
entry: ZipArchiveEntry,
channel: DataSourceChannel,
channel: DataChannel,
) {
console.add("- Found boot image entry: ${entry.name} (${entry.size} bytes)")
console.add("- Downloading")
@@ -143,7 +142,7 @@ class ExtractImage(
ZipMethod.DEFLATED.code -> {
InflaterInputStream(
channel.streamRead(entry.dataOffset, entry.size),
channel.sliceStream(entry.dataOffset, entry.size),
Inflater(true),
16 * 1024
).use { input ->
@@ -14,67 +14,29 @@ import java.nio.channels.SeekableByteChannel;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class DataSourceChannel implements SeekableByteChannel {
private static final int RANDOM_READ_CACHE_SIZE = 16 * 1024;
public abstract class DataChannel implements SeekableByteChannel {
protected static final int RANDOM_READ_CACHE_SIZE = 16 * 1024;
private static final int SEQ_READ_CACHE_SIZE = 1024 * 1024;
private static final int SEQ_READ_THRESHOLD = 1024;
private static final int DIRECT_READ_THRESHOLD = 512 * 1024;
private final OkHttpClient client;
private final String url;
private final FileChannel fileChannel;
private final boolean ownership;
private final long startOffset;
private long size;
protected final long startOffset;
protected long size;
private long position = 0;
private boolean open = true;
private byte[] cache = null;
private long cacheStart = -1;
protected byte[] cache = null;
protected long cacheStart = -1;
private DataSourceChannel(OkHttpClient client, String url, FileChannel fileChannel,
boolean ownership, long startOffset, long size) {
this.client = client;
this.url = url;
this.fileChannel = fileChannel;
this.ownership = ownership;
protected DataChannel(long startOffset, long size) {
this.startOffset = startOffset;
this.size = size;
}
public DataSourceChannel(FileChannel fileChannel) throws IOException {
this(null, null, fileChannel, true, 0, fileChannel.size());
}
public abstract DataChannel slice(long offset, long sliceSize);
public DataSourceChannel(OkHttpClient client, String url) throws IOException {
this(client, url, null, false, 0, 0);
var request = new Request.Builder()
.url(url)
.header("Range", "bytes=" + "-" + RANDOM_READ_CACHE_SIZE)
.build();
try (var response = client.newCall(request).execute()) {
if (response.code() != 206) {
throw new IOException("Unexpected response code " + response.code());
}
var contentRange = response.header("Content-Range");
if (contentRange == null) {
throw new IOException("Could not determine file size.");
}
var contentLength = contentRange.substring(contentRange.lastIndexOf('/') + 1);
size = Long.parseLong(contentLength);
cache = response.body().bytes();
cacheStart = size - cache.length;
}
}
public DataSourceChannel slice(long offset, long sliceSize) {
if (offset < 0 || sliceSize <= 0 || offset + sliceSize > size) {
throw new IllegalArgumentException("Invalid slice parameters");
}
return new DataSourceChannel(client, url, fileChannel, false,
startOffset + offset, sliceSize);
}
public abstract InputStream sliceStream(long offset, long sliceSize) throws IOException;
@Override
public int read(ByteBuffer dst) throws IOException {
@@ -161,7 +123,6 @@ public class DataSourceChannel implements SeekableByteChannel {
cache = buffer.array();
this.cacheStart = cacheStart;
}
private boolean isCacheHit(long pos, int bytesToRead) {
@@ -181,7 +142,7 @@ public class DataSourceChannel implements SeekableByteChannel {
}
private int readDirectly(ByteBuffer dst, long position) throws IOException {
try (var channel = Channels.newChannel(streamRead(position, dst.remaining()))) {
try (var channel = Channels.newChannel(sliceStream(position, dst.remaining()))) {
int totalBytesRead = 0;
while (true) {
int bytesRead = channel.read(dst);
@@ -195,40 +156,13 @@ public class DataSourceChannel implements SeekableByteChannel {
}
}
public InputStream streamRead(long position, long length) throws IOException {
long endPosition = Math.min(position + length, size) + startOffset;
var startPosition = startOffset + position;
var readLength = endPosition - startPosition;
if (fileChannel != null) {
fileChannel.position(startPosition);
return BoundedInputStream.builder()
.setInputStream(Channels.newInputStream(fileChannel))
.setMaxCount(readLength)
.setPropagateClose(false)
.get();
}
var request = new Request.Builder()
.url(url)
.header("Range", "bytes=" + startPosition + "-" + (endPosition - 1))
.build();
var response = client.newCall(request).execute();
if (response.code() != 206) {
response.close();
throw new IOException("Unexpected response code " + response.code());
}
return response.body().byteStream();
}
@Override
public long position() {
return position;
}
@Override
public DataSourceChannel position(long newPosition) throws IOException {
public DataChannel position(long newPosition) throws IOException {
if (!open) throw new ClosedChannelException();
if (newPosition < 0) {
throw new IllegalArgumentException("Position out of bounds: " + newPosition);
@@ -251,9 +185,6 @@ public class DataSourceChannel implements SeekableByteChannel {
public void close() throws IOException {
open = false;
cache = null;
if (ownership) {
fileChannel.close();
}
}
@Override
@@ -262,7 +193,112 @@ public class DataSourceChannel implements SeekableByteChannel {
}
@Override
public DataSourceChannel truncate(long size) {
public DataChannel truncate(long size) {
throw new NonWritableChannelException();
}
public static class File extends DataChannel {
private final FileChannel fileChannel;
private final boolean ownership;
public File(FileChannel fileChannel) throws IOException {
this(fileChannel, true, 0, fileChannel.size());
}
private File(FileChannel fileChannel, boolean ownership, long startOffset, long size) {
super(startOffset, size);
this.fileChannel = fileChannel;
this.ownership = ownership;
}
@Override
public File slice(long offset, long sliceSize) {
if (offset < 0 || sliceSize <= 0 || offset + sliceSize > size) {
throw new IllegalArgumentException("Invalid slice parameters");
}
return new File(fileChannel, false, startOffset + offset, sliceSize);
}
@Override
public InputStream sliceStream(long offset, long sliceSize) throws IOException {
long endPosition = Math.min(offset + sliceSize, size) + startOffset;
var startPosition = startOffset + offset;
var readLength = endPosition - startPosition;
fileChannel.position(startPosition);
return BoundedInputStream.builder()
.setInputStream(Channels.newInputStream(fileChannel))
.setMaxCount(readLength)
.setPropagateClose(false)
.get();
}
@Override
public void close() throws IOException {
super.close();
if (ownership) {
fileChannel.close();
}
}
}
public static class Http extends DataChannel {
private final OkHttpClient client;
private final String url;
public Http(OkHttpClient client, String url) throws IOException {
super(0, 0);
this.client = client;
this.url = url;
var request = new Request.Builder()
.url(url)
.header("Range", "bytes=" + "-" + RANDOM_READ_CACHE_SIZE)
.build();
try (var response = client.newCall(request).execute()) {
if (response.code() != 206) {
throw new IOException("Unexpected response code " + response.code());
}
var contentRange = response.header("Content-Range");
if (contentRange == null) {
throw new IOException("Could not determine file size.");
}
var contentLength = contentRange.substring(contentRange.lastIndexOf('/') + 1);
size = Long.parseLong(contentLength);
cache = response.body().bytes();
cacheStart = size - cache.length;
}
}
private Http(OkHttpClient client, String url, long startOffset, long size) {
super(startOffset, size);
this.client = client;
this.url = url;
}
@Override
public Http slice(long offset, long sliceSize) {
if (offset < 0 || sliceSize <= 0 || offset + sliceSize > size) {
throw new IllegalArgumentException("Invalid slice parameters");
}
return new Http(client, url, startOffset + offset, sliceSize);
}
@Override
public InputStream sliceStream(long offset, long sliceSize) throws IOException {
long endPosition = Math.min(offset + sliceSize, size) + startOffset;
var startPosition = startOffset + offset;
var request = new Request.Builder()
.url(url)
.header("Range", "bytes=" + startPosition + "-" + (endPosition - 1))
.build();
var response = client.newCall(request).execute();
if (response.code() != 206) {
response.close();
throw new IOException("Unexpected response code " + response.code());
}
return response.body().byteStream();
}
}
}