Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 50 additions & 34 deletions controller/app/src/main/java/org/iiab/controller/PRootEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,21 @@
import org.iiab.controller.network.data.FileResolvConfWriter;
import org.iiab.controller.network.data.PrefsDnsConfigRepository;
import org.iiab.controller.network.domain.ApplyDnsUseCase;
import org.iiab.controller.proot.data.PrefsSeccompModeRepository;
import org.iiab.controller.proot.data.ProotEnvironment;
import org.iiab.controller.proot.domain.SeccompFailure;
import org.iiab.controller.proot.domain.SeccompMode;

public class PRootEngine {
private static final String TAG = "IIAB-PRootEngine";

/**
* ADFA-5362: how much of a launch's output to keep for {@link SeccompFailure}. An install
* streams megabytes, so this is a tail, not a buffer of everything — and a tail is the right
* end anyway, because the abort we look for is what ends the process.
*/
private static final int TAIL_LIMIT = 8192;

private volatile Process currentProcess;
private volatile java.io.OutputStream processOutputStream;

Expand All @@ -41,6 +53,9 @@ public interface OutputListener {

public void executeInContainer(Context context, String rootfsDir, String command, OutputListener listener) {
new Thread(() -> {
// ADFA-5362: how proot must run here is remembered per device, defaulting to the fast path.
PrefsSeccompModeRepository capability = new PrefsSeccompModeRepository(context);
SeccompMode mode = capability.load();
try {
File nativeDir = new File(context.getApplicationInfo().nativeLibraryDir);
File prootBinary = new File(nativeDir, "libproot.so");
Expand Down Expand Up @@ -177,26 +192,11 @@ public void executeInContainer(Context context, String rootfsDir, String command
// =========================================================
// INJECT ENVIRONMENT VARIABLES
// =========================================================
// ADFA-5362: the environment is built in one place for every proot launch, so the
// app and the terminal cannot drift apart on the same phone.
pb.environment().clear(); // Clean toxic Android vars

// Tell PRoot where to find our Fake Termux Prefix
pb.environment().put("PREFIX", prefixDir.getCanonicalPath());

// Fallback environment variables for modern PRoot versions
if (loaderBinary.exists())
pb.environment().put("PROOT_LOADER", loaderBinary.getAbsolutePath());
File loader32 = new File(nativeDir, "libproot-loader32.so");
if (loader32.exists())
pb.environment().put("PROOT_LOADER_32", loader32.getAbsolutePath());

pb.environment().put("PROOT_TMP_DIR", prootTmpPath);
pb.environment().put("TMPDIR", "/tmp");
pb.environment().put("HOME", "/root");
pb.environment().put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
pb.environment().put("TERM", "xterm-256color");
pb.environment().put("LANG", "C.UTF-8");
pb.environment().put("USER", "root");
pb.environment().put("LOGNAME", "root");
pb.environment().putAll(ProotEnvironment.build(
nativeDir, prefixDir.getCanonicalPath(), prootTmpPath, mode));

// ADFA-4458: wait on THIS call's process, not the shared field, so a
// concurrent proot call can't make us return on the wrong process.
Expand All @@ -207,15 +207,30 @@ public void executeInContainer(Context context, String rootfsDir, String command
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
Handler mainHandler = new Handler(Looper.getMainLooper());
StringBuilder tail = new StringBuilder();

while ((line = reader.readLine()) != null) {
final String outLine = line;
Log.i("IIAB-Ansible", "[Debian] " + outLine); // Funneled straight to Logcat!
appendTail(tail, outLine);
mainHandler.post(() -> listener.onOutputLine(outLine));
}

int exitCode = proc.waitFor();

// ADFA-5362: proot has told us this kernel cannot run it with seccomp. Record it and
// report the failure as it happened — deliberately nothing relaunches here. The
// lifecycle owner already relaunches on its own tick whenever the environment is not
// alive (ServerLifecycleReconciler), and it will read the new mode when it does.
// Relaunching from inside the engine would be a second actuation path that does not
// consult `desired`, so a stop landing in that window would be overruled.
if (mode == SeccompMode.FILTER
&& SeccompFailure.isSeccompAbort(exitCode, tail.toString())) {
Log.w(TAG, "ADFA-5362: proot cannot use seccomp on this kernel — remembering"
+ " PROOT_NO_SECCOMP for this build; the next launch will use it");
capability.remember(SeccompMode.DISABLED);
}

mainHandler.post(() -> listener.onProcessExit(exitCode));

} catch (Exception e) {
Expand All @@ -225,8 +240,20 @@ public void executeInContainer(Context context, String rootfsDir, String command
}).start();
}

/** Keep only the last {@link #TAIL_LIMIT} characters of the output. */
private static void appendTail(StringBuilder tail, String line) {
tail.append(line).append('\n');
if (tail.length() > TAIL_LIMIT) {
tail.delete(0, tail.length() - TAIL_LIMIT);
}
}

/**
* Start an interactive bash session that stays live.
*
* <p>ADFA-5362: this <em>consumes</em> the remembered mode but does not learn one. A terminal is
* opened long after the environment has launched at least once, so the verdict is already known
* by the time anyone gets here; and a live session has no exit to read a verdict from.
*/
public void startInteractiveShell(Context context, String rootfsDir, OutputListener listener) {
new Thread(() -> {
Expand Down Expand Up @@ -307,22 +334,11 @@ public void startInteractiveShell(Context context, String rootfsDir, OutputListe
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);

// ADFA-5362: same single builder as executeInContainer.
pb.environment().clear();
pb.environment().put("PREFIX", prefixDir.getCanonicalPath());
if (loaderBinary.exists())
pb.environment().put("PROOT_LOADER", loaderBinary.getAbsolutePath());
File loader32 = new File(nativeDir, "libproot-loader32.so");
if (loader32.exists())
pb.environment().put("PROOT_LOADER_32", loader32.getAbsolutePath());

pb.environment().put("PROOT_TMP_DIR", prootTmpPath);
pb.environment().put("TMPDIR", "/tmp");
pb.environment().put("HOME", "/root");
pb.environment().put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
pb.environment().put("TERM", "xterm-256color");
pb.environment().put("LANG", "C.UTF-8");
pb.environment().put("USER", "root");
pb.environment().put("LOGNAME", "root");
pb.environment().putAll(ProotEnvironment.build(
nativeDir, prefixDir.getCanonicalPath(), prootTmpPath,
new PrefsSeccompModeRepository(context).load()));

// ADFA-4458: wait on THIS call's process, not the shared field, so a
// concurrent proot call can't make us return on the wrong process.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,16 @@ public void addNewSession() {
cliStr.append("BACKUPS_DIR=\"").append(backupsDir.getAbsolutePath()).append("\"\n");
cliStr.append("export PROOT_TMP_DIR=\"").append(tmpDir.getAbsolutePath()).append("\"\n");
cliStr.append("export PROOT_LOADER=\"").append(prootLoader.getAbsolutePath()).append("\"\n");
cliStr.append("export PROOT_LOADER_32=\"").append(prootLoader32.getAbsolutePath()).append("\"\n\n");
cliStr.append("export PROOT_LOADER_32=\"").append(prootLoader32.getAbsolutePath()).append("\"\n");
// ADFA-5362: the CLI only consumes the verdict the app has already learned, so the
// terminal and the app launch proot the same way on the same phone.
if (new org.iiab.controller.proot.data.PrefsSeccompModeRepository(activity).load()
== org.iiab.controller.proot.domain.SeccompMode.DISABLED) {
cliStr.append("export ")
.append(org.iiab.controller.proot.data.ProotEnvironment.NO_SECCOMP)
.append("=1\n");
}
cliStr.append("\n");

// Initialize Mount Flags
cliStr.append("MOUNT_SDCARD=false\n");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* ============================================================================
* Name : PrefsSeccompModeRepository.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-5362. Remembers how proot must be launched on this device.
* ============================================================================
*/
package org.iiab.controller.proot.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;

import org.iiab.controller.proot.domain.CapabilityKey;
import org.iiab.controller.proot.domain.SeccompMode;

/**
* The one place that remembers whether this device's kernel can run proot with seccomp.
*
* <p><b>Lifecycle.</b> Nothing is stored until a launch actually aborts, so the default is always
* {@link SeccompMode#FILTER} — the fast path — and a launch killed mid-flight leaves no verdict
* behind to be wrong about. What is stored is tied to a <em>capability key</em>: the OS build, the
* kernel and the app version. Any of the three changing means the answer may no longer hold (a
* kernel that gets fixed by an update, a different proot shipped in a new APK), so a key mismatch
* reads as "not known yet" and the next launch learns again. That is also why nothing ever needs to
* clear this: the key does it.
*/
public final class PrefsSeccompModeRepository {

private static final String PREFS = "ProotCapabilityPrefs";
private static final String K_KEY = "seccomp.key";
private static final String K_DISABLED = "seccomp.disabled";

private final SharedPreferences prefs;

public PrefsSeccompModeRepository(Context context) {
this.prefs = context.getSharedPreferences(PREFS, Context.MODE_MULTI_PROCESS);
}

/** How proot must be launched here; {@link SeccompMode#FILTER} until proved otherwise. */
public SeccompMode load() {
if (!CapabilityKey.holds(prefs.getString(K_KEY, null), capabilityKey())) {
return SeccompMode.FILTER; // never learned, or learned about a different OS/app
}
return prefs.getBoolean(K_DISABLED, false) ? SeccompMode.DISABLED : SeccompMode.FILTER;
}

/**
* Record what this device needs. Written with {@code commit()}: the very next thing that happens
* is a relaunch, and on an ungraceful kill an unwritten verdict costs another aborted launch.
*/
public void remember(SeccompMode mode) {
prefs.edit()
.putString(K_KEY, capabilityKey())
.putBoolean(K_DISABLED, mode == SeccompMode.DISABLED)
.commit();
}

/** This device's key, read off the platform; {@link CapabilityKey} owns what it means. */
private static String capabilityKey() {
return CapabilityKey.of(
Build.FINGERPRINT,
System.getProperty("os.version"),
org.iiab.controller.BuildConfig.VERSION_CODE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* ============================================================================
* Name : ProotEnvironment.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-5362. The single builder of the environment every proot
* launch runs with.
* ============================================================================
*/
package org.iiab.controller.proot.data;

import org.iiab.controller.proot.domain.SeccompMode;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* One place that answers "what environment does a proot launch run with".
*
* <p>The same block was written out four times — twice in {@code PRootEngine} (the container
* command and the interactive shell) and once as {@code export} lines in the generated
* {@code iiab} CLI, which two of its own launches share. Four copies of one fact is how the
* terminal and the app end up disagreeing on the same phone, and it is why a per-device launch
* decision (ADFA-5362) had no single place to land.
*
* <p>Pure: files are only probed for existence, nothing is written and there is no {@code android.*},
* so this is unit-tested on the JVM.
*/
public final class ProotEnvironment {

/** The guest PATH; a login shell re-derives it, but proot's own exec needs it set. */
public static final String GUEST_PATH =
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";

/** proot reads this before its own {@code execvp}; any value disables seccomp filtering. */
public static final String NO_SECCOMP = "PROOT_NO_SECCOMP";

private static final String LOADER = "libproot-loader.so";
private static final String LOADER_32 = "libproot-loader32.so";

private ProotEnvironment() {
}

/**
* The environment for a proot launch.
*
* <p>Callers apply it over a cleared environment ({@code pb.environment().clear()} then
* {@code putAll}): Android's own variables are toxic to the guest, so the launch starts from
* nothing and receives exactly this map.
*
* <p>The two loader variables are set only when the loader is actually on disk — the 32-bit
* loader ships on 64-bit ABIs only, and proot falls back to {@code PREFIX} when they are absent.
*
* @param nativeLibDir the app's native library directory (where the proot loaders live).
* @param prefixPath canonical path of the fake Termux prefix proot resolves its loader through.
* @param prootTmpPath canonical path of the host directory proot uses for its own temporaries.
* @param mode how proot must run here (ADFA-5362); only DISABLED adds a variable.
*/
public static Map<String, String> build(File nativeLibDir, String prefixPath,
String prootTmpPath, SeccompMode mode) {
Map<String, String> env = new LinkedHashMap<>();

env.put("PREFIX", prefixPath);

// ADFA-5362: absent on a healthy kernel, so the fast path is byte-identical to what shipped.
if (mode == SeccompMode.DISABLED) {
env.put(NO_SECCOMP, "1");
}

File loader = new File(nativeLibDir, LOADER);
if (loader.exists()) {
env.put("PROOT_LOADER", loader.getAbsolutePath());
}
File loader32 = new File(nativeLibDir, LOADER_32);
if (loader32.exists()) {
env.put("PROOT_LOADER_32", loader32.getAbsolutePath());
}

env.put("PROOT_TMP_DIR", prootTmpPath);
env.put("TMPDIR", "/tmp");
env.put("HOME", "/root");
env.put("PATH", GUEST_PATH);
env.put("TERM", "xterm-256color");
env.put("LANG", "C.UTF-8");
env.put("USER", "root");
env.put("LOGNAME", "root");

return env;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* ============================================================================
* Name : CapabilityKey.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-5362. When does a remembered proot verdict still apply?
* ============================================================================
*/
package org.iiab.controller.proot.domain;

/**
* The rule that keeps a remembered launch verdict from outliving what it was true about.
*
* <p>{@link SeccompMode#DISABLED} is learned from one kernel running one proot binary. Three things
* can make that answer wrong: the OS build changes (a vendor update can fix the kernel), the kernel
* string changes, or the app ships a different proot. So the verdict is stored against a key made of
* all three, and only counts while that key still describes the device. That is also why nothing
* ever has to clear the stored value — a key that no longer matches is already ignored.
*
* <p>Getting this wrong is quiet, not loud: a verdict that outlives its key leaves a healthy device
* permanently slower with no symptom to notice. Hence a pure rule with tests, rather than a string
* comparison buried in the data layer.
*/
public final class CapabilityKey {

/** Stands in for a component the platform did not report, so the key stays well-formed. */
private static final String UNKNOWN = "unknown";

private static final String SEPARATOR = "|";

private CapabilityKey() {
}

/**
* Build the key a verdict is stored against.
*
* @param osBuild the OS build identity (Android's {@code Build.FINGERPRINT}).
* @param kernel the kernel version string ({@code os.version}).
* @param appVersion the app's version code — a new APK can carry a different proot.
*/
public static String of(String osBuild, String kernel, int appVersion) {
return orUnknown(osBuild) + SEPARATOR + orUnknown(kernel) + SEPARATOR + appVersion;
}

/**
* Does a verdict stored under {@code storedKey} still describe this device?
*
* <p>False for anything that is not an exact match, including nothing stored at all: never
* having learned and having learned about something else both mean "do not use a verdict here".
*/
public static boolean holds(String storedKey, String currentKey) {
return storedKey != null && storedKey.equals(currentKey);
}

private static String orUnknown(String component) {
return (component == null || component.isEmpty()) ? UNKNOWN : component;
}
}
Loading
Loading