Add Kotlin and Rust Android agent with signed APK export
This commit is contained in:
1 parent
e366eb5bec
commit
5b3022e1f3
20 files changed
+3568
-2
No files matched your search
@@ -38,7 +38,7 @@
|
||||
| `adb/` | 本地第三方 AOSP ADB 源码检出,用于参考与研究;已被 Git 忽略,不是 adb 可执行文件目录 | 主要为 C++,另含 Python、Shell、Android.bp |
|
||||
| `scrcpy/` | 本地第三方 scrcpy 源码检出;已被 Git 忽略,不是可直接运行的发行包 | C(客户端)、Java(Android 服务端)、Meson、Gradle |
|
||||
| `QtScrcpy/` | 本地第三方 QtScrcpy 源码检出,供参考与研究;已被 Git 忽略 | C++、Qt、CMake |
|
||||
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
|
||||
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物、`apk/` Android 安装包及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
|
||||
| `target/` | Cargo 生成的编译产物与缓存;已被 Git 忽略 | Rust 构建产物,无独立源码语言 |
|
||||
| `work/` | 本地联调、测试输出、截图、日志、工具下载与临时脚本;已被 Git 忽略,不作为正式源码入口 | 混合格式,含 Python、PowerShell、日志及图片 |
|
||||
| `__pycache__/` | Python 自动生成的字节码缓存;已被 Git 忽略 | Python 字节码,无手写源码 |
|
||||
@@ -125,3 +125,5 @@ macOS 是正式交付的最大不确定性。不能把存在 API 或实验原型
|
||||
每次新发布打包将版本号的补丁位增加 1(例如 0.2.0 → 0.2.1),同步 Cargo 工作区与锁文件、Avalonia、Flutter 和安装包版本。Windows 必须生成 Setup.exe,Linux 采用 deb 安装包;普通开发编译不增加版本。同一版本的 Windows/Linux 安装包只递增一次,另一平台使用复用版本选项。打包失败后重试复用已分配版本,避免重复递增。发布产物不包含私有凭据。
|
||||
|
||||
`scripts/release-version.py` 为共享版本分配脚本(Python)。Windows 使用 `scripts/build-installers.ps1` 自动递增并重建后端与桌面安装包;同一次发布的重试或第二平台使用 `-ReuseVersion`。Linux 使用 `bash scripts/build-linux-packages.sh` 自动递增,另一平台已分配版本时设置 `ADS_REUSE_VERSION=1`,须提供该版本重新构建的原生产物。
|
||||
|
||||
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
|
||||
@@ -47,7 +47,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
|
||||
| `adb/` | 本地第三方 AOSP ADB 源码检出,用于参考与研究;已被 Git 忽略,不是 adb 可执行文件目录 | 主要为 C++,另含 Python、Shell、Android.bp |
|
||||
| `scrcpy/` | 本地第三方 scrcpy 源码检出;已被 Git 忽略,不是可直接运行的发行包 | C(客户端)、Java(Android 服务端)、Meson、Gradle |
|
||||
| `QtScrcpy/` | 本地第三方 QtScrcpy 源码检出,供参考与研究;已被 Git 忽略 | C++、Qt、CMake |
|
||||
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
|
||||
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物、`apk/` Android 安装包及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
|
||||
| `target/` | Cargo 生成的编译产物与缓存;已被 Git 忽略 | Rust 构建产物,无独立源码语言 |
|
||||
| `work/` | 本地联调、测试输出、截图、日志、工具下载与临时脚本;已被 Git 忽略,不作为正式源码入口 | 混合格式,含 Python、PowerShell、日志及图片 |
|
||||
| `__pycache__/` | Python 自动生成的字节码缓存;已被 Git 忽略 | Python 字节码,无手写源码 |
|
||||
@@ -246,3 +246,5 @@ Flutter 管理中心已迁移 Cupertino UI,设备按电脑归属分组,支
|
||||
Windows 发布精简:Avalonia 合并托管程序集、保留原生库;Flutter 源码插件静态链接 MSVC CRT。`scripts/check-windows-crt.py` 使用 Python 标准库检查 PE 直接及延迟导入,防止缺失运行库。安装升级清理应用根目录旧 DLL,保留配置和独立工具目录。
|
||||
|
||||
升级从 `Programs/TTSTD` 迁至 `Programs/TongTongStudio` 后,两个桌面客户端自动修复保存的工具路径,保留有效自定义路径及私有凭据。Flutter 在启动与连接前进行迁移和文件检查。
|
||||
|
||||
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
|
||||
@@ -0,0 +1,10 @@
|
||||
.gradle/
|
||||
**/build/
|
||||
local.properties
|
||||
native/target/
|
||||
app/src/main/jniLibs/
|
||||
*.jks
|
||||
*.keystore
|
||||
signing.local.properties
|
||||
|
||||
agent.local.properties
|
||||
@@ -0,0 +1,95 @@
|
||||
# Android 手机直接联网设备端
|
||||
|
||||
独立 Android Gradle 项目,Kotlin 传统 View(无 Compose)+ Rust JNI。手机无需连接现场电脑,通过本机 adbd 接入现有控制中心、P2P 与中继,远端继续使用 ads-client、ADB、scrcpy 和可选 ads-usb。
|
||||
|
||||
## 目录
|
||||
|
||||
| 目录 | 用途 | 语言/格式 |
|
||||
|---|---|---|
|
||||
| app/ | Android APK 模块 | Kotlin、XML、Gradle Kotlin DSL |
|
||||
| app/src/main/java/com/ttstd/ads/ | Activity、前台服务、开机恢复、配置加密、日志和 JNI 声明 | Kotlin |
|
||||
| app/src/main/jniLibs/ | 构建脚本生成的多 ABI JNI 运行库,Git 忽略 | SO,无业务源码 |
|
||||
| native/ | 独立 Cargo 工作区,JNI、生命周期、状态及输入校验 | Rust、TOML、Cargo.lock |
|
||||
| native/src/ | Rust 网关入口与单元测试 | Rust |
|
||||
| scripts/ | Windows NDK 多 ABI 构建脚本 | PowerShell |
|
||||
|
||||
build/、.gradle/、native/target/ 为自动生成产物或缓存,不纳入源码。当前直接通过源码路径复用 ../agent/src/gateway.rs 和 ../crates/ads-core,所以本目录需要与整个仓库一起检出,不能只复制此目录构建。
|
||||
|
||||
## 当前实现
|
||||
|
||||
- 支持最低 Android 6 / API 23,compile/target API 35;API 26+ 通知渠道与 startForegroundService;API 34+ specialUse 类型;不使用受新版限时约束的 dataSync 类型冒充长期连接。
|
||||
- Kotlin Activity 提供控制中心、设备 ID、内置 Agent 令牌、本机 adbd 端口、启动/停止和实时日志。
|
||||
- Service 工作线程调用 JNI,Tokio 双线程执行网络;UI 不阻塞等待网络。控制连接断线时终止旧会话,按现有网关 1–30 秒退避重连。
|
||||
- 原样复用现有网关 v1/v2:设备注册、独占租约、WebRTC P2P、独立中继回退、32 路并发限制、流控和超时。
|
||||
- 当前测试包从 Git 忽略的 agent.local.properties 读取 agentToken 并编入 BuildConfig;界面无需输入,不回显、不传 Intent、不写入日志。内置令牌可从 APK 提取,此包仅用于受控测试,不应公开分发。
|
||||
- Rust 日志有界队列 300 条;服务每秒转入 Logcat(ADS-Agent)及应用内 300 条环形日志。记录启动、ABI、adbd 探测、注册、连接失败、重试、转发失败和退出,不记录票据、SDP、ADB 内容。
|
||||
- BOOT_COMPLETED 仅在用户已启用时尝试恢复;不支持解锁前启动。停止按钮关闭下次开机恢复,关闭界面不停止服务。
|
||||
|
||||
## 系统前置条件与边界
|
||||
|
||||
按需求不实现运行时权限申请、通知权限弹窗、忽略电池优化申请、Shizuku、root、setprop 或隐藏 API 提权。Manifest 中正常声明网络、开机及前台服务权限。
|
||||
|
||||
ROM 必须预先提供可被本应用访问的原始 adbd TCP 端点(固定连接 127.0.0.1,默认 5555),并配置必要的 SELinux、系统预授权和后台策略。此处连接的是手机 adbd,不是电脑 ADB server 的 5037,也不是 Android 无线调试的配对/TLS 端口。程序不会自动开启 adbd,不会关闭 ADB 认证。电脑首次调试密钥授权仍由 adbd/ROM 管理。
|
||||
|
||||
注册成功仅代表手机已连中继,不代表 adbd 可调试。ADBD_PROBE_OK 仅代表端口可连接;探测失败仍允许注册,实际数据通道会明确报无法连接 adbd。
|
||||
|
||||
当前是 APK 内的 Rust JNI 服务,不是 init 托管 native 守护。START_STICKY 和开机广播不能保证 OEM 强杀、强制停止、Doze、未解锁或系统禁止前台启动时仍永久在线;系统签名也不能替代 ROM 的策略配置。未实现独立 init 服务和 SELinux 策略,不能宣称已完成所有 ROM 常驻适配。
|
||||
|
||||
支持 ABI:arm64-v8a、armeabi-v7a、x86_64;不包含 x86。设置 16 KB ELF 对齐,仍需在真实 16 KB 系统验收。Android 6–15 是代码适配范围,不是实机兼容认证;更高版本需要按目标 ROM 验证。
|
||||
|
||||
## 只构建,不安装
|
||||
|
||||
准备 JDK 17、Android SDK 35、Gradle 8.11.1+(当前插件 8.9.2)、NDK r28+、Rust Android targets。仓库不包含平台签名私钥,不自动签系统应用,不执行安装、刷机或更改设备配置。
|
||||
|
||||
```powershell
|
||||
# 仓库根目录;仅编译现有工具链,不安装任何目标或软件
|
||||
.\android_agent\scripts\build-native.ps1 -Ndk F:\AndroidSDK\ndk\28.2.13676358
|
||||
cd android_agent
|
||||
# ANDROID_HOME 指向已安装 SDK;或在 Git 忽略的 local.properties 配置 sdk.dir
|
||||
gradle :app:assembleDebug
|
||||
```
|
||||
|
||||
APK 构建会检查三种 ABI 的 SO 是否存在,不允许静默输出缺少 native 核心的 APK。当前默认使用本机提供的 Crosshatch 证书签名;系统预装、权限白名单和 SELinux 集成仍由设备厂商 ROM 流程完成。
|
||||
|
||||
```powershell
|
||||
cargo test --manifest-path android_agent/native/Cargo.toml --locked --lib
|
||||
# 如需纯 Kotlin/Manifest 编译检查(不能将其产物视为可用 APK)
|
||||
gradle :app:compileDebugKotlin -x verifyNative
|
||||
```
|
||||
|
||||
日志查看(将来安装验证时):`adb logcat -s ADS-Agent`。启动失败按 CONFIG_INVALID、JNI_LOAD_FAILED、FGS_DENIED、ADBD_PROBE_FAILED、START_FAILED 排查。不要把令牌/配置 JSON 添加到诊断输出。
|
||||
|
||||
参考:[前台服务类型](https://developer.android.com/develop/background-work/services/fgs/service-types)、[启动前台服务](https://developer.android.com/develop/background-work/services/fgs/launch)。
|
||||
|
||||
## 本次验证
|
||||
|
||||
- Rust 主机侧 3 项测试通过;ARM64、ARMv7、x86_64 的 Release SO 均编译完成。
|
||||
- Gradle Release 编译、Manifest/资源处理、Lint Vital 和 APK 打包通过;使用 SDK 35 本地 aapt2 解决离线工具依赖缺失。
|
||||
- apksigner verify 通过,v1/v2 签名有效;证书 SHA-256 与指定 keystore 别名导出的证书一致:`c8a2e9bccf597c2fb6dc66bee293fc13f2fc47ec77bc6b2b0d52c11f51192ab8`。
|
||||
- APK 包含三个 ABI 的 JNI 库与 classes.dex;minSdk 23、targetSdk 35。ARM64 ELF LOAD 对齐检查为 0x4000。
|
||||
- 已签名 APK:`../bin/apk/ads-android-agent-0.1.0-crosshatch.apk`(12,846,591 字节)。
|
||||
- 未安装、刷机或进行真机多版本、休眠保活及公网远程调试验收。
|
||||
|
||||
## 默认签名
|
||||
|
||||
app/build.gradle.kts 默认对 debug 和 release 使用 crosshatch 签名。当前机器的密钥位置、别名和口令存放在 Git 忽略的 signing.local.properties,不把口令写入可提交构建脚本。复制项目到其他机器时需提供该文件(storeFile、storePassword、keyAlias、keyPassword),或对应 ADS_SIGNING_STOREFILE、ADS_SIGNING_STOREPASSWORD、ADS_SIGNING_KEYALIAS、ADS_SIGNING_KEYPASSWORD 环境变量。
|
||||
|
||||
```powershell
|
||||
gradle :app:assembleRelease
|
||||
```
|
||||
|
||||
Gradle 中间输出为 app/build/outputs/apk/release/app-release.apk;成功后自动交付到 ../bin/apk/,debug 文件增加 -debug 后缀。签名不会自动获得系统应用身份、ROM 白名单或 SELinux 权限;需要与目标 ROM 平台证书及系统预装配置匹配。
|
||||
|
||||
本机打包时可使用现有 SDK 的 aapt2(PowerShell 参数需保留引号):
|
||||
|
||||
```powershell
|
||||
gradle :app:assembleRelease '-Pandroid.aapt2FromMavenOverride=F:/AndroidSDK/build-tools/35.0.0/aapt2.exe'
|
||||
```
|
||||
|
||||
## 固定 Agent 测试包(0.1.1)
|
||||
|
||||
按当前要求,构建时将现有 config/private/agent.env 中的 ADS_AGENT_TOKEN 写入 Git 忽略的 agent.local.properties,通过 BuildConfig.AGENT_TOKEN 固定在 APK 内。界面已移除令牌输入框,保存配置只保存服务器、设备 ID 和 adbd 端口;旧版加密令牌字段在保存时清理,运行时始终使用内置值。
|
||||
|
||||
重新构建仍需本机 agent.local.properties;该文件和签名配置都不得提交。没有新增自动启动或自动开启 adbd 行为,仍需用户点击保存并启动。产物为 ../bin/apk/ads-android-agent-0.1.1-crosshatch.apk,versionCode=2,默认 Crosshatch 签名。
|
||||
|
||||
后续 APK 统一交付到仓库 `bin/apk/`,该目录只保存自动生成的 APK,无业务源码且不纳入 Git。
|
||||
@@ -0,0 +1,61 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins { id("com.android.application"); id("org.jetbrains.kotlin.android") }
|
||||
val signingFile = rootProject.file("signing.local.properties")
|
||||
val crosshatchProperties = Properties().apply {
|
||||
if (signingFile.isFile) signingFile.inputStream().use { load(it) }
|
||||
}
|
||||
fun signingValue(name: String): String = crosshatchProperties.getProperty(name)
|
||||
?: providers.environmentVariable("ADS_SIGNING_${name.uppercase()}").orNull
|
||||
?: error("Missing signing property $name. Configure signing.local.properties (Git ignored).")
|
||||
val agentProperties = Properties().apply {
|
||||
rootProject.file("agent.local.properties").inputStream().use { load(it) }
|
||||
}
|
||||
val agentToken = agentProperties.getProperty("agentToken") ?: error("Missing agentToken in agent.local.properties")
|
||||
require(agentToken.length >= 32 && agentToken.all { it.code in 33..126 }) { "Invalid Agent token" }
|
||||
android {
|
||||
buildFeatures { buildConfig = true }
|
||||
|
||||
namespace = "com.ttstd.ads"
|
||||
compileSdk = 35
|
||||
defaultConfig {
|
||||
buildConfigField("String", "AGENT_TOKEN", "\"" + agentToken.replace("\\", "\\\\").replace("\"", "\\\"") + "\"")
|
||||
applicationId = "com.ttstd.ads"; minSdk = 23; targetSdk = 35; versionCode = 2; versionName = "0.1.1"; ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") } }
|
||||
signingConfigs {
|
||||
create("crosshatch") {
|
||||
storeFile = file(signingValue("storeFile"))
|
||||
storePassword = signingValue("storePassword")
|
||||
keyAlias = signingValue("keyAlias")
|
||||
keyPassword = signingValue("keyPassword")
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
getByName("debug") { signingConfig = signingConfigs.getByName("crosshatch") }
|
||||
getByName("release") { signingConfig = signingConfigs.getByName("crosshatch"); isMinifyEnabled = false }
|
||||
}
|
||||
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
|
||||
kotlinOptions { jvmTarget = "17" }
|
||||
packaging { jniLibs.useLegacyPackaging = true }
|
||||
}
|
||||
tasks.register("verifyNative") {
|
||||
doLast {
|
||||
listOf("arm64-v8a", "armeabi-v7a", "x86_64").forEach {
|
||||
check(file("src/main/jniLibs/$it/libads_android.so").isFile) { "Missing JNI library for $it. Run scripts/build-native.ps1 first." }
|
||||
}
|
||||
}
|
||||
}
|
||||
tasks.named("preBuild") { dependsOn("verifyNative") }
|
||||
|
||||
// Export deliverables after a successful assembly; bin/apk is Git ignored.
|
||||
tasks.matching { it.name == "assembleRelease" || it.name == "assembleDebug" }.configureEach {
|
||||
val variant = if (name == "assembleRelease") "release" else "debug"
|
||||
doLast {
|
||||
val source = layout.buildDirectory.file("outputs/apk/$variant/app-$variant.apk").get().asFile
|
||||
check(source.isFile) { "APK missing: $source" }
|
||||
copy {
|
||||
from(source)
|
||||
into(rootProject.file("../bin/apk"))
|
||||
rename { "ads-android-agent-${android.defaultConfig.versionName}-crosshatch${if (variant == "debug") "-debug" else ""}.apk" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
|
||||
<application android:label="ADS 手机设备端" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:allowBackup="false" android:usesCleartextTraffic="false" android:supportsRtl="true">
|
||||
<activity android:name=".MainActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
|
||||
<service android:name=".AgentService" android:exported="false" android:stopWithTask="false" android:foregroundServiceType="specialUse"><property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="User-enabled remote ADB device relay for managed system devices"/></service>
|
||||
<receiver android:name=".BootReceiver" android:exported="false"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.ttstd.ads
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Agent credential comes from an ignored build-time file; never print it. */
|
||||
object AgentConfig {
|
||||
fun prefs(c: Context) = c.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
||||
fun save(c: Context, server: String, device: String, port: Int) {
|
||||
require(device.matches(Regex("[A-Za-z0-9._-]{1,128}"))) { "Invalid device ID" }
|
||||
require(port in 1..65535) { "Invalid adbd port" }
|
||||
val uri = java.net.URI(server)
|
||||
require(uri.scheme == "wss" && !uri.host.isNullOrEmpty() && uri.userInfo == null && uri.query == null && uri.fragment == null) { "Invalid WSS URL" }
|
||||
check(prefs(c).edit().putString("server", server).putString("device", device).putInt("port", port)
|
||||
.remove("token").remove("iv").commit()) { "Configuration write failed" }
|
||||
}
|
||||
fun json(c: Context): String {
|
||||
val p = prefs(c)
|
||||
return JSONObject().put("server", p.getString("server", "wss://ttstd.com/ads"))
|
||||
.put("device", p.getString("device", "android-phone")).put("port", p.getInt("port", 5555))
|
||||
.put("token", BuildConfig.AGENT_TOKEN).toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.ttstd.ads
|
||||
|
||||
import android.util.Log
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object AgentLog {
|
||||
private val lines = ArrayDeque<String>()
|
||||
@Volatile var status = "未启动"
|
||||
@Synchronized fun add(stage: String, text: String) {
|
||||
// Call sites never supply config JSON, credentials, tickets, SDP, or ADB payloads.
|
||||
val line = "${SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).format(Date())} [$stage] ${text.take(1600)}"
|
||||
Log.i("ADS-Agent", line)
|
||||
lines.addLast(line)
|
||||
while (lines.size > 300) lines.removeFirst()
|
||||
}
|
||||
@Synchronized fun text(): String = lines.joinToString("\n")
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ttstd.ads
|
||||
|
||||
import android.app.*
|
||||
import android.content.*
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.*
|
||||
import org.json.JSONObject
|
||||
|
||||
class AgentService : Service() {
|
||||
private lateinit var thread: HandlerThread
|
||||
private lateinit var worker: Handler
|
||||
private var started = false
|
||||
private val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (!started) return
|
||||
try {
|
||||
val s = JSONObject(NativeBridge.snapshot())
|
||||
AgentLog.status = when { !s.optBoolean("running") -> "原生核心已停止"; s.optBoolean("registered") -> "已注册 · 等待/处理远程连接"; else -> "连接中 · 自动重试" }
|
||||
val logs = s.optJSONArray("logs")
|
||||
if (logs != null) for (i in 0 until logs.length()) AgentLog.add("RUST", logs.getString(i).trim())
|
||||
s.optString("error").takeIf { it.isNotEmpty() && it != "null" }?.let { AgentLog.status += " · $it" }
|
||||
} catch (e: Exception) { AgentLog.add("POLL_FAILED", e.javaClass.simpleName) }
|
||||
worker.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
thread = HandlerThread("ads-agent-control").apply { start() }; worker = Handler(thread.looper)
|
||||
AgentLog.add("SERVICE_CREATE", "Android API=${Build.VERSION.SDK_INT}; ABI=${Build.SUPPORTED_ABIS.joinToString()}; no permission requests")
|
||||
}
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (!AgentConfig.prefs(this).getBoolean("enabled", false)) { stopSelf(); return START_NOT_STICKY }
|
||||
try { foreground() } catch (e: Exception) {
|
||||
AgentLog.add("FGS_DENIED", "${e.javaClass.simpleName}: ROM must allow foreground service startup")
|
||||
stopSelf(); return START_NOT_STICKY
|
||||
}
|
||||
worker.post {
|
||||
if (!started) {
|
||||
try {
|
||||
check(NativeBridge.loadError == null) { NativeBridge.loadError!! }
|
||||
val error = NativeBridge.start(AgentConfig.json(this))
|
||||
check(error.isEmpty()) { error }
|
||||
started = true; AgentLog.add("NATIVE_STARTED", "网关已启动;registered 不等于 adbd 已授权;未自动开启 TCP ADB")
|
||||
worker.post(poll)
|
||||
} catch (e: Exception) {
|
||||
AgentLog.status = "启动失败"
|
||||
AgentLog.add("START_FAILED", if (e is IllegalStateException) e.message ?: "配置或核心错误" else "${e.javaClass.simpleName}: 配置不可用,请重新保存")
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
private fun foreground() {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
if (Build.VERSION.SDK_INT >= 26) manager.createNotificationChannel(NotificationChannel("agent", "ADS 远程调试", NotificationManager.IMPORTANCE_LOW))
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
val builder = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(this, "agent") else Notification.Builder(this)
|
||||
val notification = builder.setSmallIcon(android.R.drawable.stat_sys_upload).setContentTitle("ADS 远程调试服务")
|
||||
.setContentText("手机正连接远程调试网关,点此查看或停止").setContentIntent(open).setOngoing(true).build()
|
||||
if (Build.VERSION.SDK_INT >= 34) startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) else startForeground(1, notification)
|
||||
}
|
||||
override fun onDestroy() {
|
||||
worker.removeCallbacks(poll)
|
||||
worker.post { if (started) { NativeBridge.stop(); started = false }; AgentLog.status = "已停止"; AgentLog.add("SERVICE_STOP", "数据会话与控制连接已释放"); thread.quitSafely() }
|
||||
super.onDestroy()
|
||||
}
|
||||
override fun onBind(intent: Intent?) = null
|
||||
companion object {
|
||||
fun launch(c: Context) {
|
||||
try { val i = Intent(c, AgentService::class.java); if (Build.VERSION.SDK_INT >= 26) c.startForegroundService(i) else c.startService(i) }
|
||||
catch (e: Exception) { AgentLog.status = "系统拒绝启动"; AgentLog.add("LAUNCH_DENIED", "${e.javaClass.simpleName}: 检查系统预授权及后台启动策略") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ttstd.ads
|
||||
import android.content.*
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
|
||||
if (AgentConfig.prefs(context).getBoolean("enabled", false)) {
|
||||
AgentLog.add("BOOT", "用户已启用远程调试,尝试恢复服务(解锁后启动)")
|
||||
AgentService.launch(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ttstd.ads
|
||||
import android.app.Activity
|
||||
import android.os.*
|
||||
import android.content.Intent
|
||||
import android.text.InputType
|
||||
import android.widget.*
|
||||
|
||||
class MainActivity : Activity() {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private lateinit var state: TextView
|
||||
private lateinit var logs: TextView
|
||||
private val refresh = object : Runnable {
|
||||
override fun run() { state.text = AgentLog.status; logs.text = AgentLog.text(); handler.postDelayed(this, 1000) }
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val p = AgentConfig.prefs(this)
|
||||
val box = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(24, 24, 24, 24) }
|
||||
val scroll = ScrollView(this).apply { isFillViewport = true; addView(box) }; setContentView(scroll)
|
||||
fun label(text: String) { box.addView(TextView(this).apply { this.text = text; textSize = 16f }) }
|
||||
fun field(title: String, value: String, secret: Boolean = false): EditText {
|
||||
label(title)
|
||||
return EditText(this).apply { setSingleLine(true); setText(value); inputType = if (secret) InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_CLASS_TEXT; box.addView(this) }
|
||||
}
|
||||
label("ADS · 手机直接接入远程调试")
|
||||
label("不需要 USB 线。ROM 必须预先允许本机 adbd 接入和后台运行。本应用不申请权限、不执行提权。")
|
||||
val server = field("控制中心", p.getString("server", "wss://ttstd.com/ads")!!)
|
||||
val device = field("设备 ID", p.getString("device", "android-phone")!!)
|
||||
val port = field("本机 adbd 端口(仅连接 127.0.0.1)", p.getInt("port", 5555).toString())
|
||||
port.inputType = InputType.TYPE_CLASS_NUMBER
|
||||
label("Agent 令牌已内置,无需填写")
|
||||
box.addView(Button(this).apply { text = "保存并启动(改配置前先停止)"; setOnClickListener {
|
||||
try {
|
||||
AgentConfig.save(this@MainActivity, server.text.toString().trim(), device.text.toString().trim(), port.text.toString().toInt())
|
||||
p.edit().putBoolean("enabled", true).apply(); AgentService.launch(this@MainActivity)
|
||||
} catch (e: Exception) { AgentLog.add("CONFIG_INVALID", if (e is IllegalArgumentException) "设备 ID / WSS / 令牌 / 端口格式错误" else "${e.javaClass.simpleName}: 无法保存配置") }
|
||||
} })
|
||||
box.addView(Button(this).apply { text = "停止并关闭开机恢复"; setOnClickListener {
|
||||
p.edit().putBoolean("enabled", false).commit(); stopService(Intent(this@MainActivity, AgentService::class.java))
|
||||
AgentLog.status = "停止中"; AgentLog.add("USER_STOP", "已关闭开机恢复")
|
||||
} })
|
||||
state = TextView(this).also { box.addView(it) }
|
||||
logs = TextView(this).apply { typeface = android.graphics.Typeface.MONOSPACE; textSize = 12f; setTextIsSelectable(true); box.addView(this) }
|
||||
}
|
||||
override fun onStart() { super.onStart(); handler.post(refresh) }
|
||||
override fun onStop() { handler.removeCallbacks(refresh); super.onStop() }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ttstd.ads
|
||||
|
||||
/** JNI calls stay on the service worker; polling returns bounded, ticket-free native logs. */
|
||||
object NativeBridge {
|
||||
val loadError: String? = try { System.loadLibrary("ads_android"); null } catch (e: UnsatisfiedLinkError) { "JNI_LOAD_FAILED: ${e.javaClass.simpleName}; check APK ABI and native libraries" }
|
||||
external fun start(config: String): String
|
||||
external fun stop()
|
||||
external fun snapshot(): String
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
plugins {
|
||||
id("com.android.application") version "8.9.2" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
org.gradle.workers.max=2
|
||||
android.useAndroidX=false
|
||||
kotlin.code.style=official
|
||||
Generated
+2910
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
[workspace]
|
||||
[package]
|
||||
name = "ads-android"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
[dependencies]
|
||||
ads-core = { path = "../../crates/ads-core" }
|
||||
anyhow = "1"
|
||||
jni = "0.21"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["fmt"] }
|
||||
@@ -0,0 +1,231 @@
|
||||
use ads_core::{valid_device_id, validate_token, NetworkArgs};
|
||||
use jni::{
|
||||
objects::{JObject, JString},
|
||||
sys::jstring,
|
||||
JNIEnv,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::Write,
|
||||
sync::{Arc, Mutex, Once, OnceLock},
|
||||
thread,
|
||||
};
|
||||
// Reuse the actual v1/v2 gateway (including P2P, relay fallback, bounded streams).
|
||||
#[path = "../../../agent/src/gateway.rs"]
|
||||
mod gateway;
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
server: String,
|
||||
token: String,
|
||||
device: String,
|
||||
port: u16,
|
||||
}
|
||||
impl Config {
|
||||
fn validate(&self) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
valid_device_id(&self.device),
|
||||
"device ID must be 1-128 ASCII letters/digits/._-"
|
||||
);
|
||||
validate_token(&self.token)?;
|
||||
anyhow::ensure!(self.port > 0, "adbd port must be nonzero");
|
||||
self.network().url("/v1/agent", &[])?;
|
||||
Ok(())
|
||||
}
|
||||
fn network(&self) -> NetworkArgs {
|
||||
NetworkArgs {
|
||||
server: self.server.clone(),
|
||||
connect_address: None,
|
||||
allow_insecure: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Worker {
|
||||
stop: tokio::sync::oneshot::Sender<()>,
|
||||
join: thread::JoinHandle<()>,
|
||||
health: gateway::WorkerHealth,
|
||||
}
|
||||
static WORKER: Mutex<Option<Worker>> = Mutex::new(None);
|
||||
static LOGS: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();
|
||||
fn logs() -> &'static Mutex<VecDeque<String>> {
|
||||
LOGS.get_or_init(|| Mutex::new(VecDeque::new()))
|
||||
}
|
||||
struct LogWriter;
|
||||
impl Write for LogWriter {
|
||||
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
|
||||
let mut q = logs().lock().unwrap_or_else(|e| e.into_inner());
|
||||
q.push_back(String::from_utf8_lossy(b).into_owned());
|
||||
while q.len() > 300 {
|
||||
q.pop_front();
|
||||
}
|
||||
Ok(b.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn start(config: Config) -> anyhow::Result<()> {
|
||||
config.validate()?;
|
||||
let mut guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
anyhow::ensure!(
|
||||
guard.is_none(),
|
||||
"agent already running; stop before changing config"
|
||||
);
|
||||
static INIT: Once = Once::new();
|
||||
INIT.call_once(|| {
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.with_writer(|| LogWriter)
|
||||
.try_init();
|
||||
});
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()?;
|
||||
let health = Arc::new(Mutex::new(gateway::Health::default()));
|
||||
let state = health.clone();
|
||||
let (stop, rx) = tokio::sync::oneshot::channel();
|
||||
let args = Arc::new(gateway::Gateway {
|
||||
network: config.network(),
|
||||
token: config.token,
|
||||
device: config.device,
|
||||
target: Some(format!("127.0.0.1:{}", config.port)),
|
||||
adb_serial: None,
|
||||
adb_server: String::new(),
|
||||
device_port: config.port,
|
||||
});
|
||||
let join = thread::spawn(move || {
|
||||
runtime.block_on(async move {
|
||||
let work = async {
|
||||
tracing::info!("ANDROID_START: phone-local adbd and relay worker starting");
|
||||
match ads_core::tcp_connect(args.target.as_deref().unwrap()).await {
|
||||
Ok(s) => { drop(s); tracing::info!("ADBD_PROBE_OK: loopback reachable; ADB authentication still required"); }
|
||||
Err(_) => tracing::warn!("ADBD_PROBE_FAILED: check ROM adbd listener and SELinux; no permission requests or setprop performed"),
|
||||
}
|
||||
gateway::run(args, Some(state)).await;
|
||||
};
|
||||
tokio::select! { _ = work => {}, _ = rx => {} }
|
||||
tracing::info!("ANDROID_STOP: control and data sessions cancelled");
|
||||
});
|
||||
runtime.shutdown_timeout(std::time::Duration::from_secs(2));
|
||||
});
|
||||
*guard = Some(Worker { stop, join, health });
|
||||
Ok(())
|
||||
}
|
||||
fn stop() {
|
||||
let mut guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(w) = guard.take() {
|
||||
let _ = w.stop.send(());
|
||||
let _ = w.join.join();
|
||||
}
|
||||
}
|
||||
fn snapshot() -> String {
|
||||
let guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (running, registered, error) = match guard.as_ref() {
|
||||
Some(w) => {
|
||||
let s = w.health.lock().unwrap_or_else(|e| e.into_inner());
|
||||
(!w.join.is_finished(), s.connected, s.last_error.clone())
|
||||
}
|
||||
None => (false, false, None),
|
||||
};
|
||||
let lines: Vec<_> = logs()
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.drain(..)
|
||||
.collect();
|
||||
serde_json::json!({"running":running,"registered":registered,"error":error,"logs":lines})
|
||||
.to_string()
|
||||
}
|
||||
fn java_string(env: &mut JNIEnv, value: String) -> jstring {
|
||||
env.new_string(value)
|
||||
.map(|v| v.into_raw())
|
||||
.unwrap_or(std::ptr::null_mut())
|
||||
}
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_start(
|
||||
mut env: JNIEnv,
|
||||
_this: JObject,
|
||||
json: JString,
|
||||
) -> jstring {
|
||||
let result =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> anyhow::Result<()> {
|
||||
let raw: String = env.get_string(&json)?.into();
|
||||
let c = serde_json::from_str::<Config>(&raw)
|
||||
.map_err(|_| anyhow::anyhow!("invalid configuration JSON"))?;
|
||||
start(c)
|
||||
}));
|
||||
let message = match result {
|
||||
Ok(Ok(())) => String::new(),
|
||||
Ok(Err(e)) => format!("{e:#}"),
|
||||
Err(_) => "native start failed".into(),
|
||||
};
|
||||
java_string(&mut env, message)
|
||||
}
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_stop(_env: JNIEnv, _this: JObject) {
|
||||
stop();
|
||||
}
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_snapshot(
|
||||
mut env: JNIEnv,
|
||||
_this: JObject,
|
||||
) -> jstring {
|
||||
java_string(&mut env, snapshot())
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn config() -> Config {
|
||||
Config {
|
||||
server: "wss://ttstd.com/ads".into(),
|
||||
token: "x".repeat(32),
|
||||
device: "android-test".into(),
|
||||
port: 5555,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn validates_prefix() {
|
||||
let c = config();
|
||||
c.validate().unwrap();
|
||||
assert_eq!(
|
||||
c.network().url("/v1/agent", &[]).unwrap().path(),
|
||||
"/ads/v1/agent"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_invalid_inputs() {
|
||||
let mut c = config();
|
||||
c.port = 0;
|
||||
assert!(c.validate().is_err());
|
||||
c = config();
|
||||
c.server = "ws://example.com".into();
|
||||
assert!(c.validate().is_err());
|
||||
c = config();
|
||||
c.device = "bad/device".into();
|
||||
assert!(c.validate().is_err());
|
||||
c = config();
|
||||
c.token = "short".into();
|
||||
assert!(c.validate().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn worker_lifecycle_and_secret_free_status() {
|
||||
stop();
|
||||
let mut c = config();
|
||||
c.server = "wss://127.0.0.1:1".into();
|
||||
c.port = 1;
|
||||
start(c).unwrap();
|
||||
let s = snapshot();
|
||||
assert!(s.contains("\"running\":true"));
|
||||
assert!(!s.contains(&"x".repeat(32)));
|
||||
assert!(
|
||||
start(config()).is_err(),
|
||||
"must not create duplicate workers"
|
||||
);
|
||||
let began = std::time::Instant::now();
|
||||
stop();
|
||||
assert!(began.elapsed() < std::time::Duration::from_secs(3));
|
||||
assert!(snapshot().contains("\"running\":false"));
|
||||
stop(); // idempotent
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
param([string]$Ndk = $env:ANDROID_NDK_HOME)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $Ndk -or -not (Test-Path $Ndk)) { throw 'Set ANDROID_NDK_HOME to an installed NDK (r28+ recommended for 16 KB pages).' }
|
||||
$project = Split-Path $PSScriptRoot -Parent
|
||||
$manifest = Join-Path $project 'native/Cargo.toml'
|
||||
$targets = @(
|
||||
@{Rust='aarch64-linux-android'; Abi='arm64-v8a'; Clang='aarch64-linux-android23-clang.cmd'},
|
||||
@{Rust='armv7-linux-androideabi'; Abi='armeabi-v7a'; Clang='armv7a-linux-androideabi23-clang.cmd'},
|
||||
@{Rust='x86_64-linux-android'; Abi='x86_64'; Clang='x86_64-linux-android23-clang.cmd'}
|
||||
)
|
||||
foreach ($t in $targets) {
|
||||
$linker = Join-Path $Ndk "toolchains/llvm/prebuilt/windows-x86_64/bin/$($t.Clang)"
|
||||
if (-not (Test-Path $linker)) { throw "Missing NDK clang: $linker" }
|
||||
$key = 'CARGO_TARGET_' + $t.Rust.Replace('-', '_').ToUpper() + '_LINKER'
|
||||
[Environment]::SetEnvironmentVariable($key, $linker, 'Process')
|
||||
$ccKey = 'CC_' + $t.Rust.Replace('-', '_')
|
||||
[Environment]::SetEnvironmentVariable($ccKey, $linker, 'Process')
|
||||
$ar = Join-Path $Ndk 'toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-ar.exe'
|
||||
[Environment]::SetEnvironmentVariable(('AR_' + $t.Rust.Replace('-', '_')), $ar, 'Process')
|
||||
[Environment]::SetEnvironmentVariable(($key.Replace('_LINKER', '_RUSTFLAGS')), '-C link-arg=-Wl,-z,max-page-size=16384', 'Process')
|
||||
cargo build --manifest-path $manifest --release --target $t.Rust --locked
|
||||
if ($LASTEXITCODE -ne 0) { throw "Rust build failed: $($t.Rust). Install rust target separately if missing." }
|
||||
$out = Join-Path $project "app/src/main/jniLibs/$($t.Abi)"
|
||||
New-Item -ItemType Directory -Force $out | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $project "native/target/$($t.Rust)/release/libads_android.so") -Destination (Join-Path $out 'libads_android.so')
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
|
||||
rootProject.name = "AdsAndroidAgent"
|
||||
include(":app")
|
||||
@@ -0,0 +1,5 @@
|
||||
# Copy to signing.local.properties (Git ignored); do not commit real passwords.
|
||||
storeFile=D:/TongTongStudio/TTSTD/AospCrosshatch.keystore
|
||||
storePassword=REPLACE_LOCALLY
|
||||
keyAlias=AospCrosshatch
|
||||
keyPassword=REPLACE_LOCALLY
|
||||
Reference in new issue
Block a user