app: extract tar processing into TarProcessor

Tar firmware handling (e.g. Samsung AP tars) was entangled with
MagiskInstallImpl: BootItem and processTar lived in the installer, and
processFile set up the TarArchiveOutputStream, used a nullable
BootItem as the tar flag, and reassigned its file to new-boot.img.

Move all tar logic into a standalone TarProcessor next to
OtaPayloadExtractor and ZipExtractor. Since the output tar has to stay
open while the installer patches the image, it uses a two-phase API:
consume() extracts the boot images, copies all other entries to the
output tar, and returns the image to patch; finish() writes the
patched image and finalizes the archive. The caller still owns and
closes both raw streams, and MagiskInstallImpl no longer references
any tar types.

Additionally:
- Pass through vbmeta.img smaller than 256 bytes unpatched instead of
  looping forever, as the loop continued without advancing the entry.
- Close the output stream when patching fails instead of leaking it,
  ignoring close errors so that they cannot crash the app.

Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-06 15:53:42 -07:00
committed by John Wu
parent 5ebd48ab87
commit 09d55f2afd
2 changed files with 187 additions and 145 deletions
@@ -29,20 +29,14 @@ import com.topjohnwu.superuser.nio.ExtendedFile
import com.topjohnwu.superuser.nio.FileSystemManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStream
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.io.PushbackInputStream
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
@@ -195,137 +189,10 @@ abstract class MagiskInstallImpl protected constructor(
private suspend fun InputStream.copyAndCloseOut(out: OutputStream) =
out.use { copyAll(it, 1024 * 1024) }
private class NoAvailableStream(s: InputStream) : FilterInputStream(s) {
// Make sure available is never called on the actual stream and always return 0
// to reduce max buffer size and avoid OOM
override fun available() = 0
}
private class NoBootException : IOException()
inner class BootItem(private val entry: TarArchiveEntry) {
val name = entry.name.replace(".lz4", "")
var file = installDir.getChildFile(name)
suspend fun copyTo(tarOut: TarArchiveOutputStream) {
entry.name = name
entry.size = file.length()
file.newInputStream().use {
console.add("-- Writing : $name")
tarOut.putArchiveEntry(entry)
it.copyAll(tarOut)
tarOut.closeArchiveEntry()
}
}
}
@Throws(IOException::class)
private suspend fun processTar(
tarIn: TarArchiveInputStream,
tarOut: TarArchiveOutputStream
): BootItem {
console.add("- Processing tar file")
var entry: TarArchiveEntry? = tarIn.nextEntry
fun decompressedStream(): InputStream {
val stream = if (tarIn.currentEntry.name.endsWith(".lz4"))
FramedLZ4CompressorInputStream(tarIn, true) else tarIn
return NoAvailableStream(stream)
}
var boot: BootItem? = null
var initBoot: BootItem? = null
var recovery: BootItem? = null
while (entry != null) {
val bootItem: BootItem?
if (entry.name.startsWith("boot.img")) {
bootItem = BootItem(entry)
boot = bootItem
} else if (entry.name.startsWith("init_boot.img")) {
bootItem = BootItem(entry)
initBoot = bootItem
} else if (Config.recovery && entry.name.contains("recovery.img")) {
bootItem = BootItem(entry)
recovery = bootItem
} else {
bootItem = null
}
if (bootItem != null) {
console.add("-- Extracting: ${bootItem.name}")
decompressedStream().copyAndCloseOut(bootItem.file.newOutputStream())
} else if (entry.name.contains("vbmeta.img")) {
val rawData = decompressedStream().readBytes()
// Valid vbmeta.img should be at least 256 bytes
if (rawData.size < 256)
continue
// vbmeta partition exist, disable boot vbmeta patch
Info.patchBootVbmeta = false
val name = entry.name.replace(".lz4", "")
console.add("-- Patching : $name")
// Patch flags to AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED |
// AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED
ByteBuffer.wrap(rawData).putInt(120, 3)
// Fetch the next entry first before modifying current entry
val vbmeta = entry
entry = tarIn.nextEntry
// Update entry with new information
vbmeta.name = name
vbmeta.size = rawData.size.toLong()
// Write output
tarOut.putArchiveEntry(vbmeta)
tarOut.write(rawData)
tarOut.closeArchiveEntry()
continue
} else if (entry.name.contains("userdata.img")) {
console.add("-- Skipping : ${entry.name}")
} else {
console.add("-- Copying : ${entry.name}")
tarOut.putArchiveEntry(entry)
tarIn.copyAll(tarOut)
tarOut.closeArchiveEntry()
}
entry = tarIn.nextEntry ?: break
}
// Patch priority: recovery > init_boot > boot
return when {
recovery != null -> {
if (boot != null) {
// Repack boot image to prevent auto restore
arrayOf(
"cd $installDir",
"chmod -R 755 .",
"./magiskboot unpack boot.img",
"./magiskboot repack boot.img",
"cat new-boot.img > boot.img",
"./magiskboot cleanup",
"rm -f new-boot.img",
"cd /").sh()
boot.copyTo(tarOut)
}
recovery
}
initBoot != null -> {
boot?.copyTo(tarOut)
initBoot
}
boot != null -> boot
else -> throw NoBootException()
}
}
private suspend fun processFile(uri: Uri): Boolean {
val outStream: OutputStream
val outFile: MediaStoreUtils.UriFile
var bootItem: BootItem? = null
val tar: TarProcessor?
// Process input file
try {
@@ -343,15 +210,11 @@ abstract class MagiskInstallImpl protected constructor(
srcBoot = if (tarMagic.contentEquals("ustar".toByteArray())) {
// tar file
outFile = MediaStoreUtils.getFile("$destName.tar")
val os = outFile.uri.outputStream().buffered(1024 * 1024)
outStream = TarArchiveOutputStream(os).also {
it.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR)
it.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU)
}
outStream = outFile.uri.outputStream().buffered(1024 * 1024)
tar = TarProcessor(installDir, outStream, console, logs)
try {
bootItem = processTar(TarArchiveInputStream(src), outStream)
bootItem.file
tar.consume(src)
} catch (e: IOException) {
outStream.close()
outFile.delete()
@@ -359,6 +222,7 @@ abstract class MagiskInstallImpl protected constructor(
}
} else {
// raw image
tar = null
outFile = MediaStoreUtils.getFile("$destName.img")
outStream = outFile.uri.outputStream()
val channel = FileInputStream(uri.openFd().fileDescriptor).channel
@@ -382,7 +246,7 @@ abstract class MagiskInstallImpl protected constructor(
}
}
} catch (e: IOException) {
if (e is NoBootException)
if (e is TarProcessor.NoBootException)
console.add("! No boot image found")
console.add("! Process error")
Timber.e(e)
@@ -391,6 +255,7 @@ abstract class MagiskInstallImpl protected constructor(
// Patch file
if (!patchBoot()) {
runCatching { outStream.close() }
outFile.delete()
return false
}
@@ -398,9 +263,8 @@ abstract class MagiskInstallImpl protected constructor(
// Output file
try {
val newBoot = installDir.getChildFile("new-boot.img")
if (bootItem != null) {
bootItem.file = newBoot
bootItem.copyTo(outStream as TarArchiveOutputStream)
if (tar != null) {
tar.finish(newBoot)
} else {
newBoot.newInputStream().use { it.copyAll(outStream, 1024 * 1024) }
}
@@ -0,0 +1,178 @@
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.superuser.Shell
import com.topjohnwu.superuser.nio.ExtendedFile
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStream
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
/**
* Patch boot images in tar firmware packages (e.g. Samsung AP tar files).
*
* A single-use, two-phase processor; the caller patches the boot image in between:
* 1. [consume]: extract boot images from the input tar into [installDir], and copy all
* 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.
*
* The caller owns both the input and output streams and is responsible for closing them.
*/
class TarProcessor(
private val installDir: ExtendedFile,
output: OutputStream,
private val console: MutableList<String>,
private val logs: MutableList<String>,
) {
class NoBootException : IOException()
private val tarOut = TarArchiveOutputStream(output).apply {
setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR)
setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU)
}
// The image to be patched, selected by consume() and written by finish()
private lateinit var target: BootItem
@Throws(IOException::class)
suspend fun consume(input: InputStream): ExtendedFile {
console.add("- Processing tar file")
val tarIn = TarArchiveInputStream(input)
var entry: TarArchiveEntry? = tarIn.nextEntry
fun decompressedStream(): InputStream {
val stream = if (tarIn.currentEntry.name.endsWith(".lz4"))
FramedLZ4CompressorInputStream(tarIn, true) else tarIn
return NoAvailableStream(stream)
}
var boot: BootItem? = null
var initBoot: BootItem? = null
var recovery: BootItem? = null
while (entry != null) {
val bootItem: BootItem?
if (entry.name.startsWith("boot.img")) {
bootItem = BootItem(entry)
boot = bootItem
} else if (entry.name.startsWith("init_boot.img")) {
bootItem = BootItem(entry)
initBoot = bootItem
} else if (Config.recovery && entry.name.contains("recovery.img")) {
bootItem = BootItem(entry)
recovery = bootItem
} else {
bootItem = null
}
if (bootItem != null) {
console.add("-- Extracting: ${bootItem.name}")
bootItem.file.newOutputStream().use {
decompressedStream().copyAll(it, 1024 * 1024)
}
} else if (entry.name.contains("vbmeta.img")) {
val rawData = decompressedStream().readBytes()
val name = entry.name.replace(".lz4", "")
// Valid vbmeta.img should be at least 256 bytes
if (rawData.size >= 256) {
// vbmeta partition exist, disable boot vbmeta patch
Info.patchBootVbmeta = false
console.add("-- Patching : $name")
// Patch flags to AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED |
// AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED
ByteBuffer.wrap(rawData).putInt(120, 3)
} else {
console.add("-- Copying : $name")
}
// Fetch the next entry first before modifying current entry
val vbmeta = entry
entry = tarIn.nextEntry
// Update entry with new information
vbmeta.name = name
vbmeta.size = rawData.size.toLong()
// Write output
tarOut.putArchiveEntry(vbmeta)
tarOut.write(rawData)
tarOut.closeArchiveEntry()
continue
} else if (entry.name.contains("userdata.img")) {
console.add("-- Skipping : ${entry.name}")
} else {
console.add("-- Copying : ${entry.name}")
tarOut.putArchiveEntry(entry)
tarIn.copyAll(tarOut)
tarOut.closeArchiveEntry()
}
entry = tarIn.nextEntry ?: break
}
// Patch priority: recovery > init_boot > boot
target = when {
recovery != null -> {
if (boot != null) {
// Repack boot image to prevent auto restore
Shell.cmd(
"cd $installDir",
"chmod -R 755 .",
"./magiskboot unpack boot.img",
"./magiskboot repack boot.img",
"cat new-boot.img > boot.img",
"./magiskboot cleanup",
"rm -f new-boot.img",
"cd /"
).to(console, logs).exec()
boot.write()
}
recovery
}
initBoot != null -> {
boot?.write()
initBoot
}
boot != null -> boot
else -> throw NoBootException()
}
return target.file
}
@Throws(IOException::class)
suspend fun finish(patched: ExtendedFile) {
target.write(patched)
tarOut.finish()
}
private class NoAvailableStream(s: InputStream) : FilterInputStream(s) {
// Make sure available is never called on the actual stream and always return 0
// to reduce max buffer size and avoid OOM
override fun available() = 0
}
private inner class BootItem(private val entry: TarArchiveEntry) {
val name = entry.name.replace(".lz4", "")
val file: ExtendedFile = installDir.getChildFile(name)
// Write the image to the output tar, preserving the original entry's metadata
suspend fun write(image: ExtendedFile = file) {
entry.name = name
entry.size = image.length()
image.newInputStream().use {
console.add("-- Writing : $name")
tarOut.putArchiveEntry(entry)
it.copyAll(tarOut)
tarOut.closeArchiveEntry()
}
}
}
}