mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Linux in the local terminal: Alpine with proot, the phone's storage at /sdcard
- proot (Termux's, external/proot) and its loader built with the NDK for each ABI by native-proot/build.sh (talloc fetched and checked by SHA-256, built as one file), run by Gradle before each build and packaged as libproot.so and libproot-loader.so: extracted on install, in the native library directory, the one place Android 10 on lets an app run its own programs - LinuxSystem: Alpine's minimal root file system for the phone's ABI, found in Alpine's release list, downloaded with its SHA-256 checked, unpacked (Tar: ustar, pax and GNU names, links and modes, nothing written outside it, removed without following links), set up (the phone's name servers, a prompt) and run as root with proot: the device's /dev, /proc and /sys, made-up /proc files for those Android hides, hard links as proot's link2symlink, and the phone's shared storage at /sdcard when the app has "all files access" - Settings, Linux: install (it goes on while the user moves about the app), size, open a shell, remove; the storage permission; the terminal's menu offers "New Linux shell (Alpine)", installing first when it isn't there - Hang-up sent again shortly after the first, for a job the shell was forking as it went (found by the tests) - Tests on the host: proot built by the same script, Alpine downloaded: a root shell, the storage both ways, the window's size, hard links, apk installing a package and running it, removal leaving the storage; the tar reader against GNU and pax tars and ones made to escape; the app installing it from Settings and opening its shell. CI installs gawk and mksh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
23 files changed
+1526
-14
No files matched your search
@@ -39,8 +39,8 @@ jobs:
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
|
||||
"ndk;$NDK_VERSION" "cmake;$CMAKE_VERSION" "platforms;android-37.0"
|
||||
|
||||
- name: OpenSSH and PuTTY (for the SSH interop tests)
|
||||
run: sudo apt-get install -y -q openssh-client openssh-server putty-tools && sudo mkdir -p /run/sshd
|
||||
- name: OpenSSH, PuTTY, mksh (the interop tests), gawk (proot's build)
|
||||
run: sudo apt-get install -y -q openssh-client openssh-server putty-tools gawk mksh && sudo mkdir -p /run/sshd
|
||||
- name: Build, unit tests, lint
|
||||
run: ./gradlew assembleDebug assembleDebugAndroidTest testDebugUnitTest lintDebug
|
||||
|
||||
@@ -93,6 +93,9 @@ jobs:
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
|
||||
- name: gawk (proot's build)
|
||||
run: sudo apt-get install -y -q gawk
|
||||
|
||||
- name: KVM
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
|
||||
@@ -2,3 +2,6 @@
|
||||
path = external/d-modem-re
|
||||
url = https://github.com/Neo-Desktop/D-Modem-RE.git
|
||||
branch = claude/android-support
|
||||
[submodule "external/proot"]
|
||||
path = external/proot
|
||||
url = https://github.com/termux/proot.git
|
||||
+32
-2
@@ -30,6 +30,13 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
// proot, built for each ABI (below)
|
||||
jniLibs.directories.add(layout.buildDirectory.dir("proot/jniLibs").get().asFile.path)
|
||||
}
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
@@ -68,8 +75,9 @@ android {
|
||||
pickFirsts += setOf("META-INF/INDEX.LIST")
|
||||
}
|
||||
jniLibs {
|
||||
// 16 KB page alignment, uncompressed in the APK
|
||||
useLegacyPackaging = false
|
||||
// extracted when installed: proot and its loader (libproot*.so) are programs, run from the
|
||||
// native library directory, the one place Android 10 on lets an app run its own programs
|
||||
useLegacyPackaging = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,3 +123,25 @@ tasks.withType<Test>().configureEach {
|
||||
systemProperty("robolectric.dependency.repo.url", it)
|
||||
}
|
||||
}
|
||||
|
||||
// proot and its loader for the local shell's Linux (native-proot/build.sh: Termux's proot, external/proot)
|
||||
val prootAbis = listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86")
|
||||
val buildProot = tasks.register("buildProot") {
|
||||
description = "Builds proot and its loader for each ABI with the NDK"
|
||||
}
|
||||
for (abi in prootAbis) {
|
||||
val t = tasks.register<Exec>("buildProot_$abi") {
|
||||
val out = layout.buildDirectory.dir("proot/jniLibs/$abi")
|
||||
val work = layout.buildDirectory.dir("proot/work/$abi")
|
||||
inputs.dir(rootProject.file("external/proot/src"))
|
||||
inputs.dir(rootProject.file("native-proot"))
|
||||
outputs.dir(out)
|
||||
environment("PROOT_WORK", work.get().asFile.path)
|
||||
commandLine(
|
||||
rootProject.file("native-proot/build.sh").path, abi, out.get().asFile.path,
|
||||
androidComponents.sdkComponents.ndkDirectory.get().asFile.path,
|
||||
)
|
||||
}
|
||||
buildProot.configure { dependsOn(t) }
|
||||
}
|
||||
tasks.named("preBuild") { dependsOn(buildProot) }
|
||||
@@ -13,11 +13,23 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<!-- the terminal's bell -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<!-- the phone's shared storage in the Linux system (at /sdcard), when the user allows it:
|
||||
"all files access" from Android 11, these before -->
|
||||
<uses-permission
|
||||
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="29" />
|
||||
|
||||
<application
|
||||
android:name=".DModemApp"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
tools:ignore="DataExtractionRules"
|
||||
android:icon="@drawable/ic_modem"
|
||||
android:label="@string/app_name"
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.local
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The app's Linux (Alpine, run with proot): where it lives on this phone,
|
||||
* its install and removal (which go on while the user moves about the
|
||||
* app), and the shared storage it is given.
|
||||
*/
|
||||
@SuppressLint("StaticFieldLeak") // the application's context only
|
||||
object Linux {
|
||||
|
||||
sealed class Work {
|
||||
object Idle : Work()
|
||||
data class Busy(val what: String, val fraction: Float?) : Work()
|
||||
data class Failed(val why: String) : Work()
|
||||
}
|
||||
|
||||
private val _work = MutableStateFlow<Work>(Work.Idle)
|
||||
val work: StateFlow<Work> = _work.asStateFlow()
|
||||
|
||||
/** bumped when it's installed or removed (for the screens showing it) */
|
||||
private val _changes = MutableStateFlow(0)
|
||||
val changes: StateFlow<Int> = _changes.asStateFlow()
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
/** the system on this phone (the tests' own in theirs) */
|
||||
var factory: (Context) -> LinuxSystem = { ctx -> phoneSystem(ctx) }
|
||||
|
||||
fun system(context: Context): LinuxSystem = factory(context.applicationContext)
|
||||
|
||||
/** this phone's ABI's Alpine, or null where there is none */
|
||||
fun arch(): String? = Build.SUPPORTED_ABIS.firstNotNullOfOrNull { LinuxSystem.archFor(it) }
|
||||
|
||||
private fun phoneSystem(app: Context) = LinuxSystem(
|
||||
dir = File(app.filesDir, "linux/alpine"),
|
||||
programDir = File(app.applicationInfo.nativeLibraryDir ?: app.filesDir.path),
|
||||
tmpDir = File(app.cacheDir, "proot"),
|
||||
arch = arch() ?: "aarch64",
|
||||
storage = { if (storageGranted(app)) Environment.getExternalStorageDirectory() else null },
|
||||
nameServers = { nameServers(app) },
|
||||
)
|
||||
|
||||
/** installed (in the background); [onDone] on the main thread's caller's terms: called from IO */
|
||||
fun install(context: Context, onDone: () -> Unit = {}) {
|
||||
if (_work.value is Work.Busy) return
|
||||
val sys = system(context)
|
||||
_work.value = Work.Busy("Starting…", null)
|
||||
scope.launch {
|
||||
try {
|
||||
sys.install { what, f -> _work.value = Work.Busy(what, f) }
|
||||
_work.value = Work.Idle
|
||||
_changes.value++
|
||||
onDone()
|
||||
} catch (e: Exception) {
|
||||
_work.value = Work.Failed(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(context: Context) {
|
||||
if (_work.value is Work.Busy) return
|
||||
val sys = system(context)
|
||||
_work.value = Work.Busy("Removing…", null)
|
||||
scope.launch {
|
||||
try {
|
||||
sys.remove()
|
||||
_work.value = Work.Idle
|
||||
} catch (e: Exception) {
|
||||
_work.value = Work.Failed(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
_changes.value++
|
||||
}
|
||||
}
|
||||
|
||||
fun clearFailure() {
|
||||
if (_work.value is Work.Failed) _work.value = Work.Idle
|
||||
}
|
||||
|
||||
/** the disk it takes */
|
||||
fun size(context: Context): Long {
|
||||
var total = 0L
|
||||
system(context).dir.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.forEach {
|
||||
if (it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath())) total += it.length()
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// shared storage --------------------------------------------------
|
||||
|
||||
/** whether the app may read and write the phone's shared storage by its paths (all of it) */
|
||||
fun storageGranted(context: Context): Boolean = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
Environment.isExternalStorageManager()
|
||||
} else {
|
||||
context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
}.getOrDefault(false) // (no storage to ask about: not granted)
|
||||
|
||||
/** Android 11 on: the system's page to allow "all files access"; null before (a runtime permission there) */
|
||||
fun storageSettingsIntent(context: Context): Intent? = if (Build.VERSION.SDK_INT >= 30) {
|
||||
Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:${context.packageName}"))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
/** the phone's name servers, or public ones */
|
||||
private fun nameServers(context: Context): List<String> = try {
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java)
|
||||
val lp = cm?.getLinkProperties(cm.activeNetwork)
|
||||
lp?.dnsServers?.mapNotNull { it.hostAddress?.substringBefore('%') }?.takeIf { it.isNotEmpty() } ?: LinuxSystem.DEFAULT_DNS
|
||||
} catch (_: Exception) {
|
||||
LinuxSystem.DEFAULT_DNS
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.local
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.GZIPInputStream
|
||||
|
||||
/**
|
||||
* A Linux system to run in the local terminal: Alpine's minimal root file
|
||||
* system (its package manager, apk, to add the rest), run with proot. The
|
||||
* app can't run programs it has written itself (Android 10 on); proot is
|
||||
* the app's own (libproot.so, in its native library directory), and runs
|
||||
* the system's programs through its loader (libproot-loader.so), which
|
||||
* maps them rather than executing them.
|
||||
*
|
||||
* Inside: root (proot's fake one), the device's /dev, /proc and /sys, and
|
||||
* the phone's shared storage at /sdcard when the app may read it.
|
||||
*/
|
||||
class LinuxSystem(
|
||||
/** where it lives: rootfs/ in it */
|
||||
val dir: File,
|
||||
/** the app's native library directory: libproot.so and libproot-loader.so (a host build's, in the tests) */
|
||||
private val programDir: File,
|
||||
/** proot's own temporary files */
|
||||
private val tmpDir: File,
|
||||
/** Alpine's name for the machine: aarch64, armv7, x86_64, x86 */
|
||||
val arch: String,
|
||||
/** the phone's shared storage, when the app may use it (bound at /sdcard) */
|
||||
private val storage: () -> File? = { null },
|
||||
/** the name servers for /etc/resolv.conf (the phone's, or public ones) */
|
||||
private val nameServers: () -> List<String> = { DEFAULT_DNS },
|
||||
/** more for the system's environment (the tests' proxy) */
|
||||
private val extraEnv: Map<String, String> = emptyMap(),
|
||||
private val mirror: String = MIRROR,
|
||||
private val branch: String = BRANCH,
|
||||
/** whether a /proc file can be read here (Android hides some): ones that can't are given made-up ones */
|
||||
private val readable: (File) -> Boolean = { it.canRead() && runCatching { it.readBytes(); true }.getOrDefault(false) },
|
||||
) {
|
||||
val rootfs: File get() = File(dir, "rootfs")
|
||||
private val marker: File get() = File(dir, ".installed")
|
||||
|
||||
val installed: Boolean get() = marker.exists() && File(rootfs, "bin").exists()
|
||||
|
||||
/** the version installed ("3.22.6"), or null */
|
||||
val version: String? get() = runCatching { File(rootfs, "etc/alpine-release").readText().trim() }.getOrNull()
|
||||
|
||||
data class Release(val file: String, val version: String, val sha256: String, val size: Long) {
|
||||
val name get() = "Alpine Linux $version"
|
||||
}
|
||||
|
||||
/** the latest minimal root file system for [arch], from Alpine's own list */
|
||||
fun latestRelease(): Release {
|
||||
val yaml = fetchText("$mirror/$branch/releases/$arch/latest-releases.yaml")
|
||||
// (a list of releases, one per flavour: the minirootfs one's fields)
|
||||
val blocks = yaml.split(Regex("\n-\\s*\n|\n- ")).filter { it.contains("flavor: alpine-minirootfs") }
|
||||
val b = blocks.firstOrNull() ?: throw IOException("no minimal root file system for $arch")
|
||||
fun field(k: String) = Regex("(?m)^\\s*$k:\\s*(\\S+)").find(b)?.groupValues?.get(1)
|
||||
return Release(
|
||||
field("file") ?: throw IOException("no file in Alpine's list"),
|
||||
field("version") ?: "?",
|
||||
field("sha256") ?: throw IOException("no checksum in Alpine's list"),
|
||||
field("size")?.toLongOrNull() ?: -1,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Installed: downloaded, its checksum checked, unpacked and set up.
|
||||
* [progress]: what it's doing, and how far (0..1) when it can tell.
|
||||
*/
|
||||
fun install(progress: (String, Float?) -> Unit = { _, _ -> }) {
|
||||
progress("Finding the latest Alpine Linux…", null)
|
||||
val r = latestRelease()
|
||||
dir.mkdirs()
|
||||
val tgz = File(dir, r.file)
|
||||
progress("Downloading ${r.name}…", 0f)
|
||||
download("$mirror/$branch/releases/$arch/${r.file}", tgz, r.size) { progress("Downloading ${r.name}…", it) }
|
||||
val sum = sha256(tgz)
|
||||
if (!sum.equals(r.sha256, ignoreCase = true)) {
|
||||
tgz.delete()
|
||||
throw IOException("the download's checksum doesn't match Alpine's")
|
||||
}
|
||||
progress("Unpacking…", null)
|
||||
if (rootfs.exists()) Tar.removeTree(rootfs)
|
||||
GZIPInputStream(tgz.inputStream().buffered()).use { Tar.extract(it, rootfs) }
|
||||
tgz.delete()
|
||||
configure()
|
||||
marker.writeText(r.version + "\n")
|
||||
progress("Installed ${r.name}", 1f)
|
||||
}
|
||||
|
||||
/** its files set for this phone: name servers, host name, the prompt, mount points (again at each start) */
|
||||
fun configure() {
|
||||
val etc = File(rootfs, "etc")
|
||||
etc.mkdirs()
|
||||
File(etc, "resolv.conf").apply { delete() }.writeText(nameServers().joinToString("") { "nameserver $it\n" })
|
||||
File(etc, "hosts").apply { if (!exists() || !readText().contains("localhost")) writeText("127.0.0.1 localhost\n::1 localhost\n") }
|
||||
File(etc, "hostname").takeIf { !it.exists() }?.writeText("dmodem\n")
|
||||
File(etc, "profile.d").mkdirs()
|
||||
File(etc, "profile.d/dmodem.sh").writeText(PROFILE)
|
||||
for (d in listOf("root", "tmp", "sdcard", "dev", "proc", "sys")) File(rootfs, d).mkdirs()
|
||||
File(rootfs, "tmp").setWritable(true, false)
|
||||
}
|
||||
|
||||
/** the system removed, all of it (links removed, never followed: /sdcard's among them) */
|
||||
fun remove() = Tar.removeTree(dir)
|
||||
|
||||
/** made-up /proc files for those Android hides from apps (programs like top read them) */
|
||||
private fun fakeProc(): List<Pair<File, String>> {
|
||||
val fake = File(dir, "proc")
|
||||
val out = ArrayList<Pair<File, String>>()
|
||||
for ((name, content) in FAKE_PROC) {
|
||||
if (readable(File("/proc/$name"))) continue
|
||||
val f = File(fake, name)
|
||||
f.parentFile?.mkdirs()
|
||||
f.writeText(content)
|
||||
out.add(f to "/proc/$name")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** proot's command: the system's login shell, as root, in /root */
|
||||
fun command(): List<String> {
|
||||
val c = arrayListOf(
|
||||
File(programDir, "libproot.so").path,
|
||||
"--kill-on-exit",
|
||||
"--link2symlink",
|
||||
"-0",
|
||||
"-r", rootfs.path,
|
||||
"-b", "/dev",
|
||||
"-b", "/proc",
|
||||
"-b", "/sys",
|
||||
"-b", "/proc/self/fd:/dev/fd",
|
||||
)
|
||||
for ((f, at) in fakeProc()) c.addAll(listOf("-b", "${f.path}:$at"))
|
||||
storage()?.let { c.addAll(listOf("-b", "${it.path}:/sdcard")) }
|
||||
c.addAll(listOf("-w", "/root", "/usr/bin/env", "-i"))
|
||||
val env = linkedMapOf(
|
||||
"HOME" to "/root",
|
||||
"USER" to "root",
|
||||
"LOGNAME" to "root",
|
||||
"SHELL" to "/bin/sh",
|
||||
"LANG" to "C.UTF-8",
|
||||
"TERM" to "xterm-256color",
|
||||
"COLORTERM" to "truecolor",
|
||||
"PATH" to "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"TMPDIR" to "/tmp",
|
||||
)
|
||||
env.putAll(extraEnv)
|
||||
for ((k, v) in env) c.add("$k=$v")
|
||||
c.addAll(listOf("/bin/sh", "-l"))
|
||||
return c
|
||||
}
|
||||
|
||||
/** proot's own environment: where its loader is, its temporary files */
|
||||
fun environment(): Map<String, String> {
|
||||
tmpDir.mkdirs()
|
||||
return linkedMapOf(
|
||||
"PROOT_LOADER" to File(programDir, "libproot-loader.so").path,
|
||||
"PROOT_TMP_DIR" to tmpDir.path,
|
||||
"PATH" to "/system/bin:/system/xbin:/usr/bin:/bin",
|
||||
"HOME" to dir.path,
|
||||
)
|
||||
}
|
||||
|
||||
/** a link to a new shell in the system (configured again first: the name servers may have changed) */
|
||||
fun link(cols: Int = 80, rows: Int = 24): LocalLink {
|
||||
if (!installed) throw IOException("Alpine Linux isn't installed")
|
||||
configure()
|
||||
return LocalLink(command(), environment(), dir.path, cols, rows)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private fun open(url: String): HttpURLConnection {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
c.setRequestProperty("User-Agent", "D-Modem for Android")
|
||||
if (c.responseCode != 200) throw IOException("$url: HTTP ${c.responseCode}")
|
||||
return c
|
||||
}
|
||||
|
||||
private fun fetchText(url: String): String = open(url).let { c -> c.inputStream.use { it.readBytes().decodeToString() } }
|
||||
|
||||
private fun download(url: String, to: File, size: Long, progress: (Float) -> Unit) {
|
||||
val c = open(url)
|
||||
val total = if (size > 0) size else c.contentLengthLong
|
||||
val part = File(to.path + ".part")
|
||||
c.inputStream.use { i ->
|
||||
part.outputStream().use { o ->
|
||||
val buf = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
var shown = -1
|
||||
while (true) {
|
||||
val n = i.read(buf)
|
||||
if (n < 0) break
|
||||
o.write(buf, 0, n)
|
||||
done += n
|
||||
if (total > 0) {
|
||||
val pct = (done * 100 / total).toInt()
|
||||
if (pct != shown) { shown = pct; progress(done.toFloat() / total) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!part.renameTo(to)) throw IOException("can't keep the download")
|
||||
}
|
||||
|
||||
private fun sha256(f: File): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
f.inputStream().use { i ->
|
||||
val buf = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = i.read(buf)
|
||||
if (n < 0) break
|
||||
md.update(buf, 0, n)
|
||||
}
|
||||
}
|
||||
return md.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MIRROR = "https://dl-cdn.alpinelinux.org/alpine"
|
||||
const val BRANCH = "v3.22"
|
||||
val DEFAULT_DNS = listOf("1.1.1.1", "8.8.8.8")
|
||||
|
||||
/** Alpine's machine for an Android ABI */
|
||||
fun archFor(abi: String): String? = when (abi) {
|
||||
"arm64-v8a" -> "aarch64"
|
||||
"armeabi-v7a" -> "armv7"
|
||||
"x86_64" -> "x86_64"
|
||||
"x86" -> "x86"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** a coloured prompt, a few aliases; /sdcard named if it's there */
|
||||
val PROFILE = """
|
||||
|# D-Modem: this phone's Alpine Linux (rewritten at each start: put your own in /etc/profile.d/local.sh)
|
||||
|PS1='\[\e[1;31m\]\u@alpine\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\${'$'} '
|
||||
|alias ls='ls --color=auto'
|
||||
|alias ll='ls -l'
|
||||
|alias la='ls -la'
|
||||
|""".trimMargin()
|
||||
|
||||
/** /proc files Android keeps from apps, as proot-distro makes them up */
|
||||
val FAKE_PROC = linkedMapOf(
|
||||
"loadavg" to "0.12 0.07 0.02 2/165 765\n",
|
||||
"stat" to "cpu 1957 0 2877 93280 262 342 254 87 0 0\ncpu0 31 0 226 12027 82 10 4 9 0 0\n" +
|
||||
"intr 63361 0 0 0 0 0 0 0 0 0 0 0 0\nctxt 38014093\nbtime 1694292441\nprocesses 26442\n" +
|
||||
"procs_running 1\nprocs_blocked 0\nsoftirq 75663 0 5903 6 25375 10774 0 243 11685 0 21677\n",
|
||||
"uptime" to "124.08 932.80\n",
|
||||
"version" to "Linux version 6.1.0 (proot@dmodem) #1 SMP PREEMPT\n",
|
||||
"vmstat" to "nr_free_pages 1743136\nnr_zone_inactive_anon 179281\nnr_zone_active_anon 7183\n",
|
||||
"sys/kernel/cap_last_cap" to "40\n",
|
||||
"sys/fs/inotify/max_user_watches" to "4096\n",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,12 @@ class LocalLink(
|
||||
if (p > 0) {
|
||||
Pty.signalSession(p, Pty.SIGHUP)
|
||||
Thread({
|
||||
Thread.sleep(2000)
|
||||
// (again, for a job the shell was forking as the first went: not there to be found then)
|
||||
for (wait in listOf(100L, 400L)) {
|
||||
Thread.sleep(wait)
|
||||
Pty.signalSession(p, Pty.SIGHUP)
|
||||
}
|
||||
Thread.sleep(1500)
|
||||
if (exitStatus == null) Pty.signal(p, Pty.SIGKILL)
|
||||
}, "pty-kill-$p").apply { isDaemon = true }.start()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.local
|
||||
|
||||
import java.io.EOFException
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
/**
|
||||
* A Linux system's tar unpacked as it is: directories, files with their
|
||||
* modes, symbolic links as they are (their targets the system's own,
|
||||
* absolute ones too), hard links (as links where the file system allows,
|
||||
* else copies); ustar, pax and GNU long names. Nothing written outside the
|
||||
* destination: no "..", and no path through a link already unpacked.
|
||||
* Devices and fifos are left out (proot gives the system the device's
|
||||
* own /dev).
|
||||
*/
|
||||
object Tar {
|
||||
|
||||
class Stats {
|
||||
var files = 0
|
||||
var dirs = 0
|
||||
var links = 0
|
||||
var bytes = 0L
|
||||
}
|
||||
|
||||
fun extract(input: InputStream, dest: File, onEntry: (String) -> Unit = {}): Stats {
|
||||
val root = dest.toPath().toAbsolutePath().normalize()
|
||||
Files.createDirectories(root)
|
||||
val stats = Stats()
|
||||
val dirModes = ArrayList<Pair<Path, Int>>()
|
||||
val header = ByteArray(512)
|
||||
var longName: String? = null
|
||||
var longLink: String? = null
|
||||
var pax: Map<String, String> = emptyMap()
|
||||
while (true) {
|
||||
if (!readFully(input, header)) break
|
||||
if (header.all { it == 0.toByte() }) break
|
||||
if (!checksumOk(header)) throw IOException("not a tar (bad header checksum)")
|
||||
val type = header[156].toInt().toChar()
|
||||
val size = number(header, 124, 12)
|
||||
when (type) {
|
||||
'L' -> { longName = cString(readData(input, size)); continue }
|
||||
'K' -> { longLink = cString(readData(input, size)); continue }
|
||||
'x' -> { pax = paxRecords(readData(input, size)); continue }
|
||||
'g' -> { readData(input, size); continue }
|
||||
}
|
||||
val ustarName = run {
|
||||
val name = cString(header, 0, 100)
|
||||
val prefix = if (String(header, 257, 5, Charsets.US_ASCII) == "ustar") cString(header, 345, 155) else ""
|
||||
if (prefix.isNotEmpty()) "$prefix/$name" else name
|
||||
}
|
||||
val name = pax["path"] ?: longName ?: ustarName
|
||||
val link = pax["linkpath"] ?: longLink ?: cString(header, 157, 100)
|
||||
val entrySize = pax["size"]?.toLongOrNull() ?: size
|
||||
val mode = number(header, 100, 8).toInt() and 0xfff
|
||||
longName = null; longLink = null; pax = emptyMap()
|
||||
|
||||
val target = resolve(root, name)
|
||||
if (target == null) {
|
||||
skip(input, entrySize)
|
||||
continue
|
||||
}
|
||||
onEntry(name)
|
||||
when (type) {
|
||||
'5' -> {
|
||||
Files.createDirectories(target)
|
||||
dirModes.add(target to mode)
|
||||
stats.dirs++
|
||||
}
|
||||
'2' -> {
|
||||
Files.createDirectories(target.parent)
|
||||
Files.deleteIfExists(target)
|
||||
Files.createSymbolicLink(target, Paths.get(link))
|
||||
stats.links++
|
||||
}
|
||||
'1' -> {
|
||||
val from = resolve(root, link) ?: throw IOException("hard link out of the tree: $name -> $link")
|
||||
Files.createDirectories(target.parent)
|
||||
Files.deleteIfExists(target)
|
||||
try {
|
||||
Files.createLink(target, from)
|
||||
} catch (_: Exception) {
|
||||
Files.copy(from, target, StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS)
|
||||
}
|
||||
stats.links++
|
||||
}
|
||||
'0', '\u0000', '7' -> {
|
||||
Files.createDirectories(target.parent)
|
||||
Files.deleteIfExists(target)
|
||||
Files.newOutputStream(target).use { out ->
|
||||
copy(input, out, entrySize)
|
||||
}
|
||||
skipPadding(input, entrySize)
|
||||
setMode(target, mode)
|
||||
stats.files++
|
||||
stats.bytes += entrySize
|
||||
continue
|
||||
}
|
||||
else -> {} // devices, fifos: not here
|
||||
}
|
||||
skip(input, entrySize)
|
||||
}
|
||||
// the directories' own modes last: a read-only one would have stopped what went into it
|
||||
for ((d, m) in dirModes.asReversed()) setMode(d, m or 0b111_000_000)
|
||||
return stats
|
||||
}
|
||||
|
||||
/** where [name] goes under [root]; null for one that would leave it (or go through a link) */
|
||||
private fun resolve(root: Path, name: String): Path? {
|
||||
val clean = name.trimStart('/').removePrefix("./").trimEnd('/')
|
||||
if (clean.isEmpty() || clean == ".") return null
|
||||
val p = root.resolve(clean).normalize()
|
||||
if (!p.startsWith(root) || p == root) return null
|
||||
// no component on the way (the entry's parents) a link: writing through it could leave the tree
|
||||
var cur = root
|
||||
for (part in root.relativize(p.parent ?: root)) {
|
||||
cur = cur.resolve(part)
|
||||
if (Files.isSymbolicLink(cur)) return null
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
private fun setMode(p: Path, mode: Int) {
|
||||
val perms = HashSet<PosixFilePermission>()
|
||||
val all = PosixFilePermission.values() // OWNER_READ .. OTHERS_EXECUTE: bits 8..0
|
||||
for (i in 0 until 9) if (mode and (1 shl (8 - i)) != 0) perms.add(all[i])
|
||||
// (the app owns it all: owner's read and write kept, or it couldn't be updated or removed)
|
||||
perms.add(PosixFilePermission.OWNER_READ)
|
||||
perms.add(PosixFilePermission.OWNER_WRITE)
|
||||
try {
|
||||
Files.setPosixFilePermissions(p, perms)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [dir] removed, every file in it; links removed as links, never
|
||||
* followed (one may lead to the phone's shared storage)
|
||||
*/
|
||||
fun removeTree(dir: File) {
|
||||
val root = dir.toPath()
|
||||
if (!Files.exists(root, LinkOption.NOFOLLOW_LINKS)) return
|
||||
if (Files.isSymbolicLink(root)) {
|
||||
Files.delete(root)
|
||||
return
|
||||
}
|
||||
Files.walkFileTree(
|
||||
root,
|
||||
object : SimpleFileVisitor<Path>() {
|
||||
override fun preVisitDirectory(d: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
// (a read-only directory's entries can't be removed until it's writable)
|
||||
runCatching { d.toFile().setWritable(true, true); d.toFile().setExecutable(true, true); d.toFile().setReadable(true, true) }
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFile(f: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
Files.delete(f)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFileFailed(f: Path, exc: IOException): FileVisitResult {
|
||||
Files.deleteIfExists(f)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun postVisitDirectory(d: Path, exc: IOException?): FileVisitResult {
|
||||
Files.delete(d)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private fun readFully(i: InputStream, b: ByteArray): Boolean {
|
||||
var n = 0
|
||||
while (n < b.size) {
|
||||
val r = i.read(b, n, b.size - n)
|
||||
if (r < 0) {
|
||||
if (n == 0) return false
|
||||
throw EOFException("tar cut short")
|
||||
}
|
||||
n += r
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun readData(i: InputStream, size: Long): ByteArray {
|
||||
if (size > 1 shl 20) throw IOException("tar extended header too big")
|
||||
val b = ByteArray(size.toInt())
|
||||
if (size > 0 && !readFully(i, b)) throw EOFException("tar cut short")
|
||||
skipPadding(i, size)
|
||||
return b
|
||||
}
|
||||
|
||||
private fun copy(i: InputStream, o: java.io.OutputStream, size: Long) {
|
||||
val buf = ByteArray(64 * 1024)
|
||||
var left = size
|
||||
while (left > 0) {
|
||||
val n = i.read(buf, 0, minOf(buf.size.toLong(), left).toInt())
|
||||
if (n < 0) throw EOFException("tar cut short")
|
||||
o.write(buf, 0, n)
|
||||
left -= n
|
||||
}
|
||||
}
|
||||
|
||||
private fun skip(i: InputStream, size: Long) {
|
||||
// (OutputStream.nullOutputStream is Android 13's)
|
||||
copy(i, object : java.io.OutputStream() { override fun write(b: Int) {}; override fun write(b: ByteArray, off: Int, len: Int) {} }, size)
|
||||
skipPadding(i, size)
|
||||
}
|
||||
|
||||
private fun skipPadding(i: InputStream, size: Long) {
|
||||
val pad = ((512 - size % 512) % 512).toInt()
|
||||
if (pad > 0) readFully(i, ByteArray(pad))
|
||||
}
|
||||
|
||||
private fun cString(b: ByteArray, off: Int = 0, len: Int = b.size): String {
|
||||
var end = off
|
||||
while (end < off + len && b[end] != 0.toByte()) end++
|
||||
return String(b, off, end - off, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** an octal field, or GNU's base-256 for big ones */
|
||||
private fun number(b: ByteArray, off: Int, len: Int): Long {
|
||||
if (b[off].toInt() and 0x80 != 0) {
|
||||
var v = 0L
|
||||
for (i in 1 until len) v = (v shl 8) or (b[off + i].toLong() and 0xff)
|
||||
return v
|
||||
}
|
||||
val s = cString(b, off, len).trim()
|
||||
return if (s.isEmpty()) 0 else s.toLong(8)
|
||||
}
|
||||
|
||||
private fun checksumOk(h: ByteArray): Boolean {
|
||||
val want = number(h, 148, 8)
|
||||
var sum = 0L
|
||||
for (i in h.indices) sum += if (i in 148 until 156) 32 else (h[i].toInt() and 0xff)
|
||||
return sum == want
|
||||
}
|
||||
|
||||
/** pax's "len key=value\n" records */
|
||||
private fun paxRecords(b: ByteArray): Map<String, String> {
|
||||
val out = HashMap<String, String>()
|
||||
var i = 0
|
||||
while (i < b.size) {
|
||||
val sp = (i until b.size).firstOrNull { b[it] == ' '.code.toByte() } ?: break
|
||||
val len = String(b, i, sp - i, Charsets.US_ASCII).toIntOrNull() ?: break
|
||||
if (len <= 0 || i + len > b.size) break
|
||||
val rec = String(b, sp + 1, i + len - sp - 2, Charsets.UTF_8)
|
||||
val eq = rec.indexOf('=')
|
||||
if (eq > 0) out[rec.substring(0, eq)] = rec.substring(eq + 1)
|
||||
i += len
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import com.neodesktop.dmodem.local.Linux
|
||||
import com.neodesktop.dmodem.local.LocalShell
|
||||
import com.neodesktop.dmodem.ssh.AgentKeys
|
||||
import com.neodesktop.dmodem.ssh.ForwardSpec
|
||||
@@ -176,6 +177,30 @@ object Terminal {
|
||||
return null
|
||||
}
|
||||
|
||||
/** a shell in the Linux system opened in a new session: null, else why it can't be */
|
||||
suspend fun openLinux(context: Context): String? {
|
||||
val (cols, rows) = synchronized(session.emulator) { session.emulator.cols to session.emulator.rows }
|
||||
val link = try {
|
||||
withContext(Dispatchers.IO) { Linux.system(context).link(cols, rows) }
|
||||
} catch (e: java.io.IOException) {
|
||||
return e.message
|
||||
}
|
||||
if (!withContext(Dispatchers.IO) { link.start() }) {
|
||||
return (link.state.value as? TerminalLink.State.Closed)?.reason ?: "Linux didn't start"
|
||||
}
|
||||
val n = _sessions.value.count { it.kind == TerminalSession.Kind.LINUX }
|
||||
val s = TerminalSession(link, label = if (n == 0) "Alpine" else "Alpine ${n + 1}", kind = TerminalSession.Kind.LINUX) {
|
||||
app.getExternalFilesDir("captures")
|
||||
}
|
||||
s.charset = TermCharset.UTF8
|
||||
s.keys.backspace = BackspaceMode.DEL
|
||||
s.keys.enter = com.neodesktop.dmodem.terminal.EnterMode.CR
|
||||
_sessions.value = _sessions.value + s
|
||||
_active.value = s
|
||||
ConnectionService.update(app)
|
||||
return null
|
||||
}
|
||||
|
||||
/** a session closed and gone (the modem's stays) */
|
||||
fun close(s: TerminalSession) {
|
||||
if (s === session) return
|
||||
@@ -192,6 +217,10 @@ object Terminal {
|
||||
close(s)
|
||||
return openLocal(context)
|
||||
}
|
||||
if (s.kind == TerminalSession.Kind.LINUX) {
|
||||
close(s)
|
||||
return openLinux(context)
|
||||
}
|
||||
val e = s.entry ?: return "nothing to reconnect to"
|
||||
close(s)
|
||||
return open(context, directory.items.value.firstOrNull { it.id == e.id } ?: e)
|
||||
|
||||
@@ -30,7 +30,10 @@ class TerminalSession(
|
||||
/** where captures go */
|
||||
private val captureDir: () -> File?,
|
||||
) {
|
||||
enum class Kind { MODEM, SSH, TELNET, LOCAL }
|
||||
enum class Kind { MODEM, SSH, TELNET, LOCAL, LINUX }
|
||||
|
||||
/** a program on this phone (Android's shell, or the Linux system's): not a connection */
|
||||
val isLocal: Boolean get() = kind == Kind.LOCAL || kind == Kind.LINUX
|
||||
|
||||
val id: String = java.util.UUID.randomUUID().toString()
|
||||
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.neodesktop.dmodem.local.Linux
|
||||
import com.neodesktop.dmodem.terminal.Terminal
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** The Linux system: installed or not, its shell, the phone's storage in it, its removal. */
|
||||
@Composable
|
||||
fun LinuxSection(onOpened: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val work by Linux.work.collectAsStateWithLifecycle()
|
||||
val changes by Linux.changes.collectAsStateWithLifecycle()
|
||||
val system = remember(changes) { Linux.system(context) }
|
||||
val installed = remember(changes, work) { system.installed }
|
||||
var size by remember { mutableStateOf<Long?>(null) }
|
||||
LaunchedEffect(changes, installed) { size = if (installed) withContext(Dispatchers.IO) { Linux.size(context) } else null }
|
||||
// (the permission comes back from the system's own page: looked at again on return)
|
||||
var resumed by remember { mutableIntStateOf(0) }
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { resumed++ }
|
||||
val storage = remember(resumed) { Linux.storageGranted(context) }
|
||||
var removing by remember { mutableStateOf(false) }
|
||||
val askStorage = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { resumed++ }
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Linux", style = MaterialTheme.typography.titleMedium)
|
||||
if (Linux.arch() == null) {
|
||||
Text("There is no Alpine Linux for this phone's processor.", style = MaterialTheme.typography.bodySmall)
|
||||
return@Column
|
||||
}
|
||||
Text(
|
||||
if (installed) "Alpine Linux ${system.version ?: ""} · ${size?.let { formatSize(it) } ?: "…"}"
|
||||
else "Alpine Linux in the terminal, run with proot: a root shell, and apk for its thousands of packages (about 3 MB to download).",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
when (val w = work) {
|
||||
is Linux.Work.Busy -> {
|
||||
Text(w.what, style = MaterialTheme.typography.bodyMedium)
|
||||
if (w.fraction != null) LinearProgressIndicator(progress = { w.fraction }, modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
is Linux.Work.Failed -> Text("Failed: ${w.why}", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Linux.Work.Idle -> {}
|
||||
}
|
||||
val busy = work is Linux.Work.Busy
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (installed) {
|
||||
Button(enabled = !busy, onClick = {
|
||||
scope.launch {
|
||||
val err = Terminal.openLinux(context)
|
||||
if (err != null) Toast.makeText(context, err, Toast.LENGTH_LONG).show() else onOpened()
|
||||
}
|
||||
}) { Text("Open a shell") }
|
||||
OutlinedButton(enabled = !busy, onClick = { removing = true }) { Text("Remove") }
|
||||
} else {
|
||||
Button(enabled = !busy, onClick = { Linux.clearFailure(); Linux.install(context) }) { Text("Install Alpine Linux") }
|
||||
}
|
||||
}
|
||||
SwitchRow(
|
||||
"The phone's storage at /sdcard",
|
||||
if (storage) "Allowed: Linux sees the phone's files (Download, DCIM, …)" else "Needs \"All files access\" for the app",
|
||||
storage,
|
||||
) { want ->
|
||||
if (want && !storage) {
|
||||
val i = Linux.storageSettingsIntent(context)
|
||||
if (i != null) {
|
||||
runCatching { context.startActivity(i) }
|
||||
} else {
|
||||
askStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
}
|
||||
} else if (!want && storage) {
|
||||
// (only the system takes it back)
|
||||
Linux.storageSettingsIntent(context)?.let { runCatching { context.startActivity(it) } }
|
||||
}
|
||||
}
|
||||
if (installed) {
|
||||
Text(
|
||||
"In it: /root is home, /sdcard the phone's storage. \"apk add python3\" and the like add programs.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Default,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (removing) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { removing = false },
|
||||
title = { Text("Remove Alpine Linux?") },
|
||||
text = { Text("All of it goes: what was installed with apk, and the files in /root. The phone's own storage isn't touched.") },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
removing = false
|
||||
Terminal.sessions.value.filter { it.kind == com.neodesktop.dmodem.terminal.TerminalSession.Kind.LINUX }.forEach { Terminal.close(it) }
|
||||
Linux.remove(context)
|
||||
}) { Text("Remove", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** asked for a Linux shell before Linux is installed: installed here, then opened */
|
||||
@Composable
|
||||
fun LinuxInstallDialog(onInstalled: () -> Unit, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val work by Linux.work.collectAsStateWithLifecycle()
|
||||
val changes by Linux.changes.collectAsStateWithLifecycle()
|
||||
var started by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(changes) {
|
||||
if (started && Linux.system(context).installed) onInstalled()
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Install Alpine Linux?") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("A small Linux (about 3 MB to download) to run in the terminal, with apk to add programs: python3, git, vim, gcc and thousands more.")
|
||||
when (val w = work) {
|
||||
is Linux.Work.Busy -> {
|
||||
Text(w.what, style = MaterialTheme.typography.bodySmall)
|
||||
if (w.fraction != null) LinearProgressIndicator(progress = { w.fraction }, modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
is Linux.Work.Failed -> Text("Failed: ${w.why}", color = MaterialTheme.colorScheme.error)
|
||||
Linux.Work.Idle -> {}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = work !is Linux.Work.Busy, onClick = {
|
||||
started = true
|
||||
Linux.clearFailure()
|
||||
Linux.install(context)
|
||||
}) { Text(if (work is Linux.Work.Failed) "Try again" else "Install") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(if (work is Linux.Work.Busy) "Hide" else "Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
private fun formatSize(b: Long): String = when {
|
||||
b >= 1L shl 30 -> "%.1f GB".format(b / (1L shl 30).toDouble())
|
||||
b >= 1L shl 20 -> "%.0f MB".format(b / (1L shl 20).toDouble())
|
||||
else -> "${b / 1024} KB"
|
||||
}
|
||||
@@ -97,7 +97,7 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
TAB_TERMINAL -> TerminalScreen(m, fullscreen = full, onFullscreen = { fullscreen = it })
|
||||
TAB_DIRECTORY -> DirectoryScreen(m, onDialed = { tab = TAB_TERMINAL })
|
||||
TAB_SETTINGS -> SettingsScreen(m)
|
||||
TAB_SETTINGS -> SettingsScreen(m, onOpenTerminal = { tab = TAB_TERMINAL })
|
||||
else -> LogScreen(m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ import kotlinx.coroutines.launch
|
||||
|
||||
/** The SIP account and the modem's options; they apply when the modem next starts. */
|
||||
@Composable
|
||||
fun SettingsScreen(modifier: Modifier = Modifier) {
|
||||
fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val store = remember { SettingsStore(context.applicationContext) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -110,6 +110,8 @@ fun SettingsScreen(modifier: Modifier = Modifier) {
|
||||
TerminalSettingsSection()
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
SshKeysSection()
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
LinuxSection(onOpened = onOpenTerminal)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ import com.neodesktop.dmodem.terminal.Key
|
||||
import com.neodesktop.dmodem.terminal.TermCharset
|
||||
import com.neodesktop.dmodem.terminal.Terminal
|
||||
import com.neodesktop.dmodem.terminal.TerminalView
|
||||
import com.neodesktop.dmodem.local.Linux
|
||||
import com.neodesktop.dmodem.local.LocalLink
|
||||
import com.neodesktop.dmodem.terminal.TerminalLink
|
||||
import com.neodesktop.dmodem.terminal.TerminalSession
|
||||
@@ -103,6 +104,7 @@ fun TerminalScreen(
|
||||
var view by remember { mutableStateOf<TerminalView?>(null) }
|
||||
var showSnippets by remember { mutableStateOf(false) }
|
||||
var showSsh by remember { mutableStateOf(false) }
|
||||
var showLinuxInstall by remember { mutableStateOf(false) }
|
||||
val ssh = session.link as? com.neodesktop.dmodem.ssh.SshLink
|
||||
|
||||
// the modem session's character set follows the settings (a directory entry's own while its call
|
||||
@@ -141,6 +143,13 @@ fun TerminalScreen(
|
||||
onKeyboard = { view?.toggleKeyboard() },
|
||||
onPaste = { view?.pasteClipboard() },
|
||||
onSnippets = { showSnippets = true },
|
||||
onNewLinux = {
|
||||
if (Linux.system(context).installed) {
|
||||
scope.launch { Terminal.openLinux(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
|
||||
} else {
|
||||
showLinuxInstall = true
|
||||
}
|
||||
},
|
||||
onNewShell = {
|
||||
scope.launch { Terminal.openLocal(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
|
||||
},
|
||||
@@ -196,7 +205,7 @@ fun TerminalScreen(
|
||||
if (!isModem && closed != null) {
|
||||
Disconnected(
|
||||
closed.reason,
|
||||
local = session.kind == TerminalSession.Kind.LOCAL,
|
||||
local = session.isLocal,
|
||||
onReconnect = {
|
||||
scope.launch {
|
||||
Terminal.reconnect(context, session)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
|
||||
@@ -217,6 +226,15 @@ fun TerminalScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (showLinuxInstall) {
|
||||
LinuxInstallDialog(
|
||||
onInstalled = {
|
||||
showLinuxInstall = false
|
||||
scope.launch { Terminal.openLinux(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
|
||||
},
|
||||
onDismiss = { showLinuxInstall = false },
|
||||
)
|
||||
}
|
||||
if (showSsh && ssh != null) {
|
||||
SshSessionDialog(ssh) { showSsh = false }
|
||||
}
|
||||
@@ -270,7 +288,7 @@ private fun SessionTabs(sessions: List<TerminalSession>, active: TerminalSession
|
||||
|
||||
/** a connection's state, for the bar */
|
||||
private fun linkText(s: TerminalSession, st: TerminalLink.State, title: String): String {
|
||||
if (s.kind == TerminalSession.Kind.LOCAL) {
|
||||
if (s.isLocal) {
|
||||
val state = when (st) {
|
||||
TerminalLink.State.Connecting -> "Starting…"
|
||||
TerminalLink.State.Open -> s.label
|
||||
@@ -333,6 +351,7 @@ private fun TopBar(
|
||||
onPaste: () -> Unit,
|
||||
onSnippets: () -> Unit,
|
||||
onNewShell: () -> Unit,
|
||||
onNewLinux: () -> Unit,
|
||||
/** an SSH connection's forwards, agent and keys (null: not one) */
|
||||
onSsh: (() -> Unit)?,
|
||||
onCapture: () -> Unit,
|
||||
@@ -361,6 +380,7 @@ private fun TopBar(
|
||||
DropdownMenuItem(text = { Text(if (isModem) "Hang up" else "Disconnect") }, onClick = { menu = false; onHangUp() })
|
||||
DropdownMenuItem(text = { Text("Paste") }, onClick = { menu = false; onPaste() })
|
||||
DropdownMenuItem(text = { Text("New local shell") }, onClick = { menu = false; onNewShell() })
|
||||
DropdownMenuItem(text = { Text("New Linux shell (Alpine)") }, onClick = { menu = false; onNewLinux() })
|
||||
if (onSsh != null) {
|
||||
DropdownMenuItem(text = { Text("Port forwards, agent, keys") }, onClick = { menu = false; onSsh() })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.local
|
||||
|
||||
import com.neodesktop.dmodem.terminal.TerminalLink
|
||||
import org.junit.AfterClass
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.BeforeClass
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Alpine Linux in the local terminal, as the app runs it, on this host:
|
||||
* proot built for it by native-proot/build.sh, the root file system
|
||||
* downloaded from Alpine (where it can be reached), shells on a pty.
|
||||
* What only a phone can tell (its SELinux rules, its /proc) isn't here.
|
||||
*/
|
||||
class LinuxSystemTest {
|
||||
|
||||
companion object {
|
||||
private lateinit var base: File
|
||||
private lateinit var programs: File
|
||||
private lateinit var storage: File
|
||||
private lateinit var system: LinuxSystem
|
||||
|
||||
private fun hostArch(): String? = when (System.getProperty("os.arch")) {
|
||||
"amd64", "x86_64" -> "x86_64"
|
||||
"aarch64" -> "aarch64"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** the proxy this host reaches the net by, for apk inside (none on a phone) */
|
||||
private fun proxyEnv(): Map<String, String> {
|
||||
val out = HashMap<String, String>()
|
||||
for (k in listOf("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY")) System.getenv(k)?.let { out[k.lowercase()] = it }
|
||||
// (a proxy that re-signs TLS: its CA, for apk)
|
||||
val ca = File("/etc/ssl/certs/ca-certificates.crt")
|
||||
if (out.isNotEmpty() && ca.exists()) out["SSL_CERT_FILE"] = "/host-ca.crt"
|
||||
return out
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
@JvmStatic
|
||||
fun install() {
|
||||
val arch = hostArch()
|
||||
assumeTrue("no Alpine for ${System.getProperty("os.arch")}", arch != null)
|
||||
assumeTrue("Alpine can't be reached", runCatching { (URL(LinuxSystem.MIRROR).openConnection().apply { connectTimeout = 10_000 }).getInputStream().close(); true }.getOrDefault(false))
|
||||
for (tool in listOf("cc", "make", "gawk", "curl")) {
|
||||
assumeTrue("$tool isn't installed (to build proot)", System.getenv("PATH").split(':').any { File(it, tool).canExecute() })
|
||||
}
|
||||
Pty.load(LocalShellTest.hostPty())
|
||||
base = Files.createTempDirectory("linux").toFile()
|
||||
programs = File(base, "lib")
|
||||
val script = listOf(File("../native-proot/build.sh"), File("native-proot/build.sh")).first { it.exists() }
|
||||
val p = ProcessBuilder(script.path, "host", programs.path).redirectErrorStream(true).start()
|
||||
val log = p.inputStream.readBytes().decodeToString()
|
||||
p.waitFor(10, TimeUnit.MINUTES)
|
||||
assertEquals(log, 0, p.exitValue())
|
||||
storage = File(base, "storage").apply { mkdirs() }
|
||||
File(storage, "Download").mkdirs()
|
||||
File(storage, "Download/from-the-phone.txt").writeText("hello from shared storage\n")
|
||||
system = LinuxSystem(
|
||||
File(base, "alpine"), programs, File(base, "tmp"), arch!!,
|
||||
storage = { storage },
|
||||
nameServers = { listOf("9.9.9.9") },
|
||||
extraEnv = proxyEnv(),
|
||||
)
|
||||
val steps = ArrayList<String>()
|
||||
system.install { what, _ -> if (steps.lastOrNull() != what) steps.add(what) }
|
||||
assertTrue(steps.toString(), steps.last().startsWith("Installed Alpine Linux"))
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
@JvmStatic
|
||||
fun cleanUp() {
|
||||
if (::base.isInitialized) Tar.removeTree(base)
|
||||
}
|
||||
}
|
||||
|
||||
/** the shell's output, its colours left out; the cursor's position told when asked (busybox's shell asks, as a terminal answers) */
|
||||
private class Screen(private val link: LocalLink) : TerminalLink.Listener {
|
||||
private val sb = StringBuilder()
|
||||
override fun onData(data: ByteArray, length: Int) {
|
||||
val t = String(data, 0, length)
|
||||
if (t.contains("\u001b[6n")) link.write("\u001b[1;1R".toByteArray())
|
||||
synchronized(sb) { sb.append(t) }
|
||||
}
|
||||
val text get() = synchronized(sb) { sb.toString().replace(Regex("\u001b\\[[0-9;?]*[A-Za-z]"), "") }
|
||||
}
|
||||
|
||||
private fun shell(): Pair<LocalLink, Screen> {
|
||||
// (the host's CA bound in for its proxy: the test's own addition)
|
||||
val l = system.link(100, 30)
|
||||
val s = Screen(l)
|
||||
l.addListener(s)
|
||||
assertTrue(l.start())
|
||||
return l to s
|
||||
}
|
||||
|
||||
private fun waitFor(what: String, s: Screen, secs: Int = 20, cond: (String) -> Boolean) {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (!cond(s.text)) {
|
||||
if (System.currentTimeMillis() > end) throw AssertionError("$what; the screen:\n${s.text}")
|
||||
Thread.sleep(20)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun installedAndSetUp() {
|
||||
assertTrue(system.installed)
|
||||
assertTrue(system.version!!.matches(Regex("3\\.22\\.\\d+")))
|
||||
assertEquals("nameserver 9.9.9.9\n", File(system.rootfs, "etc/resolv.conf").readText())
|
||||
assertTrue(File(system.rootfs, "etc/profile.d/dmodem.sh").readText().contains("@alpine"))
|
||||
// the made-up /proc files only for those Android hides (none hidden here)
|
||||
assertFalse(system.command().any { it.endsWith(":/proc/stat") })
|
||||
val hidden = LinuxSystem(system.dir, programs, File(base, "tmp"), system.arch, readable = { !it.path.endsWith("stat") })
|
||||
assertTrue(hidden.command().any { it.endsWith(":/proc/stat") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRootShellWithThePhonesStorage() {
|
||||
val (l, s) = shell()
|
||||
waitFor("the prompt", s) { it.contains("root@alpine") && it.contains("~#") }
|
||||
l.write("cat /etc/alpine-release; id -u; echo \$TERM; cat /sdcard/Download/from-the-phone.txt; echo made-in-linux > /sdcard/Download/back.txt\r".toByteArray())
|
||||
waitFor("its answers", s) { it.contains("hello from shared storage") && it.contains("xterm-256color") }
|
||||
assertTrue(s.text, s.text.contains(system.version!!))
|
||||
val end = System.currentTimeMillis() + 5000
|
||||
val back = File(storage, "Download/back.txt")
|
||||
while (!back.exists() && System.currentTimeMillis() < end) Thread.sleep(20)
|
||||
assertEquals("made-in-linux\n", back.readText())
|
||||
// the size, and hard links (proot's link2symlink)
|
||||
l.write("stty size; ln /etc/hostname /root/hl && cat /root/hl\r".toByteArray())
|
||||
val hostname = File(system.rootfs, "etc/hostname").readText().trim()
|
||||
waitFor("size and link", s) { it.contains("30 100") && it.contains("\r\n$hostname\r\n") }
|
||||
l.write("exit\r".toByteArray())
|
||||
val end2 = System.currentTimeMillis() + 10_000
|
||||
while (l.state.value !is TerminalLink.State.Closed && System.currentTimeMillis() < end2) Thread.sleep(20)
|
||||
assertEquals(0, l.exitStatus)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun apkAddsPackages() {
|
||||
val (l, s) = shell()
|
||||
waitFor("the prompt", s) { it.contains("~#") }
|
||||
val ca = if (proxyEnv().containsKey("SSL_CERT_FILE")) "cp /sdcard/../host-ca.crt / 2>/dev/null; " else ""
|
||||
// (behind this host's TLS-re-signing proxy: its CA copied in from the storage folder)
|
||||
if (ca.isNotEmpty()) File("/etc/ssl/certs/ca-certificates.crt").copyTo(File(system.rootfs, "host-ca.crt"), overwrite = true)
|
||||
l.write("apk update -q && apk add -q lua5.4 && lua5.4 -e 'print(\"lua says \" .. 6*7)'\r".toByteArray())
|
||||
waitFor("lua from apk", s, secs = 180) { it.contains("lua says 42") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removedLeavingTheStorage() {
|
||||
val other = LinuxSystem(File(base, "other"), programs, File(base, "tmp2"), system.arch, storage = { storage })
|
||||
File(other.rootfs, "bin").mkdirs()
|
||||
File(other.dir, ".installed").writeText("x")
|
||||
Files.createSymbolicLink(File(other.rootfs, "phone").toPath(), storage.toPath())
|
||||
other.remove()
|
||||
assertFalse(other.dir.exists())
|
||||
assertTrue(File(storage, "Download/from-the-phone.txt").exists())
|
||||
}
|
||||
}
|
||||
@@ -133,8 +133,9 @@ class LocalShellTest {
|
||||
val marker = File(tmp.root, "job")
|
||||
// a job that would write the marker after a while, unless hung up with the shell
|
||||
l.type("(sleep 3; touch ${marker.path}) &\r")
|
||||
l.type("echo started\r")
|
||||
waitFor("the job started", s) { it.contains("started") }
|
||||
// (the shell's own output, not the terminal's echo of what was typed: "started" only once it has run the line)
|
||||
l.type("echo st''arted\r")
|
||||
waitFor("the job started", s) { t -> t.lines().any { it.trim().endsWith("started") && !it.contains("echo") } }
|
||||
l.close()
|
||||
val end = System.currentTimeMillis() + 5_000
|
||||
while (l.state.value !is TerminalLink.State.Closed && System.currentTimeMillis() < end) Thread.sleep(10)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.local
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
/** Tars as the system's tar makes them (GNU and pax), unpacked; and ones made to escape, refused. */
|
||||
class TarTest {
|
||||
@get:Rule
|
||||
val tmp = TemporaryFolder()
|
||||
|
||||
private fun tar(dir: File, format: String): File {
|
||||
assumeTrue("no tar here", File("/usr/bin/tar").canExecute() || File("/bin/tar").canExecute())
|
||||
val out = File(tmp.root, "t-$format.tar")
|
||||
val p = ProcessBuilder("tar", "--format=$format", "-cf", out.path, "-C", dir.path, ".").redirectErrorStream(true).start()
|
||||
val msg = p.inputStream.readBytes().decodeToString()
|
||||
p.waitFor()
|
||||
assertEquals(msg, 0, p.exitValue())
|
||||
return out
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTreeAsTarMadeIt() {
|
||||
val src = tmp.newFolder("src")
|
||||
File(src, "bin").mkdirs()
|
||||
val busybox = File(src, "bin/busybox").apply { writeText("#!fake busybox\n") }
|
||||
Files.setPosixFilePermissions(busybox.toPath(), PosixFilePermission.values().toSet() - PosixFilePermission.OTHERS_WRITE - PosixFilePermission.GROUP_WRITE)
|
||||
Files.createSymbolicLink(File(src, "bin/sh").toPath(), Paths.get("/bin/busybox"))
|
||||
Files.createSymbolicLink(File(src, "bin/ls").toPath(), Paths.get("busybox"))
|
||||
Files.createLink(File(src, "bin/hard").toPath(), busybox.toPath())
|
||||
val long = "a".repeat(80) + "/" + "b".repeat(80) + "/" + "c".repeat(90) + ".txt"
|
||||
File(src, long).apply { parentFile!!.mkdirs(); writeText("long\n") }
|
||||
File(src, "etc").mkdirs()
|
||||
File(src, "etc/secret").apply { writeText("x") }.also { Files.setPosixFilePermissions(it.toPath(), setOf(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)) }
|
||||
File(src, "big.bin").writeBytes(ByteArray(300_000) { (it % 251).toByte() })
|
||||
File(src, "empty").mkdirs()
|
||||
|
||||
for (format in listOf("gnu", "pax", "ustar".takeIf { false }).filterNotNull()) {
|
||||
val dest = File(tmp.root, "out-$format")
|
||||
val stats = Tar.extract(tar(src, format).inputStream(), dest)
|
||||
assertEquals(format, "#!fake busybox\n", File(dest, "bin/busybox").readText())
|
||||
assertTrue(format, File(dest, "bin/busybox").canExecute())
|
||||
assertEquals("/bin/busybox", Files.readSymbolicLink(File(dest, "bin/sh").toPath()).toString())
|
||||
assertEquals("busybox", Files.readSymbolicLink(File(dest, "bin/ls").toPath()).toString())
|
||||
assertEquals("#!fake busybox\n", File(dest, "bin/hard").readText())
|
||||
assertEquals("long\n", File(dest, long).readText())
|
||||
assertEquals(setOf(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE), Files.getPosixFilePermissions(File(dest, "etc/secret").toPath()))
|
||||
assertTrue(File(dest, "big.bin").readBytes().contentEquals(File(src, "big.bin").readBytes()))
|
||||
assertTrue(File(dest, "empty").isDirectory)
|
||||
assertTrue(stats.files >= 4 && stats.links >= 3)
|
||||
}
|
||||
}
|
||||
|
||||
/** a tar written by hand: entries the system's tar wouldn't make */
|
||||
private class Writer {
|
||||
val out = ByteArrayOutputStream()
|
||||
fun entry(name: String, type: Char, data: ByteArray = ByteArray(0), link: String = "") {
|
||||
val h = ByteArray(512)
|
||||
name.toByteArray().copyInto(h, 0)
|
||||
"0000644\u0000".toByteArray().copyInto(h, 100)
|
||||
"%011o\u0000".format(data.size).toByteArray().copyInto(h, 124)
|
||||
h[156] = type.code.toByte()
|
||||
link.toByteArray().copyInto(h, 157)
|
||||
"ustar\u000000".toByteArray().copyInto(h, 257)
|
||||
for (i in 148 until 156) h[i] = ' '.code.toByte()
|
||||
"%06o\u0000 ".format(h.sumOf { it.toInt() and 0xff }).toByteArray().copyInto(h, 148)
|
||||
out.write(h)
|
||||
out.write(data)
|
||||
out.write(ByteArray((512 - data.size % 512) % 512))
|
||||
}
|
||||
fun bytes() = out.toByteArray() + ByteArray(1024)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nothingWrittenOutside() {
|
||||
val outside = tmp.newFolder("outside")
|
||||
val dest = File(tmp.root, "dest")
|
||||
val w = Writer()
|
||||
w.entry("../escaped", '0', "no".toByteArray())
|
||||
w.entry("/abs/ok", '0', "inside".toByteArray())
|
||||
// a link to outside, then a file "through" it
|
||||
w.entry("evil", '2', link = outside.path)
|
||||
w.entry("evil/planted", '0', "no".toByteArray())
|
||||
w.entry("hard", '1', link = "../../etc/passwd")
|
||||
runCatching { Tar.extract(w.bytes().inputStream(), dest) }
|
||||
assertFalse(File(tmp.root, "escaped").exists())
|
||||
assertEquals("absolute names kept inside", "inside", File(dest, "abs/ok").readText())
|
||||
assertFalse("nothing through the link", File(outside, "planted").exists())
|
||||
assertTrue("the link itself is there", Files.isSymbolicLink(File(dest, "evil").toPath()))
|
||||
assertFalse(File(dest, "hard").exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removedWithoutFollowingLinks() {
|
||||
val outside = tmp.newFolder("storage")
|
||||
val keep = File(outside, "photo.jpg").apply { writeText("keep me") }
|
||||
val sys = tmp.newFolder("system")
|
||||
File(sys, "rootfs/usr/bin").mkdirs()
|
||||
File(sys, "rootfs/usr/bin/x").writeText("x")
|
||||
Files.createSymbolicLink(File(sys, "rootfs/sdcard").toPath(), outside.toPath())
|
||||
Files.createSymbolicLink(File(sys, "rootfs/photo").toPath(), keep.toPath())
|
||||
// a read-only directory, as packages make them
|
||||
File(sys, "rootfs/ro").mkdirs()
|
||||
File(sys, "rootfs/ro/f").writeText("f")
|
||||
File(sys, "rootfs/ro").setWritable(false)
|
||||
Tar.removeTree(sys)
|
||||
assertFalse(sys.exists())
|
||||
assertEquals("keep me", keep.readText())
|
||||
}
|
||||
}
|
||||
@@ -257,8 +257,12 @@ class OpenSshInteropTest {
|
||||
Socket("127.0.0.1", bound(l, later)).use { assertEquals("echo: five", roundTrip(it, "five")) }
|
||||
val p = bound(l, local)
|
||||
l.removeForward(local)
|
||||
// (released: free to listen on again)
|
||||
ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress("127.0.0.1", p)) }.close()
|
||||
// released: free to listen on again (once the last connection through it has finished closing)
|
||||
val freeBy = System.currentTimeMillis() + 5000
|
||||
while (runCatching { ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress("127.0.0.1", p)) }.close() }.isFailure) {
|
||||
if (System.currentTimeMillis() > freeBy) throw AssertionError("port $p still taken after its forward stopped")
|
||||
Thread.sleep(50)
|
||||
}
|
||||
assertTrue(l.forwards.value.none { it.spec == local })
|
||||
|
||||
// a port already taken: its error, the others unharmed
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ui
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.compose.ui.graphics.asAndroidBitmap
|
||||
import androidx.compose.ui.test.captureToImage
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.isSelectable
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import com.neodesktop.dmodem.local.Linux
|
||||
import com.neodesktop.dmodem.local.LinuxSystem
|
||||
import com.neodesktop.dmodem.local.LocalShellTest
|
||||
import com.neodesktop.dmodem.local.Pty
|
||||
import com.neodesktop.dmodem.local.Tar
|
||||
import com.neodesktop.dmodem.terminal.Terminal
|
||||
import com.neodesktop.dmodem.terminal.TerminalSession
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Alpine installed from Settings and its shell used (proot and Alpine for this host: see LinuxSystemTest). */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "w411dp-h891dp-xxhdpi")
|
||||
class LinuxUiTest {
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private lateinit var base: File
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
assumeTrue("not an x86_64 host", System.getProperty("os.arch") in listOf("amd64", "x86_64"))
|
||||
assumeTrue("Alpine can't be reached", runCatching { URL(LinuxSystem.MIRROR).openConnection().apply { connectTimeout = 10_000 }.getInputStream().close(); true }.getOrDefault(false))
|
||||
for (tool in listOf("cc", "make", "gawk", "curl")) {
|
||||
assumeTrue("$tool isn't installed", System.getenv("PATH").split(':').any { File(it, tool).canExecute() })
|
||||
}
|
||||
Pty.load(LocalShellTest.hostPty())
|
||||
base = Files.createTempDirectory("linux-ui").toFile()
|
||||
val programs = File(base, "lib")
|
||||
val script = listOf(File("../native-proot/build.sh"), File("native-proot/build.sh")).first { it.exists() }
|
||||
val p = ProcessBuilder(script.path, "host", programs.path).redirectErrorStream(true).start()
|
||||
val log = p.inputStream.readBytes().decodeToString()
|
||||
p.waitFor(10, TimeUnit.MINUTES)
|
||||
assertEquals(log, 0, p.exitValue())
|
||||
val storage = File(base, "storage").apply { mkdirs() }
|
||||
listOf("Download", "DCIM", "Documents", "Music").forEach { File(storage, it).mkdirs() }
|
||||
File(storage, "Download/readme.txt").writeText("from the phone\n")
|
||||
Linux.factory = { LinuxSystem(File(base, "alpine"), programs, File(base, "tmp"), "x86_64", storage = { storage }) }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
Terminal.sessions.value.filter { it.kind != TerminalSession.Kind.MODEM }.forEach { Terminal.close(it) }
|
||||
if (::base.isInitialized) Tar.removeTree(base)
|
||||
}
|
||||
|
||||
private fun shot(name: String) {
|
||||
compose.waitForIdle()
|
||||
val bmp = compose.onRoot().captureToImage().asAndroidBitmap()
|
||||
File("build/screens").mkdirs()
|
||||
File("build/screens/$name.png").outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
}
|
||||
|
||||
private fun screen(s: TerminalSession) =
|
||||
synchronized(s.emulator) { (0 until s.emulator.rows).joinToString("\n") { s.emulator.line(it).text() } }
|
||||
|
||||
private fun waitShell(s: TerminalSession, text: String, secs: Int = 20) {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (!screen(s).contains(text)) {
|
||||
if (System.currentTimeMillis() > end) throw AssertionError("no '$text' in:\n" + screen(s))
|
||||
Thread.sleep(50)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun installedFromSettingsAndUsed() {
|
||||
compose.onNode(hasText("Settings") and isSelectable()).performClick()
|
||||
compose.onNodeWithText("Install Alpine Linux").performScrollTo()
|
||||
shot("linux-1-settings")
|
||||
compose.onNodeWithText("Install Alpine Linux").performClick()
|
||||
compose.waitUntil(120_000) { compose.onAllNodesWithText("Open a shell").fetchSemanticsNodes().isNotEmpty() }
|
||||
compose.onNodeWithText("Open a shell").performScrollTo()
|
||||
shot("linux-2-installed")
|
||||
compose.onNodeWithText("Open a shell").performClick()
|
||||
compose.waitUntil(20_000) { Terminal.active.value?.kind == TerminalSession.Kind.LINUX }
|
||||
val s = Terminal.active.value!!
|
||||
waitShell(s, "root@alpine:~#")
|
||||
s.send("cat /etc/os-release | head -2; uname -m; ls --color=always /sdcard; cat /sdcard/Download/readme.txt; apk --version\r")
|
||||
waitShell(s, "from the phone")
|
||||
waitShell(s, "apk-tools")
|
||||
compose.waitUntil(5_000) { compose.onAllNodesWithText("Alpine").fetchSemanticsNodes().isNotEmpty() }
|
||||
shot("linux-3-shell")
|
||||
}
|
||||
}
|
||||
+1
Submodule external/proot added at b8c1f5c5c6.
@@ -0,0 +1,25 @@
|
||||
# proot for the local terminal's Linux
|
||||
|
||||
`build.sh` builds [Termux's proot](https://github.com/termux/proot)
|
||||
(`external/proot`, a submodule pinned to a commit) and its loader, with
|
||||
[talloc](https://talloc.samba.org/) 2.4.2 (downloaded from samba.org and
|
||||
checked against its SHA-256), for each Android ABI with the NDK, or for the
|
||||
host (the unit tests). Gradle runs it (`:app:buildProot`) before each build.
|
||||
|
||||
The outputs are programs named `libproot.so` and `libproot-loader.so`, so
|
||||
that Android installs them in the app's native library directory: from
|
||||
Android 10 on, an app can run its own programs only from there (not from
|
||||
its data directory). proot runs the Linux system's programs through the
|
||||
loader, which maps them into memory rather than executing them.
|
||||
|
||||
Needs: a C compiler (the NDK's for Android), make, GNU awk (`gawk`) and curl.
|
||||
|
||||
`talloc-shim/replace.h` stands in for the part of Samba's `lib/replace` that
|
||||
`talloc.c` uses, so that talloc builds as one file without Samba's waf.
|
||||
|
||||
The build copies proot's source tree and adds `#include <string.h>` to
|
||||
`extension/ashmem_memfd/ashmem_memfd.c`, which needs it and doesn't include
|
||||
it (an error with clang). The submodule itself is left as it is.
|
||||
|
||||
Licences: proot is GPL-2.0-or-later, talloc LGPL-3.0-or-later; their
|
||||
sources are the submodule and the pinned tarball named above.
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Copyright (C) 2026 Neo-Desktop
|
||||
#
|
||||
# proot (Termux's: external/proot) and its loader, with talloc, built for an
|
||||
# Android ABI with the NDK, or for this host (the unit tests):
|
||||
#
|
||||
# native-proot/build.sh <arm64-v8a|armeabi-v7a|x86|x86_64|host> <out dir> [ndk dir]
|
||||
#
|
||||
# Out: libproot.so and libproot-loader.so: programs, named as libraries so
|
||||
# that Android installs them in the app's native library directory, the
|
||||
# one place an app may run programs from (Android 10 on). The loader is
|
||||
# kept apart from proot (not extracted to a temporary file and run from
|
||||
# there, which Android forbids); PROOT_LOADER names it at run time.
|
||||
set -eu
|
||||
|
||||
ABI=$1
|
||||
OUT=$2
|
||||
NDK=${3:-${ANDROID_NDK_HOME:-}}
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
ROOT=$(cd "$HERE/.." && pwd)
|
||||
TALLOC_VERSION=2.4.2
|
||||
TALLOC_SHA256=85ecf9e465e20f98f9950a52e9a411e14320bc555fa257d87697b7e7a9b1d8a6
|
||||
API=26
|
||||
|
||||
WORK=${PROOT_WORK:-$OUT/.build}
|
||||
mkdir -p "$WORK" "$OUT"
|
||||
|
||||
if [ "$ABI" = host ]; then
|
||||
CC=${CC:-cc}
|
||||
AR=${AR:-ar}
|
||||
STRIP=${STRIP:-strip}
|
||||
OBJCOPY=${OBJCOPY:-objcopy}
|
||||
OBJDUMP=${OBJDUMP:-objdump}
|
||||
EXTRA_LDFLAGS=
|
||||
else
|
||||
[ -n "$NDK" ] || { echo "no NDK (third argument or ANDROID_NDK_HOME)" >&2; exit 1; }
|
||||
BIN=$(echo "$NDK"/toolchains/llvm/prebuilt/*/bin)
|
||||
case $ABI in
|
||||
arm64-v8a) TRIPLE=aarch64-linux-android ;;
|
||||
armeabi-v7a) TRIPLE=armv7a-linux-androideabi ;;
|
||||
x86) TRIPLE=i686-linux-android ;;
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
*) echo "unknown ABI $ABI" >&2; exit 1 ;;
|
||||
esac
|
||||
CC="$BIN/$TRIPLE$API-clang"
|
||||
AR="$BIN/llvm-ar"
|
||||
STRIP="$BIN/llvm-strip"
|
||||
OBJCOPY="$BIN/llvm-objcopy"
|
||||
OBJDUMP="$BIN/llvm-objdump"
|
||||
# 16 KB pages (Android 15 on)
|
||||
EXTRA_LDFLAGS="-Wl,-z,max-page-size=16384"
|
||||
fi
|
||||
|
||||
# GNU awk: proot's makefile makes the arm64 loader's symbol table with it (strtonum)
|
||||
command -v gawk >/dev/null || { echo "proot's build needs GNU awk (gawk)" >&2; exit 1; }
|
||||
mkdir -p "$WORK/bin"
|
||||
ln -sf "$(command -v gawk)" "$WORK/bin/awk"
|
||||
PATH=$WORK/bin:$PATH
|
||||
export PATH
|
||||
|
||||
# talloc: its one source file, with the little of Samba's lib/replace it uses
|
||||
TARBALL=$WORK/talloc-$TALLOC_VERSION.tar.gz
|
||||
if [ ! -f "$TARBALL" ]; then
|
||||
curl -fsSL -o "$TARBALL.part" "https://www.samba.org/ftp/talloc/talloc-$TALLOC_VERSION.tar.gz"
|
||||
mv "$TARBALL.part" "$TARBALL"
|
||||
fi
|
||||
echo "$TALLOC_SHA256 $TARBALL" | sha256sum -c - >/dev/null || { echo "talloc's checksum doesn't match" >&2; rm -f "$TARBALL"; exit 1; }
|
||||
rm -rf "$WORK/talloc"
|
||||
mkdir -p "$WORK/talloc"
|
||||
tar xzf "$TARBALL" -C "$WORK/talloc" --strip-components=1
|
||||
$CC -c -O2 -fPIC -I"$HERE/talloc-shim" -I"$WORK/talloc" "$WORK/talloc/talloc.c" -o "$WORK/talloc.o"
|
||||
rm -f "$WORK/libtalloc.a"
|
||||
$AR rcs "$WORK/libtalloc.a" "$WORK/talloc.o"
|
||||
|
||||
# proot, built in a copy of its tree (its makefile's out-of-tree build doesn't work),
|
||||
# string.h added to the one file that forgets it (an error with clang)
|
||||
rm -rf "$WORK/proot"
|
||||
cp -r "$ROOT/external/proot/src" "$WORK/proot"
|
||||
sed -i '1i #include <string.h>' "$WORK/proot/extension/ashmem_memfd/ashmem_memfd.c"
|
||||
# (the flags from the environment: the makefile adds its own to them, which it can't to ones on its command line)
|
||||
CPPFLAGS="-D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE -I. -I$WORK/talloc" \
|
||||
CFLAGS="-Wall -Wextra -O2 -DARG_MAX=131072" \
|
||||
LDFLAGS="-L$WORK -Wl,-z,noexecstack $EXTRA_LDFLAGS" \
|
||||
make -C "$WORK/proot" -j"$(nproc 2>/dev/null || echo 4)" proot loader/loader \
|
||||
CC="$CC" STRIP="$STRIP" OBJCOPY="$OBJCOPY" OBJDUMP="$OBJDUMP" \
|
||||
PROOT_UNBUNDLE_LOADER=/nonexistent HAS_LOADER_32BIT= >"$WORK/make.log" 2>&1 \
|
||||
|| { tail -40 "$WORK/make.log" >&2; exit 1; }
|
||||
|
||||
cp "$WORK/proot/proot" "$OUT/libproot.so"
|
||||
cp "$WORK/proot/loader/loader" "$OUT/libproot-loader.so"
|
||||
$STRIP "$OUT/libproot.so"
|
||||
chmod 755 "$OUT/libproot.so" "$OUT/libproot-loader.so"
|
||||
echo "built $OUT/libproot.so $OUT/libproot-loader.so"
|
||||
@@ -0,0 +1,34 @@
|
||||
/* SPDX-License-Identifier: LGPL-3.0-or-later (as talloc) -- the little of Samba's lib/replace that talloc.c uses */
|
||||
#ifndef DMODEM_TALLOC_REPLACE_H
|
||||
#define DMODEM_TALLOC_REPLACE_H
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#define _PUBLIC_ __attribute__((visibility("default")))
|
||||
#ifndef likely
|
||||
#define likely(x) __builtin_expect(!!(x), 1)
|
||||
#define unlikely(x) __builtin_expect(!!(x), 0)
|
||||
#endif
|
||||
#ifndef discard_const_p
|
||||
#define discard_const(ptr) ((void *)((uintptr_t)(ptr)))
|
||||
#define discard_const_p(type, ptr) ((type *)discard_const(ptr))
|
||||
#endif
|
||||
#ifndef MIN
|
||||
#define MIN(a, b) ((a) < (b) ? (a) : (b))
|
||||
#endif
|
||||
#define HAVE_VA_COPY 1
|
||||
#define HAVE_INTPTR_T 1
|
||||
#define HAVE_CONSTRUCTOR_ATTRIBUTE 1
|
||||
#define HAVE_DESTRUCTOR_ATTRIBUTE 1
|
||||
#define TALLOC_BUILD_VERSION_MAJOR 2
|
||||
#define TALLOC_BUILD_VERSION_MINOR 4
|
||||
#define TALLOC_BUILD_VERSION_RELEASE 2
|
||||
#endif
|
||||
Reference in new issue
Block a user