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

+7 -2
View File
@@ -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")
+22
View File
@@ -5,6 +5,10 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<!-- 在线升级:走 PackageInstaller 会话安装服务端下发的 APK,仍需系统安装器人工确认 -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- 升级完成/需要人工确认时的提示通知(Android 13+ 是运行时权限) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
@@ -42,6 +46,24 @@
android:resource="@xml/accessibility_service_config" />
</service>
<!-- 安装会话状态回执(PendingIntent 指向本 receiver) -->
<receiver
android:name=".InstallResultReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.yama.client.INSTALL_STATUS" />
</intent-filter>
</receiver>
<!-- 覆盖安装完成后,提醒用户打开 App 重新授权录屏 -->
<receiver
android:name=".ReplacedReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
</application>
</manifest>
+153 -3
View File
@@ -195,6 +195,9 @@ State g_bExit{S_CLIENT_NORMAL};
uint64_t g_myClientID = 0; // sub_conn_thread.h 需要的外部符号
static std::atomic<bool> g_running{false};
static std::atomic<uint64_t> 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<uint64_t> 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<IOCPClient> 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)
@@ -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)
}
+259
View File
@@ -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 <apk> [--ip 91.99.165.207] [--port 443]
[--admin 61f04dd637a74ee3] [--cert-sha256 b8ad4ced...]
[--sdk <AndroidSDK>]
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("<HH", local, 26)
f.seek(info.header_offset + 30 + nlen + elen)
payload = f.read(info.compress_size)
if info.compress_type == zipfile.ZIP_STORED:
return payload, False
return zlib.decompress(payload, -15), False
sos = [i for i in infos if i.filename.startswith("lib/") and i.filename.endswith("libyama.so")]
abis = sorted({i.filename.split("/")[1] for i in sos})
print("abis: %s" % (", ".join(abis) if abis else "none"))
check(bool(sos), "libyama.so present")
check("x86" not in abis and "x86_64" not in abis, "no emulator ABIs (production build)")
dex_ok = False
for i in infos:
if i.filename.startswith("classes") and i.filename.endswith(".dex"):
data = z.read(i.filename)
if b"UpdateInstaller" in data and b"yama_update" in data:
dex_ok = True
check(dex_ok, "dex has UpdateInstaller (this build can be upgraded later)")
markers = list(MARKERS)
if arg("--marker"):
markers.insert(0, arg("--marker").encode() + b"\x00")
flag_needle = None
admin_needle = None
if want_admin:
admin_needle = struct.pack("<Q", int(want_admin, 16))
# BuildDlg rewrites szFlag to the first 16 chars of the master id, which is
# the same hex string the admin id was parsed from.
flag_needle = want_admin[:16].encode()
def raw_fields(base):
ip = bytes(data[base + OFF_IP:base + OFF_IP + LEN_IP])
pt = bytes(data[base + OFF_PORT:base + OFF_PORT + LEN_PORT])
return ip, pt
def decrypted(base):
ip, pt = raw_fields(base)
if data[base + OFF_ENCRYPT]:
plain = stream_cipher(ip + pt)
ip, pt = plain[:LEN_IP], plain[LEN_IP:]
return ip.split(b"\0")[0], pt.split(b"\0")[0]
def sane(ip, pt):
return (ip and all(48 <= c <= 57 or c == 46 for c in ip) and
pt and all(48 <= c <= 57 for c in pt))
def valid_struct(base):
if base < 0 or base + OFF_ADMIN + 8 > len(data):
return False
itype = struct.unpack_from("<i", data, base + OFF_TYPE)[0]
enc = data[base + OFF_ENCRYPT]
if itype != CLIENT_TYPE_ANDROID or enc not in (0, 1):
return False
return sane(*decrypted(base))
def find_struct(d):
for m in markers:
start = 0
while True:
p = d.find(m, start)
if p < 0:
break
# pristine template: szFlag plaintext, IP not yet encrypted
if d[p + OFF_ENCRYPT] == 0 and sane(*raw_fields(p)):
return p
start = p + 1
if flag_needle:
start = 0
while True:
p = d.find(flag_needle, start)
if p < 0:
break
if valid_struct(p):
return p
start = p + 1
if admin_needle:
start = 0
while True:
p = d.find(admin_needle, start)
if p < 0:
break
base = p - OFF_ADMIN
if valid_struct(base):
return base
start = p + 1
if want_ip: # last resort: plaintext IP string
start = 0
while True:
p = d.find(want_ip.encode(), start)
if p < 0:
break
base = p - OFF_IP
if base >= 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("<Q", data, pos + OFF_ADMIN)[0]
print(" %-12s ip=%s port=%s admin=%016x enc=%d" % (abi, ip_s, port_s, admin, enc))
if admin == 0:
print(" WARN admin=0: the server's update dialog will say it cannot find "
"this master's id and offer 'send anyway'")
if want_ip:
check(ip_s == want_ip, "%s: ip %s == %s" % (abi, ip_s, want_ip))
if want_port:
check(port_s == want_port, "%s: port %s == %s" % (abi, port_s, want_port))
if want_admin:
check(admin == int(want_admin, 16),
"%s: admin %016x == %s" % (abi, admin, want_admin))
aapt = None
if sdk:
cands = sorted(glob.glob(os.path.join(sdk, "build-tools", "*", "aapt2.exe"))) or \
sorted(glob.glob(os.path.join(sdk, "build-tools", "*", "aapt2")))
aapt = cands[-1] if cands else None
if aapt:
out = subprocess.run([aapt, "dump", "badging", apk], capture_output=True, text=True).stdout
m = re.search(r"package: name='([^']+)' versionCode='(\d+)' versionName='([^']*)'", out)
if m:
print(" package=%s versionCode=%s versionName=%s" % (m.group(1), m.group(2), m.group(3)))
check(m.group(1) == "com.yama.client", "package is com.yama.client")
m = re.search(r"native-code: (.*)", out)
if m:
print(" native-code: %s" % m.group(1))
if want_cert:
print(" (check the cert with apksigner verify --print-certs; expected %s)" % want_cert)
print()
if fails:
print("RESULT: %d check(s) failed - do not send this APK" % len(fails))
return 1
print("RESULT: passed")
return 0
if __name__ == "__main__":
sys.exit(main())
+5
View File
@@ -143,6 +143,7 @@ inline int isValid_10s()
#define CLIENT_CAP_VIRTUAL_DESKTOP 0x0080 // 支持按 COMMAND_SCREEN_SPY 参数 buffer[11](wire 索引 12)强制抓取整个虚拟桌面(多显示器远程控制)
#define CLIENT_CAP_WINDOW_INFO 0x0100 // 支持 COMMAND_MCP_WINDOW_INFO(带矩形/前后台/最小化状态的窗口列表)与窗口激活(CMD_WINDOW_ACTIVATE_FLAG)
#define CLIENT_CAP_SCREEN_REGION 0x0200 // 支持 COMMAND_SCREEN_PREVIEW_REQ 扩展(区域/窗口/显示器原生分辨率截图)
#define CLIENT_CAP_APK_UPDATE 0x0400 // 支持接收 COMMAND_UPDATE 下发的 APK 并走系统安装器(仅 Android)
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
@@ -1295,6 +1296,10 @@ typedef struct LOGIN_INFOR {
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
caps |= CLIENT_CAP_C2C_RECV_ACK;
#elif defined(__ANDROID__)
// 收到服务端下发的 APK 后写盘并拉起系统安装器。老 APK 没有这个分支,
// 服务端据此提示「先手动装一次新版」,而不是发一个对方会静默丢弃的包。
caps |= CLIENT_CAP_APK_UPDATE;
#endif
return caps;
}
+118 -1
View File
@@ -23,6 +23,7 @@
#include "ConnectionsDlg.h"
#include "VideoDlg.h"
#include <vector>
#include <algorithm>
#include <map>
#include <mutex>
#include <filesystem>
@@ -5424,13 +5425,18 @@ void CMy2015RemoteDlg::OnOnlineUpdate()
MessageBoxL(_T("请选择一个被控程序进行升级!"), _T("提示"), MB_ICONWARNING);
return;
}
CString clientType = ContextObject->GetAdditionalData(RES_CLIENT_TYPE).GetString();
if (clientType == "APK") {
// Android 有自己的确认流程(选包/校验/人工安装提示),普通的「是否升级」框对它没有信息量
SendApkUpdate(ContextObject);
return;
}
if (IDYES != MessageBoxL(_T("确定升级选定的被控程序吗?\n需受控程序支持方可生效!"),
_T("提示"), MB_ICONQUESTION | MB_YESNO))
return;
PBYTE buffer = nullptr;
ULONGLONG fileSize = 0;
ULONG packetSize = 0; // LNX 载荷尾部带 32 字节 MD5,故不总是 9 + fileSize
CString clientType = ContextObject->GetAdditionalData(RES_CLIENT_TYPE).GetString();
if (clientType == "EXE") {
CUpdateDlg dlg(this);
if (dlg.DoModal() != IDOK)
@@ -5567,6 +5573,117 @@ void CMy2015RemoteDlg::OnOnlineUpdate()
}
}
// 安卓在线升级:把「生成客户端导出、并用 android/sign_apk.bat 重签过」的 APK 整包
// 发给客户端,由客户端的系统安装器弹框、人工点安装。
// 载荷布局:[cmd:1][size:8 LE][APK:size][xxh64:8 LE]
//
// 为什么要扫主控指纹:APK 里的 CONNECT_ADDRESS(服务器地址/端口/主控 ID)是
// 「生成客户端」写进去的。直接发模板(未 patch、未重签)装上去会连错服务器并失联,
// 所以这里用 GetMasterHash() 的高 8 字节在 APK 里扫一遍,扫不到默认取消,防手滑。
VOID CMy2015RemoteDlg::SendApkUpdate(context* ContextObject)
{
// 后面全是模态框;期间主机可能下线被销毁,先把手头要用的信息取出来
CString targetIp = ContextObject->GetClientData(ONLINELIST_IP);
if (!ContextObject->SupportsApkUpdate()) {
MessageBoxL(_L("该安卓客户端版本过旧,不认识在线升级命令(收到也会丢弃)。\n\n"
"请先手动在同一台设备上安装一次新版 APK,之后即可在线升级。"),
_L("提示"), MB_ICONWARNING);
return;
}
std::string lastPath = THIS_CFG.GetStr("settings", "AndroidClientPath", "");
CFileDialog dlg(TRUE, _T("apk"), lastPath.empty() ? _T("ghost.apk") : CString(lastPath.c_str()),
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Android 安装包 (*.apk)|*.apk|所有文件 (*.*)|*.*||"), this);
if (dlg.DoModal() != IDOK)
return;
CString apkPath = dlg.GetPathName();
// 客户端 IOCPClient 的 MAX_PACKET_SIZE 是 50MB,留点余量
const ULONGLONG kMaxApkSize = 40ull * 1024 * 1024;
std::ifstream in(apkPath.GetString(), std::ios::binary | std::ios::ate);
if (!in) {
CString msg;
msg.Format(_L("无法打开文件:\n%s"), apkPath.GetString());
MessageBoxL(msg, _L("提示"), MB_ICONWARNING);
return;
}
std::streamoff len = (std::streamoff)in.tellg();
if (len <= 0 || (ULONGLONG)len > kMaxApkSize) {
CString msg;
msg.Format(_L("APK 是空文件或超过 %llu 字节上限,不能下发。\n\n文件:\n%s"),
(unsigned long long)kMaxApkSize, apkPath.GetString());
MessageBoxL(msg, _L("提示"), MB_ICONWARNING);
return;
}
std::vector<BYTE> apk((size_t)len);
in.seekg(0);
if (!in.read((char*)apk.data(), len)) {
CString msg;
msg.Format(_L("读取文件失败:\n%s"), apkPath.GetString());
MessageBoxL(msg, _L("提示"), MB_ICONWARNING);
return;
}
// 路径记下来,下次默认打开同一目录(和 LinuxClientPath 一样放在 settings 段)
THIS_CFG.SetStr("settings", "AndroidClientPath", std::string(apkPath.GetString()));
auto reject = [&](LPCTSTR why) {
CString msg;
msg.Format(_L("无法下发该 APK:\n%s\n\n%s"), apkPath.GetString(), why);
MessageBoxL(msg, _L("提示"), MB_ICONWARNING);
};
if (apk.size() < 1024 || apk[0] != 'P' || apk[1] != 'K' || apk[2] != 0x03 || apk[3] != 0x04) {
reject(_L("不是 APK(ZIP)文件"));
return;
}
// CONNECT_ADDRESS.superAdmin = GetMasterHash() 前 16 个 hex 字符的 uint64,生成客户端时
// 原样写进 libyama.so;useLegacyPackaging=false 让它以 ZIP_STORED 存放,可直接搜到。
bool patched = false;
{
std::string hash = GetMasterHash();
if (hash.size() >= 16) {
uint64_t adminId = strtoull(hash.substr(0, 16).c_str(), NULL, 16);
// 必须用 BYTE:std::search 逐元素比较 *it1 == *it2,apk 是 vector<BYTE>(unsigned char),
// 若 needle 是 char 则 >=0x80 的字节(如 0xE3)会被当负数提升,永远比不上 227。
BYTE needle[8] = {};
memcpy(needle, &adminId, sizeof(needle));
patched = std::search(apk.begin(), apk.end(), needle, needle + sizeof(needle)) != apk.end();
}
}
if (!patched) {
CString msg;
msg.Format(_L("这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n"
"请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat "
"重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n"
"文件:\n%s\n\n仍然下发吗?"),
apkPath.GetString());
if (IDYES != MessageBoxL(msg, _L("确认"), MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2))
return;
}
ULONGLONG fileSize = (ULONGLONG)apk.size();
ULONG packetSize = (ULONG)(9 + fileSize + 8);
std::vector<BYTE> packet(packetSize);
packet[0] = COMMAND_UPDATE;
memcpy(&packet[1], &fileSize, 8);
memcpy(&packet[9], apk.data(), (size_t)fileSize);
uint64_t digest = XXH64(apk.data(), (size_t)fileSize, 0);
memcpy(&packet[9 + fileSize], &digest, 8);
Mprintf("[Update] Android APK %s (%llu bytes, xxh64=%016llx) → %s\n",
apkPath.GetString(), (unsigned long long)fileSize,
(unsigned long long)digest, targetIp.GetString());
SendSelectedCommand(packet.data(), packetSize);
MessageBoxL(_L("APK 已下发。\n\n"
"接下来的操作需要在设备上完成:\n"
"1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n"
"2. 点「安装」确认覆盖安装;\n"
"3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。"),
_L("提示"), MB_ICONINFORMATION);
}
std::string floatToString(float f)
{
char buf[32];
+2
View File
@@ -301,6 +301,8 @@ public:
VOID MessageHandle(CONTEXT_OBJECT* ContextObject);
VOID SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb = NULL, void* user=NULL);
VOID SendAllCommand(PBYTE szBuffer, ULONG ulLength);
// 安卓在线升级:选包 → 校验(ZIP 魔数 / 主控指纹)→ 组 [cmd][size][APK][xxh64] 下发
VOID SendApkUpdate(context* ContextObject);
// 显示用户上线信息
CWnd* m_pFloatingTip = nullptr;
// 屏幕预览:m_pFloatingTip 实际是 CPreviewTipWnd 时这里有同一指针的有类型副本,
+9
View File
@@ -139,6 +139,15 @@ public:
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
}
// 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。
// 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃,
// 服务端据此提示「先手动装一次新版」。
bool SupportsApkUpdate() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
if (caps.IsEmpty()) return false;
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_APK_UPDATE) != 0;
}
// 本机当前是不是靠「生成时内嵌的 TLS 信任锚」在加密(CLIENT_CAP_EMBEDDED_ANCHOR)。
// 这不是能力声明而是运行时状态:只有这种主机在服务端关掉 TLS 后无法自愈——在线时
// 还能收到「取消 TLS」,离线时发 ClientHello 会被 fail-closed 挡掉,再也进不来。
+9
View File
@@ -2243,3 +2243,12 @@ HTTPS
延迟高=hohe Latenz
带宽不足=geringe Bandbreite
链路改善=Link wieder gut
该安卓客户端版本过旧,不认识在线升级命令(收到也会丢弃)。\n\n请先手动在同一台设备上安装一次新版 APK,之后即可在线升级。=Dieser Android-Client ist zu alt und kennt den Online-Update-Befehl nicht (er wird verworfen).\n\nInstallieren Sie einmalig manuell ein neues APK auf demselben Geraet; danach funktionieren Online-Updates.
无法打开文件:\n%s=Datei kann nicht geoeffnet werden:\n%s
APK 是空文件或超过 %llu 字节上限,不能下发。\n\n文件:\n%s=Das APK ist leer oder groesser als das Limit von %llu Byte und kann nicht gesendet werden.\n\nDatei:\n%s
读取文件失败:\n%s=Datei konnte nicht gelesen werden:\n%s
无法下发该 APK:\n%s\n\n%s=Dieses APK kann nicht gesendet werden:\n%s\n\n%s
不是 APK(ZIP)文件=Keine APK-(ZIP-)Datei
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=Dieses APK enthaelt keine Kennung dieses Masters; nach der Installation kann es sich sehr wahrscheinlich nicht mit diesem Server verbinden.\n\nStellen Sie sicher, dass es ueber "Client erstellen -> Android" exportiert und mit android/sign_apk.bat neu signiert wurde (ein nicht neu signiertes Paket behaelt die alte Signatur, und das System verweigert die Neuinstallation).\n\nDatei:\n%s\n\nTrotzdem senden?
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=Das APK wurde gesendet.\n\nDie restlichen Schritte muessen am Geraet ausgefuehrt werden:\n1. Erscheint kein Installationsdialog, ist "Unbekannte Apps installieren" fuer YAMA vermutlich nicht erlaubt - in den App-Einstellungen des Geraets aktivieren;\n2. Auf "Installieren" tippen, um die Neuinstallation zu bestaetigen;\n3. Nach der Installation YAMA oeffnen und die Bildschirmaufnahme erneut erlauben (die Berechtigung geht bei jedem Update verloren).
确认=Bestaetigen
+9
View File
@@ -2255,3 +2255,12 @@ MCP:
延迟高=high latency
带宽不足=low bandwidth
链路改善=link improved
该安卓客户端版本过旧,不认识在线升级命令(收到也会丢弃)。\n\n请先手动在同一台设备上安装一次新版 APK,之后即可在线升级。=This Android client is too old and does not understand the online upgrade command (it will be discarded).\n\nInstall a new APK on the same device manually once, then online upgrades will work.
无法打开文件:\n%s=Cannot open file:\n%s
APK 是空文件或超过 %llu 字节上限,不能下发。\n\n文件:\n%s=The APK is empty or larger than the %llu byte limit and cannot be sent.\n\nFile:\n%s
读取文件失败:\n%s=Failed to read file:\n%s
无法下发该 APK:\n%s\n\n%s=Cannot send this APK:\n%s\n\n%s
不是 APK(ZIP)文件=Not an APK (ZIP) file
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=This APK does not contain the identifier of this master, so once installed it very likely cannot connect back to this server.\n\nMake sure it was exported by "Build Client -> Android" and re-signed with android/sign_apk.bat (a package that was not re-signed keeps the old signature and the system will refuse to overwrite the installed app).\n\nFile:\n%s\n\nSend anyway?
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=The APK has been sent.\n\nThe remaining steps must be done on the device:\n1. If no installer dialog appears, the system may not allow "install unknown apps" - enable it for YAMA in the device's app settings;\n2. Tap "Install" to confirm the overwrite install;\n3. After installing, open YAMA and grant screen capture again (the grant is always lost after an upgrade).
确认=Confirm
+9
View File
@@ -2248,3 +2248,12 @@ MCP:
延迟高=延遲高
带宽不足=頻寬不足
链路改善=鏈路改善
该安卓客户端版本过旧,不认识在线升级命令(收到也会丢弃)。\n\n请先手动在同一台设备上安装一次新版 APK,之后即可在线升级。=該安卓客戶端版本過舊,不認識線上升級命令(收到也會丟棄)。\n\n請先手動在同一台裝置上安裝一次新版 APK,之後即可線上升級。
无法打开文件:\n%s=無法開啟檔案:\n%s
APK 是空文件或超过 %llu 字节上限,不能下发。\n\n文件:\n%s=APK 是空檔案或超過 %llu 位元組上限,不能下發。\n\n檔案:\n%s
读取文件失败:\n%s=讀取檔案失敗:\n%s
无法下发该 APK:\n%s\n\n%s=無法下發該 APK:\n%s\n\n%s
不是 APK(ZIP)文件=不是 APK(ZIP)檔案
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=這個 APK 裡沒有找到本主控的標識,裝上去很可能連不回本伺服器。\n\n請確認它是「生成客戶端 → 安卓」匯出的包,並且已經用 android/sign_apk.bat 重新簽名(未重簽的包簽名對不上,系統會拒絕覆寫安裝)。\n\n檔案:\n%s\n\n仍然下發嗎?
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=APK 已下發。\n\n接下來的操作需要在裝置上完成:\n1. 若沒彈出安裝框,可能是系統未授權「安裝未知應用」——在裝置的應用設定裡給 YAMA 打開;\n2. 點「安裝」確認覆寫安裝;\n3. 安裝完成後打開 YAMA,重新授權錄屏(升級後授權一定會失效)。
确认=確認