Linux: Debian, Ubuntu, Fedora, Arch and more, and any root file system by URL

- A catalog: Alpine (its own release list), Ubuntu 24.04 (its base
  image, the newest point release), and from the Linux Containers
  images (built daily, SHA-256 sums): Debian 13, Fedora, Arch Linux,
  openSUSE Tumbleweed, Kali, Void, Rocky, AlmaLinux, Devuan; those not
  built for the phone's processor shown as such (the images' index)
- Or any root file system tarball by its URL (.tar, .tar.gz, .tar.xz;
  xz with org.tukaani:xz), its SHA-256 checked when given; one in a
  single top folder moved up; anything else refused and removed
- Several systems side by side, each in linux/<id> with system.json;
  the first release's Alpine still known
- Set up for proot at each start: resolv.conf a file (not systemd's
  link), hosts, /etc/mtab, apt's sandbox user root, pacman without its
  sandbox or space check, a prompt named for the distribution; root's
  own login shell (bash where it has it), found through usrmerge's links
  as the system sees them
- Settings, Linux: the systems installed (open, remove), "Install a
  Linux" with the catalog or a URL; the terminal's "New Linux shell…"
  asks which when there are several; installs report done as a state
  the screens watch
- Tests: the sources' indexes, archives of each kind, the proot set-up,
  checksums and refusals (offline); Alpine and a custom URL's .xz
  through proot on this host; every catalog distribution's package
  manager installing Lua when DMODEM_DISTROS names them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-16 21:39:09 +00:00
1 parent a02a578a5d
commit c921531360
12 files changed
+1135 -352

No files matched your search

+2
View File
@@ -96,6 +96,8 @@ dependencies {
implementation(libs.androidx.datastore.preferences)
// SSH: sshj on BouncyCastle (Android's own "BC" is cut down: the full one is registered at start)
implementation(libs.sshj)
// the Linux systems' root file systems (.tar.xz)
implementation(libs.xz)
implementation(libs.bcprov)
implementation(libs.bcpkix)
implementation(platform(libs.compose.bom))
@@ -0,0 +1,213 @@
// 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
/** A root file system to download: where, its checksum (if known), its size (if known), what it is. */
data class Rootfs(
val url: String,
val sha256: String?,
val size: Long,
/** "Debian 13 (trixie)" */
val name: String,
/** the release or build ("20261016_05:24", "3.22.6") */
val version: String,
)
/** The phone's processor, as each source names it. */
data class Machine(val abi: String, val alpine: String, val lxc: String, val ubuntu: String?) {
companion object {
fun forAbi(abi: String): Machine? = when (abi) {
"arm64-v8a" -> Machine(abi, "aarch64", "arm64", "arm64")
"armeabi-v7a" -> Machine(abi, "armv7", "armhf", "armhf")
"x86_64" -> Machine(abi, "x86_64", "amd64", "amd64")
"x86" -> Machine(abi, "x86", "i386", null)
else -> null
}
}
}
/**
* The distributions offered: Alpine from Alpine's own release list,
* Ubuntu from its base images, the rest from the Linux Containers
* project's images (images.linuxcontainers.org: built daily, with their
* SHA-256 sums). A custom one is any tarball's URL.
*/
sealed class Distro(
/** its directory's name, and its prompt's host */
val id: String,
val name: String,
/** a line for the list: its package manager, how big */
val about: String,
) {
abstract fun resolve(m: Machine, http: Http): Rootfs
class Alpine(private val mirror: String = ALPINE_MIRROR, private val branch: String = ALPINE_BRANCH) :
Distro("alpine", "Alpine Linux", "apk · about 3 MB · musl, small and quick") {
override fun resolve(m: Machine, http: Http): Rootfs {
val base = "$mirror/$branch/releases/${m.alpine}"
val yaml = http.text("$base/latest-releases.yaml")
// (a list of releases, one per flavour: the minirootfs one's fields)
val b = yaml.split(Regex("\n-\\s*\n|\n- ")).firstOrNull { it.contains("flavor: alpine-minirootfs") }
?: throw IOException("no Alpine for ${m.alpine}")
fun field(k: String) = Regex("(?m)^\\s*$k:\\s*(\\S+)").find(b)?.groupValues?.get(1)
val version = field("version") ?: "?"
return Rootfs(
"$base/${field("file") ?: throw IOException("no file in Alpine's list")}",
field("sha256") ?: throw IOException("no checksum in Alpine's list"),
field("size")?.toLongOrNull() ?: -1,
"Alpine Linux $version", version,
)
}
}
/** Ubuntu's base image (its own, ~30 MB): the newest point release of [release] */
class Ubuntu(private val release: String = "24.04", private val mirror: String = UBUNTU_MIRROR) :
Distro("ubuntu", "Ubuntu $release LTS", "apt · about 30 MB") {
override fun resolve(m: Machine, http: Http): Rootfs {
val arch = m.ubuntu ?: throw IOException("no Ubuntu for ${m.abi}")
val base = "$mirror/$release/release"
val sums = http.text("$base/SHA256SUMS")
val re = Regex("([0-9a-f]{64}) \\*?(ubuntu-base-([0-9.]+)-base-$arch\\.tar\\.gz)")
val newest = re.findAll(sums).maxByOrNull { versionKey(it.groupValues[3]) }
?: throw IOException("no Ubuntu $release for $arch")
val (sha, file, version) = newest.destructured
return Rootfs("$base/$file", sha, http.size("$base/$file"), "Ubuntu $version LTS", version)
}
}
/**
* A Linux Containers image: [release] of [distro], or (null) its
* newest: "current", "tumbleweed", or the highest number
*/
class Lxc(id: String, name: String, about: String, private val distro: String, private val release: String? = null) :
Distro(id, name, about) {
override fun resolve(m: Machine, http: Http): Rootfs {
val rows = lxcIndex(http).filter { it.distro == distro && it.arch == m.lxc && it.variant == "default" }
val row = (if (release != null) rows.firstOrNull { it.release == release } else newest(rows))
?: throw IOException("$name isn't built for this phone's processor (${m.lxc})")
val dir = LXC_MIRROR + row.path.trimEnd('/')
val sums = http.text("$dir/SHA256SUMS")
val sha = Regex("([0-9a-f]{64})\\s+\\*?rootfs\\.tar\\.xz").find(sums)?.groupValues?.get(1)
?: throw IOException("no checksum for $name's image")
val shown = if (release == null && row.release.firstOrNull()?.isDigit() == true) "$name ${row.release}" else name
return Rootfs("$dir/rootfs.tar.xz", sha, http.size("$dir/rootfs.tar.xz"), shown, "${row.release} ${row.build}")
}
/** whether there is one for [m] (from the index) */
fun availableFor(m: Machine, index: List<LxcRow>): Boolean =
index.any { it.distro == distro && it.arch == m.lxc && it.variant == "default" && (release == null || it.release == release) }
private fun newest(rows: List<LxcRow>): LxcRow? =
rows.firstOrNull { it.release == "current" } ?: rows.firstOrNull { it.release == "tumbleweed" }
?: rows.filter { it.release.firstOrNull()?.isDigit() == true }.maxByOrNull { versionKey(it.release) }
?: rows.firstOrNull()
}
/** any root file system tarball (.tar, .tar.gz or .tar.xz) by its URL */
class Custom(id: String, name: String, private val url: String, private val sha256: String?) :
Distro(id, name, url) {
override fun resolve(m: Machine, http: Http): Rootfs =
Rootfs(url, sha256?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }, http.size(url), name, "custom")
}
data class LxcRow(val distro: String, val release: String, val arch: String, val variant: String, val build: String, val path: String)
companion object {
const val ALPINE_MIRROR = "https://dl-cdn.alpinelinux.org/alpine"
const val ALPINE_BRANCH = "v3.22"
const val UBUNTU_MIRROR = "https://cdimage.ubuntu.com/ubuntu-base/releases"
const val LXC_MIRROR = "https://images.linuxcontainers.org"
val CATALOG: List<Distro> = listOf(
Alpine(),
Lxc("debian", "Debian 13 (trixie)", "apt · about 85 MB", "debian", "trixie"),
Ubuntu(),
Lxc("fedora", "Fedora", "dnf · about 90 MB", "fedora"),
Lxc("archlinux", "Arch Linux", "pacman · about 170 MB", "archlinux"),
Lxc("opensuse", "openSUSE Tumbleweed", "zypper · about 40 MB", "opensuse", "tumbleweed"),
Lxc("kali", "Kali Linux", "apt · about 75 MB · security tools", "kali"),
Lxc("void", "Void Linux", "xbps · about 120 MB", "voidlinux"),
Lxc("rocky", "Rocky Linux", "dnf · about 100 MB · RHEL-compatible", "rockylinux"),
Lxc("alma", "AlmaLinux", "dnf · about 80 MB · RHEL-compatible", "almalinux"),
Lxc("devuan", "Devuan", "apt · about 80 MB · Debian without systemd", "devuan"),
)
fun byId(id: String): Distro? = CATALOG.firstOrNull { it.id == id }
/** the Linux Containers images' index: distro;release;arch;variant;build;path */
fun lxcIndex(http: Http): List<LxcRow> = parseLxcIndex(http.text("$LXC_MIRROR/meta/1.0/index-system"))
fun parseLxcIndex(text: String): List<LxcRow> = text.lineSequence().mapNotNull { l ->
val f = l.trim().split(';')
if (f.size >= 6) LxcRow(f[0], f[1], f[2], f[3], f[4], f[5]) else null
}.toList()
/** "24.04.5" sortable: each number in turn */
fun versionKey(v: String): String = v.split('.', '-').joinToString(".") { it.padStart(8, '0') }
/** a custom system's id from its name */
fun customId(name: String): String =
"custom-" + name.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-').ifEmpty { "linux" }.take(40)
}
}
/** What the systems are fetched with. */
open class Http {
open fun open(url: String): HttpURLConnection {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 20_000
c.readTimeout = 60_000
c.instanceFollowRedirects = true
c.setRequestProperty("User-Agent", "D-Modem for Android")
if (c.responseCode != 200) throw IOException("$url: HTTP ${c.responseCode}")
return c
}
open fun text(url: String): String = open(url).let { c -> c.inputStream.use { it.readBytes().decodeToString() } }
/** its size from a HEAD request, or -1 */
open fun size(url: String): Long = try {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = "HEAD"
c.connectTimeout = 20_000
c.setRequestProperty("User-Agent", "D-Modem for Android")
if (c.responseCode == 200) c.contentLengthLong else -1
} catch (_: IOException) {
-1
}
/** [url] to [to] (through a .part file), its SHA-256 back; [progress] 0..1 when the size is known */
open fun download(url: String, to: File, size: Long, progress: (Float) -> Unit): String {
val c = open(url)
val total = if (size > 0) size else c.contentLengthLong
val part = File(to.path + ".part")
val md = MessageDigest.getInstance("SHA-256")
c.inputStream.use { i ->
part.outputStream().use { o ->
val buf = ByteArray(64 * 1024)
var done = 0L
var shown = -1
while (true) {
if (Thread.interrupted()) throw IOException("cancelled")
val n = i.read(buf)
if (n < 0) break
o.write(buf, 0, n)
md.update(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")
return md.digest().joinToString("") { "%02x".format(it) }
}
}
@@ -22,72 +22,122 @@ 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.
* The app's Linux systems (run with proot): where they live on this
* phone (each in linux/<id>), their installs and removals (which go on
* while the user moves about the app; one at a time), and the shared
* storage they're 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()
data class Busy(val id: String, val what: String, val fraction: Float?) : Work()
data class Failed(val id: String, 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) */
/** bumped when one is installed or removed (for the screens showing them) */
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) }
/** where the systems live and what they're given: the phone's (the tests' own in theirs) */
class Place(
val root: File,
val programDir: File,
val tmpDir: File,
val machine: Machine?,
val storage: () -> File? = { null },
val nameServers: () -> List<String> = { LinuxSystem.DEFAULT_DNS },
val extraEnv: Map<String, String> = emptyMap(),
val http: Http = Http(),
)
fun system(context: Context): LinuxSystem = factory(context.applicationContext)
var place: (Context) -> Place = { ctx -> phonePlace(ctx) }
/** 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"),
private fun phonePlace(app: Context) = Place(
root = File(app.filesDir, "linux"),
programDir = File(app.applicationInfo.nativeLibraryDir ?: app.filesDir.path),
tmpDir = File(app.cacheDir, "proot"),
arch = arch() ?: "aarch64",
machine = machine(),
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)
/** this phone's processor, or null where no Linux is built for it */
fun machine(): Machine? = Build.SUPPORTED_ABIS.firstNotNullOfOrNull { Machine.forAbi(it) }
fun system(context: Context, id: String): LinuxSystem {
val p = place(context.applicationContext)
return LinuxSystem(File(p.root, id), p.programDir, p.tmpDir, p.storage, p.nameServers, p.extraEnv)
}
/** the systems installed, the first installed first */
fun systems(context: Context): List<LinuxSystem> {
val root = place(context.applicationContext).root
return (root.listFiles() ?: emptyArray()).filter { it.isDirectory }.map { system(context, it.name) }
.filter { it.installed }.sortedBy { it.info?.installed ?: 0 }
}
/**
* which of the catalog's distributions are built for this phone (the
* Linux Containers index asked: blocking); all of them when it can't
* be asked
*/
fun available(context: Context): Map<String, Boolean> {
val p = place(context.applicationContext)
val m = p.machine ?: return Distro.CATALOG.associate { it.id to false }
val index = runCatching { Distro.lxcIndex(p.http) }.getOrNull()
return Distro.CATALOG.associate { d ->
d.id to when (d) {
is Distro.Lxc -> index == null || d.availableFor(m, index)
is Distro.Ubuntu -> m.ubuntu != null
else -> true
}
}
}
fun remove(context: Context) {
private val _done = MutableStateFlow<String?>(null)
/** the id of the system installed last (for the screen that asked for it to open it) */
val done: StateFlow<String?> = _done.asStateFlow()
/** [d] installed (in the background); [done] says so when it is */
fun install(context: Context, d: Distro) {
if (_work.value is Work.Busy) return
val sys = system(context)
_work.value = Work.Busy("Removing…", null)
val p = place(context.applicationContext)
val sys = system(context, d.id)
_work.value = Work.Busy(d.id, "Finding ${d.name}…", null)
scope.launch {
try {
if (sys.installed) throw java.io.IOException("${sys.name} is installed already")
val m = p.machine ?: throw java.io.IOException("no Linux for this phone's processor")
val r = d.resolve(m, p.http)
sys.install(r, p.http) { what, f -> _work.value = Work.Busy(d.id, what, f) }
_work.value = Work.Idle
_done.value = sys.id
_changes.value++
} catch (e: Exception) {
_work.value = Work.Failed(d.id, e.message ?: e.javaClass.simpleName)
_changes.value++
}
}
}
fun remove(context: Context, id: String) {
if (_work.value is Work.Busy) return
if (_done.value == id) _done.value = null
val sys = system(context, id)
_work.value = Work.Busy(id, "Removing ${sys.name}…", null)
scope.launch {
try {
sys.remove()
_work.value = Work.Idle
} catch (e: Exception) {
_work.value = Work.Failed(e.message ?: e.javaClass.simpleName)
_work.value = Work.Failed(id, e.message ?: e.javaClass.simpleName)
}
_changes.value++
}
@@ -97,10 +147,10 @@ object Linux {
if (_work.value is Work.Failed) _work.value = Work.Idle
}
/** the disk it takes */
fun size(context: Context): Long {
/** the disk a system takes (links not followed) */
fun size(sys: LinuxSystem): Long {
var total = 0L
system(context).dir.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.forEach {
sys.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
@@ -2,109 +2,220 @@
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.local
import org.json.JSONObject
import org.tukaani.xz.XZInputStream
import java.io.BufferedInputStream
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Paths
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.
* A Linux system to run in the local terminal (Alpine, Debian, Ubuntu,
* Fedora, Arch and the rest of [Distro.CATALOG], or one from any URL),
* 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.
* Inside: root (proot's fake one) with its own login shell, the device's
* /dev, /proc and /sys, and the phone's shared storage at /sdcard when the
* app may read it. Each system in a directory of its own: rootfs/ and
* system.json (what it is).
*/
class LinuxSystem(
/** where it lives: rootfs/ in it */
/** where it lives: rootfs/ and system.json in it; its name is the system's id */
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 id: String get() = dir.name
val rootfs: File get() = File(dir, "rootfs")
private val marker: File get() = File(dir, ".installed")
private val infoFile: File get() = File(dir, "system.json")
val installed: Boolean get() = marker.exists() && File(rootfs, "bin").exists()
/** what it is, as installed */
data class Info(val name: String, val version: String, val source: String, val installed: Long)
/** the version installed ("3.22.6"), or null */
val version: String? get() = runCatching { File(rootfs, "etc/alpine-release").readText().trim() }.getOrNull()
val info: Info?
get() = runCatching {
val o = JSONObject(infoFile.readText())
Info(o.getString("name"), o.optString("version"), o.optString("source"), o.optLong("installed"))
}.getOrNull() ?: legacyInfo()
data class Release(val file: String, val version: String, val sha256: String, val size: Long) {
val name get() = "Alpine Linux $version"
/** (the first release's Alpine: a marker file, no system.json) */
private fun legacyInfo(): Info? {
val m = File(dir, ".installed")
if (!m.exists()) return null
val v = runCatching { File(rootfs, "etc/alpine-release").readText().trim() }.getOrNull() ?: m.readText().trim()
return Info("Alpine Linux $v", v, Distro.ALPINE_MIRROR, m.lastModified())
}
/** 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,
)
val installed: Boolean get() = info != null && File(rootfs, "etc").isDirectory
val name: String get() = info?.name ?: id
/**
* Installed from [r]: downloaded, its checksum checked (when there is
* one), unpacked and set up. [progress]: what it's doing, and how far
* (0..1) when it can tell.
*/
fun install(r: Rootfs, http: Http = Http(), progress: (String, Float?) -> Unit = { _, _ -> }) {
dir.mkdirs()
if (r.size > 0) {
// (unpacked, a compressed system takes about four times its download)
val need = r.size * 5
if (dir.usableSpace in 1 until need) throw IOException("not enough space: ${need shr 20} MB needed, ${dir.usableSpace shr 20} MB free")
}
val archive = File(dir, "rootfs.download")
try {
progress("Downloading ${r.name}…", 0f)
val sum = http.download(r.url, archive, r.size) { progress("Downloading ${r.name}…", it) }
if (r.sha256 != null && !sum.equals(r.sha256, ignoreCase = true)) {
throw IOException("the download's checksum doesn't match (${sum.take(12)}…, not ${r.sha256.take(12)}…)")
}
progress("Unpacking ${r.name}…", null)
if (rootfs.exists()) Tar.removeTree(rootfs)
openArchive(archive).use { Tar.extract(it, rootfs) }
hoist()
if (!File(rootfs, "etc").isDirectory || !(File(rootfs, "bin").exists() || File(rootfs, "usr/bin").isDirectory)) {
throw IOException("that isn't a Linux root file system (no /etc and /bin in it)")
}
configure()
infoFile.writeText(
JSONObject().put("name", r.name).put("version", r.version).put("source", r.url)
.put("sha256", r.sha256 ?: "").put("installed", System.currentTimeMillis()).toString(2),
)
progress("Installed ${r.name}", 1f)
} catch (e: Exception) {
// (half a system is no use: nothing kept)
runCatching { Tar.removeTree(dir) }
throw e
} finally {
archive.delete()
}
}
/** the archive, uncompressed as its first bytes say: gzip, xz, or a plain tar */
private fun openArchive(f: File): InputStream {
val i = BufferedInputStream(f.inputStream(), 1 shl 16)
i.mark(8)
val head = ByteArray(6)
val n = i.read(head)
i.reset()
return when {
n >= 2 && head[0] == 0x1f.toByte() && head[1] == 0x8b.toByte() -> GZIPInputStream(i, 1 shl 16)
n >= 6 && head.contentEquals(byteArrayOf(0xfd.toByte(), '7'.code.toByte(), 'z'.code.toByte(), 'X'.code.toByte(), 'Z'.code.toByte(), 0)) ->
BufferedInputStream(XZInputStream(i), 1 shl 16)
n >= 3 && head[0] == 'B'.code.toByte() && head[1] == 'Z'.code.toByte() && head[2] == 'h'.code.toByte() -> {
i.close(); throw IOException("bzip2 archives aren't supported: use .tar.gz or .tar.xz")
}
n >= 4 && head[0] == 0x28.toByte() && head[1] == 0xb5.toByte() && head[2] == 0x2f.toByte() && head[3] == 0xfd.toByte() -> {
i.close(); throw IOException("zstd archives aren't supported: use .tar.gz or .tar.xz")
}
else -> i
}
}
/** a tarball with the system in one folder ("debian-rootfs/etc", …): its contents moved up */
private fun hoist() {
if (File(rootfs, "etc").isDirectory) return
val only = rootfs.listFiles()?.singleOrNull() ?: return
if (Files.isSymbolicLink(only.toPath()) || !File(only, "etc").isDirectory) return
val tmp = File(dir, "rootfs.hoist")
Files.move(only.toPath(), tmp.toPath())
Files.delete(rootfs.toPath())
Files.move(tmp.toPath(), rootfs.toPath())
}
/**
* Installed: downloaded, its checksum checked, unpacked and set up.
* [progress]: what it's doing, and how far (0..1) when it can tell.
* Its files set for this phone and for proot (again at each start):
* name servers, hosts, the prompt, mount points; apt and pacman told
* not to drop to users or sandboxes proot can't give them
*/
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")
// (a link to systemd's resolver, as many have it, replaced by a file)
File(etc, "resolv.conf").toPath().let { Files.deleteIfExists(it) }
File(etc, "resolv.conf").writeText(nameServers().joinToString("") { "nameserver $it\n" })
File(etc, "hosts").apply {
if (Files.isSymbolicLink(toPath()) || !exists() || !readText().contains("localhost")) {
Files.deleteIfExists(toPath())
writeText("127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n")
}
}
val mtab = File(etc, "mtab").toPath()
if (!Files.exists(mtab, LinkOption.NOFOLLOW_LINKS)) runCatching { Files.createSymbolicLink(mtab, Paths.get("/proc/self/mounts")) }
File(etc, "profile.d").mkdirs()
File(etc, "profile.d/dmodem.sh").writeText(PROFILE)
File(etc, "profile.d/dmodem.sh").writeText(profile(shortName()))
// apt: no dropping to the _apt user (proot's root can't)
if (File(etc, "apt").isDirectory) {
File(etc, "apt/apt.conf.d").mkdirs()
File(etc, "apt/apt.conf.d/99-dmodem-proot").writeText(
"// D-Modem: under proot, apt can't switch to its own user\nAPT::Sandbox::User \"root\";\n",
)
}
// pacman: no sandbox (Landlock) or disk space check (proot's mounts aren't the phone's)
File(etc, "pacman.conf").takeIf { it.isFile }?.let { conf ->
var t = conf.readText()
t = t.replace(Regex("(?m)^CheckSpace\\s*$"), "#CheckSpace")
if (!Regex("(?m)^DisableSandbox").containsMatchIn(t)) t = t.replaceFirst("[options]", "[options]\nDisableSandbox")
conf.writeText(t)
}
for (d in listOf("root", "tmp", "sdcard", "dev", "proc", "sys")) File(rootfs, d).mkdirs()
File(rootfs, "tmp").setWritable(true, false)
}
/** the prompt's host: the distribution's own short name */
private fun shortName(): String {
val osRelease = listOf("etc/os-release", "usr/lib/os-release").map { File(rootfs, it) }.firstOrNull { it.isFile }
val osId = osRelease?.readLines()?.firstOrNull { it.startsWith("ID=") }?.removePrefix("ID=")?.trim('"', ' ')
return (osId ?: id).replace(Regex("[^A-Za-z0-9._-]"), "").ifEmpty { "linux" }
}
/** root's login shell, as the system's /etc/passwd has it (where it is there), else /bin/sh */
fun loginShell(): String {
val passwd = File(rootfs, "etc/passwd")
val shell = runCatching { passwd.readLines().firstOrNull { it.startsWith("root:") }?.split(':')?.getOrNull(6) }.getOrNull()
return shell?.takeIf { it.startsWith("/") && existsInside(it) } ?: "/bin/sh"
}
/** [path] is in the system: its links followed as the system sees them (an absolute one from its own root) */
fun existsInside(path: String): Boolean {
var todo = ArrayDeque(path.split('/').filter { it.isNotEmpty() })
val at = ArrayList<String>()
var hops = 0
while (todo.isNotEmpty()) {
val c = todo.removeFirst()
if (c == ".") continue
if (c == "..") { at.removeLastOrNull(); continue }
val f = rootfs.toPath().resolve((at + c).joinToString("/"))
if (!Files.exists(f, LinkOption.NOFOLLOW_LINKS)) return false
if (Files.isSymbolicLink(f)) {
if (++hops > 40) return false
val t = Files.readSymbolicLink(f).toString()
if (t.startsWith("/")) at.clear()
todo = ArrayDeque(t.split('/').filter { it.isNotEmpty() } + todo)
} else {
at.add(c)
}
}
return true
}
/** the system removed, all of it (links removed, never followed: /sdcard's among them) */
fun remove() = Tar.removeTree(dir)
@@ -124,6 +235,7 @@ class LinuxSystem(
/** proot's command: the system's login shell, as root, in /root */
fun command(): List<String> {
val shell = loginShell()
val c = arrayListOf(
File(programDir, "libproot.so").path,
"--kill-on-exit",
@@ -142,7 +254,7 @@ class LinuxSystem(
"HOME" to "/root",
"USER" to "root",
"LOGNAME" to "root",
"SHELL" to "/bin/sh",
"SHELL" to shell,
"LANG" to "C.UTF-8",
"TERM" to "xterm-256color",
"COLORTERM" to "truecolor",
@@ -151,7 +263,7 @@ class LinuxSystem(
)
env.putAll(extraEnv)
for ((k, v) in env) c.add("$k=$v")
c.addAll(listOf("/bin/sh", "-l"))
c.addAll(listOf(shell, "-l"))
return c
}
@@ -168,79 +280,18 @@ class LinuxSystem(
/** 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")
if (!installed) throw IOException("$name 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\]\${'$'} '
/** a coloured prompt (bash's and busybox's sh's escapes), a few aliases */
fun profile(host: String) = """
|# D-Modem: rewritten at each start (put your own in /etc/profile.d/local.sh, or ~/.profile)
|PS1='\[\e[1;31m\]\u@$host\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\${'$'} '
|alias ls='ls --color=auto'
|alias ll='ls -l'
|alias la='ls -la'
@@ -177,19 +177,24 @@ 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? {
/** a shell in Linux system [id] opened in a new session: null, else why it can't be */
suspend fun openLinux(context: Context, id: String): String? {
val (cols, rows) = synchronized(session.emulator) { session.emulator.cols to session.emulator.rows }
val sys = Linux.system(context, id)
val link = try {
withContext(Dispatchers.IO) { Linux.system(context).link(cols, rows) }
withContext(Dispatchers.IO) { sys.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) {
// (the tab: the distribution's name without its version, numbered when there are more)
val short = sys.name.replace(Regex("\\s+[0-9(].*$"), "").removeSuffix(" Linux").ifEmpty { sys.name }
val n = _sessions.value.count { it.linuxId == id }
val s = TerminalSession(
link, label = if (n == 0) short else "$short ${n + 1}", kind = TerminalSession.Kind.LINUX, linuxId = id,
) {
app.getExternalFilesDir("captures")
}
s.charset = TermCharset.UTF8
@@ -219,7 +224,7 @@ object Terminal {
}
if (s.kind == TerminalSession.Kind.LINUX) {
close(s)
return openLinux(context)
return openLinux(context, s.linuxId ?: return "no Linux system")
}
val e = s.entry ?: return "nothing to reconnect to"
close(s)
@@ -27,6 +27,8 @@ class TerminalSession(
val kind: Kind = Kind.MODEM,
/** the directory entry it was opened from (SSH, Telnet) */
val entry: DialEntry? = null,
/** the Linux system it runs in (LINUX): its id */
val linuxId: String? = null,
/** where captures go */
private val captureDir: () -> File?,
) {
@@ -10,11 +10,20 @@ 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.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -28,150 +37,265 @@ 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.semantics.Role
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.Distro
import com.neodesktop.dmodem.local.Linux
import com.neodesktop.dmodem.local.LinuxSystem
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. */
/** The Linux systems: those installed (opened, removed), more added, the phone's storage in them. */
@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 }
var systems by remember { mutableStateOf<List<LinuxSystem>>(emptyList()) }
var sizes by remember { mutableStateOf<Map<String, Long>>(emptyMap()) }
LaunchedEffect(changes) {
systems = withContext(Dispatchers.IO) { Linux.systems(context) }
sizes = withContext(Dispatchers.IO) { systems.associate { it.id to Linux.size(it) } }
}
// (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) }
var removing by remember { mutableStateOf<LinuxSystem?>(null) }
var adding by remember { mutableStateOf(false) }
val askStorage = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { resumed++ }
val busy = work is Linux.Work.Busy
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)
if (Linux.machine() == null) {
Text("There is no Linux built 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 -> {}
if (systems.isEmpty()) {
Text(
"Linux in the terminal, run with proot: Alpine, Debian, Ubuntu, Fedora, Arch and more, each with its package manager.",
style = MaterialTheme.typography.bodySmall,
)
}
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()
for (sys in systems) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp)) {
Text(sys.name, style = MaterialTheme.typography.titleSmall)
Text(
listOfNotNull(sizes[sys.id]?.let { formatSize(it) }, sys.info?.source?.substringAfter("://")?.substringBefore('/')).joinToString(" · "),
style = MaterialTheme.typography.bodySmall,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(enabled = !busy, onClick = {
scope.launch {
val err = Terminal.openLinux(context, sys.id)
if (err != null) Toast.makeText(context, err, Toast.LENGTH_LONG).show() else onOpened()
}
}) { Text("Open a shell") }
TextButton(enabled = !busy, onClick = { removing = sys }) { Text("Remove") }
}
}) { 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") }
}
}
}
WorkLine(work)
OutlinedButton(enabled = !busy, onClick = { Linux.clearFailure(); adding = true }) {
Text(if (systems.isEmpty()) "Install a Linux" else "Add another 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) {
if (want != storage) {
val i = Linux.storageSettingsIntent(context)
if (i != null) {
runCatching { context.startActivity(i) }
} else {
} else if (want) {
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 (systems.isNotEmpty()) {
Text("In each: /root is home, /sdcard the phone's storage.", style = MaterialTheme.typography.bodySmall)
}
}
if (removing) {
removing?.let { sys ->
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.") },
onDismissRequest = { removing = null },
title = { Text("Remove ${sys.name}?") },
text = { Text("All of it goes: what was installed in it, and the files in its /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)
removing = null
Terminal.sessions.value.filter { it.linuxId == sys.id }.forEach { Terminal.close(it) }
Linux.remove(context, sys.id)
}) { Text("Remove", color = MaterialTheme.colorScheme.error) }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
dismissButton = { TextButton(onClick = { removing = null }) { Text("Cancel") } },
)
}
if (adding) {
AddLinuxDialog(
onInstalled = { sys ->
adding = false
scope.launch {
val err = Terminal.openLinux(context, sys.id)
if (err != null) Toast.makeText(context, err, Toast.LENGTH_LONG).show() else onOpened()
}
},
onDismiss = { adding = false },
)
}
}
/** asked for a Linux shell before Linux is installed: installed here, then opened */
@Composable
fun LinuxInstallDialog(onInstalled: () -> Unit, onDismiss: () -> Unit) {
private fun WorkLine(work: Linux.Work) {
when (work) {
is Linux.Work.Busy -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(work.what, style = MaterialTheme.typography.bodySmall)
if (work.fraction != null) LinearProgressIndicator(progress = { work.fraction }, modifier = Modifier.fillMaxWidth())
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
is Linux.Work.Failed -> Text("Failed: ${work.why}", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
Linux.Work.Idle -> {}
}
}
/**
* A Linux to install: one of the catalog's (those built for this phone's
* processor), or a root file system from any URL (with its SHA-256, if
* known); installed here, then [onInstalled]
*/
@Composable
fun AddLinuxDialog(onInstalled: (LinuxSystem) -> 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()
var available by remember { mutableStateOf<Map<String, Boolean>?>(null) }
var installed by remember { mutableStateOf<Set<String>>(emptySet()) }
LaunchedEffect(Unit) {
installed = withContext(Dispatchers.IO) { Linux.systems(context).map { it.id }.toSet() }
available = withContext(Dispatchers.IO) { Linux.available(context) }
}
var picked by remember { mutableStateOf<String?>(null) }
// the install this dialog started: opened when Linux says it's done
var started by remember { mutableStateOf<String?>(null) }
val done by Linux.done.collectAsStateWithLifecycle()
LaunchedEffect(done, started) {
val id = started
if (id != null && done == id) {
started = null
onInstalled(Linux.system(context, id))
}
}
var customName by remember { mutableStateOf("") }
var customUrl by remember { mutableStateOf("") }
var customSha by remember { mutableStateOf("") }
val custom = picked == CUSTOM
val urlOk = customUrl.trim().let { it.startsWith("https://") || it.startsWith("http://") }
val shaOk = customSha.isBlank() || customSha.trim().matches(Regex("[0-9a-fA-F]{64}"))
val busy = work is Linux.Work.Busy
val ready = !busy && when {
custom -> customName.isNotBlank() && urlOk && shaOk && Distro.customId(customName) !in installed
else -> picked != null
}
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Install Alpine Linux?") },
title = { Text("Install a 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 -> {}
Column(Modifier.heightIn(max = 560.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(2.dp)) {
for (d in Distro.CATALOG) {
val can = available?.get(d.id) != false && d.id !in installed
Choice(
title = d.name,
about = when {
d.id in installed -> "Installed"
available?.get(d.id) == false -> "Not built for this phone's processor"
else -> d.about
},
selected = picked == d.id, enabled = can && !busy,
) { picked = d.id }
}
HorizontalDivider(Modifier.padding(vertical = 4.dp))
Choice("From a URL…", "A root file system tarball: .tar, .tar.gz or .tar.xz", custom, !busy) { picked = CUSTOM }
if (custom) {
OutlinedTextField(customName, { customName = it }, label = { Text("Name") }, singleLine = true, modifier = Modifier.fillMaxWidth())
OutlinedTextField(
customUrl, { customUrl = it.trim() }, label = { Text("URL") }, singleLine = true, modifier = Modifier.fillMaxWidth(),
isError = customUrl.isNotEmpty() && !urlOk,
)
OutlinedTextField(
customSha, { customSha = it.trim() }, label = { Text("SHA-256 (optional, checked if given)") }, singleLine = true,
modifier = Modifier.fillMaxWidth(), isError = !shaOk,
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
)
if (Distro.customId(customName) in installed) {
Text("One by that name is installed already", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
}
WorkLine(work)
}
},
confirmButton = {
TextButton(enabled = work !is Linux.Work.Busy, onClick = {
started = true
TextButton(enabled = ready, onClick = {
val d = if (custom) {
Distro.Custom(Distro.customId(customName), customName.trim(), customUrl.trim(), customSha.trim().ifEmpty { null })
} else {
Distro.byId(picked!!) ?: return@TextButton
}
Linux.clearFailure()
Linux.install(context)
}) { Text(if (work is Linux.Work.Failed) "Try again" else "Install") }
started = d.id
Linux.install(context, d)
}) { Text("Install") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(if (work is Linux.Work.Busy) "Hide" else "Cancel") } },
dismissButton = { TextButton(onClick = onDismiss) { Text(if (busy) "Hide" else "Cancel") } },
)
}
/** asked for a Linux shell with more than one installed: which */
@Composable
fun PickLinuxDialog(systems: List<LinuxSystem>, onPick: (LinuxSystem) -> Unit, onAdd: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Open a Linux shell") },
text = {
Column {
for (sys in systems) {
TextButton(onClick = { onPick(sys) }, modifier = Modifier.fillMaxWidth()) {
Text(sys.name, Modifier.fillMaxWidth())
}
}
}
},
confirmButton = { TextButton(onClick = onAdd) { Text("Install another…") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun Choice(title: String, about: String, selected: Boolean, enabled: Boolean, onPick: () -> Unit) {
Row(
Modifier.fillMaxWidth().selectable(selected = selected, enabled = enabled, role = Role.RadioButton, onClick = onPick).padding(vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected = selected, onClick = null, enabled = enabled)
Column(Modifier.padding(start = 8.dp)) {
Text(title, style = MaterialTheme.typography.bodyLarge, color = if (enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant)
Text(about, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
private const val CUSTOM = "\u0000custom"
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())
@@ -78,6 +78,8 @@ import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import java.io.File
/** The terminal on the modem: the screen, a bar of what's going on and its actions, the extra keys. */
@@ -105,6 +107,7 @@ fun TerminalScreen(
var showSnippets by remember { mutableStateOf(false) }
var showSsh by remember { mutableStateOf(false) }
var showLinuxInstall by remember { mutableStateOf(false) }
var pickLinux by remember { mutableStateOf<List<com.neodesktop.dmodem.local.LinuxSystem>?>(null) }
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
@@ -144,10 +147,13 @@ fun TerminalScreen(
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
scope.launch {
val systems = withContext(Dispatchers.IO) { Linux.systems(context) }
when (systems.size) {
0 -> showLinuxInstall = true
1 -> Terminal.openLinux(context, systems[0].id)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
else -> pickLinux = systems
}
}
},
onNewShell = {
@@ -227,14 +233,25 @@ fun TerminalScreen(
}
if (showLinuxInstall) {
LinuxInstallDialog(
onInstalled = {
AddLinuxDialog(
onInstalled = { sys ->
showLinuxInstall = false
scope.launch { Terminal.openLinux(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
scope.launch { Terminal.openLinux(context, sys.id)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
},
onDismiss = { showLinuxInstall = false },
)
}
pickLinux?.let { systems ->
PickLinuxDialog(
systems,
onPick = { sys ->
pickLinux = null
scope.launch { Terminal.openLinux(context, sys.id)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
},
onAdd = { pickLinux = null; showLinuxInstall = true },
onDismiss = { pickLinux = null },
)
}
if (showSsh && ssh != null) {
SshSessionDialog(ssh) { showSsh = false }
}
@@ -380,7 +397,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() })
DropdownMenuItem(text = { Text("New Linux shell…") }, onClick = { menu = false; onNewLinux() })
if (onSsh != null) {
DropdownMenuItem(text = { Text("Port forwards, agent, keys") }, onClick = { menu = false; onSsh() })
}
@@ -0,0 +1,220 @@
// 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.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.tukaani.xz.LZMA2Options
import org.tukaani.xz.XZOutputStream
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.security.MessageDigest
import java.util.zip.GZIPOutputStream
private fun sha256(f: File) = MessageDigest.getInstance("SHA-256").digest(f.readBytes()).joinToString("") { "%02x".format(it) }
/**
* The distributions' sources read (from made-up indexes: no network), and
* root file systems installed from local tarballs as the downloads would
* bring them. (Robolectric for org.json.)
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35])
class DistrosTest {
@get:Rule
val tmp = TemporaryFolder()
private val arm64 = Machine.forAbi("arm64-v8a")!!
/** URLs answered from a map, downloads copied from local files */
private class FakeHttp(val pages: Map<String, String>, val files: Map<String, File> = emptyMap()) : Http() {
val asked = ArrayList<String>()
override fun text(url: String): String { asked.add(url); return pages[url] ?: throw IOException("404 $url") }
override fun size(url: String): Long = files[url]?.length() ?: -1
override fun download(url: String, to: File, size: Long, progress: (Float) -> Unit): String {
val f = files[url] ?: throw IOException("404 $url")
f.copyTo(to, overwrite = true)
progress(1f)
return sha256(f)
}
}
private val index = """
debian;bookworm;arm64;default;20261016_05:24;/images/debian/bookworm/arm64/default/20261016_05:24/
debian;trixie;arm64;cloud;20261016_05:24;/images/debian/trixie/arm64/cloud/20261016_05:24/
debian;trixie;arm64;default;20261016_05:24;/images/debian/trixie/arm64/default/20261016_05:24/
debian;trixie;amd64;default;20261016_05:24;/images/debian/trixie/amd64/default/20261016_05:24/
fedora;43;arm64;default;20261015_20:33;/images/fedora/43/arm64/default/20261015_20:33/
fedora;44;arm64;default;20261015_20:33;/images/fedora/44/arm64/default/20261015_20:33/
fedora;9;arm64;default;20261015_20:33;/images/fedora/9/arm64/default/x/
archlinux;current;amd64;default;20261016_04:18;/images/archlinux/current/amd64/default/20261016_04:18/
""".trimIndent()
@Test
fun theLinuxContainersIndex() {
val rows = Distro.parseLxcIndex(index)
assertEquals(8, rows.size)
val sha = "a".repeat(64)
val dir = "${Distro.LXC_MIRROR}/images/fedora/44/arm64/default/20261015_20:33"
val http = FakeHttp(
mapOf(
"${Distro.LXC_MIRROR}/meta/1.0/index-system" to index,
"$dir/SHA256SUMS" to "$sha rootfs.tar.xz\n${"b".repeat(64)} rootfs.squashfs\n",
),
)
// the newest Fedora (44, not 9: numbers compared as numbers)
val r = Distro.byId("fedora")!!.resolve(arm64, http)
assertEquals("$dir/rootfs.tar.xz", r.url)
assertEquals(sha, r.sha256)
assertEquals("Fedora 44", r.name)
// Debian's named release, and only for the machines it's built for
val debian = Distro.byId("debian") as Distro.Lxc
assertTrue(debian.availableFor(arm64, rows))
assertFalse(debian.availableFor(Machine.forAbi("armeabi-v7a")!!, rows))
assertFalse((Distro.byId("archlinux") as Distro.Lxc).availableFor(arm64, rows))
val e = runCatching { Distro.byId("archlinux")!!.resolve(arm64, http) }.exceptionOrNull()
assertTrue(e?.message, e?.message!!.contains("isn't built for this phone's processor"))
}
@Test
fun ubuntusNewestPointRelease() {
val base = "${Distro.UBUNTU_MIRROR}/24.04/release"
val http = FakeHttp(
mapOf(
"$base/SHA256SUMS" to """
${"1".repeat(64)} *ubuntu-base-24.04.3-base-arm64.tar.gz
${"2".repeat(64)} *ubuntu-base-24.04.10-base-arm64.tar.gz
${"3".repeat(64)} *ubuntu-base-24.04.5-base-arm64.tar.gz
${"4".repeat(64)} *ubuntu-base-24.04.11-base-amd64.tar.gz
""".trimIndent(),
),
)
val r = Distro.byId("ubuntu")!!.resolve(arm64, http)
assertEquals("$base/ubuntu-base-24.04.10-base-arm64.tar.gz", r.url)
assertEquals("2".repeat(64), r.sha256)
assertEquals("Ubuntu 24.04.10 LTS", r.name)
}
@Test
fun customNames() {
assertEquals("custom-my-arch-build-2", Distro.customId("My Arch build #2"))
assertEquals("custom-linux", Distro.customId("!!!"))
}
// installs from local tarballs ----------------------------------------
/** a tiny system: what an apt distribution's image has, under [top] if given */
private fun tree(top: String? = null): File {
val t = tmp.newFolder()
val root = if (top != null) File(t, top).apply { mkdirs() } else t
File(root, "usr/bin").mkdirs()
File(root, "usr/bin/bash").writeText("#!bash\n")
File(root, "usr/bin/env").writeText("#!env\n")
// usrmerge: /bin a relative link to usr/bin
Files.createSymbolicLink(File(root, "bin").toPath(), Paths.get("usr/bin"))
File(root, "etc/apt/apt.conf.d").mkdirs()
File(root, "etc/passwd").writeText("root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1::/:/usr/sbin/nologin\n")
File(root, "etc/os-release").writeText("PRETTY_NAME=\"Debian GNU/Linux 13 (trixie)\"\nID=debian\n")
Files.createSymbolicLink(File(root, "etc/resolv.conf").toPath(), Paths.get("../run/systemd/resolve/stub-resolv.conf"))
File(root, "etc/pacman.conf").writeText("[options]\nHoldPkg = pacman\nCheckSpace\n\n[core]\nInclude = x\n")
return t
}
private fun tar(dir: File, compress: String): File {
assumeTrue("no tar here", File("/usr/bin/tar").canExecute() || File("/bin/tar").canExecute())
val plain = File(tmp.root, "t-${System.nanoTime()}.tar")
val p = ProcessBuilder("tar", "-cf", plain.path, "-C", dir.path, ".").redirectErrorStream(true).start()
p.waitFor()
assertEquals(0, p.exitValue())
return when (compress) {
"gz" -> File(plain.path + ".gz").also { o -> GZIPOutputStream(o.outputStream()).use { it.write(plain.readBytes()) } }
"xz" -> File(plain.path + ".xz").also { o -> XZOutputStream(o.outputStream(), LZMA2Options()).use { it.write(plain.readBytes()) } }
else -> plain
}
}
private fun system(id: String) = LinuxSystem(File(tmp.root, "linux/$id"), tmp.root, tmp.newFolder(), nameServers = { listOf("10.0.0.53") })
@Test
fun installedFromEachKindOfArchive() {
for (kind in listOf("gz", "xz", "tar")) {
val f = tar(tree(top = if (kind == "xz") "debian-rootfs" else null), kind)
val url = "https://example.org/rootfs.$kind"
val sys = system("test-$kind")
sys.install(Rootfs(url, sha256(f), f.length(), "Test $kind", "1"), FakeHttp(emptyMap(), mapOf(url to f)))
assertTrue(kind, sys.installed)
assertEquals("Test $kind", sys.name)
// (xz's had its system in one folder: moved up)
assertTrue(kind, File(sys.rootfs, "etc/passwd").isFile)
assertFalse(File(sys.dir, "rootfs.download").exists())
}
}
@Test
fun setUpForProot() {
val f = tar(tree(), "gz")
val url = "https://example.org/r.tar.gz"
val sys = system("debian")
sys.install(Rootfs(url, null, -1, "Debian", "13"), FakeHttp(emptyMap(), mapOf(url to f)))
val etc = File(sys.rootfs, "etc")
// the resolver: a file, not systemd's link
assertFalse(Files.isSymbolicLink(File(etc, "resolv.conf").toPath()))
assertEquals("nameserver 10.0.0.53\n", File(etc, "resolv.conf").readText())
assertTrue(File(etc, "apt/apt.conf.d/99-dmodem-proot").readText().contains("APT::Sandbox::User \"root\";"))
val pacman = File(etc, "pacman.conf").readText()
assertTrue(pacman, pacman.contains("[options]\nDisableSandbox") && pacman.contains("#CheckSpace"))
sys.configure()
assertEquals("again: once", 1, Regex("DisableSandbox").findAll(File(etc, "pacman.conf").readText()).count())
assertEquals("/proc/self/mounts", Files.readSymbolicLink(File(etc, "mtab").toPath()).toString())
assertTrue(File(etc, "profile.d/dmodem.sh").readText().contains("\\u@debian"))
// root's shell: bash, found through the /bin -> usr/bin link
assertEquals("/bin/bash", sys.loginShell())
assertTrue(sys.command().takeLast(2) == listOf("/bin/bash", "-l"))
assertTrue(sys.existsInside("/usr/bin/../bin/env"))
assertFalse(sys.existsInside("/bin/zsh"))
// an absolute link: resolved inside, not on the host
Files.createSymbolicLink(File(sys.rootfs, "usr/bin/sh").toPath(), Paths.get("/usr/bin/bash"))
assertTrue(sys.existsInside("/bin/sh"))
Files.createSymbolicLink(File(sys.rootfs, "usr/bin/host-only").toPath(), Paths.get(tmp.root.path))
assertFalse(sys.existsInside("/bin/host-only/linux"))
}
@Test
fun aWrongChecksumOrNotASystemLeavesNothing() {
val f = tar(tree(), "gz")
val url = "https://example.org/r.tar.gz"
val sys = system("bad")
val e = runCatching { sys.install(Rootfs(url, "0".repeat(64), -1, "Bad", "1"), FakeHttp(emptyMap(), mapOf(url to f))) }.exceptionOrNull()
assertTrue(e?.message, e?.message!!.contains("checksum doesn't match"))
assertFalse(sys.dir.exists())
// a tarball of something else
val other = tmp.newFolder().apply { File(this, "README").writeText("hi") }
val g = tar(other, "gz")
val e2 = runCatching { sys.install(Rootfs(url, null, -1, "Not Linux", "1"), FakeHttp(emptyMap(), mapOf(url to g))) }.exceptionOrNull()
assertTrue(e2?.message, e2?.message!!.contains("isn't a Linux root file system"))
assertFalse(sys.installed)
assertNull(sys.info)
}
@Test
fun theFirstReleasesAlpineStillKnown() {
val sys = system("alpine")
File(sys.rootfs, "etc").mkdirs()
File(sys.rootfs, "etc/alpine-release").writeText("3.22.6\n")
File(sys.dir, ".installed").writeText("3.22.6\n")
assertTrue(sys.installed)
assertEquals("Alpine Linux 3.22.6", sys.name)
}
}
@@ -3,84 +3,100 @@
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.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
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.
* Linux systems in the local terminal, as the app runs them, on this host:
* proot built for it by native-proot/build.sh, root file systems
* downloaded from their sources (where they can be reached), shells on a
* pty, each distribution's package manager adding a package (Lua) and
* running it.
*
* Alpine always (3 MB), and a custom URL's (the Linux Containers' Alpine,
* an .xz); the others named in DMODEM_DISTROS ("debian,fedora", or "all"):
* they are big. What only a phone can tell (its SELinux rules, its /proc)
* isn't here. (Robolectric for org.json.)
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35])
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"
/** set up once for the class: proot built, the storage folder, Alpine installed */
private object Setup {
lateinit var base: File
lateinit var programs: File
lateinit var storage: File
lateinit var alpine: LinuxSystem
var done = false
var skipped: String? = null
val machine = when (System.getProperty("os.arch")) {
"amd64", "x86_64" -> Machine.forAbi("x86_64")
"aarch64" -> Machine.forAbi("arm64-v8a")
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
}
/** this host's proxy for the package managers 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 }
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"))
/** behind a proxy that re-signs TLS: its CA added to the system's own bundles (the test's doing, not the app's) */
private fun trustHostCa(sys: LinuxSystem) {
val ca = File("/etc/ssl/certs/ca-certificates.crt")
if (proxyEnv().isEmpty() || !ca.exists()) return
for (b in listOf("etc/ssl/certs/ca-certificates.crt", "etc/pki/tls/certs/ca-bundle.crt", "etc/ssl/ca-bundle.pem", "etc/ca-certificates/extracted/tls-ca-bundle.pem", "etc/ssl/cert.pem")) {
val f = File(sys.rootfs, b)
if (f.isFile && !Files.isSymbolicLink(f.toPath())) f.appendText("\n" + ca.readText())
}
}
@AfterClass
@JvmStatic
fun cleanUp() {
if (::base.isInitialized) Tar.removeTree(base)
private fun newSystem(id: String) = LinuxSystem(
File(Setup.base, id), Setup.programs, File(Setup.base, "tmp"),
storage = { Setup.storage }, nameServers = { listOf("9.9.9.9") }, extraEnv = proxyEnv(),
)
@Before
fun setUp() {
Setup.skipped?.let { assumeTrue(it, false) }
if (Setup.done) return
fun skip(why: String) { Setup.skipped = why; assumeTrue(why, false) }
if (Setup.machine == null) skip("no Linux for ${System.getProperty("os.arch")}")
if (!runCatching { URL(Distro.ALPINE_MIRROR).openConnection().apply { connectTimeout = 10_000 }.getInputStream().close(); true }.getOrDefault(false)) skip("Alpine can't be reached")
for (tool in listOf("cc", "make", "gawk", "curl")) {
if (System.getenv("PATH").split(':').none { File(it, tool).canExecute() }) skip("$tool isn't installed (to build proot)")
}
Pty.load(LocalShellTest.hostPty())
Setup.base = Files.createTempDirectory("linux").toFile().apply { deleteOnExit() }
Setup.programs = File(Setup.base, "lib")
val script = listOf(File("../native-proot/build.sh"), File("native-proot/build.sh")).first { it.exists() }
val p = ProcessBuilder(script.path, "host", Setup.programs.path).redirectErrorStream(true).start()
val log = p.inputStream.readBytes().decodeToString()
p.waitFor(10, TimeUnit.MINUTES)
assertEquals(log, 0, p.exitValue())
Setup.storage = File(Setup.base, "storage").apply { mkdirs() }
File(Setup.storage, "Download").mkdirs()
File(Setup.storage, "Download/from-the-phone.txt").writeText("hello from shared storage\n")
Setup.alpine = newSystem("alpine")
val steps = ArrayList<String>()
Setup.alpine.install(Distro.Alpine().resolve(Setup.machine!!, Http()), Http()) { what, _ -> if (steps.lastOrNull() != what) steps.add(what) }
assertTrue(steps.toString(), steps.last().startsWith("Installed Alpine Linux"))
trustHostCa(Setup.alpine)
Setup.done = true
}
/** the shell's output, its colours left out; the cursor's position told when asked (busybox's shell asks, as a terminal answers) */
@@ -91,52 +107,51 @@ class LinuxSystemTest {
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]"), "") }
val text get() = synchronized(sb) { sb.toString().replace(Regex("\u001b\\[[0-9;?]*[A-Za-z]|\u001b\\][^\u0007]*\u0007"), "") }
}
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)
private fun shell(sys: LinuxSystem): Pair<LocalLink, Screen> {
val l = sys.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) {
private fun waitFor(what: String, s: Screen, secs: Int = 30, 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)
if (System.currentTimeMillis() > end) throw AssertionError("$what; the screen:\n${s.text.takeLast(3000)}")
Thread.sleep(50)
}
}
@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") })
fun alpineInstalledAndSetUp() {
val sys = Setup.alpine
assertTrue(sys.installed)
assertTrue(sys.name, sys.name.matches(Regex("Alpine Linux 3\\.22\\.\\d+")))
assertEquals("nameserver 9.9.9.9\n", File(sys.rootfs, "etc/resolv.conf").readText())
assertTrue(File(sys.rootfs, "etc/profile.d/dmodem.sh").readText().contains("@alpine"))
// made-up /proc files only for those Android hides (none hidden here)
assertFalse(sys.command().any { it.endsWith(":/proc/stat") })
val hidden = LinuxSystem(sys.dir, Setup.programs, File(Setup.base, "tmp"), readable = { !it.path.endsWith("stat") })
assertTrue(hidden.command().any { it.endsWith(":/proc/stat") })
}
@Test
fun aRootShellWithThePhonesStorage() {
val (l, s) = shell()
val (l, s) = shell(Setup.alpine)
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())
l.write("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")
val back = File(Setup.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()
val hostname = File(Setup.alpine.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
@@ -145,24 +160,90 @@ class LinuxSystemTest {
}
@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") }
fun apkAddsPackages() = packageManager(Setup.alpine, "alpine")
/** a package added with the system's own package manager, and run */
private fun packageManager(sys: LinuxSystem, id: String) {
val (l, s) = shell(sys)
waitFor("the prompt", s, 60) { it.contains("root@") }
val cmd = INSTALL_LUA[id] ?: throw AssertionError("no command for $id")
l.write("$cmd && \$LUA -e 'print(\"lua says \" .. 6*7)'\r".toByteArray())
waitFor("Lua from $id's package manager", s, secs = 900) { it.contains("lua says 42") }
l.close()
}
/** a custom URL's: the Linux Containers' Alpine (an .xz), with its checksum */
@Test
fun fromACustomUrl() {
val m = Setup.machine!!
val row = Distro.lxcIndex(Http()).first { it.distro == "alpine" && it.arch == m.lxc && it.variant == "default" && it.release.startsWith("3.") }
val dir = Distro.LXC_MIRROR + row.path.trimEnd('/')
val sha = Regex("([0-9a-f]{64})\\s+rootfs\\.tar\\.xz").find(Http().text("$dir/SHA256SUMS"))!!.groupValues[1]
val d = Distro.Custom(Distro.customId("My Alpine"), "My Alpine", "$dir/rootfs.tar.xz", sha)
val sys = newSystem(d.id)
sys.install(d.resolve(m, Http()), Http())
assertEquals("My Alpine", sys.name)
val (l, s) = shell(sys)
waitFor("its shell", s) { it.contains("root@alpine") }
l.write("cat /etc/alpine-release\r".toByteArray())
waitFor("its release", s) { it.contains("\r\n${row.release}.") }
l.close()
sys.remove()
assertFalse(sys.dir.exists())
}
/** the big ones, each named in DMODEM_DISTROS: installed, a shell, Lua from its package manager, removed */
@Test
fun otherDistributions() {
val want = System.getenv("DMODEM_DISTROS")?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()
assumeTrue("DMODEM_DISTROS names none", want.isNotEmpty())
val ids = if (want == listOf("all")) Distro.CATALOG.map { it.id } - "alpine" else want
val failures = ArrayList<String>()
for (id in ids) {
val d = Distro.byId(id) ?: throw AssertionError("no distribution $id")
val sys = newSystem(id)
val t0 = System.currentTimeMillis()
try {
val r = d.resolve(Setup.machine!!, Http())
sys.install(r, Http())
trustHostCa(sys)
println("DISTRO $id: ${sys.name}, shell ${sys.loginShell()}, installed in ${(System.currentTimeMillis() - t0) / 1000}s")
packageManager(sys, id)
println("DISTRO $id: package manager works (${(System.currentTimeMillis() - t0) / 1000}s)")
} catch (e: Throwable) {
failures.add("$id: ${e.message?.take(1500)}")
} finally {
runCatching { sys.remove() }
}
}
assertTrue(failures.joinToString("\n\n"), failures.isEmpty())
}
@Test
fun removedLeavingTheStorage() {
val other = LinuxSystem(File(base, "other"), programs, File(base, "tmp2"), system.arch, storage = { storage })
File(other.rootfs, "bin").mkdirs()
val other = newSystem("other")
File(other.rootfs, "etc").mkdirs()
File(other.dir, ".installed").writeText("x")
Files.createSymbolicLink(File(other.rootfs, "phone").toPath(), storage.toPath())
Files.createSymbolicLink(File(other.rootfs, "phone").toPath(), Setup.storage.toPath())
other.remove()
assertFalse(other.dir.exists())
assertTrue(File(storage, "Download/from-the-phone.txt").exists())
assertTrue(File(Setup.storage, "Download/from-the-phone.txt").exists())
}
companion object {
/** Lua installed, its command in $LUA, quietly: each package manager's way */
val INSTALL_LUA = mapOf(
"alpine" to "apk update -q && apk add -q lua5.4 && LUA=lua5.4",
"debian" to "apt-get update -qq && apt-get install -y -qq --no-install-recommends lua5.4 >/dev/null && LUA=lua5.4",
"ubuntu" to "apt-get update -qq && apt-get install -y -qq --no-install-recommends lua5.4 >/dev/null && LUA=lua5.4",
"kali" to "apt-get update -qq && apt-get install -y -qq --no-install-recommends lua5.4 >/dev/null && LUA=lua5.4",
"devuan" to "apt-get update -qq && apt-get install -y -qq --no-install-recommends lua5.4 >/dev/null && LUA=lua5.4",
"fedora" to "dnf install -y -q lua >/dev/null && LUA=lua",
"rocky" to "dnf install -y -q lua >/dev/null && LUA=lua",
"alma" to "dnf install -y -q lua >/dev/null && LUA=lua",
"archlinux" to "pacman -Sy --noconfirm --needed lua >/dev/null && LUA=lua",
"opensuse" to "zypper -n -q --gpg-auto-import-keys in -y lua54 >/dev/null && LUA=lua5.4",
"void" to "xbps-install -Syu xbps >/dev/null; xbps-install -Sy lua54 >/dev/null && LUA=lua5.4",
)
}
}
@@ -14,7 +14,8 @@ 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.Distro
import com.neodesktop.dmodem.local.Machine
import com.neodesktop.dmodem.local.LocalShellTest
import com.neodesktop.dmodem.local.Pty
import com.neodesktop.dmodem.local.Tar
@@ -48,7 +49,7 @@ class LinuxUiTest {
@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))
assumeTrue("Alpine can't be reached", runCatching { URL(Distro.ALPINE_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() })
}
@@ -63,7 +64,7 @@ class LinuxUiTest {
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 }) }
Linux.place = { Linux.Place(File(base, "linux"), programs, File(base, "tmp"), Machine.forAbi("x86_64"), storage = { storage }) }
}
@After
@@ -93,20 +94,35 @@ class LinuxUiTest {
@Test
fun installedFromSettingsAndUsed() {
compose.onNode(hasText("Settings") and isSelectable()).performClick()
compose.onNodeWithText("Install Alpine Linux").performScrollTo()
compose.onNodeWithText("Install a 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 }
compose.onNodeWithText("Install a Linux").performClick()
// the catalog, those built for this machine known from the index
compose.waitUntil(30_000) { compose.onAllNodesWithText("RHEL-compatible", substring = true).fetchSemanticsNodes().isNotEmpty() }
compose.waitForIdle()
saveDialog("linux-2-catalog")
compose.onNodeWithText("Alpine Linux").performClick()
compose.onNodeWithText("Install").performClick()
// installed, its shell opened in the terminal
compose.waitUntil(180_000) { Terminal.active.value?.kind == TerminalSession.Kind.LINUX }
val s = Terminal.active.value!!
assertEquals("alpine", s.linuxId)
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")
// Settings lists it
compose.onNode(hasText("Settings") and isSelectable()).performClick()
compose.onNodeWithText("Add another Linux").performScrollTo()
compose.waitUntil(10_000) { compose.onAllNodesWithText("Alpine Linux 3.", substring = true).fetchSemanticsNodes().isNotEmpty() }
shot("linux-4-installed")
}
private fun saveDialog(name: String) {
val bmp = compose.onNode(androidx.compose.ui.test.isDialog()).captureToImage().asAndroidBitmap()
File("build/screens").mkdirs()
File("build/screens/$name.png").outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
}
}
+2
View File
@@ -9,6 +9,7 @@ datastore = "1.2.1"
junit = "4.13.2"
robolectric = "4.17"
sshj = "0.41.2"
xz = "1.10"
bouncycastle = "1.86"
mina-sshd = "2.20.0"
androidxTestCore = "1.7.0"
@@ -32,6 +33,7 @@ compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
junit = { module = "junit:junit", version.ref = "junit" }
robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
sshj = { module = "com.hierynomus:sshj", version.ref = "sshj" }
xz = { module = "org.tukaani:xz", version.ref = "xz" }
bcprov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
bcpkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" }
mina-sshd-core = { module = "org.apache.sshd:sshd-core", version.ref = "mina-sshd" }