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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-11 00:53:29 +01:00
1 parent cdd9c56b3d
commit 36618b0ad0
17 files changed
+955 -8

No files matched your search

@@ -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()
@@ -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)
}
}
}
}
@@ -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 }
@@ -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))
}
}
@@ -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()) }
}
}
@@ -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)
}