fix: install OTA updates through PackageInstaller

The refresh button found 2.2.3, downloaded it, and reported
"Kurulum reddedildi (imza uyuşmuyor?)" for a build signed with exactly the same
platform certificate as the one already running. The signature was never the
problem.

install() shelled out to `pm install -r` with a path inside the app's private
cache. pm does not read the file — it hands the path to the package manager
service, which opens it from its own process and SELinux context, where that
directory is not readable. The install failed for a reason nobody could see:
install() returned a bare boolean, and UpdateHook mapped every false to the one
message it had. The pm output that would have named the real error was captured
into a StringBuilder and discarded.

A PackageInstaller session takes no path. We open the archive ourselves, as the
app, and stream it into the session, so no second process ever has to reach our
cache. Approach taken from merthankaraman/DriveHub_Dort, which hit the same wall
on the same head unit.

Consequences worth knowing when reading a future failure:

- Committing a session is asynchronous, so the refresh button can only say an
  install started. OtaInstallResultReceiver has the verdict, and surfaces the
  package manager's own INSTALL_FAILED_* text rather than guessing.
- STATUS_PENDING_USER_ACTION is not an error. The receiver launches the
  confirmation activity the platform supplies.
- The PendingIntent must be MUTABLE or it arrives with no status extras.

install() now returns an enum, so a certificate mismatch, an unparseable or
wrong-package archive, and a failed session each say what they are.

Also checks the archive's package name against ours, which was a genuine gap:
the platform key signs every app on this unit, so a certificate match alone
never meant the APK was this app.

The `pm install -r` exit-code test goes with the shell-out it covered. Nothing
in the session path is exercisable off-device.

REQUEST_INSTALL_PACKAGES and the receiver are declared in the unstable manifest
only — the stable channel has no updater at all, and its merged manifest was
checked to confirm it gains neither.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
TCFDONMEZ
2026-09-25 14:02:55 +03:00
co-authored by Claude Opus 5
parent 322ebcc4c0
commit 091d26d6d6
7 changed files with 249 additions and 37 deletions
@@ -0,0 +1,65 @@
package com.evsuite.abrp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.util.Log;
import android.widget.Toast;
/**
* Where a {@link PackageInstaller} session reports what it did — UNSTABLE BUILDS ONLY.
*
* The session commit is asynchronous, so unlike the {@code pm install -r} it replaced, the
* install outcome cannot be the return value of the call that started it. It arrives here.
*
* STATUS_PENDING_USER_ACTION is the case worth understanding: the platform is saying it will
* install, but wants the driver to confirm. That happens when the app is not granted a silent
* install, and the only correct response is to launch the confirmation activity it hands us.
*/
public final class OtaInstallResultReceiver extends BroadcastReceiver {
static final String ACTION_INSTALL_RESULT = "com.evsuite.abrp.OTA_INSTALL_RESULT";
private static final String TAG = "EVABRP.Update";
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) return;
int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
String message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE);
Log.i(TAG, "OTA install result: status=" + status + " msg=" + message);
switch (status) {
case PackageInstaller.STATUS_PENDING_USER_ACTION:
Intent confirm = intent.getParcelableExtra(Intent.EXTRA_INTENT);
if (confirm == null) {
toast(context, context.getString(R.string.ota_install_failed, "no confirm intent"));
return;
}
confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(confirm);
} catch (Throwable t) {
Log.e(TAG, "OTA confirm UI failed: " + t.getMessage());
toast(context, context.getString(R.string.ota_install_failed,
t.getClass().getSimpleName()));
}
break;
case PackageInstaller.STATUS_SUCCESS:
toast(context, context.getString(R.string.ota_install_success));
break;
default:
// The status message is the package manager's own words — INSTALL_FAILED_*
// and friends. Surfaced verbatim, because guessing at it is what made the
// previous failure unreadable.
toast(context, context.getString(R.string.ota_install_failed,
message != null ? message : "status " + status));
break;
}
}
private static void toast(Context context, String text) {
Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
@@ -1,6 +1,9 @@
package com.evsuite.abrp;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.util.Log;
import org.json.JSONArray;
@@ -295,27 +298,112 @@ final class OtaUpdater {
return null;
}
static boolean install(Context context, File apk) {
if (!signatureMatchesRunningApp(context, apk)) return false;
/**
* What {@link #install} did. Every value except {@link #SESSION_STARTED} is a refusal,
* and they are distinct because the single "imza uyuşmuyor?" message they used to share
* sent a perfectly well-signed build to the wrong diagnosis.
*/
enum InstallResult {
/** The archive is signed by a different certificate than the running app. */
SIGNATURE_MISMATCH,
/** The package manager cannot parse the archive, or it is for another package. */
UNREADABLE_ARCHIVE,
/** Handed to the platform. The outcome arrives at {@link OtaInstallResultReceiver}. */
SESSION_STARTED,
/** The session could not be created, written or committed. */
SESSION_FAILED
}
/**
* Hands [apk] to the platform's {@link PackageInstaller}.
*
* This used to shell out to {@code pm install -r}. That fails on this head unit: the APK
* lives in the app's private cache, and the package manager service opens the path from
* its own process and SELinux context, where that directory is not readable. The failure
* surfaced as a signature error, which it never was.
*
* A session takes no path. We open the archive ourselves, as the app, and stream the bytes
* into the session — so there is no second process that has to be able to read our cache.
* The bytes are fully written before commit, which is why the caller may delete the staged
* file as soon as this returns.
*/
static InstallResult install(Context context, File apk) {
if (!signatureMatchesRunningApp(context, apk)) return InstallResult.SIGNATURE_MISMATCH;
if (!archiveIsThisPackage(context, apk)) return InstallResult.UNREADABLE_ARCHIVE;
try {
Process process = new ProcessBuilder("/system/bin/pm", "install", "-r",
apk.getAbsolutePath()).redirectErrorStream(true).start();
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) output.append(line).append('\n');
commitSession(context, apk);
return InstallResult.SESSION_STARTED;
} catch (Throwable t) {
Log.w(TAG, "OTA session install failed", t);
return InstallResult.SESSION_FAILED;
}
}
/**
* True if the archive parses and declares our own package name.
*
* A signature match alone does not say the APK is this app: the same platform key signs
* every app on the unit, so a correctly signed archive for some other package would pass
* the certificate check and then fail deep inside the installer.
*/
private static boolean archiveIsThisPackage(Context context, File apk) {
try {
android.content.pm.PackageInfo info = context.getPackageManager()
.getPackageArchiveInfo(apk.getAbsolutePath(), 0);
if (info == null || info.packageName == null) {
Log.w(TAG, "OTA archive cannot be parsed by the package manager");
return false;
}
int exitCode = process.waitFor();
return installSucceeded(exitCode, output.toString());
if (!context.getPackageName().equals(info.packageName)) {
Log.w(TAG, "OTA archive is for " + info.packageName + ", not "
+ context.getPackageName());
return false;
}
Log.i(TAG, "OTA archive ok: " + info.packageName + " " + info.versionName);
return true;
} catch (Exception e) {
Log.w(TAG, "Update install failed", e);
Log.w(TAG, "OTA archive check threw: " + e.getMessage());
return false;
}
}
static boolean installSucceeded(int exitCode, String output) {
return exitCode == 0 && output.contains("Success");
private static void commitSession(Context context, File apk) throws Exception {
PackageInstaller installer = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
if (android.os.Build.VERSION.SDK_INT >= 31) {
// Only honoured for an installer the platform already trusts; harmless otherwise,
// and this unit is API 28 where the field does not exist at all.
params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED);
}
int sessionId = installer.createSession(params);
PackageInstaller.Session session = null;
try {
session = installer.openSession(sessionId);
try (java.io.InputStream in = new java.io.FileInputStream(apk);
java.io.OutputStream out = session.openWrite("base.apk", 0, apk.length())) {
byte[] buffer = new byte[64 * 1024];
int count;
while ((count = in.read(buffer)) != -1) out.write(buffer, 0, count);
session.fsync(out);
}
Intent callback = new Intent(context, OtaInstallResultReceiver.class)
.setAction(OtaInstallResultReceiver.ACTION_INSTALL_RESULT)
.setPackage(context.getPackageName());
// MUTABLE: the platform fills in EXTRA_STATUS and, when it wants the driver to
// confirm, EXTRA_INTENT. An immutable PendingIntent would arrive empty.
PendingIntent pending = PendingIntent.getBroadcast(context, sessionId, callback,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
session.commit(pending.getIntentSender());
Log.i(TAG, "OTA session " + sessionId + " committed (" + apk.length() + " bytes)");
session = null;
} finally {
// Only reached when commit did not happen; an abandoned session frees its staging.
if (session != null) {
try { session.abandon(); } catch (Throwable ignored) { }
try { session.close(); } catch (Throwable ignored) { }
}
}
}
/**
@@ -12,10 +12,15 @@ import java.io.File;
* This fork publishes its own builds from its own repository, signed with the platform key
* the head unit already trusts, so that audit does not govern here and the seam is live.
*
* Installation goes through {@code pm install -r}, which only a platform-signed build may
* call. {@link OtaUpdater#install} checks the downloaded APK's certificate against the
* running app's first and refuses a mismatch, so an update signed with any other key is
* deleted rather than installed — the same check that makes an upstream APK unusable here.
* Installation goes through the platform {@link android.content.pm.PackageInstaller}, not
* {@code pm install -r}: that shelled out with a path inside our private cache, which the
* package manager service cannot read from its own process, and the generic failure was
* reported as a signature mismatch it never was. {@link OtaUpdater#install} still checks the
* downloaded APK's certificate against the running app's first and refuses a mismatch, so an
* update signed with any other key is deleted rather than installed.
*
* Committing a session is asynchronous, so the message this returns says an install has been
* started, never that one finished. {@link OtaInstallResultReceiver} has the verdict.
*/
final class UpdateHook {
@@ -78,12 +83,22 @@ final class UpdateHook {
if (apk == null) return "İndirme başarısız (" + update.versionName + ")";
// The cached APK is cleared whichever way install goes: a rejected archive must not
// linger, and an accepted one has already been copied out by the package manager.
boolean installed = OtaUpdater.install(app, apk);
// linger, and an accepted one has already been streamed into the installer session.
OtaUpdater.InstallResult result = OtaUpdater.install(app, apk);
if (!apk.delete()) Log.w(TAG, "Could not remove cached OTA APK");
return installed
? "Güncellendi: " + update.versionName + " — yeniden başlatın"
: "Kurulum reddedildi (imza uyuşmuyor?)";
switch (result) {
case SESSION_STARTED:
// Deliberately not "Güncellendi": committing a session is not installing. The
// platform may still want the driver to confirm, and either way the verdict
// arrives at OtaInstallResultReceiver, not here.
return "Kuruluyor: " + update.versionName + " — ekrandaki onayı bekleyin";
case SIGNATURE_MISMATCH:
return "Kurulum reddedildi: imza uyuşmuyor";
case UNREADABLE_ARCHIVE:
return "Kurulum reddedildi: APK okunamadı";
default:
return "Kurulum başlatılamadı (" + update.versionName + ") — Log sayfasına bakın";
}
}
}