diff --git a/app/src/main/java/com/redtermapp/util/DeviceToolkit.kt b/app/src/main/java/com/redtermapp/util/DeviceToolkit.kt index 913c950..0dc5269 100644 --- a/app/src/main/java/com/redtermapp/util/DeviceToolkit.kt +++ b/app/src/main/java/com/redtermapp/util/DeviceToolkit.kt @@ -183,28 +183,31 @@ object DeviceToolkit { toolkitDir: File, cwd: String, prootTmpDir: File, + extBin: String? = null, + extLib: String? = null, ): String { val prootBin = "$nativeLibDir/libproot.so" val prootLoader = "$nativeLibDir/libproot-loader.so" val toolkit = toolkitDir.absolutePath - // Absolute, not `$PATH:...`: the launcher runs under an empty - // environment (the distro pattern), so an append would be empty and - // the child would lose the device's own commands. The toolkit - // directory comes last so a device command always wins a name - // collision. - val path = "/system/bin:/system/xbin:/vendor/bin:/odm/bin:/sbin:/bin:/usr/bin:/usr/sbin:$toolkit" + val devicePrefix = "/system/bin:/system/xbin:/vendor/bin:/odm/bin:/sbin:/bin:/usr/bin:/usr/sbin" + // The extended toolkit slots between the device dirs and the lean + // toolkit: a GNU tool beats the busybox applet, and a device command + // beats both. With no extended tools, extBin is null and this is the + // path the shell has always had. + val path = ExtendedToolkit.toolkitPath(devicePrefix, extBin, toolkit) + // Bundled shared libraries for an extended tool (e.g. curl's OpenSSL) + // resolve through LD_LIBRARY_PATH; none of them shadow a bionic lib. + val libExport = if (extLib.isNullOrBlank()) "" else "export LD_LIBRARY_PATH=\"$extLib\"" // Deliberately no PS1: the bundled bash shows its own default prompt // (e.g. `bash-5.2$ `), which is more transparent than a `[shell]` - // marker -- it names the actual shell and version in use. That already - // distinguishes the toolkit's bash from the fallback system sh below - // (a different default prompt), so overriding it buys nothing and would - // also shadow a prompt the user sets in their own ~/.bashrc, which a - // real bash honours. + // marker and does not shadow a prompt the user sets in their + // ~/.bashrc, which a real bash honours. return """#!/system/bin/sh umask 022 export HOME="$cwd" export PATH=$path export TERM=xterm-256color +$libExport export PROOT_LOADER="$prootLoader" export PROOT_TMP_DIR="$prootTmpDir" mkdir -p "$prootTmpDir" @@ -228,7 +231,11 @@ exec /system/bin/sh -i prootTmp.mkdirs() val out = File(context.filesDir, "device-launch-$sessionId.sh") out.writeText( - launcherScript(context.applicationInfo.nativeLibraryDir, toolkit, cwd, prootTmp) + launcherScript( + context.applicationInfo.nativeLibraryDir, toolkit, cwd, prootTmp, + ExtendedToolkit.binDir(context)?.absolutePath, + ExtendedToolkit.libDir(context)?.absolutePath + ) ) out.setExecutable(true, true) return out diff --git a/app/src/main/java/com/redtermapp/util/ExtendedToolkit.kt b/app/src/main/java/com/redtermapp/util/ExtendedToolkit.kt new file mode 100644 index 0000000..ff5564a --- /dev/null +++ b/app/src/main/java/com/redtermapp/util/ExtendedToolkit.kt @@ -0,0 +1,219 @@ +package com.redtermapp.util + +import android.content.Context +import com.redtermapp.distro.ProotLaunch +import com.redtermapp.distro.TarExtractor +import java.io.File +import java.net.HttpURLConnection +import java.net.URL + +/** + * The on-demand "extended toolkit": extra real tools the shell can gain without + * an app update. They live on disk under `filesDir/extended-toolkit// + * {bin,lib}` and the device-shell launcher exposes that directory on PATH (and + * `lib` on LD_LIBRARY_PATH). Because the launcher only ever looks at what is on + * disk, the tool set is whatever the app and the user have placed there: + * + * - anything [install] downloads from [SOURCES] (our hosted artifacts, or a + * URL a build/host adds), + * - anything a user drops in with [importToolDir] (their own prebuilt tool), + * + * and all of it lands on PATH with no further wiring. + * + * Gated off by default the way the distro logos are: [SOURCES] is empty, so + * nothing is fetched and the shell just runs the lean built-in toolkit. Nothing + * in this object costs anything until a source or an import fills the directory. + */ +object ExtendedToolkit { + + /** + * Candidate tarball URLs (layout `device-extended-toolkit//{bin,lib}`). + * Each is fetched once and unpacked into this device's `` directory. + * Empty by default: no hosted artifact yet, so the shell stays lean. + */ + val SOURCES: List = emptyList() + + /** A fetched tool set bigger than this is not one. */ + private const val MAX_BYTES = 512L * 1024 * 1024 + + private fun dir(context: Context): File = + File(context.filesDir, "extended-toolkit").apply { if (!exists()) mkdirs() } + + /** This device's ABI dir name (aarch64/armv7a/i686/x86_64), or null. */ + private fun arch(context: Context): String? = DeviceToolkit.assetArch(ProotLaunch.deviceAbi()) + + /** + * The on-disk `/bin`, when it holds at least one tool, else null. + * This is the single source of truth the launcher exposes: tools from any + * [SOURCES] entry or a [importToolDir] all appear here. + */ + fun binDir(context: Context): File? { + val a = arch(context) ?: return null + val d = File(dir(context), "$a/bin") + return if (d.isDirectory && d.listFiles()?.isNotEmpty() == true) d else null + } + + /** The on-disk `/lib`, when it has content, else null. */ + fun libDir(context: Context): File? { + val a = arch(context) ?: return null + val d = File(dir(context), "$a/lib") + return if (d.isDirectory && d.listFiles()?.isNotEmpty() == true) d else null + } + + /** + * Fetch + unpack every [SOURCES] entry that has not been fetched yet. + * Idempotent per source (a marker under `.done/`), best-effort, and a + * no-op returning 0 while [SOURCES] is empty. Returns the count fetched + * this call. A tool a user later [importToolDir]s into the same + * `` directory is picked up by [binDir] without any re-download. + */ + fun install(context: Context): Int { + val a = arch(context) ?: return 0 + val live = dir(context) + var fetched = 0 + for (url in SOURCES) { + if (url.isEmpty() || isDone(context, url)) continue + val archive = File(context.cacheDir, "ext-kt-${marker(url)}.tar") + if (!download(context, url, archive)) { + AppLog.w(context, "ext-toolkit", "download of $url failed, keeping what is present") + continue + } + // Extract into a staging dir, never the live toolkit dir: a failed + // extraction must not leave half-written tools where binDir and + // the launcher's PATH can see them shadowing the lean toolkit. + val stage = File(context.cacheDir, "ext-kt-stage-${marker(url)}") + stage.deleteRecursively() + if (!stage.mkdirs()) { + archive.delete() + continue + } + val r = TarExtractor.extract(archive, stage, stripComponents = 1) + archive.delete() + if (!r.ok) { + AppLog.w(context, "ext-toolkit", "extract of $url: ${r.failed.size} failed: ${r.failed.take(3)}") + stage.deleteRecursively() + continue + } + // Complete: merge the staged into the live (existing + // tools from other sources or an import are kept, this source's + // files added or overwritten), then drop the staging copy. + copyInto(File(stage, a), File(live, a)) + stage.deleteRecursively() + markDone(context, url) + fetched++ + } + if (fetched > 0) AppLog.i(context, "ext-toolkit", "fetched $fetched source(s) for $a") + return fetched + } + + /** + * Import a user-supplied prebuilt tool set into this device's `` + * directory, so it joins the shell's PATH with no other wiring. Copies + * every executable under [bin] into `/bin` (and, if given, the + * shared libraries under [lib] into `/lib`, which the launcher puts + * on LD_LIBRARY_PATH). The caller is responsible for the ABI matching this + * device; this only moves files. Returns the number of files copied. + */ + fun importToolDir(context: Context, bin: File, lib: File? = null): Int { + val a = arch(context) ?: return 0 + var n = 0 + n += copyInto(bin, File(dir(context), "$a/bin")) + if (lib != null) n += copyInto(lib, File(dir(context), "$a/lib")) + if (n > 0) AppLog.i(context, "ext-toolkit", "imported $n file(s) into $a from ${bin.absolutePath}") + return n + } + + private fun copyInto(src: File, into: File): Int { + if (!src.isDirectory) return 0 + var n = 0 + // Recurse through the *source* tree, carrying the matching destination + // directory down: reading the destination instead of the source would + // silently skip any subtree whose destination dir does not exist yet. + fun walk(s: File, d: File) { + d.mkdirs() + s.listFiles()?.forEach { f -> + val t = File(d, f.name) + when { + f.isDirectory -> walk(f, t) + f.isFile -> { + f.copyTo(t, overwrite = true) + // Asset/file copies land without the exec bit; re-assert it so a + // dropped-in tool is actually runnable. + t.setExecutable(true, false) + n++ + } + } + } + } + walk(src, into) + return n + } + + private fun isDone(context: Context, url: String): Boolean = + File(dir(context), ".done/${marker(url)}").isFile + + private fun markDone(context: Context, url: String) { + File(dir(context), ".done/${marker(url)}").apply { + parentFile?.mkdirs() + writeText(url) + } + } + + /** A short, stable, filesystem-safe id for a source URL. */ + private fun marker(url: String): String = "src-${Integer.toHexString(url.hashCode())}" + + private fun download(context: Context, url: String, to: File): Boolean { + var conn: HttpURLConnection? = null + try { + conn = URL(url).openConnection() as HttpURLConnection + val c = conn!! + c.connectTimeout = 15_000 + c.readTimeout = 120_000 + c.instanceFollowRedirects = true + c.setRequestProperty("User-Agent", "RedTerm") + c.connect() + // A declared length over the cap is not the artifact; -1 (chunked, + // unknown length) is allowed and enforced by the running byte count. + if (c.responseCode != 200 || c.contentLengthLong > MAX_BYTES) return false + var written = 0L + var complete = false + c.inputStream.use { input -> + to.outputStream().use { out -> + val buf = ByteArray(64 * 1024) + while (true) { + val r = input.read(buf) + if (r < 0) { + complete = written > 0 + break + } + if (written + r > MAX_BYTES) break // over the cap: reject + written += r + out.write(buf, 0, r) + } + } + } + if (!complete) { + to.delete() // partial or over-limit: do not leave a truncated archive + return false + } + return true + } catch (e: Exception) { + to.delete() + AppLog.w(context, "ext-toolkit", "download: ${e.message}") + return false + } finally { + conn?.disconnect() + } + } + + /** + * Pure: the shell's PATH when the extended toolkit is present. The device + * dirs lead (a real command wins), the extended bin comes before the lean + * toolkit (a GNU `tar` beats the busybox applet), the toolkit last. A + * null/blank [extBin] means no extended tools, so the path is unchanged + * from today. + */ + fun toolkitPath(devicePrefix: String, extBin: String?, toolkit: String): String = + if (extBin.isNullOrBlank()) "$devicePrefix:$toolkit" + else "$devicePrefix:$extBin:$toolkit" +} diff --git a/app/src/test/java/com/redtermapp/util/ExtendedToolkitTest.kt b/app/src/test/java/com/redtermapp/util/ExtendedToolkitTest.kt new file mode 100644 index 0000000..73968e0 --- /dev/null +++ b/app/src/test/java/com/redtermapp/util/ExtendedToolkitTest.kt @@ -0,0 +1,78 @@ +package com.redtermapp.util + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class ExtendedToolkitTest { + + @Test + fun `the ext bin slots between the device dirs and the lean toolkit`() { + val devicePrefix = "/system/bin:/bin" + val ext = "/data/data/x/files/extended-toolkit/aarch64/bin" + val toolkit = "/data/data/x/files/device-toolkit/aarch64" + val p = ExtendedToolkit.toolkitPath(devicePrefix, ext, toolkit) + assertEquals("$devicePrefix:$ext:$toolkit", p) + // device dirs lead, the ext bin precedes the lean toolkit so a GNU + // tool beats the busybox applet. + assertTrue(p.indexOf(devicePrefix) == 0) + assertTrue(p.indexOf(ext) < p.indexOf(toolkit)) + } + + @Test + fun `no ext bin leaves the path unchanged`() { + val toolkit = "/data/data/x/files/device-toolkit/aarch64" + assertEquals("/bin:$toolkit", ExtendedToolkit.toolkitPath("/bin", null, toolkit)) + assertEquals("/bin:$toolkit", ExtendedToolkit.toolkitPath("/bin", " ", toolkit)) + } + + @Test + fun `the launcher puts the ext bin on PATH and the ext lib on LD_LIBRARY_PATH`() { + val script = DeviceToolkit.launcherScript( + "/data/app/lib", + File("/data/data/x/files/device-toolkit/aarch64"), + "/sdcard", + File("/data/data/x/files/device-toolkit-tmp"), + extBin = "/data/data/x/files/extended-toolkit/aarch64/bin", + extLib = "/data/data/x/files/extended-toolkit/aarch64/lib" + ) + val pathLine = script.lineSequence().first { it.startsWith("export PATH=") } + assertTrue(pathLine.contains("extended-toolkit/aarch64/bin")) + assertTrue( + "ext bin must precede the lean toolkit", + pathLine.indexOf("extended-toolkit") < pathLine.indexOf("device-toolkit") + ) + assertTrue( + script.lineSequence().any { + it.startsWith("export LD_LIBRARY_PATH=") && it.contains("extended-toolkit/aarch64/lib") + } + ) + } + + @Test + fun `the launcher omits the lib line and the ext path when there are no ext tools`() { + val script = DeviceToolkit.launcherScript( + "/data/app/lib", + File("/data/data/x/files/device-toolkit/aarch64"), + "/sdcard", + File("/data/data/x/files/device-toolkit-tmp") + ) + val pathLine = script.lineSequence().first { it.startsWith("export PATH=") } + assertFalse(pathLine.contains("extended-toolkit")) + assertFalse(script.lineSequence().any { it.startsWith("export LD_LIBRARY_PATH=") }) + } + + @Test + fun `the fallback system shell line is still the last line`() { + val script = DeviceToolkit.launcherScript( + "/data/app/lib", + File("/data/data/x/files/device-toolkit/aarch64"), + "/sdcard", + File("/data/data/x/files/device-toolkit-tmp") + ) + val lines = script.lines() + assertEquals("exec /system/bin/sh -i", lines.last()) + } +}