From 36618b0ad0366d21a16d346f7e69f24bb88822fa Mon Sep 17 00:00:00 2001
From: yuanyuanxiang <962914132@qq.com>
Date: Wed, 11 Nov 2026 00:53:29 +0100
Subject: [PATCH] Feature: Install Android APK updates pushed from the master
The master now sends COMMAND_UPDATE to Android hosts: it picks a
"Build Client -> Android" APK, checks the ZIP magic and that the package
carries this master's fingerprint, then sends [cmd][size][APK][xxh64].
The client verifies length and hash, writes filesDir/update.apk and
commits a PackageInstaller session, so the system installer still asks
the user to confirm - an app cannot replace itself silently. Write and
hash failures come back over TOKEN_CLIENT_MSG, so the master sees why
nothing happened instead of a silently dropped packet.
Sending the wrong file is what the fingerprint check guards against: a
template without the master id installs fine and then cannot connect
back. "Send anyway" is offered only after spelling that out, and the
client advertises CLIENT_CAP_APK_UPDATE (0x0400) so an old APK gets
"install a new build once by hand" instead of a packet it would discard.
Also report the real versionName/versionCode at login instead of the
hardcoded v1.0.0, add android/tools/verify_update_apk.py (pre-send check
of size, ZIP_STORED libs, ABI, package, versionCode and the decrypted
CONNECT_ADDRESS, which it still locates after BuildDlg rewrote szFlag),
and translate the nine new strings in en_US, zh_TW and de_DE.
Verified on the emulator and against the live release server: generate,
sign, send, install, and the device reconnects and re-grants screen
capture. Language packs are GBK and were appended as bytes.
Co-Authored-By: deepseek-flash
---
android/app/build.gradle | 9 +-
android/app/src/main/AndroidManifest.xml | 22 ++
android/app/src/main/cpp/main.cpp | 156 ++++++++++-
.../java/com/yama/client/CaptureService.kt | 15 +-
.../com/yama/client/InstallResultReceiver.kt | 42 +++
.../main/java/com/yama/client/MainActivity.kt | 18 ++
.../java/com/yama/client/ReplacedReceiver.kt | 22 ++
.../java/com/yama/client/UpdateInstaller.kt | 251 +++++++++++++++++
.../main/java/com/yama/client/YamaBridge.kt | 7 +-
android/tools/verify_update_apk.py | 259 ++++++++++++++++++
common/commands.h | 5 +
server/2015Remote/2015RemoteDlg.cpp | 119 +++++++-
server/2015Remote/2015RemoteDlg.h | 2 +
server/2015Remote/context.h | 9 +
server/2015Remote/lang/de_DE.ini | 9 +
server/2015Remote/lang/en_US.ini | 9 +
server/2015Remote/lang/zh_TW.ini | 9 +
17 files changed, 955 insertions(+), 8 deletions(-)
create mode 100644 android/app/src/main/java/com/yama/client/InstallResultReceiver.kt
create mode 100644 android/app/src/main/java/com/yama/client/ReplacedReceiver.kt
create mode 100644 android/app/src/main/java/com/yama/client/UpdateInstaller.kt
create mode 100644 android/tools/verify_update_apk.py
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 50c4bb4..87e0d8b 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -15,8 +15,8 @@ android {
applicationId "com.yama.client"
minSdk 21
targetSdk 35
- versionCode 1
- versionName "1.0"
+ versionCode 2
+ versionName "1.1"
ndk {
if (INCLUDE_EMULATOR_ABIS) {
@@ -41,6 +41,11 @@ android {
}
}
+ buildFeatures {
+ // AGP 8 默认不生成 BuildConfig;登录时要把真实版本号/versionCode 上报给服务端
+ buildConfig true
+ }
+
signingConfigs {
release {
storeFile file("../yama-release.jks")
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index d5b96cb..bbcd6a5 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -5,6 +5,10 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/app/src/main/cpp/main.cpp b/android/app/src/main/cpp/main.cpp
index d5221dd..67f770a 100644
--- a/android/app/src/main/cpp/main.cpp
+++ b/android/app/src/main/cpp/main.cpp
@@ -195,6 +195,9 @@ State g_bExit{S_CLIENT_NORMAL};
uint64_t g_myClientID = 0; // sub_conn_thread.h 需要的外部符号
static std::atomic g_running{false};
static std::atomic g_lastHeartbeatAckMs{0};
+// 主连接句柄:COMMAND_UPDATE 失败回报要往主连接发 ClientMsg(与 Linux 端同一套路)。
+// 只在 ConnectionThread 里赋值/置空,其他线程只读。
+static IOCPClient* g_pMainClient = nullptr;
// ---- JNI 反向调用(DataProcess → ControlService / CaptureService)----
static JavaVM* g_jvm = nullptr;
@@ -207,6 +210,7 @@ static jmethodID g_requestIdrMid = nullptr;
static jmethodID g_forceFirstFrameMid = nullptr;
static jmethodID g_statusMid = nullptr; // CaptureService.onNativeStatus(String)
static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务
+static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘
// 心跳日志限流:每 60 秒最多打一次
static std::atomic g_lastHbLogMs{0};
@@ -276,6 +280,8 @@ static std::string g_screenRes;
static std::string g_username;
static std::string g_apkPath;
static std::string g_filesDir; // context.filesDir,无需权限,用于持久化分组名
+static std::string g_versionName = "0"; // BuildConfig.VERSION_NAME,登录时上报到版本列
+static int g_versionCode = 0; // BuildConfig.VERSION_CODE
static void SaveGroupName() {
if (g_filesDir.empty()) return;
@@ -334,9 +340,30 @@ static void CallCaptureStaticVoid(jmethodID mid)
if (attached) g_jvm->DetachCurrentThread();
}
+// 带一个 String 参数的静态方法调用(onUpdateReceived(path))
+static void CallCaptureStaticString(jmethodID mid, const char* s)
+{
+ if (!g_jvm || !g_captureClass || !mid || !s) return;
+ JNIEnv* jenv = nullptr;
+ bool attached = false;
+ jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
+ if (st == JNI_EDETACHED) {
+ if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
+ attached = true;
+ } else if (st != JNI_OK || !jenv) {
+ return;
+ }
+ jstring js = jenv->NewStringUTF(s);
+ if (js) {
+ jenv->CallStaticVoidMethod(g_captureClass, mid, js);
+ jenv->DeleteLocalRef(js);
+ }
+ if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
+ if (attached) g_jvm->DetachCurrentThread();
+}
+
// 触发编码器输出关键帧(setParameters REQUEST_SYNC_FRAME)
static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid); }
-
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
@@ -440,6 +467,103 @@ static void ScreenSpyThread()
LOGI("ScreenSpyThread exit");
}
+// ------------------------------------------------------------------ 在线升级
+// 载荷布局:[COMMAND_UPDATE:1][APK 大小:8 LE][APK:size][xxh64:8 LE]
+// 校验通过后写到 filesDir/update.apk,交给 Kotlin 的 PackageInstaller 会话去装
+// (必须系统安装器 + 人工确认,APP 不能静默自替换)。
+// 任何失败都只回报、不退出:当前版本继续跑,服务端能看到原因。
+
+// ClientMsg 的 text/title 是定长数组,strcpy_s 遇到超长会触发无效参数处理器直接崩,
+// 所以统一截断后 memcpy。
+static void sendClientMsg(const char* title, const char* text)
+{
+ if (!g_pMainClient || !g_pMainClient->IsConnected()) return;
+ ClientMsg msg;
+ msg.cmd = TOKEN_CLIENT_MSG;
+ strncpy(msg.title, title ? title : "YAMA", sizeof(msg.title) - 1);
+ if (text) {
+ size_t n = strlen(text);
+ if (n > sizeof(msg.text) - 1) n = sizeof(msg.text) - 1;
+ memcpy(msg.text, text, n);
+ }
+ g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
+}
+
+static void reportUpdateFailure(const std::string& reason)
+{
+ LOGI("UPDATE failed: %s", reason.c_str());
+ PostStatus(("update: " + reason).c_str());
+ sendClientMsg("Android update failed", reason.c_str());
+}
+
+static void ApplyUpdateApk(const PBYTE szBuffer, ULONG ulLength)
+{
+ const size_t headerLen = 1 + sizeof(uint64_t);
+ const size_t trailerLen = sizeof(uint64_t);
+ if (ulLength < headerLen + trailerLen) {
+ reportUpdateFailure("payload too short");
+ return;
+ }
+ uint64_t size = 0;
+ memcpy(&size, szBuffer + 1, sizeof(size));
+ if (size < 1024 || size > (uint64_t)(ulLength - headerLen - trailerLen)) {
+ reportUpdateFailure("payload size invalid");
+ return;
+ }
+ const unsigned char* payload = szBuffer + headerLen;
+ uint64_t expect = 0;
+ memcpy(&expect, payload + size, sizeof(expect));
+ uint64_t actual = (uint64_t)XXH64(payload, (size_t)size, 0);
+ if (actual != expect) {
+ char buf[96];
+ snprintf(buf, sizeof(buf), "xxh64 mismatch (payload corrupted: %u bytes)", (unsigned)size);
+ reportUpdateFailure(buf);
+ return;
+ }
+ if (payload[0] != 'P' || payload[1] != 'K' || payload[2] != 0x03 || payload[3] != 0x04) {
+ reportUpdateFailure("payload is not an APK");
+ return;
+ }
+ if (g_filesDir.empty()) {
+ reportUpdateFailure("filesDir not set");
+ return;
+ }
+ std::string path = g_filesDir + "/update.apk";
+ int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
+ if (fd < 0) {
+ reportUpdateFailure("cannot create " + path + ": " + strerror(errno));
+ return;
+ }
+ bool ok = true;
+ size_t off = 0;
+ while (off < (size_t)size) {
+ ssize_t n = write(fd, payload + off, (size_t)size - off);
+ if (n <= 0) {
+ if (n < 0 && errno == EINTR) continue;
+ ok = false;
+ break;
+ }
+ off += (size_t)n;
+ }
+ if (ok) ok = (fsync(fd) == 0);
+ if (close(fd) != 0) ok = false;
+ if (!ok) {
+ std::string err = strerror(errno);
+ unlink(path.c_str());
+ reportUpdateFailure("cannot write " + path + ": " + err);
+ return;
+ }
+
+ LOGI("UPDATE: saved %s (%llu bytes), handing to installer", path.c_str(),
+ (unsigned long long)size);
+ char msg[128];
+ snprintf(msg, sizeof(msg), "APK received (%.1f MB), opening system installer",
+ (double)size / (1024.0 * 1024.0));
+ PostStatus(msg);
+ // 拉不起来(无障碍没开/系统限制)时 Kotlin 侧会改发通知,failure 只回报真正的前置错误
+ CallCaptureStaticString(g_updateReceivedMid, path.c_str());
+}
+
// ------------------------------------------------------------------ DataProcess
int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
{
@@ -531,6 +655,11 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
LOGI("COMMAND_SHELL (not implemented)");
break;
+ case COMMAND_UPDATE:
+ LOGI("cmd: COMMAND_UPDATE len=%lu", (unsigned long)ulLength);
+ ApplyUpdateApk(szBuffer, ulLength);
+ break;
+
case COMMAND_SYSTEM:
LOGI("COMMAND_SYSTEM (not implemented)");
break;
@@ -582,7 +711,7 @@ static void ConnectionThread()
logInfo.AddReserved("");
logInfo.AddReserved(g_location.c_str()); // [10] 地理位置
logInfo.AddReserved(g_pubIp.c_str()); // [11] 公网 IP
- logInfo.AddReserved("v1.0.0");
+ logInfo.AddReserved(("v" + g_versionName + " (" + std::to_string(g_versionCode) + ")").c_str());
logInfo.AddReserved(g_username.c_str());
logInfo.AddReserved(0); // IsRunningAsAdmin
logInfo.AddReserved(g_screenRes.c_str());
@@ -598,6 +727,7 @@ static void ConnectionThread()
std::unique_ptr client(new IOCPClient(g_bExit, false));
client->setManagerCallBack(nullptr, DataProcess, nullptr);
+ g_pMainClient = client.get(); // 升级失败回报用;线程退出前置空
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 没有 TLS 通道,WSS 会 fail-closed。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
@@ -688,6 +818,7 @@ static void ConnectionThread()
}
g_running.store(false);
+ g_pMainClient = nullptr; // client 马上析构,别让别的线程拿到悬空指针
LOGI("ConnectionThread exit");
if (g_bExit == S_CLIENT_EXIT && g_jvm && g_captureClass && g_nativeExitMid) {
@@ -714,7 +845,8 @@ Java_com_yama_client_YamaBridge_nativeInit(
jstring serverIp, jint serverPort,
jstring androidId, jstring deviceModel,
jstring androidVersion, jstring screenRes,
- jstring username, jstring apkPath, jstring filesDir)
+ jstring username, jstring apkPath, jstring filesDir,
+ jstring versionName, jint versionCode)
{
// CPP-01 fix: CAS 原子地完成"检查+设置",消除 check-then-act 竞争
bool expected = false;
@@ -739,6 +871,9 @@ Java_com_yama_client_YamaBridge_nativeInit(
g_username = toStr(username);
g_apkPath = toStr(apkPath);
g_filesDir = toStr(filesDir);
+ std::string verName = toStr(versionName);
+ if (!verName.empty()) g_versionName = verName;
+ g_versionCode = (int)versionCode;
LoadGroupName(); // 若文件存在则覆盖 g_SETTINGS.szGroupName(优先级高于编译时 patch)
// 缓存 JVM 和 Class/Method 引用。必须在 Java 线程(nativeInit 调用栈)
@@ -775,6 +910,9 @@ Java_com_yama_client_YamaBridge_nativeInit(
g_nativeExitMid = env->GetStaticMethodID(g_captureClass, "onNativeExit", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_nativeExitMid = nullptr; }
if (!g_nativeExitMid) LOGE("CaptureService.onNativeExit not found");
+ g_updateReceivedMid = env->GetStaticMethodID(g_captureClass, "onUpdateReceived", "(Ljava/lang/String;)V");
+ if (env->ExceptionCheck()) { env->ExceptionClear(); g_updateReceivedMid = nullptr; }
+ if (!g_updateReceivedMid) LOGE("CaptureService.onUpdateReceived not found");
UseAndroidLog(PostStatus);
} else {
LOGE("CaptureService class not found");
@@ -797,6 +935,18 @@ Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
g_running.store(false);
}
+// 由 Kotlin 侧(安装流程)回报结果到服务端消息栏,走 TOKEN_CLIENT_MSG
+JNIEXPORT void JNICALL
+Java_com_yama_client_YamaBridge_nativeReportMessage(JNIEnv* env, jobject, jstring msg)
+{
+ if (!msg) return;
+ const char* c = env->GetStringUTFChars(msg, nullptr);
+ if (!c) return;
+ LOGI("REPORT: %s", c);
+ sendClientMsg("Android update", c);
+ env->ReleaseStringUTFChars(msg, c);
+}
+
// 由 CaptureService 在 MediaCodec 配置完成后调用,告知 C++ 侧实际捕获尺寸
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
diff --git a/android/app/src/main/java/com/yama/client/CaptureService.kt b/android/app/src/main/java/com/yama/client/CaptureService.kt
index 6af7152..80c64c4 100644
--- a/android/app/src/main/java/com/yama/client/CaptureService.kt
+++ b/android/app/src/main/java/com/yama/client/CaptureService.kt
@@ -40,6 +40,9 @@ class CaptureService : Service() {
// CS-01 fix: 通过 idrHandler.post 序列化到主线程,避免 TOCTOU 竞争
@Volatile var instance: CaptureService? = null
+ /** onUpdateReceived 可能在服务已经销毁后从 native 线程打进来,用 application context 兜底 */
+ @Volatile var appContext: android.content.Context? = null
+
@JvmStatic
fun onNativeStatus(msg: String) {
val svc = instance ?: return
@@ -48,6 +51,14 @@ class CaptureService : Service() {
}
}
+ /** 服务端下发的升级 APK 已校验并落盘(filesDir/update.apk),交给安装流程 */
+ @JvmStatic
+ fun onUpdateReceived(path: String) {
+ val ctx = instance ?: appContext ?: return
+ Log.i(TAG, "onUpdateReceived: $path")
+ UpdateInstaller.onApkReceived(ctx, path)
+ }
+
@JvmStatic
fun onNativeExit() {
val svc = instance ?: return
@@ -115,6 +126,7 @@ class CaptureService : Service() {
override fun onCreate() {
super.onCreate()
instance = this
+ appContext = applicationContext
createNotificationChannel()
// CS-06: start with DATA_SYNC type only; upgrade to MEDIA_PROJECTION in
// onStartCommand when the token is actually available. On Android 14+
@@ -150,7 +162,8 @@ class CaptureService : Service() {
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
val initRet: Int
try {
- initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath)
+ initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath,
+ BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Native library load failed: $e")
stopSelf()
diff --git a/android/app/src/main/java/com/yama/client/InstallResultReceiver.kt b/android/app/src/main/java/com/yama/client/InstallResultReceiver.kt
new file mode 100644
index 0000000..685d08d
--- /dev/null
+++ b/android/app/src/main/java/com/yama/client/InstallResultReceiver.kt
@@ -0,0 +1,42 @@
+package com.yama.client
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+import android.os.Build
+import android.util.Log
+
+/**
+ * PackageInstaller 会话的状态回执(IntentSender 指向它)。
+ *
+ * 三种结局:
+ * - STATUS_PENDING_USER_ACTION:系统要人点「安装」,EXTRAS 里的 INTENT 就是安装器界面;
+ * 这里把它拉起来(无障碍在时不受后台启动限制),拉不起来就发通知兜底。
+ * - STATUS_SUCCESS:安装成功。APP 进程随后会被系统杀掉,这条分支经常来不及跑,
+ * 装完的提示以 MY_PACKAGE_REPLACED(ReplacedReceiver)为准。
+ * - 其它:版本降级、签名不一致、用户取消等,把系统给的原因回报给服务端。
+ */
+class InstallResultReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != UpdateInstaller.ACTION_INSTALL_STATUS) return
+ val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
+ Log.i("YAMA", "InstallResultReceiver: status=$status")
+ when (status) {
+ PackageInstaller.STATUS_PENDING_USER_ACTION -> {
+ val confirm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
+ intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
+ else
+ @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
+ UpdateInstaller.onConfirmNeeded(context, confirm)
+ }
+ PackageInstaller.STATUS_SUCCESS ->
+ UpdateInstaller.onInstallSuccess(context)
+ else -> {
+ val msg = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
+ UpdateInstaller.onInstallFailed(context, status, msg)
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/yama/client/MainActivity.kt b/android/app/src/main/java/com/yama/client/MainActivity.kt
index 7bd4d83..e6f2841 100644
--- a/android/app/src/main/java/com/yama/client/MainActivity.kt
+++ b/android/app/src/main/java/com/yama/client/MainActivity.kt
@@ -1,8 +1,11 @@
package com.yama.client
+import android.Manifest
import android.app.Activity
import android.content.Intent
+import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
+import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
@@ -16,10 +19,25 @@ class MainActivity : AppCompatActivity() {
companion object {
const val REQUEST_MEDIA_PROJECTION = 1001
+ const val REQUEST_NOTIFICATIONS = 1002
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
+ // 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
+ requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
+ }
+ // 服务端下发升级包后系统安装框没拉起来时,靠通知把用户带到这一步:
+ // 先把待确认的安装框弹出来,装完再重新授权录屏(录制授权随旧进程一起失效了)。
+ val pendingInstall = UpdateInstaller.consumePendingConfirm()
+ if (pendingInstall != null) {
+ Log.i(CaptureService.TAG, "MainActivity: resuming pending install confirm")
+ runCatching { startActivity(pendingInstall) }
+ finish()
+ return
+ }
// MA-01 fix: 系统重建 Activity 时 savedInstanceState != null,
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
if (savedInstanceState != null) { finish(); return }
diff --git a/android/app/src/main/java/com/yama/client/ReplacedReceiver.kt b/android/app/src/main/java/com/yama/client/ReplacedReceiver.kt
new file mode 100644
index 0000000..166b576
--- /dev/null
+++ b/android/app/src/main/java/com/yama/client/ReplacedReceiver.kt
@@ -0,0 +1,22 @@
+package com.yama.client
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.util.Log
+
+/**
+ * 覆盖安装完成后的第一现场:系统在新版本进程里发 MY_PACKAGE_REPLACED(只有被替换的 APP
+ * 自己收得到)。此刻 MediaProjection 授权已经随旧进程一起失效,客户端不会自动恢复录屏,
+ * 必须由人打开 App 重新授权 —— 用一条通知把这一步交到用户手上。
+ */
+class ReplacedReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
+ Log.i("YAMA", "MY_PACKAGE_REPLACED: upgraded, asking user to grant screen capture")
+ UpdateInstaller.notifyUser(context, 201, "YAMA 已升级",
+ "点按打开 YAMA 并重新授权录屏,远程控制才能恢复。",
+ UpdateInstaller.mainActivityPendingIntent(context))
+ }
+}
diff --git a/android/app/src/main/java/com/yama/client/UpdateInstaller.kt b/android/app/src/main/java/com/yama/client/UpdateInstaller.kt
new file mode 100644
index 0000000..7192314
--- /dev/null
+++ b/android/app/src/main/java/com/yama/client/UpdateInstaller.kt
@@ -0,0 +1,251 @@
+package com.yama.client
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import android.util.Log
+import java.io.File
+
+/**
+ * 服务端下发的 APK 落到 filesDir/update.apk 之后的安装流程。
+ *
+ * 关键限制:
+ * - Android 不允许 APP 静默自替换,必须走 PackageInstaller 会话 + 系统安装器,
+ * 由人在设备上点「安装」;
+ * - 需要「安装未知应用」授权(每台设备一次,授权后不再问);
+ * - 只有更低的 versionCode 会被系统拒绝(INSTALL_FAILED_VERSION_DOWNGRADE),
+ * 同 versionCode 可以覆盖安装 —— 所以联调时不需要专门发新版本;
+ * - 安装完成后本进程会被杀掉,MediaProjection 授权必失效,得重新打开 App 授权录屏。
+ *
+ * 后台拉起安装确认框(BAL):已启用的无障碍服务是系统绑定服务,不受后台启动
+ * Activity 限制 —— 远控本来就要开无障碍,所以主路径是直接用 ControlService 拉起;
+ * 没有无障碍时退回一条通知,用户点开 MainActivity 后由它把确认框补上。
+ */
+object UpdateInstaller {
+
+ private const val TAG = "YAMA"
+
+ private const val CHANNEL_ID = "yama_update"
+ private const val NOTIF_CONFIRM = 101
+ private const val NOTIF_PROBLEM = 102
+
+ const val ACTION_INSTALL_STATUS = "com.yama.client.INSTALL_STATUS"
+ const val EXTRA_SESSION_ID = "session_id"
+
+ /** 待人工确认的安装 Intent;MainActivity 启动时拿它兜底重新拉一次 */
+ @Volatile
+ var pendingConfirmIntent: Intent? = null
+ private set
+
+ fun consumePendingConfirm(): Intent? {
+ val i = pendingConfirmIntent
+ pendingConfirmIntent = null
+ return i
+ }
+
+ private fun report(msg: String) {
+ Log.i(TAG, "UpdateInstaller: $msg")
+ // 走 native 主连接发 ClientMsg,服务端消息栏能看到失败原因。
+ // 注意服务端会为每条 ClientMsg 弹一个模态框,所以只报「需要人知道」的结论,
+ // 中间进度一律走 note()。
+ runCatching { YamaBridge.nativeReportMessage(msg) }
+ }
+
+ private fun note(msg: String) {
+ Log.i(TAG, "UpdateInstaller: $msg")
+ }
+
+ // ---------------------------------------------------------------- 入口
+
+ fun onApkReceived(ctx: Context, path: String) {
+ val app = ctx.applicationContext
+ Thread({
+ try {
+ install(app, path)
+ } catch (t: Throwable) {
+ report("install failed: $t")
+ }
+ }, "yama-install").start()
+ }
+
+ private fun install(ctx: Context, path: String) {
+ val file = File(path)
+ if (!file.isFile || file.length() <= 0L) {
+ report("apk missing or empty: $path")
+ return
+ }
+ val apkInfo = archiveInfo(ctx, path)
+ if (apkInfo == null) {
+ report("cannot parse apk (not a valid package)")
+ return
+ }
+ val apkCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
+ apkInfo.longVersionCode else apkInfo.versionCode.toLong()
+ val selfCode = selfVersionCode(ctx)
+ if (apkCode < selfCode) {
+ report("apk versionCode $apkCode < installed $selfCode, system refuses downgrade")
+ notifyUser(ctx, NOTIF_PROBLEM, "升级包版本过低",
+ "服务端下发的 APK 版本号($apkCode)低于已安装版本($selfCode),系统会拒绝安装。", null)
+ return
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
+ !ctx.packageManager.canRequestPackageInstalls()) {
+ report("install blocked: allow 'install unknown apps' for YAMA, then retry")
+ notifyUser(ctx, NOTIF_PROBLEM, "需要授权安装",
+ "请在系统设置里允许 YAMA 安装未知应用,然后重新在服务端点击升级。",
+ settingsPendingIntent(ctx))
+ return
+ }
+
+ val installer = ctx.packageManager.packageInstaller
+ val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
+ setAppPackageName(ctx.packageName)
+ setSize(file.length())
+ }
+ val sessionId = installer.createSession(params)
+ var session: PackageInstaller.Session? = null
+ try {
+ val s = installer.openSession(sessionId)
+ session = s
+ file.inputStream().use { input ->
+ s.openWrite("base.apk", 0, file.length()).use { output ->
+ input.copyTo(output)
+ s.fsync(output)
+ }
+ }
+ var flags = PendingIntent.FLAG_UPDATE_CURRENT
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
+ flags = flags or PendingIntent.FLAG_MUTABLE
+ val statusIntent = Intent(ACTION_INSTALL_STATUS)
+ .setPackage(ctx.packageName)
+ .putExtra(EXTRA_SESSION_ID, sessionId)
+ val pi = PendingIntent.getBroadcast(ctx, sessionId, statusIntent, flags)
+ s.commit(pi.intentSender)
+ note("installer session committed (versionCode $apkCode, ${file.length() / 1024} KB)")
+ } catch (t: Throwable) {
+ report("installer session failed: $t")
+ runCatching { session?.abandon() }
+ } finally {
+ runCatching { session?.close() }
+ }
+ }
+
+ // ---------------------------------------------------------------- 安装状态回调
+
+ /** 系统要求人工确认:把安装器界面拉到前台 */
+ fun onConfirmNeeded(ctx: Context, confirm: Intent?) {
+ if (confirm == null) {
+ report("installer: confirm intent missing")
+ return
+ }
+ confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ pendingConfirmIntent = confirm
+
+ val acc = ControlService.instance
+ if (acc != null) {
+ val ok = runCatching { acc.startActivity(confirm) }.isSuccess
+ if (ok) {
+ note("installer: confirm dialog opened")
+ return
+ }
+ note("installer: accessibility startActivity failed, falling back to notification")
+ } else {
+ note("installer: no accessibility, posting notification")
+ }
+ notifyUser(ctx, NOTIF_CONFIRM, "YAMA 有新版本待安装",
+ "点按继续完成安装。若没有反应,请先允许 YAMA 安装未知应用。",
+ mainActivityPendingIntent(ctx))
+ }
+
+ fun onInstallSuccess(ctx: Context) {
+ report("install success, app will restart")
+ pendingConfirmIntent = null
+ runCatching { File(ctx.filesDir, "update.apk").delete() }
+ // 安装完成后进程会被系统杀掉,这条通知通常来不及显示;
+ // 真正的「装好了,去授权录屏」提示由 ReplacedReceiver(MY_PACKAGE_REPLACED)负责。
+ }
+
+ fun onInstallFailed(ctx: Context, status: Int, message: String?) {
+ report("install failed: status=$status message=${message ?: "?"}")
+ pendingConfirmIntent = null
+ notifyUser(ctx, NOTIF_PROBLEM, "YAMA 升级失败", message ?: "系统拒绝了这次安装(status=$status)", null)
+ }
+
+ // ---------------------------------------------------------------- 辅助
+
+ private fun selfVersionCode(ctx: Context): Long = try {
+ val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
+ ctx.packageManager.getPackageInfo(ctx.packageName, PackageManager.PackageInfoFlags.of(0))
+ else
+ @Suppress("DEPRECATION") ctx.packageManager.getPackageInfo(ctx.packageName, 0)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) info.longVersionCode
+ else @Suppress("DEPRECATION") info.versionCode.toLong()
+ } catch (t: Throwable) {
+ Log.w(TAG, "selfVersionCode failed: $t")
+ 0L
+ }
+
+ private fun archiveInfo(ctx: Context, path: String): android.content.pm.PackageInfo? = try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
+ ctx.packageManager.getPackageArchiveInfo(path, PackageManager.PackageInfoFlags.of(0))
+ else
+ @Suppress("DEPRECATION") ctx.packageManager.getPackageArchiveInfo(path, 0)
+ } catch (t: Throwable) {
+ Log.w(TAG, "getPackageArchiveInfo failed: $t")
+ null
+ }
+
+ private fun settingsPendingIntent(ctx: Context): PendingIntent? {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null
+ val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
+ Uri.parse("package:${ctx.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ var flags = PendingIntent.FLAG_UPDATE_CURRENT
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
+ flags = flags or PendingIntent.FLAG_IMMUTABLE
+ return PendingIntent.getActivity(ctx, 0, intent, flags)
+ }
+
+ /** 点开后打开 MainActivity(由它把待确认的安装框补上 / 请求录屏授权) */
+ fun mainActivityPendingIntent(ctx: Context): PendingIntent? {
+ val intent = Intent(ctx, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ var flags = PendingIntent.FLAG_UPDATE_CURRENT
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
+ flags = flags or PendingIntent.FLAG_IMMUTABLE
+ return PendingIntent.getActivity(ctx, 0, intent, flags)
+ }
+
+ /** 升级相关通知。Android 13+ 没给通知权限就只记日志——不追加授权弹窗,免得和录屏授权抢注意力 */
+ fun notifyUser(ctx: Context, id: Int, title: String, text: String, action: PendingIntent?) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ ctx.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
+ PackageManager.PERMISSION_GRANTED) {
+ note("notification skipped ($title): POST_NOTIFICATIONS not granted")
+ return
+ }
+ // minSdk 21:不能用 getSystemService(Class)(API 23+)
+ val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ nm.createNotificationChannel(
+ NotificationChannel(CHANNEL_ID, "YAMA 升级", NotificationManager.IMPORTANCE_HIGH))
+ }
+ val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
+ Notification.Builder(ctx, CHANNEL_ID)
+ else
+ @Suppress("DEPRECATION") Notification.Builder(ctx)
+ b.setSmallIcon(android.R.drawable.stat_sys_download_done)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setStyle(Notification.BigTextStyle().bigText(text))
+ .setAutoCancel(true)
+ if (action != null) b.setContentIntent(action)
+ runCatching { nm.notify(id, b.build()) }
+ }
+}
diff --git a/android/app/src/main/java/com/yama/client/YamaBridge.kt b/android/app/src/main/java/com/yama/client/YamaBridge.kt
index 254cb83..283732f 100644
--- a/android/app/src/main/java/com/yama/client/YamaBridge.kt
+++ b/android/app/src/main/java/com/yama/client/YamaBridge.kt
@@ -14,7 +14,9 @@ object YamaBridge {
screenRes: String,
username: String,
apkPath: String,
- filesDir: String
+ filesDir: String,
+ versionName: String,
+ versionCode: Int
): Int
external fun nativeStop()
@@ -24,4 +26,7 @@ object YamaBridge {
/** MediaCodec 每输出一帧 H.264 NALU 时调用 */
external fun nativeOnH264Frame(data: ByteArray, offset: Int, size: Int, isKeyframe: Boolean)
+
+ /** 把一行文本回报到服务端消息栏(TOKEN_CLIENT_MSG),用于升级流程的成败说明 */
+ external fun nativeReportMessage(msg: String)
}
diff --git a/android/tools/verify_update_apk.py b/android/tools/verify_update_apk.py
new file mode 100644
index 0000000..445860d
--- /dev/null
+++ b/android/tools/verify_update_apk.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python3
+"""Pre-flight check for an Android APK before installing or pushing it as an update.
+
+Usage:
+ verify_update_apk.py [--ip 91.99.165.207] [--port 443]
+ [--admin 61f04dd637a74ee3] [--cert-sha256 b8ad4ced...]
+ [--sdk ]
+
+Checks:
+ * size <= 40MB (server-side SendApkUpdate limit)
+ * APK/ZIP, and lib/*/libyama.so stored (not deflated) so the server can patch it
+ * each ABI's CONNECT_ADDRESS: IP / port / superAdmin match expectations
+ -> 「生成客户端」 checks "encrypt IP" by default, so szServerIP/szPort are
+ ciphertext; this script decrypts with StreamCipher(0x12345678), the same
+ algorithm the client uses in ServerIP()/ServerPort().
+ * dex contains UpdateInstaller (the build can accept COMMAND_UPDATE later)
+ * with --sdk: prints package / versionCode / native-code
+
+Locating the struct: first by the szFlag plaintext ("Hello, World!" in the pristine
+template), then by the master id string (BuildDlg rewrites szFlag to it), then by
+the superAdmin needle (base = hit - 228), then by the plaintext IP string.
+Exit code 0 = all checks passed, 1 = something failed.
+"""
+import glob
+import os
+import re
+import struct
+import subprocess
+import sys
+import zipfile
+import zlib
+
+MARKERS = [b"Hello, World!\x00"]
+OFF_IP, LEN_IP = 32, 100
+OFF_PORT, LEN_PORT = 132, 8
+OFF_TYPE = 140
+OFF_ENCRYPT = 144
+OFF_ADMIN = 228
+CLIENT_TYPE_ANDROID = 8
+MAX_SIZE = 40 * 1024 * 1024
+
+
+def arg(name, default=None):
+ if name in sys.argv:
+ return sys.argv[sys.argv.index(name) + 1]
+ return default
+
+
+def stream_cipher(data, key=0x12345678):
+ """Same as common/ip_enc.h StreamCipher::process (xorshift32 + xor)."""
+ state = key
+ out = bytearray()
+ for b in data:
+ state ^= (state << 13) & 0xFFFFFFFF
+ state ^= state >> 17
+ state ^= (state << 5) & 0xFFFFFFFF
+ state &= 0xFFFFFFFF
+ out.append(b ^ ((state & 0xFF) ^ ((state >> 8) & 0xFF)))
+ return bytes(out)
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(__doc__)
+ return 1
+ apk = sys.argv[1]
+ want_ip = arg("--ip")
+ want_port = arg("--port")
+ want_admin = arg("--admin")
+ want_cert = (arg("--cert-sha256") or "").replace(":", "").lower()
+ sdk = arg("--sdk")
+
+ fails = []
+
+ def check(ok, msg):
+ print((" OK " if ok else " FAIL ") + msg)
+ if not ok:
+ fails.append(msg)
+
+ size = os.path.getsize(apk)
+ print("apk: %s (%d bytes)" % (apk, size))
+ check(size <= MAX_SIZE, "size %d <= 40MB" % size)
+
+ with open(apk, "rb") as f:
+ head = f.read(4)
+ check(head == b"PK\x03\x04", "ZIP magic")
+
+ z = zipfile.ZipFile(apk)
+ infos = z.infolist()
+
+ def read_entry(name):
+ """z.read() that tolerates a stale CRC-32.
+
+ BuildDlg patches libyama.so in place without recomputing the ZIP CRC, so
+ every generated APK fails zipfile's CRC check even though the payload is
+ fine. Read the raw stored bytes instead.
+ """
+ try:
+ return z.read(name), True
+ except zipfile.BadZipFile:
+ info = z.getinfo(name)
+ with open(apk, "rb") as f:
+ f.seek(info.header_offset)
+ local = f.read(30)
+ if len(local) < 30 or local[:4] != b"PK\x03\x04":
+ raise
+ nlen, elen = struct.unpack_from(" len(data):
+ return False
+ itype = struct.unpack_from("= 0 and valid_struct(base):
+ return base
+ start = p + 1
+ return -1
+
+ for i in sos:
+ check(i.compress_type == 0, "%s stored (not deflated)" % i.filename)
+ data, crc_ok = read_entry(i.filename)
+ if not crc_ok:
+ print(" WARN %s: ZIP CRC is stale (patched in place, as BuildDlg does) - "
+ "harmless for install, but the APK must be re-signed" % i.filename)
+ pos = find_struct(data)
+ abi = i.filename.split("/")[1]
+ if pos < 0:
+ check(False, "%s: CONNECT_ADDRESS not found" % i.filename)
+ continue
+ ip, port = decrypted(pos)
+ ip_s, port_s = ip.decode("latin1"), port.decode("latin1")
+ enc = data[pos + OFF_ENCRYPT]
+ admin = struct.unpack_from("
+#include
#include