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>
310 lines
12 KiB
C++
310 lines
12 KiB
C++
// 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;
|
||
};
|