diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt index 975aa6a07..aad784912 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt @@ -1,6 +1,7 @@ package com.topjohnwu.magisk.core.tasks import android.net.Uri +import android.os.ParcelFileDescriptor import android.os.Process import android.system.Os import androidx.annotation.WorkerThread @@ -18,7 +19,6 @@ import com.topjohnwu.magisk.core.ktx.writeTo 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 import com.topjohnwu.magisk.core.utils.MediaStoreUtils.openFd import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream import com.topjohnwu.magisk.core.utils.RootUtils @@ -32,11 +32,10 @@ import kotlinx.coroutines.withContext import org.apache.commons.compress.archivers.zip.ZipFile import timber.log.Timber import java.io.File -import java.io.FileInputStream 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 @@ -190,62 +189,65 @@ abstract class MagiskInstallImpl protected constructor( out.use { copyAll(it, 1024 * 1024) } private suspend fun processFile(uri: Uri): Boolean { - val outStream: OutputStream - val outFile: MediaStoreUtils.UriFile - val tar: TarProcessor? + val input = try { + DataChannel.File(ParcelFileDescriptor.AutoCloseInputStream(uri.openFd()).channel) + } catch (e: IOException) { + console.add("! Process error") + Timber.e(e) + return false + } + return processInput(input) + } - // Process input file + private suspend fun processUrl(url: String): Boolean { + val input = try { + DataChannel.Http(ServiceLocator.okhttp, url) + } catch (e: IOException) { + console.add("! Error: " + e.message) + Timber.e(e) + return false + } + return processInput(input) + } + + private suspend fun processInput(input: DataChannel): Boolean { try { - PushbackInputStream(uri.inputStream().buffered(1024 * 1024), 512).use { src -> + input.use { val head = ByteArray(512) - if (src.read(head) != head.size) { + if (input.read(ByteBuffer.wrap(head), 0) != head.size) { console.add("! Invalid input file") return false } - src.unread(head) val magic = head.copyOf(4) val tarMagic = head.copyOfRange(257, 262) - srcBoot = if (tarMagic.contentEquals("ustar".toByteArray())) { - // tar file - outFile = MediaStoreUtils.getFile("$destName.tar") - outStream = outFile.uri.outputStream().buffered(1024 * 1024) - tar = TarProcessor(installDir, outStream, console, logs) - - try { - tar.consume(src) - } catch (e: IOException) { - outStream.close() - outFile.delete() - throw e - } + return if (tarMagic.contentEquals("ustar".toByteArray())) { + processArchive(input) } else { - // raw image - tar = null - outFile = MediaStoreUtils.getFile("$destName.img") - outStream = outFile.uri.outputStream() - val channel = FileInputStream(uri.openFd().fileDescriptor).channel - val boot = installDir.getChildFile("boot.img") - - try { - if (magic.contentEquals("CrAU".toByteArray())) { - OtaPayloadExtractor(boot, console, logs).consume(DataChannel.File(channel)) - } else if (magic.contentEquals("PK\u0003\u0004".toByteArray())) { - ZipExtractor(boot, console, logs).consume(DataChannel.File(channel)) - } else { - console.add("- Copying image to cache") - src.copyAndCloseOut(boot.newOutputStream()) - } - boot - } catch (e: IOException) { - outStream.close() - outFile.delete() - throw e - } + extractAndProcessImage(input, magic) } } } catch (e: IOException) { + console.add("! Process error") + Timber.e(e) + return false + } + } + + // 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 processArchive(input: DataChannel): Boolean { + val outFile = MediaStoreUtils.getFile("$destName.tar") + val outStream = outFile.uri.outputStream().buffered(1024 * 1024) + val tar = TarProcessor(installDir, outStream, console, logs) + + // Process input file + try { + srcBoot = tar.consume(input) + } catch (e: IOException) { + runCatching { outStream.close() } + outFile.delete() if (e is TarProcessor.NoBootException) console.add("! No boot image found") console.add("! Process error") @@ -263,18 +265,8 @@ abstract class MagiskInstallImpl protected constructor( // Output file try { val newBoot = installDir.getChildFile("new-boot.img") - if (tar != null) { - tar.finish(newBoot) - } else { - newBoot.newInputStream().use { it.copyAll(outStream, 1024 * 1024) } - } + tar.finish(newBoot) newBoot.delete() - - console.add("") - console.add("****************************") - console.add(" Output file is written to ") - console.add(" $outFile ") - console.add("****************************") } catch (e: IOException) { console.add("! Failed to output to $outFile") outFile.delete() @@ -284,46 +276,40 @@ abstract class MagiskInstallImpl protected constructor( outStream.close() } - // Fix up binaries - srcBoot.delete() - "cp_readlink $installDir".sh() - - return true + return onOutputWritten(outFile) } - private fun processUrl(url: String): Boolean { - // Download image from url + // Extract the boot image from the input, and output the patched boot image + private suspend fun extractAndProcessImage(input: DataChannel, magic: ByteArray): Boolean { + // Process input file + srcBoot = installDir.getChildFile("boot.img") try { - srcBoot = installDir.getChildFile("boot.img") - ZipExtractor(srcBoot, console, logs) - .consume(DataChannel.Http(ServiceLocator.okhttp, url)) + if (magic.contentEquals("CrAU".toByteArray())) { + OtaPayloadExtractor(srcBoot, console, logs).consume(input) + } else if (magic.contentEquals("PK\u0003\u0004".toByteArray())) { + ZipExtractor(srcBoot, console, logs).consume(input) + } else { + console.add("- Copying image to cache") + input.stream().use { it.copyAndCloseOut(srcBoot.newOutputStream()) } + } } catch (e: IOException) { - console.add("! Error: " + e.message) + console.add("! Process error") Timber.e(e) return false } // Patch file - if (!patchBoot()) { + if (!patchBoot()) return false - } // Output file val outFile = MediaStoreUtils.getFile("$destName.img") try { val newBoot = installDir.getChildFile("new-boot.img") outFile.uri.outputStream().use { out -> - FileInputStream(newBoot).use { input -> - input.copyTo(out) - } + newBoot.newInputStream().use { it.copyAll(out, 1024 * 1024) } } newBoot.delete() - - console.add("") - console.add("****************************") - console.add(" Output file is written to ") - console.add(" $outFile ") - console.add("****************************") } catch (e: IOException) { console.add("! Failed to output to $outFile") outFile.delete() @@ -331,6 +317,16 @@ abstract class MagiskInstallImpl protected constructor( return false } + return onOutputWritten(outFile) + } + + private fun onOutputWritten(outFile: MediaStoreUtils.UriFile): Boolean { + console.add("") + console.add("****************************") + console.add(" Output file is written to ") + console.add(" $outFile ") + console.add("****************************") + // Fix up binaries srcBoot.delete() "cp_readlink $installDir".sh() diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/TarProcessor.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/TarProcessor.kt index 3f084e5d9..5cc4c1959 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/TarProcessor.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/TarProcessor.kt @@ -3,6 +3,7 @@ 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 @@ -23,7 +24,8 @@ 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. * - * The caller owns both the input and output streams and is responsible for closing them. + * [consume] closes the input channel. The caller owns the output stream and is + * responsible for closing it. */ class TarProcessor( private val installDir: ExtendedFile, @@ -42,9 +44,14 @@ class TarProcessor( private lateinit var target: BootItem @Throws(IOException::class) - suspend fun consume(input: InputStream): ExtendedFile { + suspend fun consume(channel: DataChannel): ExtendedFile = channel.use { + val tarIn = TarArchiveInputStream(it.stream().buffered(1024 * 1024)) + tarIn.use { processEntries(tarIn) } + } + + @Throws(IOException::class) + private suspend fun processEntries(tarIn: TarArchiveInputStream): ExtendedFile { console.add("- Processing tar file") - val tarIn = TarArchiveInputStream(input) var entry: TarArchiveEntry? = tarIn.nextEntry fun decompressedStream(): InputStream { diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/ZipExtractor.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/ZipExtractor.kt index 7e0b4f36f..4efa3677f 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/ZipExtractor.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/ZipExtractor.kt @@ -142,7 +142,7 @@ class ZipExtractor( ZipMethod.DEFLATED.code -> { InflaterInputStream( - channel.sliceStream(entry.dataOffset, entry.size), + channel.stream(entry.dataOffset, entry.size), Inflater(true), 16 * 1024 ).use { input -> diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/DataChannel.java b/app/core/src/main/java/com/topjohnwu/magisk/core/utils/DataChannel.java index 96683c956..3a253e206 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/DataChannel.java +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/utils/DataChannel.java @@ -36,7 +36,14 @@ public abstract class DataChannel implements SeekableByteChannel { public abstract DataChannel slice(long offset, long sliceSize); - public abstract InputStream sliceStream(long offset, long sliceSize) throws IOException; + public abstract InputStream stream(long offset, long sliceSize) throws IOException; + + /** + * Create an InputStream of the entire channel. The caller must close it. + */ + public InputStream stream() throws IOException { + return stream(0, size); + } @Override public int read(ByteBuffer dst) throws IOException { @@ -142,7 +149,7 @@ public abstract class DataChannel implements SeekableByteChannel { } private int readDirectly(ByteBuffer dst, long position) throws IOException { - try (var channel = Channels.newChannel(sliceStream(position, dst.remaining()))) { + try (var channel = Channels.newChannel(stream(position, dst.remaining()))) { int totalBytesRead = 0; while (true) { int bytesRead = channel.read(dst); @@ -220,7 +227,7 @@ public abstract class DataChannel implements SeekableByteChannel { } @Override - public InputStream sliceStream(long offset, long sliceSize) throws IOException { + public InputStream stream(long offset, long sliceSize) throws IOException { long endPosition = Math.min(offset + sliceSize, size) + startOffset; var startPosition = startOffset + offset; var readLength = endPosition - startPosition; @@ -284,7 +291,7 @@ public abstract class DataChannel implements SeekableByteChannel { } @Override - public InputStream sliceStream(long offset, long sliceSize) throws IOException { + public InputStream stream(long offset, long sliceSize) throws IOException { long endPosition = Math.min(offset + sliceSize, size) + startOffset; var startPosition = startOffset + offset;