增加应用列表排序

This commit is contained in:
xgh 2026-11-04 17:48:42 +08:00
parent a3f1f63fe8
commit b0d4bbbc3b
5 changed files with 231 additions and 171 deletions

View File

@ -25,17 +25,19 @@
## 使用步骤 ## 使用步骤
1. **手机端准备 atx-agent**(非 root,需一次性 adb): 1. 在 Root 设备上安装并打开 CP Bridge APK,填写服务器地址(如 `ws://192.168.1.100:8000/ws/device`)、token(服务器启用时才需要)、设备名称并保存。
2. 在启动桥接服务前,点击「部署 atx-agent(需 Root)」并在 Root 管理器中授权。APK 会将内置 atx-agent 复制到 `/data/local/tmp/atx-agent` 并启动它,以系统进程列表中能查到该进程作为部署成功条件。
3. 点击「启动桥接服务」;状态卡显示「已连接服务器」即接入成功。
4. 管理平台 Web 页面(http://服务器:8000)会出现该设备,可执行支持的设备操作。
没有 Root 时,可使用 ADB 手动推送并启动:
```bash ```bash
adb push atx-agent /data/local/tmp/atx-agent adb push atx-agent /data/local/tmp/atx-agent
adb shell chmod 755 /data/local/tmp/atx-agent adb shell chmod 755 /data/local/tmp/atx-agent
adb shell /data/local/tmp/atx-agent server -d # 启动 atx-agent adb shell /data/local/tmp/atx-agent server -d
``` ```
2. 安装并打开 CP Bridge APK,填写服务器地址(如 `ws://192.168.1.100:8000/ws/device`)、token(服务器启用时才需要)、设备名称,保存
3. 点击「启动桥接服务」;状态卡显示「已连接服务器」即接入成功
4. 管理平台 Web 页面(http://服务器:8000)会出现该设备,可执行 Shell / 查看设备信息
> 重启手机后 atx-agent 进程会丢失,需重新 `adb shell /data/local/tmp/atx-agent server -d`(root 设备可自行加入启动脚本)。 Root 部署和 ADB 部署都使用 `/data/local/tmp/atx-agent`。文件只需安装一次;设备重启后进程会退出,重新点部署按钮(Root)或执行启动命令(ADB)即可。
## 模块说明 ## 模块说明

View File

@ -10,12 +10,12 @@ import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.pm.ServiceInfo import android.content.pm.ServiceInfo
import android.os.Build import android.os.Build
import android.os.PowerManager
import android.provider.Settings import android.provider.Settings
import android.util.Log import android.util.Log
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import com.cpagent.bridge.agent.AtxClient import com.cpagent.bridge.agent.AtxClient
import com.cpagent.bridge.agent.AtxDeployer
import com.cpagent.bridge.agent.DeviceBasicInfo import com.cpagent.bridge.agent.DeviceBasicInfo
import com.cpagent.bridge.handler.CommandRouter import com.cpagent.bridge.handler.CommandRouter
import com.cpagent.bridge.monitor.HeartbeatMonitor import com.cpagent.bridge.monitor.HeartbeatMonitor
@ -28,7 +28,6 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
/** /**
@ -78,21 +77,7 @@ class BridgeService : Service() {
private var wsClient: BridgeWsClient? = null private var wsClient: BridgeWsClient? = null
private var deviceId: String = "" private var deviceId: String = ""
private var atxClient: AtxClient? = null private var atxClient: AtxClient? = null
private var deployer: AtxDeployer? = null private var wakeLock: PowerManager.WakeLock? = null
/** 手动触发:root 检测 + 部署 + 启动 atx-agent,结果通过回调返回。 */
fun deployAtxAgent(onResult: (Boolean, String) -> Unit) {
val atx = atxClient ?: AtxClient().also { atxClient = it }
val d = deployer ?: AtxDeployer(this).also { deployer = it }
scope.launch {
val ok = d.ensureRunning(atx)
val msg = if (ok) "atx-agent 已就绪" else "部署失败(无 root 或启动超时),详见日志 CpBridgeAtxDeploy"
if (ok) agentHealthy = true
notifyState()
withContext(Dispatchers.Main) { onResult(ok, msg) }
}
}
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
@ -119,8 +104,6 @@ class BridgeService : Service() {
private fun startBridge() { private fun startBridge() {
Log.i(TAG, "startBridge() called, running=$running") Log.i(TAG, "startBridge() called, running=$running")
if (running) return if (running) return
running = true
lastError = ""
ServiceCompat.startForeground( ServiceCompat.startForeground(
this, NOTIFICATION_ID, buildNotification("连接中..."), this, NOTIFICATION_ID, buildNotification("连接中..."),
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
@ -134,10 +117,14 @@ class BridgeService : Service() {
if (serverUrl.isBlank()) { if (serverUrl.isBlank()) {
Log.e(TAG, "serverUrl 为空,服务不启动") Log.e(TAG, "serverUrl 为空,服务不启动")
lastError = "未配置服务器地址" lastError = "未配置服务器地址"
updateNotification("未配置服务器地址") stopSelf()
return return
} }
running = true
lastError = ""
acquireWakeLock()
val basicInfo = DeviceBasicInfo.of(deviceId, deviceName) val basicInfo = DeviceBasicInfo.of(deviceId, deviceName)
val atx = AtxClient().also { atxClient = it } val atx = AtxClient().also { atxClient = it }
@ -194,6 +181,7 @@ class BridgeService : Service() {
running = false running = false
instance = null instance = null
wsClient?.close() wsClient?.close()
releaseWakeLock()
scope.cancel() scope.cancel()
notifyState() notifyState()
super.onDestroy() super.onDestroy()
@ -201,6 +189,24 @@ class BridgeService : Service() {
override fun onBind(intent: Intent?) = null override fun onBind(intent: Intent?) = null
/** 屏幕关闭时维持 CPU 活跃,避免桥接心跳和 WebSocket 指令处理被深度休眠暂停。 */
private fun acquireWakeLock() {
if (wakeLock?.isHeld == true) return
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$TAG:Bridge").apply {
setReferenceCounted(false)
acquire()
}
Log.i(TAG, "已获取部分唤醒锁")
}
private fun releaseWakeLock() {
wakeLock?.let { lock ->
if (lock.isHeld) lock.release()
}
wakeLock = null
}
private fun buildNotification(text: String): Notification { private fun buildNotification(text: String): Notification {
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

View File

@ -33,7 +33,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BatteryAlert import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Memory
import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
@ -60,6 +59,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@ -69,8 +69,10 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import com.cpagent.bridge.agent.AtxDeployer
import com.cpagent.bridge.ws.WsState import com.cpagent.bridge.ws.WsState
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
@ -333,8 +335,9 @@ private fun ConfigCard(
@Composable @Composable
private fun ControlCard(context: Context) { private fun ControlCard(context: Context) {
val running = BridgeService.running val running = BridgeService.running
val scope = rememberCoroutineScope()
var deploying by remember { mutableStateOf(false) } var deploying by remember { mutableStateOf(false) }
var deployMsg by remember { mutableStateOf("") } var deployMessage by remember { mutableStateOf("") }
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
@ -342,38 +345,45 @@ private fun ControlCard(context: Context) {
) { ) {
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("桥接服务", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("桥接服务", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
if (running) { if (!running) {
OutlinedButton( OutlinedButton(
enabled = !deploying,
onClick = { onClick = {
if (deploying) return@OutlinedButton scope.launch {
deploying = true deploying = true
deployMsg = "检测 root 并部署中..." deployMessage = "正在请求 Root 并部署 atx-agent…"
BridgeService.instance?.deployAtxAgent { ok, msg -> val started = AtxDeployer(context.applicationContext).ensureRunning()
deployMessage = if (started) "atx-agent 进程已启动,可以启动桥接服务"
else "部署失败:请检查 Root 授权状态和应用日志;也可使用 ADB 手动启动"
deploying = false deploying = false
deployMsg = if (ok) "✓ $msg" else "✗ $msg"
} }
}, },
enabled = !deploying,
modifier = Modifier.fillMaxWidth().height(48.dp), modifier = Modifier.fillMaxWidth().height(48.dp),
shape = RoundedCornerShape(14.dp), shape = RoundedCornerShape(14.dp),
) { ) {
if (deploying) { if (deploying) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) else Text("部署 atx-agent(需 Root)")
} else { }
Icon(Icons.Filled.Memory, null, Modifier.size(18.dp)) if (deployMessage.isNotBlank()) {
} Text(deployMessage, style = MaterialTheme.typography.bodySmall,
color = if (deployMessage.startsWith("部署失败")) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant)
}
Button(
enabled = !deploying,
onClick = {
context.startForegroundService(Intent(context, BridgeService::class.java).apply {
action = BridgeService.ACTION_START
})
},
modifier = Modifier.fillMaxWidth().height(48.dp),
shape = RoundedCornerShape(14.dp),
) {
Icon(Icons.Filled.PlayArrow, null, Modifier.size(18.dp))
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text(if (deploying) "部署中..." else "部署 atx-agent(需 Root)") Text("启动桥接服务")
}
if (deployMsg.isNotBlank()) {
Text(
deployMsg,
style = MaterialTheme.typography.bodySmall,
color = if (deployMsg.startsWith("✓")) MaterialTheme.colorScheme.primary
else if (deployMsg.startsWith("✗")) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant,
)
} }
} else {
Button( Button(
onClick = { onClick = {
context.startService(Intent(context, BridgeService::class.java).apply { context.startService(Intent(context, BridgeService::class.java).apply {
@ -389,20 +399,6 @@ private fun ControlCard(context: Context) {
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text("停止服务", color = MaterialTheme.colorScheme.onErrorContainer) Text("停止服务", color = MaterialTheme.colorScheme.onErrorContainer)
} }
} else {
Button(
onClick = {
context.startForegroundService(Intent(context, BridgeService::class.java).apply {
action = BridgeService.ACTION_START
})
},
modifier = Modifier.fillMaxWidth().height(48.dp),
shape = RoundedCornerShape(14.dp),
) {
Icon(Icons.Filled.PlayArrow, null, Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("启动桥接服务")
}
} }
} }
} }
@ -428,6 +424,11 @@ private fun HintCard(context: Context) {
else "建议加入电池优化白名单,防止服务被系统休眠时杀掉", else "建议加入电池优化白名单,防止服务被系统休眠时杀掉",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
) )
Text(
"桥接服务运行时会保持 CPU 唤醒,以便屏幕关闭后继续收发指令;持续运行会增加耗电。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f),
)
if (!ignoring) { if (!ignoring) {
OutlinedButton( OutlinedButton(
onClick = { onClick = {
@ -441,7 +442,7 @@ private fun HintCard(context: Context) {
} }
} }
Text( Text(
"Root 设备可在上方「桥接服务」中一键部署 atx-agent;非 Root 设备需 adb 手动启动:adb shell /data/local/tmp/atx-agent server -d", "Root 设备可先点“部署 atx-agent(需 Root)”,授权后会从 APK 安装并启动,并确认进程已运行;没有 Root 时,可按 README 中的 ADB 命令手动启动。设备重启后需重新启动 atx-agent。",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f), color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f),
) )

View File

@ -3,103 +3,142 @@ package com.cpagent.bridge.agent
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File import java.io.File
import java.util.concurrent.TimeUnit
/** /** Root deployment of the APK-bundled atx-agent. */
* root 设备上自动部署并启动 atx-agent:
* 1. 探活 7912,在线则跳过
* 2. 无 root 则跳过(需手动 adb 启动)
* 3. 从 assets 释放二进制到 /data/local/tmp/atx-agent(chmod 755)
* 4. su 启动 `atx-agent server -d`,轮询等待就绪
*/
class AtxDeployer(private val context: Context) { class AtxDeployer(private val context: Context) {
companion object { companion object {
private const val TAG = "CpBridgeAtxDeploy" private const val TAG = "CpBridgeAtxDeploy"
private const val TARGET = "/data/local/tmp/atx-agent" private const val TARGET = "/data/local/tmp/atx-agent"
private const val ASSET = "atx-agent" private const val ASSET = "atx-agent"
private const val COMMAND_TIMEOUT_SECONDS = 25L
private const val EXIT_MARKER = "CP_BRIDGE_SHELL_EXIT="
} }
data class SuResult(val ok: Boolean, val output: String) private data class SuResult(val exitCode: Int?, val output: String, val timedOut: Boolean = false) {
val ok get() = exitCode == 0 && !timedOut
}
private fun su(cmd: String): SuResult = try { private fun findSu(): String? = listOf("/system/bin/su", "/system/xbin/su", "/sbin/su")
val p = Runtime.getRuntime().exec(arrayOf("su", "-c", cmd)) .firstOrNull { File(it).exists() }
val out = buildString {
p.inputStream.bufferedReader().use { append(it.readText()) } /** Some su implementations execute argv directly; give scripts to an explicit shell via stdin. */
p.errorStream.bufferedReader().use { append(it.readText()) } private fun su(binary: String, command: String): SuResult {
val process = try {
ProcessBuilder(binary, "-c", "/system/bin/sh")
.redirectErrorStream(true)
.start()
} catch (e: Exception) {
return SuResult(null, e.message ?: e.javaClass.simpleName)
}
val output = StringBuffer()
val reader = Thread {
// Closing the stream after a timeout must not raise an uncaught thread exception.
runCatching {
process.inputStream.bufferedReader(Charsets.UTF_8).use { input ->
val buffer = CharArray(2048)
while (true) {
val count = input.read(buffer)
if (count < 0) break
synchronized(output) {
output.append(buffer, 0, count)
if (output.length > 65536) output.delete(0, output.length - 65536)
}
}
}
}
}.apply { isDaemon = true; start() }
return try {
process.outputStream.bufferedWriter(Charsets.UTF_8).use { input ->
// EXIT also catches explicit exit and set -e failures in deployment scripts.
input.write("trap 'cp_bridge_status=\$?; printf \"\\n${EXIT_MARKER}%s\\n\" \"\$cp_bridge_status\"' EXIT\n")
input.write(command)
input.write("\n")
}
if (!process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
process.destroyForcibly()
SuResult(null, output.toString().trim(), timedOut = true)
} else {
reader.join(1000)
val lines = output.toString().lines()
val shellExit = lines.lastOrNull { it.startsWith(EXIT_MARKER) }
?.removePrefix(EXIT_MARKER)?.trim()?.toIntOrNull()
val commandOutput = lines.filterNot { it.startsWith(EXIT_MARKER) }.joinToString("\n").trim()
if (shellExit == null) {
SuResult(null, "Root shell 未返回执行结果,su exit=${process.exitValue()}: $commandOutput")
} else {
SuResult(shellExit, commandOutput)
}
}
} catch (e: Exception) {
process.destroyForcibly()
SuResult(null, e.message ?: e.javaClass.simpleName)
} finally {
runCatching { process.outputStream.close() }
runCatching { process.inputStream.close() }
runCatching { process.errorStream.close() }
} }
SuResult(p.waitFor() == 0, out.trim())
} catch (e: Exception) {
SuResult(false, e.message ?: e.javaClass.simpleName)
} }
fun hasRoot(): Boolean { /** Deploy before BridgeService starts; success means the OS reports an atx-agent process. */
val r = su("id") suspend fun ensureRunning(): Boolean = withContext(Dispatchers.IO) {
return r.ok && r.output.contains("uid=0") val suBinary = findSu()
} if (suBinary == null) {
Log.w(TAG, "未找到 su 文件,无法 Root 部署")
return@withContext false
}
/** atx-agent 已在线返回 true;否则 root 部署+启动;失败/无 root 返回 false。 */ val existing = su(suBinary, "pidof atx-agent")
suspend fun ensureRunning(atx: AtxClient): Boolean = withContext(Dispatchers.IO) { if (existing.timedOut || existing.exitCode == null || existing.exitCode !in 0..1) {
if (atx.ping()) { Log.e(TAG, "Root shell 进程查询失败,exit=${existing.exitCode}, timeout=${existing.timedOut}: ${existing.output}")
Log.i(TAG, "atx-agent 已在线,跳过部署") return@withContext false
}
if (existing.ok && existing.output.isNotBlank()) {
Log.i(TAG, "atx-agent 进程已运行,PID=${existing.output}")
return@withContext true return@withContext true
} }
if (!hasRoot()) {
Log.i(TAG, "无 root 权限,跳过自动部署(需手动启动 atx-agent)")
return@withContext false
}
Log.i(TAG, "检测到 root,开始自动部署 atx-agent")
if (su("pidof atx-agent").output.isNotBlank()) { val stage = File(context.cacheDir, ASSET)
// 进程在但 7912 不通:杀掉重装 try {
Log.w(TAG, "atx-agent 进程存在但端口不通,重启")
su("pkill -f atx-agent")
delay(1000)
}
if (!install()) {
Log.e(TAG, "atx-agent 安装失败")
return@withContext false
}
val start = su("nohup $TARGET server -d >/dev/null 2>&1 &")
if (!start.ok) {
Log.e(TAG, "atx-agent 启动失败: ${start.output}")
return@withContext false
}
Log.i(TAG, "atx-agent 启动命令已执行,等待 7912 就绪...")
val ready = withTimeoutOrNull(20_000) {
while (true) {
if (atx.ping()) return@withTimeoutOrNull true
delay(500)
}
@Suppress("UNREACHABLE_CODE") false
}
if (ready == true) {
Log.i(TAG, "atx-agent 自动部署成功并已就绪")
} else {
Log.e(TAG, "atx-agent 启动后 20s 内未就绪")
}
ready == true
}
private fun install(): Boolean {
val stage = File(context.cacheDir, "atx-agent-stage")
return try {
context.assets.open(ASSET).use { input -> context.assets.open(ASSET).use { input ->
stage.outputStream().use { input.copyTo(it) } stage.outputStream().use { output -> input.copyTo(output) }
} }
stage.setReadable(true, false)
stage.setExecutable(true, false)
val r = su("cp '${stage.absolutePath}' $TARGET && chmod 755 $TARGET")
stage.delete()
if (!r.ok) Log.e(TAG, "复制到 $TARGET 失败: ${r.output}")
r.ok
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "释放 assets 失败: ${e.message}") Log.e(TAG, "读取 APK 内 atx-agent 失败", e)
return@withContext false
}
val stagedPath = stage.absolutePath.replace("'", "'\\''")
val installCommand = "set -e; id; cp '$stagedPath' '$TARGET'; chmod 755 '$TARGET'; " +
"test -f '$TARGET'; test -x '$TARGET'; echo CP_BRIDGE_INSTALL_OK; ls -l '$TARGET'"
val install = su(suBinary, installCommand)
if (!install.ok || !install.output.contains("CP_BRIDGE_INSTALL_OK")) {
val reason = if (install.timedOut) "su 部署命令超时" else "su 部署失败,exit=${install.exitCode},目标文件校验未通过"
Log.e(TAG, "$reason: ${install.output}")
return@withContext false
}
Log.i(TAG, "已在设备上验证 atx-agent 文件存在且可执行: ${install.output}")
val start = su(suBinary, "'$TARGET' server -d >/dev/null 2>&1 </dev/null &")
if (!start.ok) {
val reason = if (start.timedOut) "su 启动命令超时" else "su 启动失败,exit=${start.exitCode}"
Log.e(TAG, "$reason: ${start.output}")
return@withContext false
}
val process = su(
suBinary,
"i=0; while [ \$i -lt 20 ]; do pidof atx-agent && exit 0; i=\$((i+1)); sleep 1; done; exit 1",
)
if (process.ok && process.output.isNotBlank()) {
Log.i(TAG, "Root 部署成功,atx-agent 进程已启动,PID=${process.output}")
true
} else {
val reason = if (process.timedOut) "进程检查超时" else "20 秒内未发现 atx-agent 进程"
Log.e(TAG, "$reason: ${process.output}")
false false
} }
} }

View File

@ -46,7 +46,7 @@ class CommandRouter(
) { ) {
companion object { companion object {
private const val TAG = "CpBridgeRouter" private const val TAG = "CpBridgeRouter"
private const val DOWNLOAD_ROOT = "/sdcard/Download" private const val SD_CARD_ROOT = "/sdcard"
private const val MAX_TRANSFER_SIZE = 512L * 1024 * 1024 private const val MAX_TRANSFER_SIZE = 512L * 1024 * 1024
private const val MAX_CHUNK_SIZE = 64 * 1024 private const val MAX_CHUNK_SIZE = 64 * 1024
private const val TRANSFER_TTL_MS = 15 * 60 * 1000L private const val TRANSFER_TTL_MS = 15 * 60 * 1000L
@ -167,10 +167,10 @@ class CommandRouter(
if (!TRANSFER_ID.matches(it)) throw IllegalArgumentException("传输 ID 无效") if (!TRANSFER_ID.matches(it)) throw IllegalArgumentException("传输 ID 无效")
} }
/** 接受 Download 根目录相对路径,词法上拒绝绝对路径、控制字符和穿越段。 */ /** 接受 /sdcard 根目录相对路径,词法上拒绝绝对路径、控制字符和穿越段。 */
private fun relativePath(raw: String?, allowRoot: Boolean = false): String { private fun relativePath(raw: String?, allowRoot: Boolean = false): String {
val path = raw ?: throw IllegalArgumentException("缺少 path") val path = raw ?: throw IllegalArgumentException("缺少 path")
if (path.length > 2048 || '\\' in path || path.startsWith("/")) throw IllegalArgumentException("只能访问 /sdcard/Download") if (path.length > 2048 || '\\' in path || path.startsWith("/")) throw IllegalArgumentException("只能访问 /sdcard")
if (path.any { it.code < 32 || it.code == 127 }) throw IllegalArgumentException("文件路径包含控制字符") if (path.any { it.code < 32 || it.code == 127 }) throw IllegalArgumentException("文件路径包含控制字符")
if (path.isEmpty() && allowRoot) return "" if (path.isEmpty() && allowRoot) return ""
if (path.isBlank()) throw IllegalArgumentException("文件路径不能为空") if (path.isBlank()) throw IllegalArgumentException("文件路径不能为空")
@ -181,7 +181,7 @@ class CommandRouter(
private fun shellQuote(value: String): String = "'" + value.replace("'", "'\\''") + "'" private fun shellQuote(value: String): String = "'" + value.replace("'", "'\\''") + "'"
private fun remotePath(relative: String): String = if (relative.isEmpty()) DOWNLOAD_ROOT else "$DOWNLOAD_ROOT/$relative" private fun remotePath(relative: String): String = if (relative.isEmpty()) SD_CARD_ROOT else "$SD_CARD_ROOT/$relative"
private suspend fun canonicalPath(path: String): String { private suspend fun canonicalPath(path: String): String {
val result = atx.shell("readlink -f ${shellQuote(path)}", 10) val result = atx.shell("readlink -f ${shellQuote(path)}", 10)
@ -189,23 +189,23 @@ class CommandRouter(
return result.output.trim().lineSequence().last() return result.output.trim().lineSequence().last()
} }
/** 校验设备上的真实解析路径,拦截 Download 中指向外部目录的符号链接。 */ /** 校验设备上的真实解析路径,拦截 /sdcard 中指向外部目录的符号链接。 */
private suspend fun requireInsideDownload(path: String, allowMissingLeaf: Boolean = false): String { private suspend fun requireInsideSdCard(path: String, allowMissingLeaf: Boolean = false): String {
val root = canonicalPath(DOWNLOAD_ROOT).trimEnd('/') val root = canonicalPath(SD_CARD_ROOT).trimEnd('/')
if (path == DOWNLOAD_ROOT) return root if (path == SD_CARD_ROOT) return root
val candidate = remotePath(path.removePrefix("/sdcard/Download/").takeIf { path.startsWith("/sdcard/Download/") } ?: path) val candidate = remotePath(path)
val actual = if (allowMissingLeaf) { val actual = if (allowMissingLeaf) {
val existing = atx.shell("test -e ${shellQuote(candidate)} || test -L ${shellQuote(candidate)}", 5).exitCode == 0 val existing = atx.shell("test -e ${shellQuote(candidate)} || test -L ${shellQuote(candidate)}", 5).exitCode == 0
if (existing) { if (existing) {
canonicalPath(candidate) canonicalPath(candidate)
} else { } else {
val parent = candidate.substringBeforeLast('/', DOWNLOAD_ROOT) val parent = candidate.substringBeforeLast('/', SD_CARD_ROOT)
val leaf = candidate.substringAfterLast('/') val leaf = candidate.substringAfterLast('/')
val canonicalParent = canonicalPath(parent).trimEnd('/') val canonicalParent = canonicalPath(parent).trimEnd('/')
"$canonicalParent/$leaf" "$canonicalParent/$leaf"
} }
} else canonicalPath(candidate) } else canonicalPath(candidate)
if (actual != root && !actual.startsWith("$root/")) throw IllegalArgumentException("只能访问 /sdcard/Download") if (actual != root && !actual.startsWith("$root/")) throw IllegalArgumentException("只能访问 /sdcard")
return actual return actual
} }
@ -232,7 +232,7 @@ class CommandRouter(
private fun handleFileList(envelope: Envelope) = scope.launch { private fun handleFileList(envelope: Envelope) = scope.launch {
try { try {
val relative = relativePath(envelope.str("path"), allowRoot = true) val relative = relativePath(envelope.str("path"), allowRoot = true)
val dir = requireInsideDownload(relative) val dir = requireInsideSdCard(relative)
val result = atx.shell("ls -1A ${shellQuote(dir)}", 20) val result = atx.shell("ls -1A ${shellQuote(dir)}", 20)
checkShell(result, "读取目录失败") checkShell(result, "读取目录失败")
val names = result.output.lineSequence().map(String::trimEnd).filter { it.isNotEmpty() } val names = result.output.lineSequence().map(String::trimEnd).filter { it.isNotEmpty() }
@ -242,7 +242,7 @@ class CommandRouter(
for (name in names) { for (name in names) {
try { try {
val childRel = if (relative.isEmpty()) name else "$relative/$name" val childRel = if (relative.isEmpty()) name else "$relative/$name"
val childAbs = requireInsideDownload(childRel) val childAbs = requireInsideSdCard(childRel)
val info = try { val info = try {
json.parseToJsonElement(atx.get("/finfo/${encodedPath(childAbs)}")).jsonObject json.parseToJsonElement(atx.get("/finfo/${encodedPath(childAbs)}")).jsonObject
} catch (_: Exception) { } catch (_: Exception) {
@ -261,7 +261,7 @@ class CommandRouter(
put("modifiedAt", modifiedAt) put("modifiedAt", modifiedAt)
} }
} catch (_: Exception) { } catch (_: Exception) {
// Skip entries that disappear or resolve outside Download while listing. // Skip entries that disappear or resolve outside /sdcard while listing.
} }
} }
send(Proto.response(envelope.id, envelope.action, Proto.STATUS_SUCCESS, buildJsonObject { send(Proto.response(envelope.id, envelope.action, Proto.STATUS_SUCCESS, buildJsonObject {
@ -278,16 +278,16 @@ class CommandRouter(
private fun handleFileMutation(envelope: Envelope, operation: String) = scope.launch { private fun handleFileMutation(envelope: Envelope, operation: String) = scope.launch {
try { try {
val relative = relativePath(envelope.str("path")) val relative = relativePath(envelope.str("path"))
val actual = requireInsideDownload(relative, allowMissingLeaf = operation == "mkdir") val actual = requireInsideSdCard(relative, allowMissingLeaf = operation == "mkdir")
val result = when (operation) { val result = when (operation) {
"mkdir" -> atx.shell("mkdir ${shellQuote(actual)}", 15) "mkdir" -> atx.shell("mkdir ${shellQuote(actual)}", 15)
"delete" -> { "delete" -> {
if (actual == canonicalPath(DOWNLOAD_ROOT)) throw IllegalArgumentException("不能删除 Download 根目录") if (actual == canonicalPath(SD_CARD_ROOT)) throw IllegalArgumentException("不能删除 /sdcard 根目录")
atx.shell("rm -rf ${shellQuote(actual)}", 30) atx.shell("rm -rf ${shellQuote(actual)}", 30)
} }
"rename" -> { "rename" -> {
val newRelative = relativePath(envelope.str("newPath")) val newRelative = relativePath(envelope.str("newPath"))
val destination = requireInsideDownload(newRelative, allowMissingLeaf = true) val destination = requireInsideSdCard(newRelative, allowMissingLeaf = true)
atx.shell("mv ${shellQuote(actual)} ${shellQuote(destination)}", 30) atx.shell("mv ${shellQuote(actual)} ${shellQuote(destination)}", 30)
} }
else -> throw IllegalArgumentException("不支持的文件操作") else -> throw IllegalArgumentException("不支持的文件操作")
@ -306,7 +306,7 @@ class CommandRouter(
cleanTransfers() cleanTransfers()
val id = transferId(envelope) val id = transferId(envelope)
val relative = relativePath(envelope.str("path")) val relative = relativePath(envelope.str("path"))
requireInsideDownload(relative, allowMissingLeaf = true) requireInsideSdCard(relative, allowMissingLeaf = true)
val size = envelope.str("size")?.toLongOrNull() ?: throw IllegalArgumentException("文件大小无效") val size = envelope.str("size")?.toLongOrNull() ?: throw IllegalArgumentException("文件大小无效")
if (size !in 0..MAX_TRANSFER_SIZE) throw IllegalArgumentException("文件不能超过 512 MiB") if (size !in 0..MAX_TRANSFER_SIZE) throw IllegalArgumentException("文件不能超过 512 MiB")
val file = File(transferDir, "$id.upload.part") val file = File(transferDir, "$id.upload.part")
@ -354,7 +354,7 @@ class CommandRouter(
if (transfer.received != transfer.size || transfer.file.length() != transfer.size) throw IllegalArgumentException("上传文件长度不匹配") if (transfer.received != transfer.size || transfer.file.length() != transfer.size) throw IllegalArgumentException("上传文件长度不匹配")
if (sha256(transfer.file) != expectedSha256) throw IllegalArgumentException("上传文件 SHA-256 校验失败") if (sha256(transfer.file) != expectedSha256) throw IllegalArgumentException("上传文件 SHA-256 校验失败")
} }
val target = requireInsideDownload(transfer.relativePath, allowMissingLeaf = true) val target = requireInsideSdCard(transfer.relativePath, allowMissingLeaf = true)
val name = target.substringAfterLast('/') val name = target.substringAfterLast('/')
val response = atx.uploadFile("/upload/${encodedPath(target.removePrefix("/"))}", transfer.file, name, readTimeoutSec = 300) val response = atx.uploadFile("/upload/${encodedPath(target.removePrefix("/"))}", transfer.file, name, readTimeoutSec = 300)
val body = json.parseToJsonElement(response.ifBlank { "{}" }) val body = json.parseToJsonElement(response.ifBlank { "{}" })
@ -375,7 +375,7 @@ class CommandRouter(
val id = transferId(envelope) val id = transferId(envelope)
if (downloads.containsKey(id) || uploads.containsKey(id)) throw IllegalArgumentException("传输 ID 已存在") if (downloads.containsKey(id) || uploads.containsKey(id)) throw IllegalArgumentException("传输 ID 已存在")
val relative = relativePath(envelope.str("path")) val relative = relativePath(envelope.str("path"))
val remote = requireInsideDownload(relative) val remote = requireInsideSdCard(relative)
if (atx.shell("test -f ${shellQuote(remote)}", 5).exitCode != 0) throw IllegalArgumentException("目标不是普通文件") if (atx.shell("test -f ${shellQuote(remote)}", 5).exitCode != 0) throw IllegalArgumentException("目标不是普通文件")
transferDir.mkdirs() transferDir.mkdirs()
val file = File(transferDir, "$id.download.part") val file = File(transferDir, "$id.download.part")
@ -431,7 +431,7 @@ class CommandRouter(
try { try {
val relative = relativePath(envelope.str("path")) val relative = relativePath(envelope.str("path"))
if (!relative.lowercase().endsWith(".apk")) throw IllegalArgumentException("只能安装 APK 文件") if (!relative.lowercase().endsWith(".apk")) throw IllegalArgumentException("只能安装 APK 文件")
val apk = requireInsideDownload(relative) val apk = requireInsideSdCard(relative)
if (atx.shell("test -f ${shellQuote(apk)}", 5).exitCode != 0) throw IllegalArgumentException("APK 文件不存在") if (atx.shell("test -f ${shellQuote(apk)}", 5).exitCode != 0) throw IllegalArgumentException("APK 文件不存在")
val result = atx.shell("pm install -r ${shellQuote(apk)}", 180) val result = atx.shell("pm install -r ${shellQuote(apk)}", 180)
val success = result.exitCode == 0 && result.output.contains("Success", ignoreCase = true) val success = result.exitCode == 0 && result.output.contains("Success", ignoreCase = true)
@ -681,13 +681,18 @@ class CommandRouter(
} }
.map { info -> .map { info ->
val pkg = info.activityInfo.packageName val pkg = info.activityInfo.packageName
val ver = try { val packageInfo = try {
val pi = pm.getPackageInfo(pkg, 0) pm.getPackageInfo(pkg, 0)
(pi.versionName ?: "") to (pi.longVersionCode.toInt())
} catch (_: Exception) { } catch (_: Exception) {
"" to 0 null
} }
AppEntry(pkg, info.loadLabel(pm).toString(), ver.first, ver.second) AppEntry(
pkg,
info.loadLabel(pm).toString(),
packageInfo?.versionName ?: "",
packageInfo?.longVersionCode?.toInt() ?: 0,
packageInfo?.firstInstallTime ?: 0L,
)
} }
.distinctBy { it.packageName } .distinctBy { it.packageName }
.sortedBy { it.label.lowercase() } .sortedBy { it.label.lowercase() }
@ -698,6 +703,7 @@ class CommandRouter(
put("name", app.label) put("name", app.label)
put("versionName", app.versionName) put("versionName", app.versionName)
put("versionCode", app.versionCode) put("versionCode", app.versionCode)
put("firstInstallTime", app.firstInstallTime)
} }
} }
} }
@ -708,7 +714,13 @@ class CommandRouter(
} }
} }
private data class AppEntry(val packageName: String, val label: String, val versionName: String, val versionCode: Int) private data class AppEntry(
val packageName: String,
val label: String,
val versionName: String,
val versionCode: Int,
val firstInstallTime: Long,
)
private fun handleAppLaunch(envelope: Envelope) = scope.launch { private fun handleAppLaunch(envelope: Envelope) = scope.launch {
val pkg = envelope.str("package") ?: "" val pkg = envelope.str("package") ?: ""