Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e20e0bbdb | ||
|
|
340fb20518 | ||
|
|
be19744898 | ||
|
|
ae46b7b53b | ||
|
|
94cb4584c8 | ||
|
|
798456032e | ||
|
|
de9e9a7369 | ||
|
|
913b74097b | ||
|
|
326e162d16 | ||
|
|
7eebd3bd6c | ||
|
|
63c7cdf588 | ||
|
|
b466f568ab | ||
|
|
d6ea5fddea | ||
|
|
1320bb81a6 | ||
|
|
d9fe93ff1e | ||
|
|
b704258ba4 | ||
|
|
46434b46d0 | ||
|
|
db148c4a69 | ||
|
|
b7f87c958a | ||
|
|
998c16edc5 | ||
|
|
28c0c9a2a6 | ||
|
|
7172ab376d | ||
|
|
1401ff0a4c | ||
|
|
3ae54c808e | ||
|
|
d987941e57 | ||
|
|
7faca2c01b |
No files matched your search
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`.
|
Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`.
|
||||||
|
|
||||||
- [zlib v1.3.2](https://zlib.net)
|
- [zlib v1.4](https://zlib.net)
|
||||||
- [zstd v1.5.7](https://github.com/facebook/zstd/tree/v1.5.7)
|
- [zstd v1.5.7](https://github.com/facebook/zstd/tree/v1.5.7)
|
||||||
- [x264 v0.164.3194](https://github.com/corecodec/x264) — GPL-2.0, see note below
|
- [x264 v0.164.3194](https://github.com/corecodec/x264) — GPL-2.0, see note below
|
||||||
- [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv)
|
- [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv)
|
||||||
|
|||||||
@@ -1,11 +1,25 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?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" />
|
<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" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||||
|
<!-- 摄像头管理(COMMAND_WEBCAM):Camera2 JPEG 上行;后台使用需要 camera 类型前台服务 -->
|
||||||
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||||
<!-- 语音监听(COMMAND_AUDIO):AudioRecord 采集麦克风;后台采集要求前台服务带
|
<!-- 语音监听(COMMAND_AUDIO):AudioRecord 采集麦克风;后台采集要求前台服务带
|
||||||
microphone 类型(Android 11+),类型权限在上面的 FOREGROUND_SERVICE_MICROPHONE -->
|
microphone 类型(Android 11+),类型权限在上面的 FOREGROUND_SERVICE_MICROPHONE -->
|
||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
@@ -19,6 +33,7 @@
|
|||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
|
android:requestLegacyExternalStorage="true"
|
||||||
android:extractNativeLibs="false"
|
android:extractNativeLibs="false"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
@@ -43,7 +58,7 @@
|
|||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".CaptureService"
|
android:name=".CaptureService"
|
||||||
android:foregroundServiceType="dataSync|mediaProjection|microphone"
|
android:foregroundServiceType="dataSync|mediaProjection|microphone|camera"
|
||||||
android:exported="false" />
|
android:exported="false" />
|
||||||
|
|
||||||
<service
|
<service
|
||||||
|
|||||||
@@ -4,17 +4,19 @@
|
|||||||
// 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp):
|
// 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp):
|
||||||
// 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START]
|
// 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START]
|
||||||
// → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始
|
// → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始
|
||||||
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节 GSM 流](服务端 CAudio::PlayBuffer 固定按
|
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节]。前 975 字节是 15 个完整 GSM 块,
|
||||||
// 1000 字节一块拷贝,包长必须正好 1000,且不能短——短了服务端会越界读)
|
// 后 25 字节补零。
|
||||||
|
// waveOut 只转换整数个 65 字节块,末尾不足一块的字节既不转换也不保留,
|
||||||
|
// 所以 65 字节块绝不能跨包切开 —— 切开的半块会被直接丢掉,块边界一错位
|
||||||
|
// 整条流就是噪声。服务端 CAudio::PlayBuffer 按包截断到整块,那 25 个零
|
||||||
|
// 正好被丢掉。包长仍保持 1000:老版本服务端按 m_ulBufferLength 整块
|
||||||
|
// 拷贝,包长小于 1000 会越界读。
|
||||||
// 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块
|
// 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块
|
||||||
//
|
//
|
||||||
// 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道,
|
// 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道,
|
||||||
// 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包
|
// 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包
|
||||||
// (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。
|
// (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。
|
||||||
// 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。
|
// 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。
|
||||||
//
|
|
||||||
// 语音流是连续的:1000 不是 65 的整数倍,65 字节块会跨包切开,这是允许的——
|
|
||||||
// 服务端把每个 1000 字节缓冲按顺序写给 waveOut,编解码状态跨缓冲延续。
|
|
||||||
#include "common/commands.h"
|
#include "common/commands.h"
|
||||||
#include "common/logger.h"
|
#include "common/logger.h"
|
||||||
#include "client/IOCPClient.h"
|
#include "client/IOCPClient.h"
|
||||||
@@ -30,6 +32,12 @@
|
|||||||
#define LOGI_AUD(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_AUD", __VA_ARGS__)
|
#define LOGI_AUD(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_AUD", __VA_ARGS__)
|
||||||
#define LOGE_AUD(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_AUD", __VA_ARGS__)
|
#define LOGE_AUD(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_AUD", __VA_ARGS__)
|
||||||
|
|
||||||
|
// 上行包:15 个 GSM 块(975 字节)+ 25 字节补零 = 1000 字节。
|
||||||
|
// 补零是为了让包长与老协议一致(老服务端按 m_ulBufferLength 整块 memcpy,
|
||||||
|
// 包长小于 1000 会越界读),服务端按块截断时正好把这 25 个零丢掉。
|
||||||
|
static const size_t AUDIO_PKT_BLOCKS = 15 * 65; // 975 = 整块载荷
|
||||||
|
static const size_t AUDIO_PKT_WIRE = 1000; // 线上包长(含尾部补零)
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#include "gsm.h"
|
#include "gsm.h"
|
||||||
}
|
}
|
||||||
@@ -125,18 +133,26 @@ private:
|
|||||||
gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节
|
gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节
|
||||||
m_frameFill = 0;
|
m_frameFill = 0;
|
||||||
|
|
||||||
// 65 字节块可能跨 1000 字节包切分;音频流仍然是连续的
|
// 一个包只装整数个 65 字节块,剩下的补零 —— 绝不让块跨包切开。
|
||||||
|
// m_frameBuf 正好一块(65)、AUDIO_PKT_BLOCKS 是 15 块,所以 m_pktFill 恒为
|
||||||
|
// 65 的倍数,room 恒 ≥ 65,一轮就拷完。room 为 0 只在常量被改成非整块数时
|
||||||
|
// 才可能出现,那时必须跳出,否则 n=0 会死循环卡住音频线程。
|
||||||
size_t off = 0;
|
size_t off = 0;
|
||||||
while (off < sizeof(m_frameBuf)) {
|
while (off < sizeof(m_frameBuf)) {
|
||||||
const size_t n = std::min(sizeof(m_frameBuf) - off, (size_t)1000 - m_pktFill);
|
const size_t room = AUDIO_PKT_BLOCKS - m_pktFill;
|
||||||
|
const size_t n = std::min(sizeof(m_frameBuf) - off, room);
|
||||||
|
if (n == 0)
|
||||||
|
break;
|
||||||
memcpy(m_pkt + 1 + m_pktFill, m_frameBuf + off, n);
|
memcpy(m_pkt + 1 + m_pktFill, m_frameBuf + off, n);
|
||||||
m_pktFill += n;
|
m_pktFill += n;
|
||||||
off += n;
|
off += n;
|
||||||
if (m_pktFill == 1000) {
|
if (m_pktFill == AUDIO_PKT_BLOCKS) {
|
||||||
m_client->Send2Server((char*)m_pkt, 1 + 1000);
|
memset(m_pkt + 1 + AUDIO_PKT_BLOCKS, 0, AUDIO_PKT_WIRE - AUDIO_PKT_BLOCKS);
|
||||||
|
m_client->Send2Server((char*)m_pkt, 1 + AUDIO_PKT_WIRE);
|
||||||
m_pktFill = 0;
|
m_pktFill = 0;
|
||||||
if (++m_pktsSent == 1)
|
if (++m_pktsSent == 1)
|
||||||
LOGI_AUD("first uplink packet sent (1+1000 bytes = 615 ms GSM)");
|
LOGI_AUD("first uplink packet sent (1+%u bytes = %u ms GSM)",
|
||||||
|
(unsigned)(1 + AUDIO_PKT_WIRE), (unsigned)(AUDIO_PKT_BLOCKS * 40 / 65));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,7 +195,7 @@ private:
|
|||||||
size_t m_pendingCount;
|
size_t m_pendingCount;
|
||||||
uint8_t m_frameBuf[65];
|
uint8_t m_frameBuf[65];
|
||||||
size_t m_frameFill; // 0 = 下一帧写 32 字节;32 = 下一帧写 33 字节
|
size_t m_frameFill; // 0 = 下一帧写 32 字节;32 = 下一帧写 33 字节
|
||||||
uint8_t m_pkt[1 + 1000]; // [TOKEN_AUDIO_DATA][音频]
|
uint8_t m_pkt[1 + AUDIO_PKT_WIRE]; // [TOKEN_AUDIO_DATA][975 字节整块 + 25 补零]
|
||||||
size_t m_pktFill;
|
size_t m_pktFill;
|
||||||
unsigned m_pktsSent;
|
unsigned m_pktsSent;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
};
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// ProcessManagerAndroid.h - Android 进程管理(COMMAND_SYSTEM)
|
||||||
|
//
|
||||||
|
// 协议与 Linux(linux/SystemManager.h)完全一致:
|
||||||
|
// 子连接构造即发 [TOKEN_PSLIST][pid:4][名字:架构\0][完整路径\0]...
|
||||||
|
// 收到 COMMAND_PSLIST → 重发列表
|
||||||
|
// 收到 COMMAND_KILLPROCESS → [pid:4]*,杀完刷新
|
||||||
|
// 收到 COMMAND_WSLIST → 回空窗口列表(Android 没有 Windows 意义上的窗口)
|
||||||
|
//
|
||||||
|
// 能力前提:Android 7+ 的 /proc 是 hidepid=2 + SELinux untrusted_app 限制,
|
||||||
|
// 普通 APK 枚举不到其它进程。本模块只在设备有 su 时启用(登录时按
|
||||||
|
// RootProcess.isRootAvailable() 声明 CLIENT_CAP_PROCESS),非 root 设备上服务端
|
||||||
|
// 直接返回「不支持」,不会下发 COMMAND_SYSTEM。
|
||||||
|
//
|
||||||
|
// 枚举/杀进程都交给 RootProcess.kt(su shell),这里只做协议封装。
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "common/commands.h"
|
||||||
|
#include "common/logger.h"
|
||||||
|
#include "client/IOCPClient.h"
|
||||||
|
|
||||||
|
#define LOGE_PROC(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_PROC", __VA_ARGS__)
|
||||||
|
|
||||||
|
// 由 main.cpp 通过 JNI 实现(RootProcess.kt)
|
||||||
|
bool AndroidRootAvailable();
|
||||||
|
std::string AndroidProcessSnapshot(); // "pid\tcomm\texe\n"
|
||||||
|
bool AndroidKillProcesses(const std::vector<int>& pids);
|
||||||
|
|
||||||
|
class AndroidProcessManager : public IOCPManager
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit AndroidProcessManager(IOCPClient* client) : m_client(client)
|
||||||
|
{
|
||||||
|
// 与 Linux 一致:构造即发首包,服务端据此打开进程管理器
|
||||||
|
SendProcessList();
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||||
|
{
|
||||||
|
if (!szBuffer || ulLength == 0) return;
|
||||||
|
switch (szBuffer[0]) {
|
||||||
|
case COMMAND_PSLIST:
|
||||||
|
SendProcessList();
|
||||||
|
break;
|
||||||
|
case COMMAND_KILLPROCESS: {
|
||||||
|
std::vector<int> pids;
|
||||||
|
for (ULONG i = 1; i + 4 <= ulLength; i += 4) {
|
||||||
|
int32_t pid = 0;
|
||||||
|
memcpy(&pid, szBuffer + i, sizeof(int32_t));
|
||||||
|
if (pid > 1) pids.push_back(pid);
|
||||||
|
}
|
||||||
|
AndroidKillProcesses(pids);
|
||||||
|
Sleep(100); // 给内核回收留一点时间,再刷新列表
|
||||||
|
SendProcessList();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case COMMAND_WSLIST: {
|
||||||
|
// Android 没有可枚举的桌面窗口;回空列表让服务端的窗口管理器不挂起
|
||||||
|
BYTE token = (BYTE)TOKEN_WSLIST;
|
||||||
|
if (m_client) m_client->Send2Server((char*)&token, 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
LOGE_PROC("unhandled cmd=%d", (int)szBuffer[0]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void SendProcessList()
|
||||||
|
{
|
||||||
|
if (!m_client) return;
|
||||||
|
|
||||||
|
const std::string text = AndroidProcessSnapshot();
|
||||||
|
std::vector<uint8_t> buf;
|
||||||
|
buf.reserve(64 * 1024);
|
||||||
|
buf.push_back((uint8_t)TOKEN_PSLIST);
|
||||||
|
|
||||||
|
const char* arch = (sizeof(void*) == 8) ? "arm64" : "arm";
|
||||||
|
size_t start = 0;
|
||||||
|
size_t count = 0;
|
||||||
|
while (start < text.size()) {
|
||||||
|
size_t nl = text.find('\n', start);
|
||||||
|
std::string line = text.substr(
|
||||||
|
start, nl == std::string::npos ? std::string::npos : nl - start);
|
||||||
|
start = (nl == std::string::npos) ? text.size() : nl + 1;
|
||||||
|
if (line.empty()) continue;
|
||||||
|
|
||||||
|
size_t t1 = line.find('\t');
|
||||||
|
if (t1 == std::string::npos) continue;
|
||||||
|
size_t t2 = line.find('\t', t1 + 1);
|
||||||
|
std::string pidStr = line.substr(0, t1);
|
||||||
|
std::string name = (t2 == std::string::npos)
|
||||||
|
? line.substr(t1 + 1)
|
||||||
|
: line.substr(t1 + 1, t2 - t1 - 1);
|
||||||
|
std::string path = (t2 == std::string::npos) ? "" : line.substr(t2 + 1);
|
||||||
|
|
||||||
|
const long pid = strtol(pidStr.c_str(), nullptr, 10);
|
||||||
|
if (pid <= 0) continue;
|
||||||
|
|
||||||
|
// 与 Linux 端一致:名字后面拼 ":架构",服务端按这个名字显示
|
||||||
|
name += ":";
|
||||||
|
name += arch;
|
||||||
|
|
||||||
|
const uint32_t dwPid = (uint32_t)pid;
|
||||||
|
const uint8_t* p = (const uint8_t*)&dwPid;
|
||||||
|
buf.insert(buf.end(), p, p + sizeof(dwPid));
|
||||||
|
buf.insert(buf.end(), name.begin(), name.end());
|
||||||
|
buf.push_back(0);
|
||||||
|
buf.insert(buf.end(), path.begin(), path.end());
|
||||||
|
buf.push_back(0);
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||||
|
LOGE_PROC("SendProcessList: %zu process(es), %zu bytes", count, buf.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
IOCPClient* m_client = nullptr;
|
||||||
|
};
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
#include "common/logger.h"
|
#include "common/logger.h"
|
||||||
#include "client/IOCPClient.h"
|
#include "client/IOCPClient.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
@@ -21,6 +22,11 @@
|
|||||||
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
|
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
|
||||||
|
|
||||||
extern uint64_t g_myClientID;
|
extern uint64_t g_myClientID;
|
||||||
|
// 定义在 main.cpp:把消息发进主控消息栏(TOKEN_CLIENT_MSG)。
|
||||||
|
// 远程桌面编码器零输出时,主控端停在「请等待」,必须主动回一条说明。
|
||||||
|
extern void SendClientMessageToMain(const char* title, const char* text);
|
||||||
|
// 定义在 main.cpp:编码器零输出时让 Kotlin 用同一个 MediaProjection 重建采集管线。
|
||||||
|
extern void NotifyEncoderStalled();
|
||||||
// 定义在 main.cpp,供子连接的 OnReceive 调用
|
// 定义在 main.cpp,供子连接的 OnReceive 调用
|
||||||
extern void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY);
|
extern void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY);
|
||||||
extern void DispatchClipboardText(const uint8_t* data, size_t size);
|
extern void DispatchClipboardText(const uint8_t* data, size_t size);
|
||||||
@@ -113,7 +119,12 @@ public:
|
|||||||
memcpy(&buf[off + 16], &ss, sizeof(ss));
|
memcpy(&buf[off + 16], &ss, sizeof(ss));
|
||||||
|
|
||||||
m_client->Send2Server((char*)buf.data(), total);
|
m_client->Send2Server((char*)buf.data(), total);
|
||||||
LOGI_SH("SendBitmapInfo %dx%d clientID=%" PRIu64, m_width, m_height, clientID);
|
// 档位和帧率一并打出来。Kotlin 侧真正喂给 MediaCodec 的 bitRateKbps / fps /
|
||||||
|
// KEY_OPERATING_RATE 只进 logcat,主控端取不到;这里按 ScreenTuning 的规则
|
||||||
|
// (fps = maxFps>0 ? maxFps : 档位表 maxFPS,再 clamp 到 1..60)就能反推,
|
||||||
|
// 是判断「编码器为什么一帧不出」唯一能从服务端看到的线索。
|
||||||
|
LOGI_SH("SendBitmapInfo %dx%d clientID=%" PRIu64 " maxFps=%d level=%d",
|
||||||
|
m_width, m_height, clientID, ss.MaxFPS, ss.QualityLevel);
|
||||||
|
|
||||||
// H.264 是推送模式,不需要等 COMMAND_NEXT 才开始发帧。
|
// H.264 是推送模式,不需要等 COMMAND_NEXT 才开始发帧。
|
||||||
// 服务端在 auth 通过瞬间发 COMMAND_NEXT,此时 setManagerCallBack 尚未注册,
|
// 服务端在 auth 通过瞬间发 COMMAND_NEXT,此时 setManagerCallBack 尚未注册,
|
||||||
@@ -267,11 +278,58 @@ private:
|
|||||||
std::thread m_sendThread;
|
std::thread m_sendThread;
|
||||||
|
|
||||||
void SendLoop() {
|
void SendLoop() {
|
||||||
|
// "一帧都没进来"是 Android 侧「请等待」最常见的成因:MediaProjection 被系统停掉、
|
||||||
|
// createVirtualDisplay 返回 null、硬件编码器不接受当前尺寸,都会让 MediaCodec
|
||||||
|
// 零输出。原先这里无限期阻塞在 wait 上,队列一直空就什么日志都不打,服务端只能
|
||||||
|
// 干等。改成带超时的等待,把「没有帧」和「帧被当 P 帧丢弃」区分开。
|
||||||
|
const auto startTick = std::chrono::steady_clock::now();
|
||||||
|
bool noFrameWarned = false;
|
||||||
|
bool stallNotified = false;
|
||||||
while (m_running) {
|
while (m_running) {
|
||||||
std::unique_lock<std::mutex> lk(m_mutex);
|
std::unique_lock<std::mutex> lk(m_mutex);
|
||||||
m_cond.wait(lk, [&]{ return (!m_queue.empty() && m_started) || !m_running; });
|
m_cond.wait_for(lk, std::chrono::seconds(1),
|
||||||
|
[&]{ return (!m_queue.empty() && m_started) || !m_running; });
|
||||||
if (!m_running) break;
|
if (!m_running) break;
|
||||||
|
|
||||||
|
if (m_queue.empty() || !m_started) {
|
||||||
|
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
|
||||||
|
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
|
||||||
|
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
|
||||||
|
const auto elapsed = std::chrono::steady_clock::now() - startTick;
|
||||||
|
if (!noFrameWarned && m_started && !m_firstSent &&
|
||||||
|
elapsed > std::chrono::seconds(5)) {
|
||||||
|
noFrameWarned = true;
|
||||||
|
// 发消息/重建都是慢操作,不能拿着 m_mutex:生产者(编码回调)推帧要拿它。
|
||||||
|
lk.unlock();
|
||||||
|
LOGE_SH("SendLoop: no frame from MediaCodec after 5s — encoder is not producing "
|
||||||
|
"(MediaProjection stopped, VirtualDisplay null, or unsupported %dx%d)",
|
||||||
|
m_width, m_height);
|
||||||
|
// 电视睡眠后常见:投影还在,但旧的 VirtualDisplay 收不到合成帧。先用同一个
|
||||||
|
// MediaProjection 重建采集管线(不需要重新授权);重建结果由 Kotlin 侧记录。
|
||||||
|
NotifyEncoderStalled();
|
||||||
|
} else if (noFrameWarned && !stallNotified && m_started && !m_firstSent &&
|
||||||
|
elapsed > std::chrono::seconds(13)) {
|
||||||
|
stallNotified = true;
|
||||||
|
// 自愈也没救回来:主控端停在「请等待……」,明确回一条消息说明原因。
|
||||||
|
// 多个观看者各自 13 秒都会走到这里,进程内 60 秒只发一条,避免刷屏。
|
||||||
|
lk.unlock();
|
||||||
|
static std::atomic<long long> lastNotifyMs{0};
|
||||||
|
const long long nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||||
|
long long prevMs = lastNotifyMs.load();
|
||||||
|
// 多个观看者各自 13 秒都会走到这里;进程内 60 秒只发一条,避免刷屏。
|
||||||
|
// prevMs == 0 表示本次开机还没发过(steady_clock 的 0 点是开机)。
|
||||||
|
if ((prevMs == 0 || nowMs - prevMs > 60 * 1000) &&
|
||||||
|
lastNotifyMs.compare_exchange_strong(prevMs, nowMs)) {
|
||||||
|
SendClientMessageToMain(
|
||||||
|
"Remote desktop",
|
||||||
|
"The device screen encoder produced no frame (hardware encoder may reject "
|
||||||
|
"this size or config). Remote desktop cannot start.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
Frame f = std::move(m_queue.front());
|
Frame f = std::move(m_queue.front());
|
||||||
m_queue.pop();
|
m_queue.pop();
|
||||||
lk.unlock();
|
lk.unlock();
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// VideoHandlerAndroid.h - Android 摄像头管理(COMMAND_WEBCAM)
|
||||||
|
//
|
||||||
|
// 协议与 Windows 客户端一致(client/VideoManager.cpp、server/2015Remote/VideoDlg.cpp):
|
||||||
|
// [TOKEN_WEBCAM_BITMAPINFO][BITMAPINFO] 服务端据此打开视频窗口;
|
||||||
|
// 之后每帧 [TOKEN_WEBCAM_DIB][isCompress=1][fccHandler:4][帧数据]。
|
||||||
|
// 与 Windows 不同的是 BITMAPINFO 不在子连接建立时立即发,而是等第一帧到达、
|
||||||
|
// 从 JPEG 的 SOF 里读出真实宽高再发(HAL 物理旋转会让宽高互换)。
|
||||||
|
//
|
||||||
|
// 与 Windows 的区别只在编码:Windows 用 VFW 的 MJPEG/H.263 编解码器,Android 相机
|
||||||
|
// 原生输出 JPEG,fccHandler 用 WEBCAM_FOURCC_JPEG_DIRECT('JPGD'),服务端走
|
||||||
|
// turbojpeg 直解,不依赖目标机安装任何编解码器。
|
||||||
|
//
|
||||||
|
// 采集与编码在 Kotlin 侧(CameraCapture.kt,Camera2 → ImageReader(JPEG)),这里只
|
||||||
|
// 负责协议封装与 JPEG 广播;帧回调从 Java 线程进入(YamaBridge.nativeOnCameraJpeg)。
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstring>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "common/commands.h"
|
||||||
|
#include "common/logger.h"
|
||||||
|
#include "client/IOCPClient.h"
|
||||||
|
#include "ScreenHandler.h" // BmpInfoHeader(与 Windows BITMAPINFOHEADER 同布局)
|
||||||
|
|
||||||
|
#define LOGE_V(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_VIDEO", __VA_ARGS__)
|
||||||
|
|
||||||
|
// 由 main.cpp 实现(JNI → CameraCapture.start/stop)
|
||||||
|
bool StartJavaCamera(int* outWidth, int* outHeight);
|
||||||
|
void StopJavaCamera();
|
||||||
|
|
||||||
|
class AndroidVideoHandler : public IOCPManager
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit AndroidVideoHandler(IOCPClient* client) : m_client(client) {}
|
||||||
|
~AndroidVideoHandler() override { StopCapture(); }
|
||||||
|
|
||||||
|
// 打开相机并发送 BITMAPINFO。失败(无相机 / 无 CAMERA 权限)返回 false,
|
||||||
|
// 调用方应关掉子连接并给主控回一条消息。
|
||||||
|
bool StartCapture()
|
||||||
|
{
|
||||||
|
int w = 0, h = 0;
|
||||||
|
if (!StartJavaCamera(&w, &h) || w <= 0 || h <= 0) return false;
|
||||||
|
m_width = w;
|
||||||
|
m_height = h;
|
||||||
|
m_running.store(true, std::memory_order_release);
|
||||||
|
// BITMAPINFO 推迟到第一帧再发:HAL 可能把 JPEG 按 JPEG_ORIENTATION 物理
|
||||||
|
// 旋转(宽高互换),也可能只写 EXIF。以第一帧实际的 SOF 宽高为准,
|
||||||
|
// 服务端就不会因为尺寸对不上而丢帧黑屏。
|
||||||
|
LOGE_V("camera started %dx%d (bitmapinfo deferred to first frame)", w, h);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void StopCapture()
|
||||||
|
{
|
||||||
|
if (!m_running.exchange(false)) return;
|
||||||
|
StopJavaCamera();
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||||
|
{
|
||||||
|
if (!szBuffer || ulLength == 0) return;
|
||||||
|
switch (szBuffer[0]) {
|
||||||
|
case COMMAND_NEXT:
|
||||||
|
// 服务端视频窗口已打开
|
||||||
|
m_dialogOpen.store(true, std::memory_order_relaxed);
|
||||||
|
LOGE_V("camera dialog opened");
|
||||||
|
break;
|
||||||
|
case COMMAND_WEBCAM_ENABLECOMPRESS:
|
||||||
|
case COMMAND_WEBCAM_DISABLECOMPRESS:
|
||||||
|
// JPEG 帧始终是压缩数据,两个开关都不需要改编码路径
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
LOGE_V("camera: unhandled cmd=%d", (int)szBuffer[0]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Java 侧每帧 JPEG 进来时调用(CameraCapture 的 ImageReader 回调线程)
|
||||||
|
void SendJpeg(const uint8_t* data, size_t len)
|
||||||
|
{
|
||||||
|
IOCPClient* client = m_client;
|
||||||
|
if (!client || !m_running.load(std::memory_order_acquire) || !data || len == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// 第一帧:按实际 SOF 宽高发 BITMAPINFO(服务端收到它才会打开视频窗口),
|
||||||
|
// 这一帧本身也照发;之后的帧再等服务端回 COMMAND_NEXT。
|
||||||
|
if (!m_infoSent) {
|
||||||
|
int w = m_width, h = m_height;
|
||||||
|
if (JpegDimensions(data, len, &w, &h)) {
|
||||||
|
m_width = w;
|
||||||
|
m_height = h;
|
||||||
|
}
|
||||||
|
SendBitmapInfo();
|
||||||
|
m_infoSent = true;
|
||||||
|
LOGE_V("bitmapinfo sent %dx%d (jpeg %zu bytes)", m_width, m_height, len);
|
||||||
|
} else if (!m_dialogOpen.load(std::memory_order_relaxed)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t head = 1 + 1 + 4;
|
||||||
|
std::vector<uint8_t> pkt(head + len);
|
||||||
|
pkt[0] = (uint8_t)TOKEN_WEBCAM_DIB;
|
||||||
|
pkt[1] = 1; // isCompress
|
||||||
|
uint32_t fcc = WEBCAM_FOURCC_JPEG_DIRECT;
|
||||||
|
memcpy(&pkt[2], &fcc, 4);
|
||||||
|
memcpy(&pkt[head], data, len);
|
||||||
|
client->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
int Width() const { return m_width; }
|
||||||
|
int Height() const { return m_height; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// 从 JPEG 的 SOF0/SOF2 段取真实宽高(跳过 APPn/EXIF 等段)。
|
||||||
|
// 用于兼容「HAL 按 JPEG_ORIENTATION 物理旋转导致宽高互换」的机型。
|
||||||
|
static bool JpegDimensions(const uint8_t* d, size_t n, int* w, int* h)
|
||||||
|
{
|
||||||
|
if (!d || n < 4 || d[0] != 0xFF || d[1] != 0xD8) return false;
|
||||||
|
size_t i = 2;
|
||||||
|
while (i + 9 < n) {
|
||||||
|
if (d[i] != 0xFF) { ++i; continue; }
|
||||||
|
const uint8_t m = d[i + 1];
|
||||||
|
if (m == 0xD8 || m == 0xD9 || (m >= 0xD0 && m <= 0xD7)) { i += 2; continue; }
|
||||||
|
if (i + 4 > n) return false;
|
||||||
|
const size_t segLen = ((size_t)d[i + 2] << 8) | d[i + 3];
|
||||||
|
if (segLen < 2 || i + 2 + segLen > n) return false;
|
||||||
|
const bool isSof =
|
||||||
|
(m >= 0xC0 && m <= 0xC3) || (m >= 0xC5 && m <= 0xC7) ||
|
||||||
|
(m >= 0xC9 && m <= 0xCB) || (m >= 0xCD && m <= 0xCF);
|
||||||
|
if (isSof) {
|
||||||
|
if (segLen < 7) return false;
|
||||||
|
const int hh = ((int)d[i + 5] << 8) | d[i + 6];
|
||||||
|
const int ww = ((int)d[i + 7] << 8) | d[i + 8];
|
||||||
|
if (ww <= 0 || hh <= 0) return false;
|
||||||
|
*w = ww;
|
||||||
|
*h = hh;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
i += 2 + segLen;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Linux/macOS 的 BmpInfoHeader 就是 Windows 的 BITMAPINFOHEADER(40 字节)。
|
||||||
|
// Windows 客户端发的是 sizeof(BITMAPINFO)=44 字节(含 1 个 bmiColors),
|
||||||
|
// 这里补 4 字节零保持一致,服务端按 biSizeImage 分配转码缓冲。
|
||||||
|
void SendBitmapInfo()
|
||||||
|
{
|
||||||
|
if (!m_client) return;
|
||||||
|
uint8_t buf[1 + sizeof(BmpInfoHeader) + 4] = { 0 };
|
||||||
|
buf[0] = (uint8_t)TOKEN_WEBCAM_BITMAPINFO;
|
||||||
|
|
||||||
|
BmpInfoHeader hdr{};
|
||||||
|
hdr.biSize = sizeof(BmpInfoHeader);
|
||||||
|
hdr.biWidth = m_width;
|
||||||
|
hdr.biHeight = m_height; // bottom-up,与 Windows 摄像头一致
|
||||||
|
hdr.biPlanes = 1;
|
||||||
|
hdr.biBitCount = 24; // 服务端解码成 BGR24
|
||||||
|
hdr.biCompression = 0; // BI_RGB:描述的是解码后的位图
|
||||||
|
// DIB 每行按 DWORD 对齐(DrawDib 与保存 AVI 都按这个 stride 解释)
|
||||||
|
const int stride = (m_width * 3 + 3) & ~3;
|
||||||
|
hdr.biSizeImage = (uint32_t)(stride * m_height);
|
||||||
|
memcpy(buf + 1, &hdr, sizeof(hdr));
|
||||||
|
m_client->Send2Server((char*)buf, (ULONG)sizeof(buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
IOCPClient* m_client = nullptr;
|
||||||
|
std::atomic<bool> m_running{false};
|
||||||
|
std::atomic<bool> m_dialogOpen{false};
|
||||||
|
bool m_infoSent = false;
|
||||||
|
int m_width = 0;
|
||||||
|
int m_height = 0;
|
||||||
|
};
|
||||||
+1148
-47
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,259 @@
|
|||||||
|
package com.yama.client
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.ImageFormat
|
||||||
|
import android.hardware.camera2.CameraCaptureSession
|
||||||
|
import android.hardware.camera2.CameraCharacteristics
|
||||||
|
import android.hardware.camera2.CameraDevice
|
||||||
|
import android.hardware.camera2.CameraManager
|
||||||
|
import android.hardware.camera2.CaptureRequest
|
||||||
|
import android.media.ImageReader
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.HandlerThread
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.Surface
|
||||||
|
import android.view.WindowManager
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 摄像头管理(COMMAND_WEBCAM)的 Android 采集端。
|
||||||
|
*
|
||||||
|
* 走 Camera2 的 JPEG 输出:ImageReader 直接拿一帧完整 JPEG,交给 native 侧的
|
||||||
|
* AndroidVideoHandler 按 [TOKEN_WEBCAM_DIB][isCompress=1][fccHandler=JPGD][JPEG]
|
||||||
|
* 发给服务端;服务端用 turbojpeg 解码显示(不需要装任何 VFW 编解码器)。
|
||||||
|
*
|
||||||
|
* 为什么不用 MediaCodec H.264:服务端摄像头对话框原本走 VFW ICM 解码,H.264
|
||||||
|
* 需要系统装 x264vfw;JPEG 直解改动最小、且 Android 相机原生支持 JPEG 输出。
|
||||||
|
*
|
||||||
|
* 生命周期:C++ 收到 COMMAND_WEBCAM 后调 start(),子连接断开时调 stop()。
|
||||||
|
* start() 同步返回所选分辨率(可能为 null=无相机/无权限),真正开流是异步的:
|
||||||
|
* 服务端已按返回的分辨率发 BITMAPINFO,第一帧通常比对话框打开晚几百毫秒。
|
||||||
|
*/
|
||||||
|
object CameraCapture {
|
||||||
|
private const val TAG = "YAMA_CAM"
|
||||||
|
private const val TARGET_FPS = 8
|
||||||
|
private const val MIN_INTERVAL_MS = 1000L / TARGET_FPS
|
||||||
|
// 720p 足够看清,且 8fps 的 JPEG 上行在弱网下也不至于把主连接挤死
|
||||||
|
private const val MAX_W = 1280
|
||||||
|
private const val MAX_H = 720
|
||||||
|
|
||||||
|
private var thread: HandlerThread? = null
|
||||||
|
private var handler: Handler? = null
|
||||||
|
private var camera: CameraDevice? = null
|
||||||
|
private var session: CameraCaptureSession? = null
|
||||||
|
private var reader: ImageReader? = null
|
||||||
|
private var lastSent = 0L
|
||||||
|
|
||||||
|
@Volatile private var running = false
|
||||||
|
@Volatile private var currentSize: IntArray? = null
|
||||||
|
// 每次 start() 自增;旧相机的回调靠它识别「自己已经是上一代了」
|
||||||
|
@Volatile private var generation = 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开摄像头。成功返回 [width, height];失败返回 null(无权限 / 无相机)。
|
||||||
|
* 重复调用安全(已在采集时直接返回当前分辨率)。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@Synchronized
|
||||||
|
fun start(): IntArray? {
|
||||||
|
if (running) return currentSize
|
||||||
|
|
||||||
|
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return null
|
||||||
|
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.CAMERA)
|
||||||
|
!= PackageManager.PERMISSION_GRANTED) {
|
||||||
|
Log.w(TAG, "start: CAMERA permission not granted")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val manager = ctx.getSystemService(Context.CAMERA_SERVICE) as? CameraManager ?: return null
|
||||||
|
val cameraId = pickCamera(manager) ?: return null
|
||||||
|
val size = pickSize(manager, cameraId) ?: return null
|
||||||
|
|
||||||
|
running = true
|
||||||
|
val gen = ++generation
|
||||||
|
currentSize = intArrayOf(size.first, size.second)
|
||||||
|
lastSent = 0L
|
||||||
|
|
||||||
|
val ht = HandlerThread("yama-camera")
|
||||||
|
ht.start()
|
||||||
|
thread = ht
|
||||||
|
handler = Handler(ht.looper)
|
||||||
|
val h = handler!!
|
||||||
|
|
||||||
|
runCatching {
|
||||||
|
manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
|
||||||
|
override fun onOpened(cam: CameraDevice) {
|
||||||
|
if (!running || gen != generation) { cam.close(); return }
|
||||||
|
camera = cam
|
||||||
|
openSession(ctx, cam, size.first, size.second, gen)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDisconnected(cam: CameraDevice) {
|
||||||
|
Log.w(TAG, "camera disconnected")
|
||||||
|
cam.close()
|
||||||
|
if (camera === cam) camera = null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onError(cam: CameraDevice, error: Int) {
|
||||||
|
Log.e(TAG, "camera error=$error")
|
||||||
|
cam.close()
|
||||||
|
if (camera === cam) camera = null
|
||||||
|
// 让 native 侧知道这路会话没有画面,避免服务端对话框一直黑着
|
||||||
|
runCatching { YamaBridge.nativeOnCameraError("Camera error $error") }
|
||||||
|
}
|
||||||
|
}, h)
|
||||||
|
}.onFailure {
|
||||||
|
Log.e(TAG, "openCamera failed: $it")
|
||||||
|
stop()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "start: camera=$cameraId size=${size.first}x${size.second}")
|
||||||
|
return currentSize
|
||||||
|
}
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
@Synchronized
|
||||||
|
fun stop() {
|
||||||
|
running = false
|
||||||
|
currentSize = null
|
||||||
|
// 先把当前这一代的句柄摘下来,避免删到下一次 start() 新建的 handler/camera:
|
||||||
|
// stop 是 post 到旧 HandlerThread 上执行的,执行前 start() 可能已经跑完了。
|
||||||
|
val h = handler
|
||||||
|
val s = session
|
||||||
|
val c = camera
|
||||||
|
val r = reader
|
||||||
|
val ht = thread
|
||||||
|
session = null
|
||||||
|
camera = null
|
||||||
|
reader = null
|
||||||
|
handler = null
|
||||||
|
thread = null
|
||||||
|
|
||||||
|
val closer = {
|
||||||
|
runCatching { s?.close() }
|
||||||
|
runCatching { c?.close() }
|
||||||
|
runCatching { r?.close() }
|
||||||
|
runCatching { ht?.quitSafely() }
|
||||||
|
Log.i(TAG, "camera stopped")
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
if (h != null) h.post(closer) else closer()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openSession(ctx: Context, cam: CameraDevice, width: Int, height: Int, gen: Int) {
|
||||||
|
// 这些调用跑在相机 HandlerThread 上,异常逃出去会直接杀进程
|
||||||
|
val r = try {
|
||||||
|
ImageReader.newInstance(width, height, ImageFormat.JPEG, 3)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "ImageReader.newInstance failed: $e")
|
||||||
|
YamaBridge.nativeOnCameraError("Camera init failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reader = r
|
||||||
|
r.setOnImageAvailableListener({ ir ->
|
||||||
|
val image = try { ir.acquireLatestImage() } catch (e: Exception) { null } ?: return@setOnImageAvailableListener
|
||||||
|
try {
|
||||||
|
if (!running || gen != generation) return@setOnImageAvailableListener
|
||||||
|
val now = SystemClock.elapsedRealtime()
|
||||||
|
if (now - lastSent < MIN_INTERVAL_MS) return@setOnImageAvailableListener
|
||||||
|
lastSent = now
|
||||||
|
val buf = image.planes[0].buffer
|
||||||
|
val bytes = ByteArray(buf.remaining())
|
||||||
|
buf.get(bytes)
|
||||||
|
YamaBridge.nativeOnCameraJpeg(bytes)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "frame failed: $e")
|
||||||
|
} finally {
|
||||||
|
image.close()
|
||||||
|
}
|
||||||
|
}, handler)
|
||||||
|
|
||||||
|
val surfaces = listOf(r.surface)
|
||||||
|
val callback = object : CameraCaptureSession.StateCallback() {
|
||||||
|
override fun onConfigured(s: CameraCaptureSession) {
|
||||||
|
if (!running || gen != generation) { s.close(); return }
|
||||||
|
session = s
|
||||||
|
runCatching {
|
||||||
|
val req = cam.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
|
||||||
|
req.addTarget(r.surface)
|
||||||
|
req.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)
|
||||||
|
req.set(CaptureRequest.JPEG_ORIENTATION, orientation(ctx, cam))
|
||||||
|
s.setRepeatingRequest(req.build(), null, handler)
|
||||||
|
Log.i(TAG, "repeating request started")
|
||||||
|
}.onFailure {
|
||||||
|
Log.e(TAG, "setRepeatingRequest failed: $it")
|
||||||
|
YamaBridge.nativeOnCameraError("Camera stream failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConfigureFailed(s: CameraCaptureSession) {
|
||||||
|
Log.e(TAG, "capture session configure failed")
|
||||||
|
YamaBridge.nativeOnCameraError("Camera session failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// createCaptureSession 在相机线程上执行,抛异常同样会杀进程
|
||||||
|
try {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
cam.createCaptureSession(surfaces, callback, handler)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "createCaptureSession failed: $e")
|
||||||
|
YamaBridge.nativeOnCameraError("Camera session failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 让 JPEG 按当前屏幕方向摆正(手机竖屏时传感器画面是横的)。 */
|
||||||
|
private fun orientation(ctx: Context, cam: CameraDevice): Int {
|
||||||
|
val chars = runCatching {
|
||||||
|
(ctx.getSystemService(Context.CAMERA_SERVICE) as CameraManager)
|
||||||
|
.getCameraCharacteristics(cam.id)
|
||||||
|
}.getOrNull() ?: return 0
|
||||||
|
val sensor = chars.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
|
||||||
|
val facing = chars.get(CameraCharacteristics.LENS_FACING)
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val wm = ctx.getSystemService(Context.WINDOW_SERVICE) as? WindowManager
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val rotation = runCatching { wm?.defaultDisplay?.rotation }.getOrNull() ?: Surface.ROTATION_0
|
||||||
|
val device = when (rotation) {
|
||||||
|
Surface.ROTATION_90 -> 90
|
||||||
|
Surface.ROTATION_180 -> 180
|
||||||
|
Surface.ROTATION_270 -> 270
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
return if (facing == CameraCharacteristics.LENS_FACING_FRONT)
|
||||||
|
(sensor + device) % 360
|
||||||
|
else
|
||||||
|
(sensor - device + 360) % 360
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pickCamera(manager: CameraManager): String? {
|
||||||
|
val ids = runCatching { manager.cameraIdList }.getOrNull() ?: return null
|
||||||
|
if (ids.isEmpty()) return null
|
||||||
|
// 优先后摄;电视盒子/无后摄设备退到任意一个
|
||||||
|
for (id in ids) {
|
||||||
|
val facing = runCatching {
|
||||||
|
manager.getCameraCharacteristics(id).get(CameraCharacteristics.LENS_FACING)
|
||||||
|
}.getOrNull()
|
||||||
|
if (facing == CameraCharacteristics.LENS_FACING_BACK) return id
|
||||||
|
}
|
||||||
|
return ids.first()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pickSize(manager: CameraManager, id: String): Pair<Int, Int>? {
|
||||||
|
val chars = runCatching { manager.getCameraCharacteristics(id) }.getOrNull() ?: return null
|
||||||
|
val map = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: return null
|
||||||
|
val sizes = runCatching { map.getOutputSizes(ImageFormat.JPEG) }.getOrNull() ?: return null
|
||||||
|
if (sizes.isEmpty()) return null
|
||||||
|
val fit = sizes.filter { it.width <= MAX_W && it.height <= MAX_H }
|
||||||
|
// 没有 ≤720p 的档位时选最小的一档:直接挑最大档会以 5-12 MP 推流,
|
||||||
|
// 8fps 就能把控制连接挤死
|
||||||
|
val best = if (fit.isNotEmpty()) fit.maxByOrNull { it.width * it.height }
|
||||||
|
else sizes.minByOrNull { it.width * it.height }
|
||||||
|
best ?: return null
|
||||||
|
return best.width to best.height
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ import android.os.Bundle
|
|||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.os.SystemClock
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.util.DisplayMetrics
|
import android.util.DisplayMetrics
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
@@ -31,6 +32,18 @@ import android.widget.Toast
|
|||||||
|
|
||||||
import java.nio.charset.Charset
|
import java.nio.charset.Charset
|
||||||
|
|
||||||
|
// 关键日志同时写进 native 的 Logger ring(服务端「运行日志」/ MCP get_client_log 可导出)。
|
||||||
|
// 电视等没有 adb 的设备上,这是唯一能把编码器状态带回主控的通道。
|
||||||
|
// native 库没加载成功时退回落 logcat——否则「Native library load failed」这类
|
||||||
|
// 关键错误反而看不到(那次调用本身就依赖 native 库)。
|
||||||
|
private fun ylog(priority: Int, msg: String) {
|
||||||
|
val ok = runCatching { YamaBridge.nativeLog(priority, "YAMA", msg) }.isSuccess
|
||||||
|
if (!ok) Log.println(priority, "YAMA", msg)
|
||||||
|
}
|
||||||
|
private fun ylogI(msg: String) = ylog(Log.INFO, msg)
|
||||||
|
private fun ylogW(msg: String) = ylog(Log.WARN, msg)
|
||||||
|
private fun ylogE(msg: String) = ylog(Log.ERROR, msg)
|
||||||
|
private fun ylogD(msg: String) = ylog(Log.DEBUG, msg)
|
||||||
class CaptureService : Service() {
|
class CaptureService : Service() {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -38,6 +51,9 @@ class CaptureService : Service() {
|
|||||||
const val CHANNEL_ID = "yama_service"
|
const val CHANNEL_ID = "yama_service"
|
||||||
const val NOTIF_ID = 1
|
const val NOTIF_ID = 1
|
||||||
|
|
||||||
|
// 采集零输出时重建管线的节流时间戳(毫秒)
|
||||||
|
@Volatile private var lastStallRestartMs = 0L
|
||||||
|
|
||||||
const val EXTRA_SERVER_IP = "server_ip"
|
const val EXTRA_SERVER_IP = "server_ip"
|
||||||
const val EXTRA_SERVER_PORT = "server_port"
|
const val EXTRA_SERVER_PORT = "server_port"
|
||||||
const val EXTRA_PROJECTION_RESULT = "projection_result"
|
const val EXTRA_PROJECTION_RESULT = "projection_result"
|
||||||
@@ -63,7 +79,7 @@ class CaptureService : Service() {
|
|||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun onUpdateReceived(path: String) {
|
fun onUpdateReceived(path: String) {
|
||||||
val ctx = instance ?: appContext ?: return
|
val ctx = instance ?: appContext ?: return
|
||||||
Log.i(TAG, "onUpdateReceived: $path")
|
ylogI("onUpdateReceived: $path")
|
||||||
UpdateInstaller.onApkReceived(ctx, path)
|
UpdateInstaller.onApkReceived(ctx, path)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +87,7 @@ class CaptureService : Service() {
|
|||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun onUninstallRequested() {
|
fun onUninstallRequested() {
|
||||||
val ctx = instance ?: appContext ?: return
|
val ctx = instance ?: appContext ?: return
|
||||||
Log.i(TAG, "onUninstallRequested")
|
ylogI("onUninstallRequested")
|
||||||
Uninstaller.request(ctx)
|
Uninstaller.request(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,12 +101,12 @@ class CaptureService : Service() {
|
|||||||
fun onClipboardText(bytes: ByteArray) {
|
fun onClipboardText(bytes: ByteArray) {
|
||||||
val ctx = instance ?: appContext
|
val ctx = instance ?: appContext
|
||||||
if (ctx == null) {
|
if (ctx == null) {
|
||||||
Log.w(TAG, "onClipboardText: no context, ${bytes.size} bytes dropped")
|
ylogW("onClipboardText: no context, ${bytes.size} bytes dropped")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
||||||
if (cm == null) {
|
if (cm == null) {
|
||||||
Log.e(TAG, "onClipboardText: no ClipboardManager")
|
ylogE("onClipboardText: no ClipboardManager")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT,
|
// 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT,
|
||||||
@@ -98,17 +114,17 @@ class CaptureService : Service() {
|
|||||||
val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000')
|
val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000')
|
||||||
try {
|
try {
|
||||||
cm.setPrimaryClip(ClipData.newPlainText("YAMA", text))
|
cm.setPrimaryClip(ClipData.newPlainText("YAMA", text))
|
||||||
Log.i(TAG, "onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
ylogI("onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
// Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程
|
// Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程
|
||||||
Log.e(TAG, "onClipboardText: setPrimaryClip failed: $e")
|
ylogE("onClipboardText: setPrimaryClip failed: $e")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun onNativeExit() {
|
fun onNativeExit() {
|
||||||
val svc = instance ?: return
|
val svc = instance ?: return
|
||||||
Log.i(TAG, "onNativeExit: server requested disconnect, stopping service")
|
ylogI("onNativeExit: server requested disconnect, stopping service")
|
||||||
svc.idrHandler.post { svc.stopSelf() }
|
svc.idrHandler.post { svc.stopSelf() }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,8 +156,8 @@ class CaptureService : Service() {
|
|||||||
p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000)
|
p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000)
|
||||||
codec.setParameters(p)
|
codec.setParameters(p)
|
||||||
svc.currentBitRateKbps = kbps
|
svc.currentBitRateKbps = kbps
|
||||||
Log.i(TAG, "bitrate -> $kbps kbps")
|
ylogI("bitrate -> $kbps kbps")
|
||||||
}.onFailure { Log.e(TAG, "bitrate change to $kbps failed: $it") }
|
}.onFailure { ylogE("bitrate change to $kbps failed: $it") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,17 +176,93 @@ class CaptureService : Service() {
|
|||||||
val w = ControlService.encW
|
val w = ControlService.encW
|
||||||
val h = ControlService.encH
|
val h = ControlService.encH
|
||||||
val dpi = svc.resources.displayMetrics.densityDpi
|
val dpi = svc.resources.displayMetrics.densityDpi
|
||||||
Log.d(TAG, "forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
ylogD("forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
||||||
vd.resize(w + 2, h, dpi)
|
vd.resize(w + 2, h, dpi)
|
||||||
svc.idrHandler.postDelayed({
|
svc.idrHandler.postDelayed({
|
||||||
runCatching { vd.resize(w, h, dpi) }
|
runCatching { vd.resize(w, h, dpi) }
|
||||||
Log.d(TAG, "forceFirstFrame: restored ${w}x${h}")
|
ylogD("forceFirstFrame: restored ${w}x${h}")
|
||||||
}, 150)
|
}, 150)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 远程桌面请求时没有可用的投影会话(Android TV 从未授权,或 Android 14 的单次
|
||||||
|
* 授权在服务重启后失效):尝试拉起 MainActivity 重新走一遍系统「屏幕捕获」授权。
|
||||||
|
* 优先用无障碍服务的 startActivity——系统绑定服务不受后台启动 Activity 限制。
|
||||||
|
* 调用方是 native 的 ScreenSpyThread(g_requestPermMid),10 分钟内最多触发一次。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
fun requestScreenCapturePermission() {
|
||||||
|
val ctx = appContext ?: instance ?: return
|
||||||
|
// request_projection:MainActivity 还活着时走 onNewIntent,靠这个 extra 重新发起授权;
|
||||||
|
// 也避免把用户主动点图标打开 App 的情况误判成授权请求。
|
||||||
|
val intent = Intent(ctx, MainActivity::class.java)
|
||||||
|
// SINGLE_TOP:MainActivity 还活着且位于栈顶时走 onNewIntent 重新授权;
|
||||||
|
// 没有它,NEW_TASK 只是把任务前置,既不走 onCreate 也不走 onNewIntent,
|
||||||
|
// 授权界面永远弹不出来。
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
.putExtra(MainActivity.EXTRA_REQUEST_PROJECTION, true)
|
||||||
|
val acc = ControlService.instance
|
||||||
|
// AccessibilityService.startActivity(Intent) 是 API 24+;minSdk 21 上会抛
|
||||||
|
// NoSuchMethodError,失败时回退到普通 startActivity。
|
||||||
|
var launched = false
|
||||||
|
if (acc != null) launched = runCatching { acc.startActivity(intent) }.isSuccess
|
||||||
|
if (!launched) launched = runCatching { ctx.startActivity(intent) }.isSuccess
|
||||||
|
ylogI("screen-capture permission prompt: launched=$launched")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SendLoop 检测到「采集在跑、但编码器零输出」时调用(电视睡眠后最常见:
|
||||||
|
* MediaProjection 还在,SurfaceFlinger 却不再往旧的 VirtualDisplay 送帧)。
|
||||||
|
* 用同一个 MediaProjection 重建编码器 + 虚拟显示(token 不消耗、无需重新授权);
|
||||||
|
* 投影本身已经失效时把 native 尺寸清零,让下一次远程桌面重新走授权。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
fun onEncoderStalled() {
|
||||||
|
val svc = instance ?: return
|
||||||
|
svc.idrHandler.post {
|
||||||
|
val now = SystemClock.elapsedRealtime() // 单调时钟:墙上时间回拨不会让节流永久失效
|
||||||
|
// last==0 是「本次开机还没重建过」:单调时钟 0 点是开机,开机 30 秒内
|
||||||
|
// 不能因为 now-0 < 30000 就把第一次自愈吞掉。
|
||||||
|
if (lastStallRestartMs != 0L && now - lastStallRestartMs < 30_000) return@post
|
||||||
|
lastStallRestartMs = now
|
||||||
|
val mp = svc.mediaProjection
|
||||||
|
if (mp == null) {
|
||||||
|
ylogI("capture stalled: projection gone, clearing screen size")
|
||||||
|
YamaBridge.nativeSetScreenSize(0, 0)
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
val (pw, ph) = svc.getPhysicalResolution()
|
||||||
|
// 复用当前会话的编码尺寸,避免主控端解码器与新的 SPS 尺寸不一致。
|
||||||
|
val keep = if (ControlService.encW > 0 && ControlService.encH > 0)
|
||||||
|
Pair(ControlService.encW, ControlService.encH) else null
|
||||||
|
ylogI("capture stalled: rebuilding encoder/virtual display (phys=${pw}x${ph}, keepEnc=${keep != null})")
|
||||||
|
svc.releaseCaptureKeepProjection()
|
||||||
|
val rebuilt = runCatching {
|
||||||
|
svc.startCapture(mp, pw, ph, registerProjectionCallback = false, forcedEnc = keep)
|
||||||
|
}.onFailure { ylogE("capture rebuild threw: $it") }.isSuccess
|
||||||
|
// startCapture 先赋值 mediaCodec、后调 createVirtualDisplay;投影失效时
|
||||||
|
// createVirtualDisplay 会抛异常,所以单看 mediaCodec 判不出失败。半初始化的
|
||||||
|
// 编码器必须收干净、native 尺寸清零,否则后续远程桌面会一直带着旧尺寸停在
|
||||||
|
// 「请等待」,也不会走重新授权。
|
||||||
|
if (!rebuilt || svc.mediaCodec == null || svc.virtualDisplay == null) {
|
||||||
|
ylogE("capture rebuild failed; clearing screen size")
|
||||||
|
svc.releaseCaptureKeepProjection()
|
||||||
|
YamaBridge.nativeSetScreenSize(0, 0)
|
||||||
|
} else {
|
||||||
|
// 静止画面(电视停在桌面/暂停的视频)没有任何脏区,新 VirtualDisplay
|
||||||
|
// 不会合成出帧。和首条管线一样,用一次 ±2px resize 触发合成。
|
||||||
|
forceFirstFrame()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nativeInit 是否已完成。MainActivity 重新授权会再次 startForegroundService,同一个
|
||||||
|
// Service 实例会收到第二次 onStartCommand:这时不能再次 nativeInit(main.cpp 的 CAS
|
||||||
|
// 会返回 -1),否则失败分支会 stopSelf → nativeStop → 客户端直接掉线。
|
||||||
|
private var nativeReady = false
|
||||||
private var mediaProjection: MediaProjection? = null
|
private var mediaProjection: MediaProjection? = null
|
||||||
private var virtualDisplay: VirtualDisplay? = null
|
private var virtualDisplay: VirtualDisplay? = null
|
||||||
private var mediaCodec: MediaCodec? = null
|
private var mediaCodec: MediaCodec? = null
|
||||||
@@ -220,29 +312,39 @@ class CaptureService : Service() {
|
|||||||
val res = "1:${sw}*${sh}"
|
val res = "1:${sw}*${sh}"
|
||||||
val user = Build.USER
|
val user = Build.USER
|
||||||
|
|
||||||
|
// 初始化前不能走 ylog*/YamaBridge:那会触发 loadLibrary,失败时把类初始化搞坏,
|
||||||
|
// 后面的 nativeInit 会变成 NoClassDefFoundError(不是下面两个 catch 能接住的)。
|
||||||
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
|
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
|
||||||
|
|
||||||
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
|
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
|
||||||
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
|
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
|
||||||
val initRet: Int
|
if (!nativeReady) {
|
||||||
try {
|
var initRet = 0
|
||||||
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath,
|
try {
|
||||||
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user,
|
||||||
} catch (e: UnsatisfiedLinkError) {
|
packageCodePath ?: "", filesDir.absolutePath,
|
||||||
Log.e(TAG, "Native library load failed: $e")
|
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
||||||
stopSelf()
|
} catch (e: UnsatisfiedLinkError) {
|
||||||
return START_NOT_STICKY
|
ylogE("Native library load failed: $e")
|
||||||
} catch (e: ExceptionInInitializerError) {
|
stopSelf()
|
||||||
Log.e(TAG, "Native library init failed: ${e.cause}")
|
return START_NOT_STICKY
|
||||||
stopSelf()
|
} catch (e: ExceptionInInitializerError) {
|
||||||
return START_NOT_STICKY
|
ylogE("Native library init failed: ${e.cause}")
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
// 类初始化失败后再次访问 YamaBridge 会抛 NoClassDefFoundError
|
||||||
|
ylogE("nativeInit threw: $e")
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
if (initRet != 0 && initRet != -1) { // -1 = 已在运行(重复 start),不算失败
|
||||||
|
ylogE("nativeInit failed: ret=$initRet")
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
nativeReady = true
|
||||||
}
|
}
|
||||||
if (initRet != 0) {
|
|
||||||
Log.e(TAG, "nativeInit failed: ret=$initRet")
|
|
||||||
stopSelf()
|
|
||||||
return START_NOT_STICKY
|
|
||||||
}
|
|
||||||
|
|
||||||
val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1)
|
val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1)
|
||||||
val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
||||||
intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java)
|
intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java)
|
||||||
@@ -253,6 +355,22 @@ class CaptureService : Service() {
|
|||||||
// Android 14+: upgrade foreground type to MEDIA_PROJECTION in the same
|
// Android 14+: upgrade foreground type to MEDIA_PROJECTION in the same
|
||||||
// start command that calls getMediaProjection(), as required by API 34+.
|
// start command that calls getMediaProjection(), as required by API 34+.
|
||||||
startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
|
startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
|
||||||
|
// 重复打开 MainActivity 会再次走到这里:它只在系统重建 Activity
|
||||||
|
// (savedInstanceState != null)时才跳过授权,用户手动再点一次图标仍会
|
||||||
|
// 重新走授权 → startForegroundService → 本函数。不先收掉上一次的
|
||||||
|
// VirtualDisplay 和编码器,就会同时存在两套镜像 + 两路编码,白耗 CPU,
|
||||||
|
// 而且旧 projection 一直挂在 onStop 回调上。
|
||||||
|
//
|
||||||
|
// mediaProjection 也必须纳入判断:本函数先赋值 mediaProjection,之后才进
|
||||||
|
// startCapture() 建编码器。若 startCapture 在 mediaCodec 赋值之前抛异常
|
||||||
|
// (createEncoderByType 失败、三套 configure 全失败),或分辨率非法压根
|
||||||
|
// 没进 startCapture,就会停在「只有 mediaProjection 非空」的状态。只看
|
||||||
|
// codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着,
|
||||||
|
// 它的 onStop 回调也继续挂着。
|
||||||
|
if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) {
|
||||||
|
ylogI("onStartCommand: releasing previous capture before restart")
|
||||||
|
stopCapture()
|
||||||
|
}
|
||||||
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||||
val mp = pm.getMediaProjection(projResult, projData)
|
val mp = pm.getMediaProjection(projResult, projData)
|
||||||
mediaProjection = mp
|
mediaProjection = mp
|
||||||
@@ -261,13 +379,13 @@ class CaptureService : Service() {
|
|||||||
try {
|
try {
|
||||||
startCapture(mp, sw, sh)
|
startCapture(mp, sw, sh)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "Screen capture failed: $e — running without capture")
|
ylogE("Screen capture failed: $e — running without capture")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture")
|
ylogE("Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Log.w(TAG, "No MediaProjection token, skipping screen capture")
|
ylogW("No MediaProjection token, skipping screen capture")
|
||||||
}
|
}
|
||||||
|
|
||||||
return START_STICKY
|
return START_STICKY
|
||||||
@@ -277,23 +395,34 @@ class CaptureService : Service() {
|
|||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
instance = null
|
instance = null
|
||||||
stopCapture()
|
stopCapture()
|
||||||
YamaBridge.nativeStop()
|
// nativeInit 没成功过就不要碰 YamaBridge(类初始化失败后会抛 NoClassDefFoundError)
|
||||||
Log.i(TAG, "CaptureService destroyed")
|
ylogI("CaptureService destroyed")
|
||||||
|
if (nativeReady) runCatching { YamaBridge.nativeStop() }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- MediaProjection + MediaCodec
|
// ---------------------------------------------------------------- MediaProjection + MediaCodec
|
||||||
|
|
||||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) {
|
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int, registerProjectionCallback: Boolean = true, forcedEnc: Pair<Int, Int>? = null) {
|
||||||
val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE)
|
// 重建时必须沿用原会话的编码尺寸:主控端的解码器已按最初的 BITMAPINFO 初始化,
|
||||||
|
// 睡眠后物理分辨率可能变化(实测 1080x606 → 1280x720),重新推导可能得到不同的
|
||||||
|
// 编码尺寸,主控端会黑屏。forcedEnc 由 onEncoderStalled 传入。
|
||||||
|
val (encW, encH) = forcedEnc ?: scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||||
val dpi = resources.displayMetrics.densityDpi
|
val dpi = resources.displayMetrics.densityDpi
|
||||||
|
|
||||||
// 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致)
|
// 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致)
|
||||||
val (bitRateKbps, fps) = ScreenTuning.startupRate()
|
val (bitRateKbps, fps) = ScreenTuning.startupRate()
|
||||||
Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
ylogI("Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
||||||
"bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}")
|
"bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}")
|
||||||
|
|
||||||
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
||||||
val surface = configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
// configureEncoder 三套配置都失败时会抛异常;此时 mediaCodec 还没赋值,
|
||||||
|
// releaseCaptureKeepProjection 收不到它,必须在这里释放,否则每次重建失败都漏一个编码器。
|
||||||
|
val surface = try {
|
||||||
|
configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
runCatching { codec.release() }
|
||||||
|
throw e
|
||||||
|
}
|
||||||
currentBitRateKbps = bitRateKbps
|
currentBitRateKbps = bitRateKbps
|
||||||
|
|
||||||
var configData: ByteArray? = null
|
var configData: ByteArray? = null
|
||||||
@@ -329,23 +458,37 @@ class CaptureService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
|
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
|
||||||
Log.e(TAG, "MediaCodec error: $e")
|
ylogE("MediaCodec error: $e")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
|
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
|
||||||
Log.i(TAG, "Output format: $format")
|
ylogI("Output format: $format")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
codec.start()
|
try {
|
||||||
|
codec.start()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// 同上:start 抛异常时 mediaCodec 还没赋值,编码器会漏掉
|
||||||
|
runCatching { codec.release() }
|
||||||
|
throw e
|
||||||
|
}
|
||||||
mediaCodec = codec
|
mediaCodec = codec
|
||||||
|
|
||||||
idrHandler.postDelayed(idrRunnable, 500)
|
idrHandler.postDelayed(idrRunnable, 500)
|
||||||
|
|
||||||
// Android 14+ requires callback registered before createVirtualDisplay()
|
// Android 14+ requires callback registered before createVirtualDisplay()
|
||||||
mp.registerCallback(object : MediaProjection.Callback() {
|
if (registerProjectionCallback) mp.registerCallback(object : MediaProjection.Callback() {
|
||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
|
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
|
||||||
|
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
|
||||||
|
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
|
||||||
|
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
|
||||||
|
if (mediaProjection !== mp) {
|
||||||
|
ylogI("stale MediaProjection onStop ignored")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ylogI("MediaProjection stopped — switching to dataSync foreground type")
|
||||||
stopCapture()
|
stopCapture()
|
||||||
// Android 14+: system auto-kills a foreground service whose mediaProjection
|
// Android 14+: system auto-kills a foreground service whose mediaProjection
|
||||||
// is revoked. Re-declare as dataSync-only to survive without screen capture.
|
// is revoked. Re-declare as dataSync-only to survive without screen capture.
|
||||||
@@ -353,12 +496,40 @@ class CaptureService : Service() {
|
|||||||
}
|
}
|
||||||
}, null)
|
}, null)
|
||||||
|
|
||||||
virtualDisplay = mp.createVirtualDisplay(
|
val vd = mp.createVirtualDisplay(
|
||||||
"YAMA",
|
"YAMA",
|
||||||
encW, encH, dpi,
|
encW, encH, dpi,
|
||||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||||
surface, null, null
|
surface, null, null
|
||||||
)
|
)
|
||||||
|
// 返回 null 不会抛异常。原实现直接往下走并调用 nativeSetScreenSize,于是
|
||||||
|
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
|
||||||
|
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
|
||||||
|
if (vd == null) {
|
||||||
|
ylogE("createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
|
||||||
|
"no frames will be produced; check MediaProjection token")
|
||||||
|
// 500ms 前已经 postDelayed 过 idrRunnable,不收掉它会每秒空转(mediaCodec
|
||||||
|
// 已置 null,setParameters 是 null-safe,但没意义)。
|
||||||
|
idrHandler.removeCallbacks(idrRunnable)
|
||||||
|
runCatching { codec.stop() }
|
||||||
|
runCatching { codec.release() }
|
||||||
|
mediaCodec = null
|
||||||
|
// projection 也要收掉:token 是一次性的,留着它既占资源,又让 onStop 回调
|
||||||
|
// 继续挂在上面;下次授权拿到的会是另一个 projection。
|
||||||
|
// 先置 null,让下面 mp.stop() 触发的异步 onStop 落到 stale 分支,不会再把
|
||||||
|
// 刚降级好的前台类型改回去、也不会重入 stopCapture。
|
||||||
|
mediaProjection = null
|
||||||
|
// 关键:进本函数前 onStartCommand 已把前台类型升级成 MEDIA_PROJECTION。
|
||||||
|
// projection 一旦 stop(),Android 14+ 会把仍声明该类型的前台服务一并停掉,
|
||||||
|
// 服务被杀 → onDestroy → nativeStop → 主控端直接掉线。这里虽然没有画面可抓,
|
||||||
|
// 但鼠标键盘控制、以及靠这条连接下发新档位/触发重新授权的通道都要保住,
|
||||||
|
// 所以必须先降级回 DATA_SYNC(与 onStop 处理器同一套处理)。降级放在 stop()
|
||||||
|
// 之前,避免系统按「此刻仍是 mediaProjection 类型」判定。
|
||||||
|
startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||||
|
runCatching { mp.stop() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
virtualDisplay = vd
|
||||||
|
|
||||||
YamaBridge.nativeSetScreenSize(encW, encH)
|
YamaBridge.nativeSetScreenSize(encW, encH)
|
||||||
|
|
||||||
@@ -367,7 +538,7 @@ class CaptureService : Service() {
|
|||||||
ControlService.encW = encW
|
ControlService.encW = encW
|
||||||
ControlService.encH = encH
|
ControlService.encH = encH
|
||||||
|
|
||||||
Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
ylogI("MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean,
|
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean,
|
||||||
@@ -379,7 +550,13 @@ class CaptureService : Service() {
|
|||||||
setInteger(MediaFormat.KEY_FRAME_RATE, fps)
|
setInteger(MediaFormat.KEY_FRAME_RATE, fps)
|
||||||
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
|
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
|
||||||
setInteger(MediaFormat.KEY_PRIORITY, 0)
|
setInteger(MediaFormat.KEY_PRIORITY, 0)
|
||||||
setInteger(MediaFormat.KEY_OPERATING_RATE, fps)
|
// KEY_OPERATING_RATE 是给编码器的资源规划提示,不是限帧开关——真正的出帧
|
||||||
|
// 节奏由画面内容和 KEY_FRAME_RATE 的码控决定。3ab5154 把它从写死的 30 改成
|
||||||
|
// fps 之后,只要档位低于 30(Good=20、Medium=15、Low=12、Minimal=8)就会把
|
||||||
|
// 它压到 30 以下;部分硬件编码器(TV 芯片尤其明显)会据此进入低功耗档,
|
||||||
|
// configure/start 都成功却一帧都不输出,表现就是主控端一直停在"请等待"。
|
||||||
|
// 保持不低于 30,与改动前固定 30 的行为一致。
|
||||||
|
setInteger(MediaFormat.KEY_OPERATING_RATE, maxOf(fps, 30))
|
||||||
if (lowLatency) {
|
if (lowLatency) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
|
||||||
setInteger(MediaFormat.KEY_LATENCY, 0)
|
setInteger(MediaFormat.KEY_LATENCY, 0)
|
||||||
@@ -391,22 +568,26 @@ class CaptureService : Service() {
|
|||||||
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
|
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容
|
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容。
|
||||||
|
// 电视(isTvDevice:leanback/television/uiMode)的硬件编码器对低延迟配置尤其敏感:
|
||||||
|
// configure/createInputSurface/start 全部成功,但 KEY_LOW_LATENCY 下可能一帧都不输出
|
||||||
|
// (与 KEY_OPERATING_RATE 压到 30 以下同类的低功耗行为)。电视上因此先试「默认配置」,
|
||||||
|
// 手机保持原顺序。注意这与 D-pad 输入策略的 leanback 判定是两件事。
|
||||||
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int,
|
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int,
|
||||||
bitRateKbps: Int, fps: Int): android.view.Surface {
|
bitRateKbps: Int, fps: Int): android.view.Surface {
|
||||||
val configs = listOf(
|
val isTv = ControlService.isTvDevice(this)
|
||||||
true to true,
|
val configs = if (isTv)
|
||||||
true to false,
|
listOf(false to false, true to false, true to true)
|
||||||
false to false,
|
else
|
||||||
)
|
listOf(true to true, true to false, false to false)
|
||||||
for ((ll, bl) in configs) {
|
for ((ll, bl) in configs) {
|
||||||
try {
|
try {
|
||||||
val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps)
|
val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps)
|
||||||
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||||
Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl")
|
ylogI("Encoder configured: lowLatency=$ll baseline=$bl")
|
||||||
return codec.createInputSurface()
|
return codec.createInputSurface()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
ylogW("Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||||
try { codec.reset() } catch (_: Exception) {}
|
try { codec.reset() } catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -423,6 +604,27 @@ class CaptureService : Service() {
|
|||||||
virtualDisplay = null
|
virtualDisplay = null
|
||||||
mediaCodec = null
|
mediaCodec = null
|
||||||
mediaProjection = null
|
mediaProjection = null
|
||||||
|
// 编码器已经没了,必须把 native 侧记录的尺寸一起清零。ScreenSpyThread 只靠
|
||||||
|
// g_screenWidth != 0 判断「投屏就绪」,不清零就会出现:MediaProjection 被系统
|
||||||
|
// 停掉(电视待机/切走/系统回收都会触发 onStop)后编码器已释放,但尺寸还是旧值,
|
||||||
|
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
|
||||||
|
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
|
||||||
|
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
|
||||||
|
// native 初始化失败时(onDestroy 仍会走到这里)碰 YamaBridge 会抛
|
||||||
|
// NoClassDefFoundError,必须由 nativeReady 挡住。
|
||||||
|
if (nativeReady) runCatching { YamaBridge.nativeSetScreenSize(0, 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只拆编码器与虚拟显示、保留 MediaProjection:Android 14 的投影 token 是一次性的,
|
||||||
|
// stop() 之后就只能重新授权。电视睡眠后旧的 VirtualDisplay 收不到合成帧时,用同一个
|
||||||
|
// 投影重建一条新的虚拟显示即可恢复,不必打扰设备前的用户。
|
||||||
|
private fun releaseCaptureKeepProjection() {
|
||||||
|
idrHandler.removeCallbacks(idrRunnable)
|
||||||
|
runCatching { virtualDisplay?.release() }
|
||||||
|
runCatching { mediaCodec?.stop() }
|
||||||
|
runCatching { mediaCodec?.release() }
|
||||||
|
virtualDisplay = null
|
||||||
|
mediaCodec = null
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- 辅助函数
|
// ---------------------------------------------------------------- 辅助函数
|
||||||
@@ -490,13 +692,19 @@ class CaptureService : Service() {
|
|||||||
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||||
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
|
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
|
||||||
}
|
}
|
||||||
|
// 摄像头管理(COMMAND_WEBCAM)要在后台用相机:Android 11+ 要求前台服务带 camera 类型。
|
||||||
|
// 没授权时不能带,否则 startForeground 直接抛 SecurityException。
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
|
||||||
|
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||||||
|
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
startForeground(NOTIF_ID, buildNotification(), types)
|
startForeground(NOTIF_ID, buildNotification(), types)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "startForeground(types=0x${types.toString(16)}) failed: $e")
|
ylogE("startForeground(types=0x${types.toString(16)}) failed: $e")
|
||||||
if (types != base) {
|
if (types != base) {
|
||||||
runCatching { startForeground(NOTIF_ID, buildNotification(), base) }
|
runCatching { startForeground(NOTIF_ID, buildNotification(), base) }
|
||||||
.onFailure { Log.e(TAG, "startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
.onFailure { ylogE("startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,13 @@ package com.yama.client
|
|||||||
import android.accessibilityservice.AccessibilityService
|
import android.accessibilityservice.AccessibilityService
|
||||||
import android.accessibilityservice.GestureDescription
|
import android.accessibilityservice.GestureDescription
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.KeyguardManager
|
||||||
import android.content.BroadcastReceiver
|
import android.content.BroadcastReceiver
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.IntentFilter
|
import android.content.IntentFilter
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.content.res.Configuration
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
import android.graphics.Path
|
import android.graphics.Path
|
||||||
import android.graphics.PixelFormat
|
import android.graphics.PixelFormat
|
||||||
@@ -21,6 +24,7 @@ import android.view.View
|
|||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import android.view.accessibility.AccessibilityEvent
|
import android.view.accessibility.AccessibilityEvent
|
||||||
import android.view.accessibility.AccessibilityNodeInfo
|
import android.view.accessibility.AccessibilityNodeInfo
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AccessibilityService that injects touch gestures and global key actions
|
* AccessibilityService that injects touch gestures and global key actions
|
||||||
@@ -37,6 +41,15 @@ class ControlService : AccessibilityService() {
|
|||||||
companion object {
|
companion object {
|
||||||
const val TAG = "YAMA_CTRL"
|
const val TAG = "YAMA_CTRL"
|
||||||
|
|
||||||
|
/** 电视判定唯一实现:D-pad 输入、SCREEN_ON 清锁屏、编码器配置顺序都用它,
|
||||||
|
* 避免两处判定漂移。非 GMS 的国产电视可能没有 leanback 特性,补 television/uiMode。 */
|
||||||
|
@JvmStatic
|
||||||
|
fun isTvDevice(context: Context): Boolean =
|
||||||
|
context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
|
||||||
|
context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
|
||||||
|
(context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK) ==
|
||||||
|
Configuration.UI_MODE_TYPE_TELEVISION
|
||||||
|
|
||||||
// 锁定时注入手势前的放行等待(毫秒):见 sendGesture 的说明。100ms 是实测能
|
// 锁定时注入手势前的放行等待(毫秒):见 sendGesture 的说明。100ms 是实测能
|
||||||
// 稳稳让 WMS 应用完 FLAG_NOT_TOUCHABLE 的最小值量级(官方没有回调可等)。
|
// 稳稳让 WMS 应用完 FLAG_NOT_TOUCHABLE 的最小值量级(官方没有回调可等)。
|
||||||
private const val OVERLAY_BYPASS_DELAY_MS = 100
|
private const val OVERLAY_BYPASS_DELAY_MS = 100
|
||||||
@@ -45,8 +58,37 @@ class ControlService : AccessibilityService() {
|
|||||||
@Volatile var instance: ControlService? = null
|
@Volatile var instance: ControlService? = null
|
||||||
|
|
||||||
// ── Active foreground window ─────────────────────────────────────
|
// ── Active foreground window ─────────────────────────────────────
|
||||||
@JvmStatic
|
// 服务端心跳读的是这个属性的 Java getter(C++ 按 getActiveWindow 查找)。
|
||||||
@Volatile var activeWindow: String = "Android"
|
// 锁屏时与其他平台对齐返回 "Locked: HH:MM:SS"(已锁时长),否则返回前台包名。
|
||||||
|
@Volatile private var foregroundPkg: String = "Android"
|
||||||
|
@Volatile private var lockedAtElapsed: Long = 0L
|
||||||
|
|
||||||
|
@get:JvmStatic
|
||||||
|
val activeWindow: String
|
||||||
|
get() {
|
||||||
|
val svc = instance
|
||||||
|
// 无障碍服务不在时无法判断锁屏状态。以前这里保留上一次的 lockedAtElapsed,
|
||||||
|
// 服务被杀/重启后会一直上报 "Locked: HH:MM:SS"(时长还一直在涨)。
|
||||||
|
if (svc == null) {
|
||||||
|
lockedAtElapsed = 0L
|
||||||
|
return foregroundPkg
|
||||||
|
}
|
||||||
|
val now = SystemClock.elapsedRealtime()
|
||||||
|
// 只认 ACTION_SCREEN_OFF 记下的起点:db148c4 起改成每次心跳都问
|
||||||
|
// KeyguardManager,而部分电视(如 Changhong AI PONT)这个值恒为 true,
|
||||||
|
// 正在看 YouTube 也会一直上报 "Locked: HH:MM:SS",前台应用永远不更新。
|
||||||
|
// 手机上的锁屏由 SCREEN_OFF → USER_PRESENT 这对广播覆盖,不需要再问 keyguard。
|
||||||
|
if (lockedAtElapsed != 0L)
|
||||||
|
return "Locked: " + formatElapsed(now - lockedAtElapsed)
|
||||||
|
return foregroundPkg
|
||||||
|
}
|
||||||
|
|
||||||
|
// 锁屏时长,格式与 Windows/macOS 的 "Locked: HH:MM:SS" 一致
|
||||||
|
private fun formatElapsed(ms: Long): String {
|
||||||
|
val total = (ms / 1000).coerceAtLeast(0)
|
||||||
|
return String.format(Locale.US, "%02d:%02d:%02d",
|
||||||
|
total / 3600, (total % 3600) / 60, total % 60)
|
||||||
|
}
|
||||||
|
|
||||||
// ── 历史活动采样用的前台应用标题(C++ ActivityHistory 的 probe 每秒调一次)──
|
// ── 历史活动采样用的前台应用标题(C++ ActivityHistory 的 probe 每秒调一次)──
|
||||||
// 辅助功能服务没启用时返回 null,让「历史活动」报告能说清是缺权限,而不是
|
// 辅助功能服务没启用时返回 null,让「历史活动」报告能说清是缺权限,而不是
|
||||||
@@ -56,10 +98,12 @@ class ControlService : AccessibilityService() {
|
|||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun currentActivityTitle(): String? {
|
fun currentActivityTitle(): String? {
|
||||||
val svc = instance ?: return null
|
val svc = instance ?: return null
|
||||||
val pkg = activeWindow
|
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长。
|
||||||
|
// 与 activeWindow 一致:只看 SCREEN_OFF 记下的起点,不问 KeyguardManager。
|
||||||
|
if (lockedAtElapsed != 0L) return "Locked"
|
||||||
|
val pkg = foregroundPkg
|
||||||
return when {
|
return when {
|
||||||
pkg.isEmpty() -> null
|
pkg.isEmpty() -> null
|
||||||
pkg == "Locked" -> pkg // 锁屏/息屏:C++ 侧当空闲处理,不记录
|
|
||||||
pkg == "Android" -> svc.getString(R.string.activity_home)
|
pkg == "Android" -> svc.getString(R.string.activity_home)
|
||||||
else -> synchronized(labelCache) {
|
else -> synchronized(labelCache) {
|
||||||
labelCache.getOrPut(pkg) { describeApp(svc, pkg) }
|
labelCache.getOrPut(pkg) { describeApp(svc, pkg) }
|
||||||
@@ -177,19 +221,48 @@ class ControlService : AccessibilityService() {
|
|||||||
private val screenReceiver = object : BroadcastReceiver() {
|
private val screenReceiver = object : BroadcastReceiver() {
|
||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
override fun onReceive(context: Context?, intent: Intent?) {
|
||||||
when (intent?.action) {
|
when (intent?.action) {
|
||||||
Intent.ACTION_SCREEN_OFF -> activeWindow = "Locked"
|
// 只记录起点;上报时由 activeWindow 的 getter 算 "Locked: HH:MM:SS"
|
||||||
Intent.ACTION_USER_PRESENT -> activeWindow = "Android"
|
Intent.ACTION_SCREEN_OFF -> lockedAtElapsed = SystemClock.elapsedRealtime()
|
||||||
|
// 亮屏时判断是否还需要解锁:
|
||||||
|
// · 电视(isTvLike)没有锁屏,且 ACTION_USER_PRESENT 往往根本不来;
|
||||||
|
// · 没设置锁屏密码的手机/平板(keyguard 未锁)也不会收到 USER_PRESENT。
|
||||||
|
// 这两种情况必须清掉 SCREEN_OFF 记下的起点,否则会一直上报
|
||||||
|
// 「Locked: 23:12:57」这种越涨越久的假锁屏。
|
||||||
|
// 有锁屏的手机保持起点,等 USER_PRESENT(或服务重连时的校准)来清。
|
||||||
|
Intent.ACTION_SCREEN_ON -> if (isTvLike || !isKeyguardLockedNow()) lockedAtElapsed = 0L
|
||||||
|
Intent.ACTION_USER_PRESENT -> {
|
||||||
|
lockedAtElapsed = 0L
|
||||||
|
foregroundPkg = "Android"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 锁屏判断只用于「事件点的校准」(SCREEN_ON / 服务重连),不要放回每次心跳的
|
||||||
|
// activeWindow getter:部分电视/机型恒返回 true,那正是活动窗口卡在 Locked 的原因。
|
||||||
|
private fun isKeyguardLockedNow(): Boolean {
|
||||||
|
val km = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager ?: return false
|
||||||
|
return km.isKeyguardLocked
|
||||||
|
}
|
||||||
|
|
||||||
// ── Main-thread handler ───────────────────────────────────────────────
|
// ── Main-thread handler ───────────────────────────────────────────────
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
// ── TV (Google TV / Android TV) D-pad mode ───────────────────────────
|
// ── TV (Google TV / Android TV) D-pad mode ───────────────────────────
|
||||||
// Activated when FEATURE_LEANBACK is present. Mouse events are translated
|
// Activated when FEATURE_LEANBACK is present. Mouse events are translated
|
||||||
// to accessibility focus navigation — no touchscreen or root required.
|
// to accessibility focus navigation — no touchscreen or root required.
|
||||||
private var isTV = false
|
//
|
||||||
|
// 两个判定必须分开,且都用不可变惰性值(不要改成生命周期里赋值的 var):
|
||||||
|
// · isTV —— 输入策略:D-pad 焦点导航 vs 直接触摸注入。只认 leanback。
|
||||||
|
// 在不需要 D-pad 的设备上误开会让远程鼠标完全失效;反过来
|
||||||
|
// 在需要 D-pad 的电视上误关会让控制完全失效(2026-11-22 事故)。
|
||||||
|
// · isTvLike —— 电视特征(锁屏启发式):leanback/television/uiMode 任一命中。
|
||||||
|
// 这两者合并过一次,结果就是一台电视的远程控制被关掉;用 typed 命名拆开。
|
||||||
|
// 曾因一次脚本替换丢掉赋值,isTV 静默保持 false。改成 lazy val 后,"漏赋值"不再合法。
|
||||||
|
private val isTV: Boolean by lazy {
|
||||||
|
packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
||||||
|
}
|
||||||
|
private val isTvLike: Boolean by lazy { isTvDevice(this) }
|
||||||
private var tvLastEncX = -1f
|
private var tvLastEncX = -1f
|
||||||
private var tvLastEncY = -1f
|
private var tvLastEncY = -1f
|
||||||
private var tvAccumDX = 0f
|
private var tvAccumDX = 0f
|
||||||
@@ -225,10 +298,25 @@ class ControlService : AccessibilityService() {
|
|||||||
override fun onServiceConnected() {
|
override fun onServiceConnected() {
|
||||||
super.onServiceConnected()
|
super.onServiceConnected()
|
||||||
instance = this
|
instance = this
|
||||||
isTV = packageManager.hasSystemFeature("android.software.leanback")
|
// 输入策略与电视特征(isTV / isTvLike)是不可变惰性值,见字段声明处的说明。
|
||||||
if (isTV) Log.i(TAG, "TV mode: D-pad navigation enabled")
|
// 启动时把解析结果打进日志:远程控制异常时先看这一行,判断是不是输入策略选错了。
|
||||||
|
// 同时尽量写进 native ring(服务端「运行日志」能取回);无障碍服务可能先于
|
||||||
|
// nativeInit 连接,这时 native 不可用,退回 logcat 即可。
|
||||||
|
val inputMode = "input=${if (isTV) "dpad" else "touch"} tvLike=$isTvLike"
|
||||||
|
Log.i(TAG, inputMode)
|
||||||
|
runCatching { YamaBridge.nativeLog(Log.INFO, TAG, inputMode) }
|
||||||
|
// 手机在无障碍服务重启时可能仍处于锁屏:SCREEN_OFF 广播发生在本次服务启动之前,
|
||||||
|
// 之后也不会再补发,只有 USER_PRESENT 才会来。连上时按 keyguard 校准一次:
|
||||||
|
// 锁着就补记起点,没锁就清掉旧起点——否则"锁屏时服务重连、之后已解锁"会让
|
||||||
|
// 假 Locked 一直挂着(时长还一直涨)。电视不认 keyguard(部分机型恒为 true,
|
||||||
|
// 正是 db148c4 把活动窗口卡在 Locked 的原因)。
|
||||||
|
if (!isTvLike) {
|
||||||
|
val keyguardLocked = (getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager)?.isKeyguardLocked == true
|
||||||
|
lockedAtElapsed = if (keyguardLocked) SystemClock.elapsedRealtime() else 0L
|
||||||
|
}
|
||||||
val filter = IntentFilter().apply {
|
val filter = IntentFilter().apply {
|
||||||
addAction(Intent.ACTION_SCREEN_OFF)
|
addAction(Intent.ACTION_SCREEN_OFF)
|
||||||
|
addAction(Intent.ACTION_SCREEN_ON)
|
||||||
addAction(Intent.ACTION_USER_PRESENT)
|
addAction(Intent.ACTION_USER_PRESENT)
|
||||||
}
|
}
|
||||||
registerReceiver(screenReceiver, filter)
|
registerReceiver(screenReceiver, filter)
|
||||||
@@ -238,7 +326,11 @@ class ControlService : AccessibilityService() {
|
|||||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
|
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
|
||||||
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
|
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
|
||||||
val pkg = event.packageName?.toString()
|
val pkg = event.packageName?.toString()
|
||||||
if (!pkg.isNullOrEmpty()) activeWindow = pkg
|
if (!pkg.isNullOrEmpty()) {
|
||||||
|
// 只更新前台包名;锁定起点由 SCREEN_OFF / USER_PRESENT(电视另有
|
||||||
|
// SCREEN_ON)维护,getter 不再询问 KeyguardManager。
|
||||||
|
foregroundPkg = pkg
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
override fun onInterrupt() {}
|
override fun onInterrupt() {}
|
||||||
|
|||||||
@@ -2,11 +2,16 @@ package com.yama.client
|
|||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.media.projection.MediaProjectionManager
|
import android.media.projection.MediaProjectionManager
|
||||||
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.Settings
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
|
||||||
@@ -17,11 +22,19 @@ class MainActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
private lateinit var projectionManager: MediaProjectionManager
|
private lateinit var projectionManager: MediaProjectionManager
|
||||||
|
|
||||||
|
// 授权流程只能走一次:从「所有文件访问」系统设置返回时 onResume 会再来一遍
|
||||||
|
private var flowStarted = false
|
||||||
|
private var awaitingStorageSettings = false
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
// 远程桌面的屏幕捕获授权失效时,native 会拉起本 Activity;实例还活着时靠这个 extra 走 onNewIntent
|
||||||
|
const val EXTRA_REQUEST_PROJECTION = "request_projection"
|
||||||
const val REQUEST_MEDIA_PROJECTION = 1001
|
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
|
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?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
@@ -47,7 +60,66 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
|
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
|
||||||
if (savedInstanceState != null) { finish(); return }
|
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>()
|
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 &&
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
// 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
|
// 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
|
||||||
@@ -58,6 +130,10 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// 主控打开语音监听时客户端会回一条「麦克风不可用」的提示
|
// 主控打开语音监听时客户端会回一条「麦克风不可用」的提示
|
||||||
missing.add(Manifest.permission.RECORD_AUDIO)
|
missing.add(Manifest.permission.RECORD_AUDIO)
|
||||||
}
|
}
|
||||||
|
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
// 摄像头管理(COMMAND_WEBCAM);拒绝后主控打开视频管理会收到「摄像头不可用」
|
||||||
|
missing.add(Manifest.permission.CAMERA)
|
||||||
|
}
|
||||||
if (missing.isNotEmpty()) {
|
if (missing.isNotEmpty()) {
|
||||||
requestPermissions(missing.toTypedArray(), REQUEST_PERMISSIONS)
|
requestPermissions(missing.toTypedArray(), REQUEST_PERMISSIONS)
|
||||||
return
|
return
|
||||||
@@ -65,6 +141,15 @@ class MainActivity : AppCompatActivity() {
|
|||||||
startProjection()
|
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(
|
override fun onRequestPermissionsResult(
|
||||||
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||||
@@ -109,6 +194,15 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent?) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
// native 请求重新授权时(ScreenSpyThread 发现没有投影会话):若本 Activity 还活着,
|
||||||
|
// onCreate 不会再执行,这里补一次系统「屏幕捕获」授权。
|
||||||
|
if (intent?.getBooleanExtra(EXTRA_REQUEST_PROJECTION, false) == true && !awaitingStorageSettings) {
|
||||||
|
startProjection()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,122 @@
|
|||||||
|
package com.yama.client
|
||||||
|
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 进程管理(COMMAND_SYSTEM)的 Android 端。
|
||||||
|
*
|
||||||
|
* Android 7 起 /proc 挂载带 hidepid=2,且 SELinux 的 untrusted_app 域看不到其它
|
||||||
|
* PID——普通 APK 连进程名都枚举不出来,更杀不掉别人。因此这项能力只在取得 root
|
||||||
|
* (su)的设备上声明 CLIENT_CAP_PROCESS,非 root 设备由服务端直接拒绝。
|
||||||
|
*
|
||||||
|
* 数据格式与服务端 TOKEN_PSLIST 对齐:[pid:4][名字:架构\0][完整路径\0]...
|
||||||
|
* 这里只负责产出 "pid\tcomm\texe\n" 文本,二进制封装在 native 侧
|
||||||
|
* (android/app/src/main/cpp/ProcessManagerAndroid.h),避免在 Kotlin 里重复协议常量。
|
||||||
|
*/
|
||||||
|
object RootProcess {
|
||||||
|
private const val TAG = "YAMA_PROC"
|
||||||
|
private const val SU_TIMEOUT_SEC = 6L
|
||||||
|
private const val SU_PROBE_TIMEOUT_SEC = 3L
|
||||||
|
// 否定结果只缓存 5 分钟:用户可能只是当时点了「拒绝」,重启 App 才能恢复太蠢
|
||||||
|
private const val NEGATIVE_TTL_MS = 5 * 60 * 1000L
|
||||||
|
|
||||||
|
private val suCandidates = listOf(
|
||||||
|
"/system/bin/su", "/system/xbin/su", "/sbin/su", "/su/bin/su",
|
||||||
|
"/debug_ramdisk/su", "/data/adb/ksu/bin/su", "/data/adb/magisk/su"
|
||||||
|
)
|
||||||
|
|
||||||
|
@Volatile private var cachedTrue = false
|
||||||
|
@Volatile private var cachedFalseAt = 0L
|
||||||
|
|
||||||
|
/** su 是否存在。true 永久缓存;false 只缓存 5 分钟。 */
|
||||||
|
@JvmStatic
|
||||||
|
@Synchronized
|
||||||
|
fun isRootAvailable(): Boolean {
|
||||||
|
if (cachedTrue) return true
|
||||||
|
val now = SystemClock.elapsedRealtime()
|
||||||
|
if (cachedFalseAt != 0L && now - cachedFalseAt < NEGATIVE_TTL_MS) return false
|
||||||
|
|
||||||
|
var exists = suCandidates.any { runCatching { File(it).exists() }.getOrDefault(false) } ||
|
||||||
|
runCatching {
|
||||||
|
val p = ProcessBuilder("which", "su").redirectErrorStream(true).start()
|
||||||
|
val done = p.waitFor(2, TimeUnit.SECONDS)
|
||||||
|
if (!done) { p.destroyForcibly(); false } else p.exitValue() == 0
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
|
// 路径探测对 Magisk/DenyList 之类「隐藏 su」的配置不可靠;再做一次真实调用。
|
||||||
|
// 这会触发一次 root 授权框(只在探测时),授权成功才认为有 root。
|
||||||
|
// 探测超时用 3 秒,别让登录等太久。
|
||||||
|
if (!exists) {
|
||||||
|
val out = runSu("id", SU_PROBE_TIMEOUT_SEC)
|
||||||
|
exists = out != null && out.contains("uid=0")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exists) cachedTrue = true else cachedFalseAt = now
|
||||||
|
Log.i(TAG, "root available=$exists")
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 su 枚举 /proc。返回每行 "pid\tcomm\texe",失败返回空串。
|
||||||
|
* 脚本在 root shell 里跑,应用自身的 SELinux 限制不适用。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
fun snapshot(): String {
|
||||||
|
if (!isRootAvailable()) return ""
|
||||||
|
// 单引号包裹的 sh 脚本;printf 的 \t \n 由 sh 解释
|
||||||
|
// comm/exe 里可能含制表符/换行(进程名可被 prctl 改成任意内容),
|
||||||
|
// 先 tr 成空格,否则 native 侧按 \t 解析会被伪造的进程名打乱。
|
||||||
|
val script =
|
||||||
|
"for p in /proc/[0-9]*; do " +
|
||||||
|
"pid=\${p##*/}; " +
|
||||||
|
"comm=\$(cat \$p/comm 2>/dev/null | tr '\\t\\n\\r' ' '); " +
|
||||||
|
"exe=\$(readlink \$p/exe 2>/dev/null | tr '\\t\\n\\r' ' '); " +
|
||||||
|
"if [ -n \"\$comm\" ]; then printf '%s\\t%s\\t%s\\n' \"\$pid\" \"\$comm\" \"\$exe\"; fi; " +
|
||||||
|
"done"
|
||||||
|
return runSu(script) ?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 批量 SIGKILL。返回是否全部下发(不保证进程已退出)。 */
|
||||||
|
@JvmStatic
|
||||||
|
fun kill(pids: IntArray): Boolean {
|
||||||
|
if (!isRootAvailable() || pids.isEmpty()) return false
|
||||||
|
val list = pids.filter { it > 1 }.joinToString(" ")
|
||||||
|
if (list.isEmpty()) return false
|
||||||
|
val out = runSu("kill -9 $list")
|
||||||
|
Log.i(TAG, "kill [$list] -> ${out != null}")
|
||||||
|
return out != null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runSu(script: String, timeoutSec: Long = SU_TIMEOUT_SEC): String? {
|
||||||
|
return runCatching {
|
||||||
|
val p = ProcessBuilder("su", "-c", script)
|
||||||
|
.redirectErrorStream(true)
|
||||||
|
.start()
|
||||||
|
|
||||||
|
// 必须在等待的同时把 stdout 读走:几百个进程的输出可能超过管道缓冲,
|
||||||
|
// 写满后子进程会阻塞,waitFor 只能等到超时。
|
||||||
|
val out = StringBuilder()
|
||||||
|
val reader = Thread {
|
||||||
|
runCatching {
|
||||||
|
p.inputStream.bufferedReader().use { out.append(it.readText()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reader.isDaemon = true
|
||||||
|
reader.start()
|
||||||
|
|
||||||
|
val done = p.waitFor(timeoutSec, TimeUnit.SECONDS)
|
||||||
|
if (!done) {
|
||||||
|
p.destroyForcibly()
|
||||||
|
Log.w(TAG, "su timed out")
|
||||||
|
return@runCatching null
|
||||||
|
}
|
||||||
|
reader.join(1000)
|
||||||
|
val text = out.toString()
|
||||||
|
// 用户拒绝授权时 su 通常返回非 0,且输出为空/拒绝信息
|
||||||
|
if (p.exitValue() != 0 && text.isBlank()) null else text
|
||||||
|
}.onFailure { Log.w(TAG, "su failed: $it") }.getOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -30,6 +30,12 @@ object YamaBridge {
|
|||||||
/** 把一行文本回报到服务端消息栏(TOKEN_CLIENT_MSG),用于升级流程的成败说明 */
|
/** 把一行文本回报到服务端消息栏(TOKEN_CLIENT_MSG),用于升级流程的成败说明 */
|
||||||
external fun nativeReportMessage(msg: String)
|
external fun nativeReportMessage(msg: String)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把一行日志写进 native 的 Logger ring:服务端「运行日志」菜单 / MCP get_client_log
|
||||||
|
* 会取回这份 ring。电视、机顶盒这类没有 adb 的设备靠它回传编码器/投影状态。
|
||||||
|
*/
|
||||||
|
external fun nativeLog(priority: Int, tag: String, msg: String)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 远程交谈:发送一条已按 GBK 编码的消息(不含结尾 NUL,native 补)。
|
* 远程交谈:发送一条已按 GBK 编码的消息(不含结尾 NUL,native 补)。
|
||||||
* 没有活跃的交谈子连接时返回 false。
|
* 没有活跃的交谈子连接时返回 false。
|
||||||
@@ -41,4 +47,13 @@ object YamaBridge {
|
|||||||
* GSM 6.10/WAV49 并写入语音子连接。没有活跃会话时直接丢弃。
|
* GSM 6.10/WAV49 并写入语音子连接。没有活跃会话时直接丢弃。
|
||||||
*/
|
*/
|
||||||
external fun nativeAudioSendPcm(samples: ShortArray)
|
external fun nativeAudioSendPcm(samples: ShortArray)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 摄像头管理:Camera2 每输出一帧 JPEG,交给 native 封装成
|
||||||
|
* [TOKEN_WEBCAM_DIB][isCompress][fcc][JPEG] 发给服务端。
|
||||||
|
*/
|
||||||
|
external fun nativeOnCameraJpeg(data: ByteArray)
|
||||||
|
|
||||||
|
/** 摄像头采集失败(无权限 / 被占用 / 会话配置失败),回报主控 */
|
||||||
|
external fun nativeOnCameraError(msg: String)
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,31 @@
|
|||||||
@echo off
|
@echo off
|
||||||
:: SimpleRemoter Quick Build Script
|
:: SimpleRemoter Quick Build Script
|
||||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client]
|
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client] [-name NAME]
|
||||||
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
|
:: go-server Build Go fallback server only - Bin\YamaGo_x64.exe
|
||||||
:: go-server publish Same, plus UPX --best compression
|
:: go-server publish Same, plus UPX --best compression
|
||||||
:: server-linux Cross-compile Go server for Linux -> Bin\server_linux_amd64
|
:: server-linux Cross-compile Go server for Linux - Bin\server_linux_amd64
|
||||||
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
|
:: serverd Debug server only (x64) - Bin\Yama_x64d.exe
|
||||||
:: client Debug client (x64) -> x64\Debug\ghost.exe
|
:: client Debug client (x64) - x64\Debug\ghost.exe
|
||||||
|
:: -name NAME Server output name, writes Bin\NAME_x64.exe instead of
|
||||||
|
:: Bin\Yama_x64.exe. Use it to build while the Release
|
||||||
|
:: server is running and Bin\Yama_x64.exe is locked:
|
||||||
|
:: build.cmd server -name YamaTest
|
||||||
|
:: Applies to server / serverd / publish.
|
||||||
|
::
|
||||||
|
:: NOTE: keep this file pure ASCII. cmd reads .cmd as the OEM code page (936
|
||||||
|
:: here), so UTF-8 text can swallow the following newline and merge the next
|
||||||
|
:: command into a comment line - which then turns its ">" into a redirect.
|
||||||
|
|
||||||
setlocal enabledelayedexpansion
|
setlocal enabledelayedexpansion
|
||||||
|
|
||||||
|
:: Capture the script directory before any shift: shift moves %0 along with
|
||||||
|
:: %1..%9, after which %~dp0 resolves to the current directory instead.
|
||||||
|
set SCRIPT_DIR=%~dp0
|
||||||
|
|
||||||
set CONFIG=Release
|
set CONFIG=Release
|
||||||
set PLATFORM=x64
|
set PLATFORM=x64
|
||||||
set EXTRA_ARGS=
|
set EXTRA_ARGS=
|
||||||
|
set SERVER_NAME=
|
||||||
|
|
||||||
:parse_args
|
:parse_args
|
||||||
if "%~1"=="" goto :run
|
if "%~1"=="" goto :run
|
||||||
@@ -28,6 +42,16 @@ if /i "%~1"=="server-linux" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServerLinux& shift&
|
|||||||
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
|
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
|
||||||
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
|
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
|
||||||
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
|
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
|
||||||
|
if /i "%~1"=="-name" (
|
||||||
|
if "%~2"=="" (
|
||||||
|
echo ERROR: -name needs a value, e.g. build.cmd server -name YamaTest
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
set SERVER_NAME=%~2
|
||||||
|
shift
|
||||||
|
shift
|
||||||
|
goto :parse_args
|
||||||
|
)
|
||||||
echo Unknown argument: %~1
|
echo Unknown argument: %~1
|
||||||
shift
|
shift
|
||||||
goto :parse_args
|
goto :parse_args
|
||||||
@@ -35,9 +59,13 @@ goto :parse_args
|
|||||||
:run
|
:run
|
||||||
echo.
|
echo.
|
||||||
echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM%
|
echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM%
|
||||||
|
if not "%SERVER_NAME%"=="" echo Server name: %SERVER_NAME%
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
powershell -ExecutionPolicy Bypass -File "%~dp0build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS%
|
set NAME_ARG=
|
||||||
|
if not "%SERVER_NAME%"=="" set NAME_ARG=-ServerName "%SERVER_NAME%"
|
||||||
|
|
||||||
|
powershell -ExecutionPolicy Bypass -File "%SCRIPT_DIR%build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS% %NAME_ARG%
|
||||||
|
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
echo.
|
echo.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# SimpleRemoter Build Script
|
# SimpleRemoter Build Script
|
||||||
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
|
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish] [-ServerName NAME]
|
||||||
#
|
#
|
||||||
# Requirements:
|
# Requirements:
|
||||||
# - Visual Studio 2019 or 2022
|
# - Visual Studio 2019 or 2022
|
||||||
@@ -19,7 +19,12 @@ param(
|
|||||||
[switch]$Clean, # Clean before build
|
[switch]$Clean, # Clean before build
|
||||||
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
|
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
|
||||||
[switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
[switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
||||||
[switch]$GoServerLinux # Cross-compile the Go server for Linux -> Bin/server_linux_amd64
|
[switch]$GoServerLinux, # Cross-compile the Go server for Linux -> Bin/server_linux_amd64
|
||||||
|
|
||||||
|
# 服务端输出名,默认 Yama(-> Bin\Yama_x64.exe)。vcxproj 里输出名是
|
||||||
|
# $(SolutionDir)Bin\$(TargetName)_<platform><ext>,所以这里覆盖 TargetName 即可。
|
||||||
|
# 用途:Release 服务端正在运行、Bin\Yama_x64.exe 被占用时,编译到另一个名字。
|
||||||
|
[string]$ServerName = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
@@ -28,6 +33,23 @@ $rootDir = $PSScriptRoot
|
|||||||
$binDir = Join-Path $rootDir "Bin"
|
$binDir = Join-Path $rootDir "Bin"
|
||||||
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
|
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
|
||||||
|
|
||||||
|
# 服务端输出名。vcxproj 把输出写成 $(SolutionDir)Bin\$(TargetName)_<platform><ext>,
|
||||||
|
# 覆盖 TargetName 就能换文件名,不用改工程。默认仍是 Yama -> Bin\Yama_x64.exe,
|
||||||
|
# 行为与以前一致;指定别的名字主要是为了在 Release 服务端运行中
|
||||||
|
# (Bin\Yama_x64.exe 被独占)时还能编译。
|
||||||
|
if ($ServerName) {
|
||||||
|
if ($ServerName -notmatch '^[A-Za-z0-9][A-Za-z0-9_.-]*$') {
|
||||||
|
Write-Host "ERROR: invalid -ServerName '$ServerName'." -ForegroundColor Red
|
||||||
|
Write-Host " Use letters, digits, underscore, dot or dash, and do not start with a symbol." -ForegroundColor Yellow
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
if ($ClientOnly) {
|
||||||
|
Write-Host "WARNING: -ServerName does not apply to -ClientOnly (client output is always ghost.exe), ignored." -ForegroundColor Yellow
|
||||||
|
$ServerName = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$serverTargetName = if ($ServerName) { $ServerName } else { "Yama" }
|
||||||
|
|
||||||
# Build Go fallback server. No-op (with warning) if Go compiler is not installed.
|
# Build Go fallback server. No-op (with warning) if Go compiler is not installed.
|
||||||
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
|
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
|
||||||
function Build-GoServer {
|
function Build-GoServer {
|
||||||
@@ -289,7 +311,9 @@ function Build-Project {
|
|||||||
[string]$Project,
|
[string]$Project,
|
||||||
[string]$Configuration,
|
[string]$Configuration,
|
||||||
[string]$Platform,
|
[string]$Platform,
|
||||||
[bool]$ForceClean = $false
|
[bool]$ForceClean = $false,
|
||||||
|
# 额外传给 MSBuild 的 /p: 属性,例如 /p:TargetName=YamaTest
|
||||||
|
[string[]]$ExtraProps = @()
|
||||||
)
|
)
|
||||||
|
|
||||||
# Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names
|
# Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names
|
||||||
@@ -307,6 +331,10 @@ function Build-Project {
|
|||||||
"/v:minimal" # Minimal verbosity
|
"/v:minimal" # Minimal verbosity
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if ($ExtraProps.Count -gt 0) {
|
||||||
|
$buildArgs += $ExtraProps
|
||||||
|
}
|
||||||
|
|
||||||
if ($Clean -or $ForceClean) {
|
if ($Clean -or $ForceClean) {
|
||||||
# Use :Rebuild target for single project rebuild
|
# Use :Rebuild target for single project rebuild
|
||||||
$buildArgs[1] = "/t:${Project}:Rebuild"
|
$buildArgs[1] = "/t:${Project}:Rebuild"
|
||||||
@@ -407,6 +435,9 @@ Write-Host " Config: $Config" -ForegroundColor Cyan
|
|||||||
Write-Host " Platform: $Platform" -ForegroundColor Cyan
|
Write-Host " Platform: $Platform" -ForegroundColor Cyan
|
||||||
Write-Host " VS: $vsYear" -ForegroundColor Cyan
|
Write-Host " VS: $vsYear" -ForegroundColor Cyan
|
||||||
Write-Host " Clean: $Clean" -ForegroundColor Cyan
|
Write-Host " Clean: $Clean" -ForegroundColor Cyan
|
||||||
|
if ($ServerName) {
|
||||||
|
Write-Host " Server: $serverTargetName" -ForegroundColor Cyan
|
||||||
|
}
|
||||||
if ($Publish) {
|
if ($Publish) {
|
||||||
Write-Host " UPX: Yes" -ForegroundColor Cyan
|
Write-Host " UPX: Yes" -ForegroundColor Cyan
|
||||||
}
|
}
|
||||||
@@ -426,10 +457,15 @@ if (-not $ServerOnly) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Step 2: Building server (Yama)..." -ForegroundColor Magenta
|
Write-Host "Step 2: Building server ($serverTargetName)..." -ForegroundColor Magenta
|
||||||
|
|
||||||
|
# 指定了 -ServerName 就覆盖 TargetName,让输出落到 Bin\<名称>_x64.exe,
|
||||||
|
# 从而绕开正在运行的 Bin\Yama_x64.exe(被独占时链接会报 LNK1104)。
|
||||||
|
$serverMsBuildProps = @()
|
||||||
|
if ($ServerName) { $serverMsBuildProps += "/p:TargetName=$ServerName" }
|
||||||
|
|
||||||
foreach ($plat in $platforms) {
|
foreach ($plat in $platforms) {
|
||||||
Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish
|
Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish -ExtraProps $serverMsBuildProps
|
||||||
}
|
}
|
||||||
|
|
||||||
# UPX compression in Publish mode
|
# UPX compression in Publish mode
|
||||||
@@ -438,7 +474,7 @@ if ($Publish) {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta
|
Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta
|
||||||
|
|
||||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama_x64.exe"
|
$binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}_x64.exe"
|
||||||
|
|
||||||
if (-not (Test-Path $upxPath)) {
|
if (-not (Test-Path $upxPath)) {
|
||||||
Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red
|
Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red
|
||||||
@@ -490,13 +526,13 @@ if ($finalOutput) {
|
|||||||
# Check both possible output locations (project has custom OutputFile)
|
# Check both possible output locations (project has custom OutputFile)
|
||||||
$suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" }
|
$suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" }
|
||||||
if ($Config -eq "Debug") { $suffix += "d" }
|
if ($Config -eq "Debug") { $suffix += "d" }
|
||||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama$suffix.exe"
|
$binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}${suffix}.exe"
|
||||||
|
|
||||||
$outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" }
|
$outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" }
|
||||||
if ($Config -eq "Debug") {
|
if ($Config -eq "Debug") {
|
||||||
$outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" }
|
$outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" }
|
||||||
}
|
}
|
||||||
$stdPath = Join-Path (Join-Path $rootDir $outDir) "Yama.exe"
|
$stdPath = Join-Path (Join-Path $rootDir $outDir) "${serverTargetName}.exe"
|
||||||
|
|
||||||
# Prefer Bin output, fallback to standard path
|
# Prefer Bin output, fallback to standard path
|
||||||
$outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null }
|
$outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null }
|
||||||
|
|||||||
+73
-11
@@ -44,7 +44,9 @@ CAudio::CAudio()
|
|||||||
m_InAudioData[i] = new BYTE[m_ulBufferLength];
|
m_InAudioData[i] = new BYTE[m_ulBufferLength];
|
||||||
m_InAudioHeader[i] = new WAVEHDR;
|
m_InAudioHeader[i] = new WAVEHDR;
|
||||||
|
|
||||||
m_OutAudioData[i] = new BYTE[m_ulBufferLength];
|
// 播放缓冲按 AUDIO_OUT_MAX(16 个 GSM 块 = 1040 字节)分配:一个包最多
|
||||||
|
// 交给 waveOut 这么多,超出的部分在 PlayBuffer 里分多次写。
|
||||||
|
m_OutAudioData[i] = new BYTE[AUDIO_OUT_MAX];
|
||||||
m_OutAudioHeader[i] = new WAVEHDR;
|
m_OutAudioHeader[i] = new WAVEHDR;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,9 +90,12 @@ CAudio::~CAudio()
|
|||||||
|
|
||||||
if (m_bIsWaveOutUsed) {
|
if (m_bIsWaveOutUsed) {
|
||||||
waveOutReset(m_hWaveOut);
|
waveOutReset(m_hWaveOut);
|
||||||
|
// 这里原来 unprepare 的是 m_InAudioHeader —— 那是录音侧的头,而且上面
|
||||||
|
// 已经 delete 掉了(悬垂指针),unprepare 的对象完全错了。播放侧要收的是
|
||||||
|
// m_OutAudioHeader。
|
||||||
for (int i = 0; i < 2; ++i) {
|
for (int i = 0; i < 2; ++i) {
|
||||||
if (m_InAudioHeader[i])
|
if (m_OutAudioHeader[i])
|
||||||
waveOutUnprepareHeader(m_hWaveOut, m_InAudioHeader[i], sizeof(WAVEHDR));
|
waveOutUnprepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
|
||||||
}
|
}
|
||||||
waveOutClose(m_hWaveOut);
|
waveOutClose(m_hWaveOut);
|
||||||
}
|
}
|
||||||
@@ -150,6 +155,13 @@ LPBYTE CAudio::GetRecordBuffer(LPDWORD dwBufferSize)
|
|||||||
|
|
||||||
SetEvent(m_hStartRecord);
|
SetEvent(m_hStartRecord);
|
||||||
WaitForSingleObject(m_hEventWaveIn, INFINITE);
|
WaitForSingleObject(m_hEventWaveIn, INFINITE);
|
||||||
|
// 这里故意仍按 m_ulBufferLength(1000)整包返回,不用 dwBytesRecorded 裁短。
|
||||||
|
//
|
||||||
|
// waveIn 录 GSM610 时驱动只写整数个 65 字节块,1000 字节的缓冲实际只填 975,
|
||||||
|
// 尾部 25 字节是驱动从未写过的残留。看着像垃圾,但播放侧按块截断时会正好把
|
||||||
|
// 这 25 字节丢掉,所以它在线上是无害的;反过来,包长一旦小于 1000,老主控
|
||||||
|
// (v1.4.2 及更早)的 PlayBuffer 按 m_ulBufferLength 整块 memcpy 就会越界读,
|
||||||
|
// 读到的才是真垃圾。保持 1000 才能让新客户端连老主控。
|
||||||
*dwBufferSize = m_ulBufferLength;
|
*dwBufferSize = m_ulBufferLength;
|
||||||
return m_InAudioData[m_nWaveInIndex]; //返出真正数据
|
return m_InAudioData[m_nWaveInIndex]; //返出真正数据
|
||||||
}
|
}
|
||||||
@@ -196,14 +208,60 @@ DWORD WINAPI CAudio::waveInCallBack(LPVOID lParam)
|
|||||||
BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize)
|
BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize)
|
||||||
{
|
{
|
||||||
if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备
|
if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备
|
||||||
return NULL;
|
return FALSE;
|
||||||
|
if (!szBuffer || !dwBufferSize)
|
||||||
|
return FALSE;
|
||||||
|
|
||||||
for (int i = 0; i < dwBufferSize; i += m_ulBufferLength) {
|
// 按包截断到整数个 65 字节块,余数直接丢弃 —— 不能攒到下一包。
|
||||||
memcpy(m_OutAudioData[m_nWaveOutIndex], szBuffer, m_ulBufferLength);
|
//
|
||||||
waveOutWrite(m_hWaveOut, m_OutAudioHeader[m_nWaveOutIndex], sizeof(WAVEHDR));
|
// waveOut 只转换整块,末尾不足一块的字节既不转换也不保留。曾经的写法是把
|
||||||
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
|
// 余数攒起来跨包拼接(当成一条连续的流处理),在 Android 那种「包与包之间
|
||||||
|
// 连续」的上行流上是对的,却把既有 Windows 客户端的监听整条搞成了噪声:
|
||||||
|
// Windows 主机用 waveIn 录 GSM610,1000 字节的缓冲驱动只写 975 字节,尾部
|
||||||
|
// 25 字节是驱动从未写过的堆残留,客户端把这 1000 字节整包发上来。攒余数就
|
||||||
|
// 等于每 1000 字节往 GSM 流里插进 25 字节垃圾,块边界从第二包起全部错位。
|
||||||
|
// 按包截断则正好丢掉这 25 字节残留,和老版本行为一致。
|
||||||
|
//
|
||||||
|
// 代价是发送侧必须保证「一个包 = 整数个块」:Windows 端天然满足(驱动只写
|
||||||
|
// 整块),Android 端见 AudioHandler.h 的 975 字节整块打包。
|
||||||
|
DWORD n = (dwBufferSize / AUDIO_GSM_BLOCK) * AUDIO_GSM_BLOCK;
|
||||||
|
if (n == 0)
|
||||||
|
return FALSE;
|
||||||
|
|
||||||
|
// 一个包可能超过一块播放缓冲,分多次写。AUDIO_OUT_MAX 本身是 65 的整数倍,
|
||||||
|
// 所以每一段都是整块。
|
||||||
|
for (DWORD off = 0; off < n; off += AUDIO_OUT_MAX) {
|
||||||
|
DWORD len = n - off;
|
||||||
|
if (len > AUDIO_OUT_MAX)
|
||||||
|
len = AUDIO_OUT_MAX;
|
||||||
|
if (!WriteAligned(szBuffer + off, len))
|
||||||
|
break; // 设备忙:剩下的整块丢掉,丢整块不会破坏对齐
|
||||||
}
|
}
|
||||||
return true;
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把 len 字节(必须是 65 的整数倍)交给 waveOut。两个缓冲轮转,还在队列里的不能
|
||||||
|
// 复用:waveOutWrite 会返回 WAVERR_BUSY 且数据被静默丢弃,原实现忽略返回值,
|
||||||
|
// 丢包没有任何痕迹。
|
||||||
|
BOOL CAudio::WriteAligned(LPBYTE p, DWORD len)
|
||||||
|
{
|
||||||
|
if (!p || len == 0 || len > AUDIO_OUT_MAX ||
|
||||||
|
(len % AUDIO_GSM_BLOCK) != 0)
|
||||||
|
return FALSE;
|
||||||
|
|
||||||
|
LPWAVEHDR h = m_OutAudioHeader[m_nWaveOutIndex];
|
||||||
|
if (h->dwFlags & WHDR_INQUEUE)
|
||||||
|
return FALSE;
|
||||||
|
|
||||||
|
memcpy(m_OutAudioData[m_nWaveOutIndex], p, len);
|
||||||
|
h->dwBufferLength = len;
|
||||||
|
MMRESULT mmResult = waveOutWrite(m_hWaveOut, h, sizeof(WAVEHDR));
|
||||||
|
if (mmResult != MMSYSERR_NOERROR) {
|
||||||
|
Mprintf("waveOutWrite(%lu) failed: %u\n", len, (unsigned)mmResult);
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
|
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
|
||||||
|
return TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
BOOL CAudio::InitializeWaveOut()
|
BOOL CAudio::InitializeWaveOut()
|
||||||
@@ -212,16 +270,20 @@ BOOL CAudio::InitializeWaveOut()
|
|||||||
return FALSE;
|
return FALSE;
|
||||||
|
|
||||||
for (int i = 0; i < 2; ++i)
|
for (int i = 0; i < 2; ++i)
|
||||||
memset(m_OutAudioData[i], 0, m_ulBufferLength); //声音数据
|
memset(m_OutAudioData[i], 0, AUDIO_OUT_MAX); //声音数据
|
||||||
|
|
||||||
MMRESULT mmResult;
|
MMRESULT mmResult;
|
||||||
mmResult = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL);
|
mmResult = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL);
|
||||||
if (mmResult != MMSYSERR_NOERROR)
|
if (mmResult != MMSYSERR_NOERROR)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
m_nWaveOutIndex = 0;
|
||||||
|
|
||||||
for (int i = 0; i < 2; ++i) {
|
for (int i = 0; i < 2; ++i) {
|
||||||
m_OutAudioHeader[i]->lpData = (LPSTR)m_OutAudioData[i];
|
m_OutAudioHeader[i]->lpData = (LPSTR)m_OutAudioData[i];
|
||||||
m_OutAudioHeader[i]->dwBufferLength = m_ulBufferLength;
|
// 按最大容量 prepare;实际每次写入的长度在 WriteAligned 里按整块数设置,
|
||||||
|
// 只会更短,不会越过这块缓冲。
|
||||||
|
m_OutAudioHeader[i]->dwBufferLength = AUDIO_OUT_MAX;
|
||||||
m_OutAudioHeader[i]->dwFlags = 0;
|
m_OutAudioHeader[i]->dwFlags = 0;
|
||||||
m_OutAudioHeader[i]->dwLoops = 0;
|
m_OutAudioHeader[i]->dwLoops = 0;
|
||||||
waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
|
waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
|
||||||
|
|||||||
@@ -11,6 +11,16 @@
|
|||||||
#include <MMSYSTEM.H>
|
#include <MMSYSTEM.H>
|
||||||
#include <MMReg.h>
|
#include <MMReg.h>
|
||||||
|
|
||||||
|
// GSM610 的 ACM 编解码器按 65 字节块(wfx.nBlockAlign)工作。waveOutWrite /
|
||||||
|
// waveIn 对末尾不足一块的字节既不转换也不保留,直接丢弃 —— 实测 4 个 1000 字节
|
||||||
|
// 缓冲只播出 15360 采样(少 640),而 4 个 975 字节缓冲正好 16000。
|
||||||
|
//
|
||||||
|
// 所以线协议的不变式是:**一个音频包必须由整数个 65 字节块组成**。
|
||||||
|
// 播放侧按包截断、余数丢弃(见 Audio.cpp 的 PlayBuffer);发送侧各自保证自己
|
||||||
|
// 发出去的包是整块(Windows 端 waveIn 驱动本来就只写整块,Android 端见
|
||||||
|
// AudioHandler.h)。余数绝不能攒到下一包 —— 原因见 PlayBuffer 的注释。
|
||||||
|
#define AUDIO_GSM_BLOCK 65
|
||||||
|
#define AUDIO_OUT_MAX (16 * AUDIO_GSM_BLOCK) // 1040 = 16 块 = 640ms
|
||||||
|
|
||||||
class CAudio
|
class CAudio
|
||||||
{
|
{
|
||||||
@@ -40,6 +50,8 @@ public:
|
|||||||
LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续
|
LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续
|
||||||
BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize);
|
BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize);
|
||||||
BOOL InitializeWaveOut();
|
BOOL InitializeWaveOut();
|
||||||
|
// 把整块数据交给 waveOut。两个缓冲轮转,还在队列里的不能复用
|
||||||
|
BOOL WriteAligned(LPBYTE p, DWORD len);
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_)
|
#endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_)
|
||||||
+58
-32
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include "stdafx.h"
|
#include "stdafx.h"
|
||||||
#include "CaptureVideo.h"
|
#include "CaptureVideo.h"
|
||||||
|
#include <dvdmedia.h> // VIDEOINFOHEADER2:不少摄像头/驱动给的是 FORMAT_VideoInfo2
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////
|
||||||
// Construction/Destruction
|
// Construction/Destruction
|
||||||
@@ -46,13 +47,14 @@ CCaptureVideo::~CCaptureVideo()
|
|||||||
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||||||
{
|
{
|
||||||
Mprintf("CCaptureVideo call Open\n");
|
Mprintf("CCaptureVideo call Open\n");
|
||||||
HRESULT hResult = S_FALSE;
|
HRESULT hResult = E_FAIL; // 默认失败:只有图真正跑起来才算成功
|
||||||
|
bool graphRunning = false;
|
||||||
do {
|
do {
|
||||||
hResult = InitCaptureGraphBuilder();
|
hResult = InitCaptureGraphBuilder();
|
||||||
if (FAILED(hResult))
|
if (FAILED(hResult))
|
||||||
break;
|
break;
|
||||||
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
|
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
|
||||||
hResult = S_FALSE;
|
hResult = E_FAIL; // 没有可用的 DirectShow 采集设备
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,10 +99,29 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
|||||||
|
|
||||||
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
|
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
|
||||||
|
|
||||||
VIDEOINFOHEADER * vih = (VIDEOINFOHEADER*) mt.pbFormat;
|
// 只按 VIDEOINFOHEADER 解释 mt.pbFormat 不够:很多摄像头/驱动(尤其
|
||||||
|
// 笔记本内置摄像头)给出的格式是 FORMAT_VideoInfo2,两者头部布局不同,
|
||||||
|
// 直接强转会读出垃圾宽高,后面按它分配缓冲/逐帧 memcpy 就会崩。两种都认,
|
||||||
|
// 其它格式或非法尺寸一律当失败处理,让上层优雅退出而不是带病跑。
|
||||||
|
BITMAPINFOHEADER* bmi = NULL;
|
||||||
|
if (mt.formattype == FORMAT_VideoInfo && mt.pbFormat != NULL
|
||||||
|
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER)) {
|
||||||
|
bmi = &((VIDEOINFOHEADER*)mt.pbFormat)->bmiHeader;
|
||||||
|
} else if (mt.formattype == FORMAT_VideoInfo2 && mt.pbFormat != NULL
|
||||||
|
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER2)) {
|
||||||
|
bmi = &((VIDEOINFOHEADER2*)mt.pbFormat)->bmiHeader;
|
||||||
|
}
|
||||||
|
if (bmi == NULL || bmi->biWidth <= 0 || bmi->biHeight == 0
|
||||||
|
|| bmi->biWidth > 16384 || abs(bmi->biHeight) > 16384) {
|
||||||
|
Mprintf("CCaptureVideo: unsupported media type (formattype=%08lx cbFormat=%lu), abort\n",
|
||||||
|
(unsigned long)mt.formattype.Data1, (unsigned long)mt.cbFormat);
|
||||||
|
FreeMediaType(mt);
|
||||||
|
hResult = E_FAIL;
|
||||||
|
break;
|
||||||
|
}
|
||||||
//mCB 是个另外一个类 并且全局变量 有个回调
|
//mCB 是个另外一个类 并且全局变量 有个回调
|
||||||
mCB.m_ulFullWidth = vih->bmiHeader.biWidth;
|
mCB.m_ulFullWidth = (ULONG)bmi->biWidth;
|
||||||
mCB.m_ulFullHeight = vih->bmiHeader.biHeight;
|
mCB.m_ulFullHeight = (ULONG)abs(bmi->biHeight);
|
||||||
|
|
||||||
FreeMediaType(mt);
|
FreeMediaType(mt);
|
||||||
|
|
||||||
@@ -120,11 +141,19 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
|||||||
|
|
||||||
if(FAILED(hResult))
|
if(FAILED(hResult))
|
||||||
break;
|
break;
|
||||||
|
// IMediaControl::Run 在「状态切换尚未完成、稍后异步完成」时会返回 S_FALSE,
|
||||||
|
// 这时图已经在跑、SampleGrabber 回调随时会到。以前把它原样返回给上层,
|
||||||
|
// 上层用 == S_OK 判断就误判成「摄像头没打开」并提前中止(8d4c118 引入),
|
||||||
|
// 而回调随后拿还没分配的 m_BitmapData_Full 做 memcpy —— 写地址 0 崩溃。
|
||||||
|
hResult = S_OK;
|
||||||
|
graphRunning = true;
|
||||||
} while (false);
|
} while (false);
|
||||||
|
|
||||||
Mprintf("CCaptureVideo Open %s\n", FAILED(hResult) ? "failed" : "succeed");
|
Mprintf("CCaptureVideo Open %s (hr=%08lX)\n",
|
||||||
|
graphRunning ? "succeed" : "failed", (unsigned long)hResult);
|
||||||
|
|
||||||
return hResult;
|
// 图没跑起来时一律返回失败码(S_FALSE 也是「成功」语义,会让上层误判)
|
||||||
|
return graphRunning ? S_OK : (FAILED(hResult) ? hResult : E_FAIL);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -164,43 +193,40 @@ LPBITMAPINFO CCaptureVideo::GetBmpInfor()
|
|||||||
|
|
||||||
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
|
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
|
||||||
{
|
{
|
||||||
if (deviceId < 0)
|
if (deviceId < 0 || pFilter == NULL)
|
||||||
return FALSE;// enumerate all video capture devices
|
return FALSE;// enumerate all video capture devices
|
||||||
|
*pFilter = NULL;
|
||||||
|
|
||||||
CComPtr<ICreateDevEnum> pCreateDevEnum;
|
CComPtr<ICreateDevEnum> pCreateDevEnum;
|
||||||
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
|
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
|
||||||
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
|
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
|
||||||
if (hr != NOERROR) {
|
if (hr != NOERROR)
|
||||||
return FALSE;
|
return FALSE;
|
||||||
}
|
|
||||||
CComPtr<IEnumMoniker> pEm;
|
CComPtr<IEnumMoniker> pEm;
|
||||||
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pEm, 0);
|
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
|
||||||
if (hr != NOERROR) {
|
if (hr != S_OK) // S_FALSE = 该类别下没有任何 DirectShow 设备
|
||||||
return FALSE;
|
return FALSE;
|
||||||
}
|
|
||||||
pEm->Reset();
|
pEm->Reset();
|
||||||
ULONG cFetched;
|
ULONG cFetched = 0;
|
||||||
IMoniker *pM;
|
IMoniker* pM = NULL;
|
||||||
int index = 0;
|
int index = 0;
|
||||||
while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK, index <= deviceId) {
|
// 原实现写成逗号表达式 `while (hr = Next(...), hr == S_OK, index <= deviceId)`:
|
||||||
IPropertyBag *pBag;
|
// 循环条件实际只看 index,枚举结束后还会继续用未初始化/已释放的 pM 调
|
||||||
//通过BindToStorage 可以访问该设备的标识集
|
// BindToStorage。机器上 VFW 能枚举到摄像头、DirectShow 却一个都没有时必崩。
|
||||||
hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
|
while (pEm->Next(1, &pM, &cFetched) == S_OK && pM != NULL) {
|
||||||
if(SUCCEEDED(hr)) {
|
if (index == deviceId) {
|
||||||
VARIANT var;
|
hr = pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
|
||||||
var.vt = VT_BSTR;
|
pM->Release();
|
||||||
hr = pBag->Read(L"FriendlyName", &var, NULL);
|
return SUCCEEDED(hr) && *pFilter != NULL;
|
||||||
if (hr == NOERROR) {
|
|
||||||
if (index == deviceId) {
|
|
||||||
pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
|
|
||||||
}
|
|
||||||
SysFreeString(var.bstrVal);
|
|
||||||
}
|
|
||||||
pBag->Release(); //引用计数--
|
|
||||||
}
|
}
|
||||||
pM->Release();
|
pM->Release();
|
||||||
index++;
|
pM = NULL;
|
||||||
|
++index;
|
||||||
}
|
}
|
||||||
return TRUE;
|
Mprintf("CCaptureVideo: no DirectShow video device #%d (enumerated %d)\n", deviceId, index);
|
||||||
|
return FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+21
-4
@@ -123,10 +123,19 @@ public:
|
|||||||
|
|
||||||
LPBITMAPINFO ConstructBI(ULONG ulbiBitCount)
|
LPBITMAPINFO ConstructBI(ULONG ulbiBitCount)
|
||||||
{
|
{
|
||||||
int ColorNum = ulbiBitCount <= 8 ? 1 << ulbiBitCount : 0;
|
// 宽高来自摄像头驱动,必须挡住 0/超大值:否则 biSizeImage 会溢出成小值,
|
||||||
ULONG ulBitmapLength = sizeof(BITMAPINFOHEADER) + (ColorNum * sizeof(RGBQUAD)); //BITMAPINFOHEADER + 调色板的个数
|
// 之后每帧 memcpy 都变成堆越界——「换一台机器一开视频就崩」多半出在这里。
|
||||||
|
if (m_ulFullWidth == 0 || m_ulFullHeight == 0
|
||||||
|
|| m_ulFullWidth > 16384 || m_ulFullHeight > 16384)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
m_BitmapInfor_Full = (BITMAPINFO *) new BYTE[ulBitmapLength];
|
// 分配「头部 + 完整 256 项调色板」:BITMAPINFO 本身只声明 bmiColors[1]
|
||||||
|
// (sizeof=44),而按 biBitCount 索引调色板的调用方会读到 44 字节之外。
|
||||||
|
// 当前只以 24bpp 调用(RGBQUAD 用不到),但按最大调色板预留 1KB 最省心,
|
||||||
|
// 也顺便修正了旧代码分配 40 字节、SendBitMapInfor 按 44 字节读取的越界。
|
||||||
|
const size_t biSize = sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD);
|
||||||
|
m_BitmapInfor_Full = (BITMAPINFO*) new BYTE[biSize];
|
||||||
|
ZeroMemory(m_BitmapInfor_Full, biSize);
|
||||||
|
|
||||||
BITMAPINFOHEADER* BitmapInforHeader = &(m_BitmapInfor_Full->bmiHeader);
|
BITMAPINFOHEADER* BitmapInforHeader = &(m_BitmapInfor_Full->bmiHeader);
|
||||||
|
|
||||||
@@ -192,8 +201,16 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (bStact==CMD_CAN_COPY) { //未初始化 发送的同差异的一样
|
if (bStact==CMD_CAN_COPY) { //未初始化 发送的同差异的一样
|
||||||
|
// 驱动送来的帧可能比协商格式大(分辨率切换、格式回退、驱动自带填充):
|
||||||
|
// 不校验长度就 memcpy 会直接把堆写坏,表现就是进程当场崩溃。
|
||||||
|
// 注意必须返回 S_OK:BufferCB 返回错误可能让 SampleGrabber 停流,
|
||||||
|
// 那会让「图刚跑起来、缓冲区还没建好」时的第一帧把整条视频流掐死。
|
||||||
|
if (m_BitmapData_Full == NULL || m_dwSize == 0 || ulBufferSize <= 0
|
||||||
|
|| (unsigned long)ulBufferSize > m_dwSize) {
|
||||||
|
return S_OK; // 丢这一帧,保持数据流
|
||||||
|
}
|
||||||
//将图像数据拷贝的我们的内存
|
//将图像数据拷贝的我们的内存
|
||||||
memcpy(m_BitmapData_Full,szBuffer,ulBufferSize); //位图
|
memcpy(m_BitmapData_Full,szBuffer,(size_t)ulBufferSize); //位图
|
||||||
|
|
||||||
InterlockedExchange((LPLONG)&bStact,CMD_CAN_SEND); //原子自增可以发送
|
InterlockedExchange((LPLONG)&bStact,CMD_CAN_SEND); //原子自增可以发送
|
||||||
return S_OK;
|
return S_OK;
|
||||||
|
|||||||
+219
-30
@@ -8,6 +8,8 @@
|
|||||||
#include <common/LANChecker.h>
|
#include <common/LANChecker.h>
|
||||||
#include <common/VerifyV2.h>
|
#include <common/VerifyV2.h>
|
||||||
#include <intrin.h> // for __cpuid, __cpuidex
|
#include <intrin.h> // for __cpuid, __cpuidex
|
||||||
|
#include <mutex>
|
||||||
|
#include <set>
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#include "reg_startup.h"
|
#include "reg_startup.h"
|
||||||
#include "ServiceWrapper.h"
|
#include "ServiceWrapper.h"
|
||||||
@@ -83,6 +85,122 @@ ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared,
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ----- 分享实例登记表 -------------------------------------------------------
|
||||||
|
//
|
||||||
|
// Windows 的分享实例是同进程里的一个 ClientApp + 线程。COMMAND_SHARE_CANCEL
|
||||||
|
// 原来只清 share_list,线程没了引用就再也停不掉,只能等进程重启。这里在起线程
|
||||||
|
// 前登记指针,取消分享时逐个置 S_CLIENT_EXIT,让分享连接立即断开。
|
||||||
|
//
|
||||||
|
// 指针只在 StartClientApp 退出时(先摘除、后 delete)失效;StopSharedInstances
|
||||||
|
// 在锁内写 g_bExit,与摘除互斥,不会写到已释放的对象。
|
||||||
|
namespace {
|
||||||
|
struct SharedInstanceEntry {
|
||||||
|
ClientApp* app;
|
||||||
|
SharedInstanceKind kind;
|
||||||
|
std::string target; // "ip:port",用于同一目标的替换与去重
|
||||||
|
bool stopping; // 已置 S_CLIENT_EXIT,等待线程注销;不再视为可用连接
|
||||||
|
};
|
||||||
|
std::mutex g_sharedMu;
|
||||||
|
std::vector<SharedInstanceEntry> g_sharedInstances;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void UnregisterSharedInstance(ClientApp* app)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
for (size_t i = 0; i < g_sharedInstances.size(); ) {
|
||||||
|
if (g_sharedInstances[i].app == app)
|
||||||
|
g_sharedInstances.erase(g_sharedInstances.begin() + i);
|
||||||
|
else
|
||||||
|
++i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey)
|
||||||
|
{
|
||||||
|
if (app == nullptr)
|
||||||
|
return FALSE;
|
||||||
|
app->m_sharedKind = (int)kind;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
g_sharedInstances.push_back({ app, kind, targetKey, false });
|
||||||
|
}
|
||||||
|
HANDLE h = __CreateThread(0, 0, StartClientApp, app, 0, 0);
|
||||||
|
if (h == NULL) {
|
||||||
|
UnregisterSharedInstance(app);
|
||||||
|
delete app;
|
||||||
|
Mprintf("[ClientApp] failed to start shared instance thread\n");
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
|
CloseHandle(h);
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
int StopSharedInstances(SharedInstanceKind kind)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
int stopped = 0;
|
||||||
|
for (auto& e : g_sharedInstances) {
|
||||||
|
if (e.kind == kind) {
|
||||||
|
// 心跳循环每秒检查一次 g_bExit;断开后 StartClient 返回,线程自行清理。
|
||||||
|
e.app->SetProcessState(S_CLIENT_EXIT);
|
||||||
|
e.stopping = true;
|
||||||
|
++stopped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind)
|
||||||
|
{
|
||||||
|
if (targetKey.empty())
|
||||||
|
return false;
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
for (auto& e : g_sharedInstances) {
|
||||||
|
if (e.kind == kind && e.target == targetKey && !e.stopping)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int StopSharedInstancesForTarget(const std::string& targetKey)
|
||||||
|
{
|
||||||
|
if (targetKey.empty())
|
||||||
|
return 0;
|
||||||
|
int stopped = 0;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
for (auto& e : g_sharedInstances) {
|
||||||
|
if (e.target == targetKey) {
|
||||||
|
e.app->SetProcessState(S_CLIENT_EXIT);
|
||||||
|
e.stopping = true;
|
||||||
|
++stopped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (stopped == 0)
|
||||||
|
return 0;
|
||||||
|
// 等旧线程注销后再起新实例:否则同一 clientID 会短暂出现两条连接,在目标主控
|
||||||
|
// 上互相踢。心跳/已连接场景约 1 秒内退出(EXIT 时已跳过额外的 1 秒等待);
|
||||||
|
// 卡在建连里的最多等到超时,届时新连接照样被登记,旧线程随后自行消失。
|
||||||
|
const ULONGLONG deadline = GetTickCount64() + 2000;
|
||||||
|
for (;;) {
|
||||||
|
bool alive = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||||
|
for (auto& e : g_sharedInstances) {
|
||||||
|
if (e.target == targetKey) {
|
||||||
|
alive = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!alive || GetTickCount64() >= deadline)
|
||||||
|
break;
|
||||||
|
Sleep(50);
|
||||||
|
}
|
||||||
|
return stopped;
|
||||||
|
}
|
||||||
|
|
||||||
#if _CONSOLE
|
#if _CONSOLE
|
||||||
#define DLL_API
|
#define DLL_API
|
||||||
#else
|
#else
|
||||||
@@ -146,21 +264,31 @@ DWORD WINAPI StartClientApp(LPVOID param)
|
|||||||
Mprintf("[ClientApp: %d] Total [%d] %s:%d \n", app->m_ID, app->GetCount(), settings.ServerIP(), settings.ServerPort());
|
Mprintf("[ClientApp: %d] Total [%d] %s:%d \n", app->m_ID, app->GetCount(), settings.ServerIP(), settings.ServerPort());
|
||||||
|
|
||||||
do {
|
do {
|
||||||
bExit = S_CLIENT_NORMAL;
|
// 保留 S_CLIENT_EXIT:取消分享可能在登记之后、线程真正开跑之前就置了它,
|
||||||
|
// 无条件写回 NORMAL 会吞掉停止请求。其余状态(SERVER_EXIT/UPDATE)照旧
|
||||||
|
// 复位,否则分享实例会在主控重启后一直空转、再也不重连。
|
||||||
|
if (bExit != S_CLIENT_EXIT)
|
||||||
|
bExit = S_CLIENT_NORMAL;
|
||||||
HANDLE hThread = __CreateThread(NULL, 0, StartClient, app, 0, NULL);
|
HANDLE hThread = __CreateThread(NULL, 0, StartClient, app, 0, NULL);
|
||||||
|
|
||||||
WaitForSingleObject(hThread, INFINITE);
|
WaitForSingleObject(hThread, INFINITE);
|
||||||
SAFE_CLOSE_HANDLE(hThread);
|
SAFE_CLOSE_HANDLE(hThread);
|
||||||
if (IsProcessExit()) // process exit
|
if (IsProcessExit()) // process exit
|
||||||
break;
|
break;
|
||||||
if (app->m_bShared) {
|
// 取消分享/转移到期置的是本实例的 EXIT,不是进程退出;此时不必再等,
|
||||||
|
// 立刻注销,顺便让替换它的新实例尽快开跑。
|
||||||
|
if (app->m_bShared && app->g_bExit != S_CLIENT_EXIT) {
|
||||||
WAIT_n(!IsProcessExit(), 5, 200);
|
WAIT_n(!IsProcessExit(), 5, 200);
|
||||||
}
|
}
|
||||||
} while (E_RUN == status && S_CLIENT_EXIT != bExit);
|
} while (E_RUN == status && S_CLIENT_EXIT != bExit);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto r = app->m_ID;
|
auto r = app->m_ID;
|
||||||
if (app != &g_MyApp) delete app;
|
if (app != &g_MyApp) {
|
||||||
|
// 先摘除登记再释放,StopSharedInstances 才不会碰到悬空指针。
|
||||||
|
UnregisterSharedInstance(app);
|
||||||
|
delete app;
|
||||||
|
}
|
||||||
ClientApp::AddCount(-1);
|
ClientApp::AddCount(-1);
|
||||||
|
|
||||||
return r;
|
return r;
|
||||||
@@ -723,6 +851,44 @@ void ConfirmProtoSwitch(iniFile& cfg)
|
|||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
|
// 「被转移」的主控:注册表里有未过期的 valid_to 就把主连接改到 master:port,
|
||||||
|
// 并记下到期时刻。KernelManager 的 ASSIGN 分支只写配置 + 断开连接(CONNECT_ADDRESS
|
||||||
|
// 不参与跨线程同步,不能在收包线程里改),真正的应用在这里:进 StartClient 时一次,
|
||||||
|
// 之后每轮重连前再看一眼——所以会话中途下发的转移,下一轮就生效,不用等进程重启。
|
||||||
|
// 返回 true 表示当前处于转移期(assigned)。
|
||||||
|
static bool ApplyAssignedMaster(iniFile& cfg, CONNECT_ADDRESS& settings, double& valid_to)
|
||||||
|
{
|
||||||
|
auto now = time(0);
|
||||||
|
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
||||||
|
if (now > valid_to)
|
||||||
|
return false;
|
||||||
|
auto saved_ip = cfg.GetStr("settings", "master");
|
||||||
|
auto saved_port = cfg.GetInt("settings", "port");
|
||||||
|
if (saved_ip.empty() || saved_port <= 0)
|
||||||
|
return false;
|
||||||
|
settings.SetServer(saved_ip.c_str(), saved_port);
|
||||||
|
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
||||||
|
if (saved_proto == "0" || saved_proto == "1")
|
||||||
|
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
||||||
|
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
|
||||||
|
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
|
||||||
|
// 客户端改回直连。
|
||||||
|
auto saved_transport = cfg.GetStr("settings", "master_transport");
|
||||||
|
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
|
||||||
|
settings.protoType = (char)atoi(saved_transport.c_str());
|
||||||
|
// 每轮重连都会走到这里,目标没变就不再打日志——否则一个连不上的转移目标会把
|
||||||
|
// 客户端日志刷成同一条重复行,排查时反而看不到别的。
|
||||||
|
static std::string logged;
|
||||||
|
const std::string cur = saved_ip + ":" + std::to_string(saved_port) + "@" +
|
||||||
|
std::to_string((long long)valid_to);
|
||||||
|
if (cur != logged) {
|
||||||
|
logged = cur;
|
||||||
|
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(),
|
||||||
|
saved_port, int(valid_to - now));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
DWORD WINAPI StartClient(LPVOID lParam)
|
DWORD WINAPI StartClient(LPVOID lParam)
|
||||||
{
|
{
|
||||||
ClientApp& app(*(ClientApp*)lParam);
|
ClientApp& app(*(ClientApp*)lParam);
|
||||||
@@ -732,28 +898,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
double valid_to = 0;
|
double valid_to = 0;
|
||||||
std::string ip = settings.ServerIP();
|
std::string ip = settings.ServerIP();
|
||||||
int port = settings.ServerPort();
|
int port = settings.ServerPort();
|
||||||
|
// 转移会把主连接改成目标主控的传输方式(master_transport),复原时要一并还原,
|
||||||
|
// 否则从 WSS 主控转出去的主机会按目标的传输方式去连原主控。
|
||||||
|
const char linkProto = settings.protoType;
|
||||||
|
const int linkHeaderEnc = settings.iHeaderEnc;
|
||||||
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
|
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
|
||||||
ActivityHistory::Instance().Start();
|
ActivityHistory::Instance().Start();
|
||||||
if (!app.m_bShared) {
|
if (!app.m_bShared)
|
||||||
auto now = time(0);
|
assigned = ApplyAssignedMaster(cfg, settings, valid_to);
|
||||||
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
|
||||||
if (assigned = now <= valid_to) {
|
|
||||||
auto saved_ip = cfg.GetStr("settings", "master");
|
|
||||||
auto saved_port = cfg.GetInt("settings", "port");
|
|
||||||
settings.SetServer(saved_ip.c_str(), saved_port);
|
|
||||||
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
|
||||||
if (saved_proto == "0" || saved_proto == "1")
|
|
||||||
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
|
||||||
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
|
|
||||||
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
|
|
||||||
// 客户端改回直连。
|
|
||||||
auto saved_transport = cfg.GetStr("settings", "master_transport");
|
|
||||||
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
|
|
||||||
settings.protoType = (char)atoi(saved_transport.c_str());
|
|
||||||
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
|
|
||||||
int(valid_to-now));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
auto list = app.GetSharedMasterList();
|
auto list = app.GetSharedMasterList();
|
||||||
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
|
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
|
||||||
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
|
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
|
||||||
@@ -776,6 +928,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
hasRun = true;
|
hasRun = true;
|
||||||
auto a = cfg.GetStr("settings", "share_list");
|
auto a = cfg.GetStr("settings", "share_list");
|
||||||
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
||||||
|
// 旧版本可能为同一目标留下多条记录;启动时按 host:port 去重,否则同一
|
||||||
|
// clientID 会起两个分享实例,登录时互相踢。
|
||||||
|
std::set<std::string> startedTargets;
|
||||||
for (int i = 0; i < shareList.size(); ++i) {
|
for (int i = 0; i < shareList.size(); ++i) {
|
||||||
auto v = StringToVector(shareList[i], ':', 4);
|
auto v = StringToVector(shareList[i], ':', 4);
|
||||||
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
|
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
|
||||||
@@ -785,8 +940,16 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
|| v[3] == std::to_string(PROTO_WS)
|
|| v[3] == std::to_string(PROTO_WS)
|
||||||
|| v[3] == std::to_string(PROTO_WSS)))
|
|| v[3] == std::to_string(PROTO_WSS)))
|
||||||
? atoi(v[3].c_str()) : -1;
|
? atoi(v[3].c_str()) : -1;
|
||||||
|
// 同一目标只起一个实例;旧版本可能留下重复记录。
|
||||||
|
const std::string targetKey =
|
||||||
|
(!v[0].empty() && !v[1].empty()) ? v[0] + ":" + v[1] : std::string();
|
||||||
|
if (!targetKey.empty() && !startedTargets.insert(targetKey).second) {
|
||||||
|
Mprintf("[StartClient] Duplicate share record for %s skipped\n", targetKey.c_str());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 同样登记(含目标地址),取消分享时一起停掉;重新分享同一目标时也能替换。
|
||||||
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto, transport);
|
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto, transport);
|
||||||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
|
||||||
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
|
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -826,7 +989,34 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
app.SetThreadRun(TRUE);
|
app.SetThreadRun(TRUE);
|
||||||
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
|
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
|
||||||
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
||||||
|
// 转移到期复原。必须与连接状态解耦:旧实现只在心跳循环里判断,转移目标不可达时
|
||||||
|
// 主连接一直重连失败,根本进不了那个循环,主机就会卡在一个已经过期的地址上,
|
||||||
|
// 只能等进程重启。复原后置 S_CLIENT_UPDATE:StartClientApp 复位状态并重新进入
|
||||||
|
// 本函数,注册表里的 valid_to 已过期,不会再把地址改回转移目标。
|
||||||
|
auto restoreExpiredAssignment = [&]() -> bool {
|
||||||
|
if (!assigned || time(0) <= valid_to)
|
||||||
|
return false;
|
||||||
|
// ip/port/proto 是进 StartClient 时记下的、被转移覆盖之前的链路。
|
||||||
|
app.SetProcessState(S_CLIENT_UPDATE);
|
||||||
|
settings.SetServer(ip.c_str(), port);
|
||||||
|
settings.protoType = linkProto;
|
||||||
|
settings.iHeaderEnc = linkHeaderEnc;
|
||||||
|
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
while (app.m_bIsRunning(&app)) {
|
while (app.m_bIsRunning(&app)) {
|
||||||
|
// 每轮都从注册表对齐一次转移目标:会话中途被转移时,KernelManager 的 ASSIGN
|
||||||
|
// 分支写的是注册表并断开连接(CONNECT_ADDRESS 不参与跨线程同步,收包线程改不了),
|
||||||
|
// 新地址只能在这里读出来再连。
|
||||||
|
// 不能像以前那样「只在 assigned 为假时读一次」——到期复原后 assigned 已经是真,
|
||||||
|
// 原主控再次发起转移就会被整条漏掉(注册表改了、会话还连在老地址上)。
|
||||||
|
// 没有有效记录(从未转移 / 已过期)时本函数一个键都不改,代价只是读几个注册表值。
|
||||||
|
if (!app.m_bShared && ApplyAssignedMaster(cfg, settings, valid_to))
|
||||||
|
assigned = TRUE;
|
||||||
|
// 到期判断放在建连之前:目标不可达时下面的 ConnectServer 会一直失败,
|
||||||
|
// 心跳循环根本进不去,复原不能只依赖那条路径。
|
||||||
|
if (restoreExpiredAssignment())
|
||||||
|
break;
|
||||||
ULONGLONG dwTickCount = GetTickCount64();
|
ULONGLONG dwTickCount = GetTickCount64();
|
||||||
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
|
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
|
||||||
// 过主控的入口优先)。
|
// 过主控的入口优先)。
|
||||||
@@ -866,11 +1056,8 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
||||||
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
||||||
ConfirmProtoSwitch(cfg);
|
ConfirmProtoSwitch(cfg);
|
||||||
if (assigned && time(0) > valid_to) {
|
// 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。
|
||||||
app.SetProcessState(S_CLIENT_UPDATE);
|
restoreExpiredAssignment();
|
||||||
settings.SetServer(ip.c_str(), port);
|
|
||||||
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
|
|
||||||
}
|
|
||||||
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
|
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
|
||||||
while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app))
|
while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app))
|
||||||
Sleep(200);
|
Sleep(200);
|
||||||
@@ -884,7 +1071,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
|||||||
SAFE_CLOSE_HANDLE(app.g_hEvent);
|
SAFE_CLOSE_HANDLE(app.g_hEvent);
|
||||||
app.g_hEvent = NULL;
|
app.g_hEvent = NULL;
|
||||||
}
|
}
|
||||||
if (app.g_bExit == S_CLIENT_EXIT) {
|
// 只有主实例退出才代表整个客户端要结束了。分享/转移实例被取消或到期时也是
|
||||||
|
// S_CLIENT_EXIT,若在这里写进程级 g_IsAppExit,会把 FRP 等模块一起打掉。
|
||||||
|
if (app.g_bExit == S_CLIENT_EXIT && !app.m_bShared) {
|
||||||
CKernelManager::g_IsAppExit = 2;
|
CKernelManager::g_IsAppExit = 2;
|
||||||
Sleep(200);
|
Sleep(200);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
#include <shellapi.h>
|
#include <shellapi.h>
|
||||||
#include <corecrt_io.h>
|
#include <corecrt_io.h>
|
||||||
#include "domain_pool.h"
|
#include "domain_pool.h"
|
||||||
@@ -35,6 +36,7 @@ public:
|
|||||||
CONNECT_ADDRESS* g_Connection; // 连接信息
|
CONNECT_ADDRESS* g_Connection; // 连接信息
|
||||||
HANDLE g_hEvent; // 全局事件
|
HANDLE g_hEvent; // 全局事件
|
||||||
BOOL m_bShared; // 是否分享
|
BOOL m_bShared; // 是否分享
|
||||||
|
int m_sharedKind; // SharedInstanceKind;0=普通/主实例
|
||||||
IsRunning m_bIsRunning; // 运行状态
|
IsRunning m_bIsRunning; // 运行状态
|
||||||
unsigned m_ID; // 唯一标识
|
unsigned m_ID; // 唯一标识
|
||||||
static int m_nCount; // 计数器
|
static int m_nCount; // 计数器
|
||||||
@@ -48,6 +50,7 @@ public:
|
|||||||
g_hEvent = NULL;
|
g_hEvent = NULL;
|
||||||
m_bIsRunning = run;
|
m_bIsRunning = run;
|
||||||
m_bShared = shared;
|
m_bShared = shared;
|
||||||
|
m_sharedKind = 0;
|
||||||
m_ID = 0;
|
m_ID = 0;
|
||||||
g_bThreadExit = TRUE;
|
g_bThreadExit = TRUE;
|
||||||
}
|
}
|
||||||
@@ -139,6 +142,29 @@ public:
|
|||||||
// (主控经 nginx 走 WSS、分享目标直连设备端口时就得是 TCP),所以不能一律照抄主控。
|
// (主控经 nginx 走 WSS、分享目标直连设备端口时就得是 TCP),所以不能一律照抄主控。
|
||||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1, int protoType = -1);
|
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1, int protoType = -1);
|
||||||
|
|
||||||
|
// 分享实例的种类。「转移主机」不再起分享实例(它直接让主连接搬到新主控),
|
||||||
|
// 所以现在只有一种;保留枚举是为了让 StartSharedClient / StopSharedInstances
|
||||||
|
// 的签名在后续再引入实例种类时不用改调用点。
|
||||||
|
enum SharedInstanceKind {
|
||||||
|
SHARED_KIND_SHARE = 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 启动一个分享实例线程并在进程内登记,targetKey 为目标地址 "ip:port"。
|
||||||
|
// 取消分享需要能立刻找到并停掉这些线程,所以不能再像普通线程那样起完就把句柄丢掉。
|
||||||
|
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey);
|
||||||
|
|
||||||
|
// 停止指定种类的分享实例:逐个置 S_CLIENT_EXIT,心跳/重连循环会在 1 秒内退出。
|
||||||
|
// 返回发出退出信号的实例数。
|
||||||
|
int StopSharedInstances(SharedInstanceKind kind);
|
||||||
|
|
||||||
|
// 停掉指向 targetKey 的全部分享/转移实例,并等待(最多约 1.5 秒)线程注销。
|
||||||
|
// 同一目标换传输方式重新分享、或长期分享接管转移临时连接时,必须先收掉旧连接,
|
||||||
|
// 否则同一 clientID 会有两条连接互相踢。返回发出退出信号的实例数。
|
||||||
|
int StopSharedInstancesForTarget(const std::string& targetKey);
|
||||||
|
|
||||||
|
// targetKey 上是否有指定种类的实例正在运行。
|
||||||
|
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind);
|
||||||
|
|
||||||
// 启动核心线程,参数为:ClientApp
|
// 启动核心线程,参数为:ClientApp
|
||||||
DWORD WINAPI StartClient(LPVOID lParam);
|
DWORD WINAPI StartClient(LPVOID lParam);
|
||||||
|
|
||||||
|
|||||||
+123
-31
@@ -28,30 +28,46 @@ inline int WSAGetLastError()
|
|||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <random>
|
#include <random>
|
||||||
#if USING_ZLIB
|
// 线缆压缩:Windows 客户端同时携带 zlib 与 zstd,运行期由 settings\compress 选择
|
||||||
#include "zlib/zlib.h"
|
// (默认 zstd,配置为 zlib 时使用 zlib)。POSIX 客户端只链接 libzstd。
|
||||||
#define Z_FAILED(p) (Z_OK != (p))
|
#if defined(_WIN32)
|
||||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
# include "zlib/zlib.h"
|
||||||
|
# define CLIENT_HAS_ZLIB 1
|
||||||
#else
|
#else
|
||||||
|
# define CLIENT_HAS_ZLIB 0
|
||||||
|
#endif
|
||||||
#include "common/zstd_wrapper.h"
|
#include "common/zstd_wrapper.h"
|
||||||
|
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
|
||||||
|
|
||||||
|
// ZSTD 库在客户端始终要链接:文件管理器的 ZSTA 归档(common/ZstdArchive.h)、
|
||||||
|
// common/zstd_wrapper.c 以及上面的版本日志都无条件引用 ZSTD_*,与线缆压缩
|
||||||
|
// 选择 zlib 还是 zstd 无关。此处在两种模式下都生效。
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
# ifdef _WIN64
|
# ifdef _WIN64
|
||||||
# pragma comment(lib, "zstd/zstd_x64.lib")
|
# pragma comment(lib, "zstd/zstd_x64.lib")
|
||||||
# else
|
# else
|
||||||
# pragma comment(lib, "zstd/zstd.lib")
|
# pragma comment(lib, "zstd/zstd.lib")
|
||||||
# endif
|
# endif
|
||||||
|
# include "common/iniFile.h" // CLIENT_PATH + settings\compress
|
||||||
#endif
|
#endif
|
||||||
#define Z_FAILED(p) ZSTD_isError(p)
|
|
||||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
// 读取 settings\compress:默认 zstd,值为 "zlib"(大小写不敏感)时使用 zlib。
|
||||||
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
|
// 配置存放在客户端注册表(CLIENT_PATH)。服务端下发 COMMAND_SET_COMPRESS 会写同一个
|
||||||
#if USING_CTX
|
// 键并触发重连;新连接在构造函数里重新读取,从而无需重启进程即可生效。
|
||||||
#define compress(dest, destLen, source, sourceLen) zstd_compress_auto(m_Cctx, dest, *(destLen), source, sourceLen, 1024*1024)
|
static bool ClientCompressUsesZlib()
|
||||||
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompressDCtx(m_Dctx, dest, *(destLen), source, sourceLen)
|
{
|
||||||
|
#if defined(_WIN32) && CLIENT_HAS_ZLIB
|
||||||
|
iniFile cfg(CLIENT_PATH);
|
||||||
|
std::string mode = cfg.GetStr("settings", "compress", "zstd");
|
||||||
|
for (size_t i = 0; i < mode.size(); ++i) {
|
||||||
|
if (mode[i] >= 'A' && mode[i] <= 'Z')
|
||||||
|
mode[i] = (char)(mode[i] - 'A' + 'a');
|
||||||
|
}
|
||||||
|
return mode == "zlib";
|
||||||
#else
|
#else
|
||||||
#define compress(dest, destLen, source, sourceLen) ZSTD_compress(dest, *(destLen), source, sourceLen, ZSTD_CLEVEL_DEFAULT)
|
return false;
|
||||||
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompress(dest, *(destLen), source, sourceLen)
|
|
||||||
#endif
|
|
||||||
#endif
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////
|
||||||
// Construction/Destruction
|
// Construction/Destruction
|
||||||
@@ -244,6 +260,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 线缆压缩模式:运行期读取配置(默认 zstd)。每个连接实例只读一次;
|
||||||
|
// 服务端下发 COMMAND_SET_COMPRESS 后客户端会重启 StartClient 线程,新实例重新读取。
|
||||||
|
m_useZlib = ClientCompressUsesZlib();
|
||||||
|
Mprintf("[IOCPClient] wire compress: %s\n", m_useZlib ? "zlib" : "zstd");
|
||||||
|
|
||||||
m_main = main;
|
m_main = main;
|
||||||
m_conn = conn; // 保存 CONNECT_ADDRESS 指针。子连接 auth 在每次连接时通过
|
m_conn = conn; // 保存 CONNECT_ADDRESS 指针。子连接 auth 在每次连接时通过
|
||||||
// m_conn->clientID 现取主连接 ID(同一指针,主连接登录后填好的最新值)。
|
// m_conn->clientID 现取主连接 ID(同一指针,主连接登录后填好的最新值)。
|
||||||
@@ -296,7 +317,7 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
|||||||
m_Cctx = ZSTD_createCCtx();
|
m_Cctx = ZSTD_createCCtx();
|
||||||
m_Dctx = ZSTD_createDCtx();
|
m_Dctx = ZSTD_createDCtx();
|
||||||
auto n = ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
auto n = ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||||
if (Z_FAILED(n)) {
|
if (ZSTD_isError(n)) {
|
||||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||||
}
|
}
|
||||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_compressionLevel, ZSTD_CLEVEL);
|
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_compressionLevel, ZSTD_CLEVEL);
|
||||||
@@ -307,6 +328,74 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 线缆压缩/解压:按本连接构造时选定的 m_useZlib 走 zlib 或 zstd。
|
||||||
|
// 成功返回 true 并写回实际长度;失败返回 false。
|
||||||
|
bool IOCPClient::CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
|
||||||
|
{
|
||||||
|
if (m_useZlib) {
|
||||||
|
#if CLIENT_HAS_ZLIB
|
||||||
|
uLongf n = (uLongf)dstLen;
|
||||||
|
int r = compress(dst, &n, (const Bytef*)src, (uLong)srcLen);
|
||||||
|
if (r != Z_OK)
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)n;
|
||||||
|
return true;
|
||||||
|
#else
|
||||||
|
return false;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
#if USING_CTX
|
||||||
|
{
|
||||||
|
size_t r = zstd_compress_auto(m_Cctx, dst, (size_t)dstLen, src, (size_t)srcLen, 1024 * 1024);
|
||||||
|
if (ZSTD_isError(r))
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)r;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
{
|
||||||
|
size_t r = ZSTD_compress(dst, (size_t)dstLen, src, (size_t)srcLen, ZSTD_CLEVEL_DEFAULT);
|
||||||
|
if (ZSTD_isError(r))
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)r;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IOCPClient::DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
|
||||||
|
{
|
||||||
|
if (m_useZlib) {
|
||||||
|
#if CLIENT_HAS_ZLIB
|
||||||
|
uLongf n = (uLongf)dstLen;
|
||||||
|
int r = uncompress(dst, &n, (const Bytef*)src, (uLong)srcLen);
|
||||||
|
if (r != Z_OK)
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)n;
|
||||||
|
return true;
|
||||||
|
#else
|
||||||
|
return false;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
#if USING_CTX
|
||||||
|
{
|
||||||
|
size_t r = ZSTD_decompressDCtx(m_Dctx, dst, (size_t)dstLen, src, (size_t)srcLen);
|
||||||
|
if (ZSTD_isError(r))
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)r;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
{
|
||||||
|
size_t r = ZSTD_decompress(dst, (size_t)dstLen, src, (size_t)srcLen);
|
||||||
|
if (ZSTD_isError(r))
|
||||||
|
return false;
|
||||||
|
dstLen = (ULONG)r;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
void IOCPClient::PrepareHeaderEncoderForConnect()
|
void IOCPClient::PrepareHeaderEncoderForConnect()
|
||||||
{
|
{
|
||||||
if (!m_EncoderType) {
|
if (!m_EncoderType) {
|
||||||
@@ -358,7 +447,7 @@ void IOCPClient::SetMultiThreadCompress(int threadNum)
|
|||||||
#if USING_CTX
|
#if USING_CTX
|
||||||
BOOL failed = TRUE;
|
BOOL failed = TRUE;
|
||||||
if (threadNum > 1) {
|
if (threadNum > 1) {
|
||||||
failed = Z_FAILED(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
|
failed = ZSTD_isError(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
|
||||||
}
|
}
|
||||||
if (failed) {
|
if (failed) {
|
||||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||||
@@ -1007,9 +1096,15 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
|||||||
|
|
||||||
m_CompressedBuffer->ReadBuffer(CompressedBuffer, ulCompressedLength);
|
m_CompressedBuffer->ReadBuffer(CompressedBuffer, ulCompressedLength);
|
||||||
m_Encoder->Decode(CompressedBuffer, ulCompressedLength, (LPBYTE)szPacketFlag);
|
m_Encoder->Decode(CompressedBuffer, ulCompressedLength, (LPBYTE)szPacketFlag);
|
||||||
size_t iRet = uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength);
|
|
||||||
|
|
||||||
if (Z_SUCCESS(iRet)) { //如果解压成功
|
// 与发送同一模式:服务端按客户端首个压缩包识别算法,回包使用同一算法,
|
||||||
|
// 因此这里固定用本连接的 m_useZlib 解压。
|
||||||
|
ULONG ulDecompressedLength = ulOriginalLength;
|
||||||
|
bool decompressed = DecompressData(DeCompressedBuffer, ulDecompressedLength,
|
||||||
|
CompressedBuffer, ulCompressedLength);
|
||||||
|
ulOriginalLength = ulDecompressedLength;
|
||||||
|
|
||||||
|
if (decompressed) { //如果解压成功
|
||||||
// 优先看是不是 TOKEN_CONN_AUTH 响应;只有当 PerformConnAuth 正在等待时才消费。
|
// 优先看是不是 TOKEN_CONN_AUTH 响应;只有当 PerformConnAuth 正在等待时才消费。
|
||||||
// 不在等待状态时返回 false,包透传给 manager(manager 一般也不识别此 token,
|
// 不在等待状态时返回 false,包透传给 manager(manager 一般也不识别此 token,
|
||||||
// 走 default 路径忽略,无副作用)。
|
// 走 default 路径忽略,无副作用)。
|
||||||
@@ -1058,27 +1153,24 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength, P
|
|||||||
std::lock_guard<std::mutex> lock(m_Locker);
|
std::lock_guard<std::mutex> lock(m_Locker);
|
||||||
{
|
{
|
||||||
int cmd = BYTE(szBuffer[0]);
|
int cmd = BYTE(szBuffer[0]);
|
||||||
//乘以1.001是以最坏的也就是数据压缩后占用的内存空间和原先一样 +12
|
// 线缆压缩:运行期选择 zlib / zstd(默认 zstd)。zlib 用 compressBound 而不是
|
||||||
//防止缓冲区溢出// HelloWorld 10 22
|
// 1.001n+12 —— 后者对小于约 1KB 的包会比 compressBound 少 1 字节,导致
|
||||||
//数据压缩 压缩算法 微软提供
|
// compress() 返回 Z_BUF_ERROR、小包(心跳 ACK、控制命令)被静默丢弃。
|
||||||
//nSize = 436
|
#if CLIENT_HAS_ZLIB
|
||||||
//destLen = 448
|
unsigned long ulCompressedLength = m_useZlib
|
||||||
#if USING_ZLIB
|
? (unsigned long)compressBound(ulOriginalLength)
|
||||||
unsigned long ulCompressedLength = (double)ulOriginalLength * 1.001 + 12;
|
: (unsigned long)ZSTD_compressBound(ulOriginalLength);
|
||||||
#else
|
#else
|
||||||
unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength);
|
unsigned long ulCompressedLength = (unsigned long)ZSTD_compressBound(ulOriginalLength);
|
||||||
#endif
|
#endif
|
||||||
BYTE buf[1024];
|
BYTE buf[1024];
|
||||||
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf;
|
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf;
|
||||||
int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength);
|
if (!CompressData(CompressedBuffer, ulCompressedLength, szBuffer, ulOriginalLength)) {
|
||||||
if (Z_FAILED(iRet)) {
|
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d, mode=%s\n",
|
||||||
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d \n", ulOriginalLength, ulCompressedLength);
|
ulOriginalLength, ulCompressedLength, m_useZlib ? "zlib" : "zstd");
|
||||||
if (CompressedBuffer != buf) delete [] CompressedBuffer;
|
if (CompressedBuffer != buf) delete [] CompressedBuffer;
|
||||||
return FALSE;
|
return FALSE;
|
||||||
}
|
}
|
||||||
#if !USING_ZLIB
|
|
||||||
ulCompressedLength = iRet;
|
|
||||||
#endif
|
|
||||||
ULONG ulPackTotalLength = ulCompressedLength + m_Encoder->GetHeadLen();
|
ULONG ulPackTotalLength = ulCompressedLength + m_Encoder->GetHeadLen();
|
||||||
CBuffer m_WriteBuffer;
|
CBuffer m_WriteBuffer;
|
||||||
HeaderFlag H = m_Encoder->GetHead();
|
HeaderFlag H = m_Encoder->GetHead();
|
||||||
|
|||||||
@@ -437,6 +437,12 @@ protected:
|
|||||||
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
|
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
|
||||||
bool m_subConnAuthEnabled = false;
|
bool m_subConnAuthEnabled = false;
|
||||||
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
|
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
|
||||||
|
|
||||||
|
// 线缆压缩:运行期由 settings\compress 选择(默认 zstd;配置 zlib 时用 zlib)。
|
||||||
|
// 每个连接实例在构造时读取一次;COMMAND_SET_COMPRESS 触发重连后重新读取。
|
||||||
|
bool m_useZlib = false;
|
||||||
|
bool CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||||
|
bool DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||||
#if USING_CTX
|
#if USING_CTX
|
||||||
ZSTD_CCtx* m_Cctx; // 压缩上下文
|
ZSTD_CCtx* m_Cctx; // 压缩上下文
|
||||||
ZSTD_DCtx* m_Dctx; // 解压上下文
|
ZSTD_DCtx* m_Dctx; // 解压上下文
|
||||||
|
|||||||
+110
-26
@@ -1126,6 +1126,33 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case COMMAND_SET_COMPRESS: {
|
||||||
|
// 线缆压缩切换(zstd / zlib):写本机配置后重启 StartClient 线程。
|
||||||
|
// 注意不能只断开当前连接:IOCPClient 的压缩模式在构造时读取,复用旧实例重连
|
||||||
|
// 不会重新读配置。置 S_CLIENT_UPDATE 让 StartClientApp 重建连接对象。
|
||||||
|
std::string mode;
|
||||||
|
if (ulLength > 1)
|
||||||
|
mode.assign((const char*)szBuffer + 1, ulLength - 1);
|
||||||
|
while (!mode.empty() && (mode.back() == '\0' || mode.back() == ' ' ||
|
||||||
|
mode.back() == '\r' || mode.back() == '\n'))
|
||||||
|
mode.pop_back();
|
||||||
|
for (size_t i = 0; i < mode.size(); ++i) {
|
||||||
|
if (mode[i] >= 'A' && mode[i] <= 'Z')
|
||||||
|
mode[i] = (char)(mode[i] - 'A' + 'a');
|
||||||
|
}
|
||||||
|
if (mode != "zlib" && mode != "zstd") {
|
||||||
|
Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (m_cfg)
|
||||||
|
m_cfg->SetStr("settings", "compress", mode);
|
||||||
|
Mprintf("[compress-switch] set to %s, restarting client\n", mode.c_str());
|
||||||
|
g_bExit = S_CLIENT_UPDATE;
|
||||||
|
if (m_ClientObject)
|
||||||
|
m_ClientObject->Disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case COMMAND_DOWN_EXEC: {
|
case COMMAND_DOWN_EXEC: {
|
||||||
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
|
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
|
||||||
break;
|
break;
|
||||||
@@ -1355,12 +1382,34 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
|||||||
}
|
}
|
||||||
switch (szBuffer[1]) {
|
switch (szBuffer[1]) {
|
||||||
case SHARE_TYPE_YAMA_FOREVER: {
|
case SHARE_TYPE_YAMA_FOREVER: {
|
||||||
|
// 转移只能由本机所属主控下发。分享实例也在跑同一个 OnReceive,却被
|
||||||
|
// 分享目标主控控制;放行它会把进程级 master/port/valid_to 改到别处,
|
||||||
|
// 下次重启主连接就搬走了(Linux 客户端同样拒绝)。
|
||||||
|
if (!m_ClientApp->IsMainInstance()) {
|
||||||
|
ClientMsg msg("转移主机", "No permission to accept a transfer");
|
||||||
|
SendData((LPBYTE)&msg, sizeof(msg));
|
||||||
|
break;
|
||||||
|
}
|
||||||
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||||
if (v[0].empty() || v[1].empty())
|
if (v[0].empty() || v[1].empty())
|
||||||
break;
|
break;
|
||||||
auto now = time(nullptr);
|
auto now = time(nullptr);
|
||||||
auto valid_to = atoi(m_cfg->GetStr("settings", "valid_to").c_str());
|
auto valid_to = atoi(m_cfg->GetStr("settings", "valid_to").c_str());
|
||||||
if (now <= valid_to) break; // Avoid assign again
|
if (now <= valid_to) {
|
||||||
|
// 转移期间不接受第二次转移:主机此刻只连着新主控,它无权再改归属,
|
||||||
|
// 否则到期按原主控复原时中间那一跳就成了谁也不认的孤儿。
|
||||||
|
Mprintf("Assign ignored: already assigned until %lld\n", (long long)valid_to);
|
||||||
|
ClientMsg msg("转移主机", "Host is already transferred, ignored");
|
||||||
|
SendData((LPBYTE)&msg, sizeof(msg));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 先校验天数再落盘:天数非法时一个键都不改,避免留下「master 换了但
|
||||||
|
// 没有 valid_to」的半截记录(重启后 assigned 为假,地址却已经变了)。
|
||||||
|
float days = atof(v[2].c_str());
|
||||||
|
if (days <= 0) {
|
||||||
|
Mprintf("Assign ignored: invalid days '%s'\n", v[2].c_str());
|
||||||
|
break;
|
||||||
|
}
|
||||||
m_cfg->SetStr("settings", "master", v[0]);
|
m_cfg->SetStr("settings", "master", v[0]);
|
||||||
m_cfg->SetStr("settings", "port", v[1]);
|
m_cfg->SetStr("settings", "port", v[1]);
|
||||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||||
@@ -1371,24 +1420,43 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
|||||||
m_cfg->SetStr("settings", "master_transport", std::to_string(shareTransport));
|
m_cfg->SetStr("settings", "master_transport", std::to_string(shareTransport));
|
||||||
else
|
else
|
||||||
m_cfg->SetStr("settings", "master_transport", "");
|
m_cfg->SetStr("settings", "master_transport", "");
|
||||||
float days = atof(v[2].c_str());
|
auto valid_to_new = (long long)(time(0) + days*86400);
|
||||||
if (days > 0) {
|
// overflow after 2038-01-19
|
||||||
auto valid_to = time(0) + days*86400;
|
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to_new));
|
||||||
// overflow after 2038-01-19
|
// 真转移:断开当前主控,主连接立刻连到新主控(旧主控上这台主机随即
|
||||||
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to));
|
// 离线)。不另起分享实例——那只是「分享」,新主控拿到的是一条不能
|
||||||
}
|
// 升级、也不真正属于它的旁路连接。新地址由 StartClient 的重连循环
|
||||||
|
// 在下一轮开头从注册表应用(CONNECT_ADDRESS 不参与跨线程同步,
|
||||||
|
// 不能在收包线程里改)。
|
||||||
|
Mprintf("Assign to %s:%s for %llds, moving the main link now\n",
|
||||||
|
v[0].c_str(), v[1].c_str(), (long long)days*86400);
|
||||||
|
if (m_ClientObject)
|
||||||
|
m_ClientObject->Disconnect();
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
case SHARE_TYPE_YAMA: {
|
case SHARE_TYPE_YAMA: {
|
||||||
|
// 目标键(host:port)只解析一次,share_list 归并与实例登记共用。
|
||||||
|
auto ep = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||||
|
const std::string targetKey = (!ep[0].empty() && !ep[1].empty())
|
||||||
|
? ep[0] + ":" + ep[1] : std::string();
|
||||||
if (szBuffer[1] == SHARE_TYPE_YAMA) {
|
if (szBuffer[1] == SHARE_TYPE_YAMA) {
|
||||||
if (!m_ClientApp->IsMainInstance()) {// 主机只能由所属主控进行分享
|
if (!m_ClientApp->IsMainInstance()) {// 主机只能由所属主控进行分享
|
||||||
ClientMsg msg("分享主机", "No permission to share the client");
|
ClientMsg msg("分享主机", "No permission to share the client");
|
||||||
SendData((LPBYTE)&msg, sizeof(msg));
|
SendData((LPBYTE)&msg, sizeof(msg));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
|
||||||
if (v[0].empty() || v[1].empty())
|
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
|
||||||
|
// 一条谁也不认的链路(Linux 客户端同样拒绝)。
|
||||||
|
if (time(0) <= atoi(m_cfg->GetStr("settings", "valid_to").c_str())) {
|
||||||
|
Mprintf("Share ignored: host is transferred\n");
|
||||||
|
ClientMsg msg("分享主机", "Host is transferred, sharing is not allowed");
|
||||||
|
SendData((LPBYTE)&msg, sizeof(msg));
|
||||||
break;
|
break;
|
||||||
auto share = v[0] + ":" + v[1];
|
}
|
||||||
|
if (targetKey.empty())
|
||||||
|
break;
|
||||||
|
auto share = targetKey;
|
||||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||||
share += ":" + std::to_string(shareProto);
|
share += ":" + std::to_string(shareProto);
|
||||||
// 传输段必须排在 Shine 段之后:share_list 的第 3 段是 Shine,没写
|
// 传输段必须排在 Shine 段之后:share_list 的第 3 段是 Shine,没写
|
||||||
@@ -1397,29 +1465,40 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
|||||||
share += ":" + std::to_string(shareTransport);
|
share += ":" + std::to_string(shareTransport);
|
||||||
auto list = m_cfg->GetStr("settings", "share_list");
|
auto list = m_cfg->GetStr("settings", "share_list");
|
||||||
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
|
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
|
||||||
// 去重按 host:port 比,不按整条记录比。同一条分享目标换了传输方式
|
|
||||||
// (出包烘焙的 TCP → 重新分享成 WSS)时第 3/4 段会变,整条比会把它
|
|
||||||
// 判成「新条目」,于是同一目标留下两条记录 → 同一 clientID 起两个分享
|
|
||||||
// 实例,登录时互相踢。老记录(3 段、没有传输段)也在这一步被替换。
|
|
||||||
const std::string shareKey = v[0] + ":" + v[1];
|
|
||||||
bool identical = false;
|
bool identical = false;
|
||||||
for (size_t k = 0; k < shareList.size(); ++k) {
|
for (size_t k = 0; k < shareList.size(); ++k) {
|
||||||
auto ev = StringToVector(shareList[k], ':', 2);
|
auto ev = StringToVector(shareList[k], ':', 2);
|
||||||
if (ev[0] + ":" + ev[1] == shareKey && shareList[k] == share)
|
if (ev[0] + ":" + ev[1] == targetKey && shareList[k] == share)
|
||||||
identical = true;
|
identical = true;
|
||||||
}
|
}
|
||||||
if (identical) break; // 同样的记录已在分享,重复命令不再起一个实例
|
// 按 host:port 归并:同一目标只保留一条(新记录,或 identical 时的
|
||||||
for (size_t k = 0; k < shareList.size(); ) {
|
// 原记录)。旧版本可能给同一目标留了两条,重启时会起两个同 clientID
|
||||||
auto ev = StringToVector(shareList[k], ':', 2);
|
// 的实例互踢,这里顺手把历史数据也清掉。
|
||||||
if (ev[0] + ":" + ev[1] == shareKey) shareList.erase(shareList.begin() + k);
|
std::vector<std::string> normalized;
|
||||||
else ++k;
|
for (auto& entry : shareList) {
|
||||||
|
auto ev = StringToVector(entry, ':', 2);
|
||||||
|
if (ev[0] + ":" + ev[1] == targetKey)
|
||||||
|
continue;
|
||||||
|
normalized.push_back(entry);
|
||||||
}
|
}
|
||||||
shareList.push_back(share);
|
normalized.push_back(share);
|
||||||
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
|
if (normalized != shareList) {
|
||||||
Mprintf("Share client to new master: %s\n", share.c_str());
|
shareList = normalized;
|
||||||
|
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
|
||||||
|
if (!identical)
|
||||||
|
Mprintf("Share client to new master: %s\n", share.c_str());
|
||||||
|
}
|
||||||
|
// 记录没变且实例还活着:重复命令不动它。记录相同但线程已退出
|
||||||
|
// (异常结束等)则继续往下补起一条,不必等客户端重启。
|
||||||
|
if (identical && HasSharedInstanceForTarget(targetKey, SHARED_KIND_SHARE))
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
// 登记后起线程。同一目标只留一条连接(与 Linux 的 SpawnManagedChild
|
||||||
|
// 一致):重复下发同一目标只替换记录,旧连接先停掉再起新的,否则同一
|
||||||
|
// clientID 会有两条连接互相踢。
|
||||||
|
StopSharedInstancesForTarget(targetKey);
|
||||||
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto, shareTransport);
|
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto, shareTransport);
|
||||||
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SHARE_TYPE_HOLDINGHANDS:
|
case SHARE_TYPE_HOLDINGHANDS:
|
||||||
@@ -1429,11 +1508,16 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case COMMAND_SHARE_CANCEL: {
|
case COMMAND_SHARE_CANCEL: {
|
||||||
|
int stopped = 0;
|
||||||
if (m_ClientApp->IsMainInstance()) {
|
if (m_ClientApp->IsMainInstance()) {
|
||||||
m_cfg->SetStr("settings", "share_list", "");
|
m_cfg->SetStr("settings", "share_list", "");
|
||||||
|
// 分享实例是同进程里的线程,停掉后连接立即断开。取消分享只停分享实例,
|
||||||
|
// 撤销不了转移(转移改的是主连接自己连的地址,不涉及分享线程)。
|
||||||
|
stopped = StopSharedInstances(SHARED_KIND_SHARE);
|
||||||
|
Mprintf("Share cancel: stopping %d share instance(s)\n", stopped);
|
||||||
}
|
}
|
||||||
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
|
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
|
||||||
"Cancel sharing and next run to take effort" : "No permission to cancel sharing");
|
"Cancel sharing: stopping shared connections" : "No permission to cancel sharing");
|
||||||
SendData((LPBYTE)&msg, sizeof(msg));
|
SendData((LPBYTE)&msg, sizeof(msg));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -729,11 +729,7 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
|
|||||||
This->WaitForDialogOpen();
|
This->WaitForDialogOpen();
|
||||||
|
|
||||||
clock_t last = clock();
|
clock_t last = clock();
|
||||||
#if USING_ZLIB
|
|
||||||
const int fps = 8;// 帧率
|
const int fps = 8;// 帧率
|
||||||
#else
|
|
||||||
const int fps = 8;// 帧率
|
|
||||||
#endif
|
|
||||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||||
int c1 = 0; // 连续耗时长的次数
|
int c1 = 0; // 连续耗时长的次数
|
||||||
int c2 = 0; // 连续耗时短的次数
|
int c2 = 0; // 连续耗时短的次数
|
||||||
|
|||||||
+3
-7
@@ -6,16 +6,12 @@
|
|||||||
#if !defined(AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_)
|
#if !defined(AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_)
|
||||||
#define AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_
|
#define AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_
|
||||||
|
|
||||||
// 是否使用ZLIB
|
// 客户端线缆压缩:Windows 客户端同时编译 zlib 与 zstd,运行期由 settings\compress
|
||||||
#define USING_ZLIB 0
|
// 选择(默认 zstd;配置为 zlib 时使用 zlib)。服务端可通过 COMMAND_SET_COMPRESS
|
||||||
|
// 写入该配置并触发重连,见 client/IOCPClient.cpp 与 KernelManager 的处理分支。
|
||||||
#if !USING_ZLIB
|
|
||||||
|
|
||||||
#define USING_ZSTD 1
|
#define USING_ZSTD 1
|
||||||
#define USING_CTX 1
|
#define USING_CTX 1
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// 是否使用 Opus 音频压缩 (需要 opus 库)
|
// 是否使用 Opus 音频压缩 (需要 opus 库)
|
||||||
// 设为 1 启用 Opus 压缩,设为 0 使用 PCM 无压缩
|
// 设为 1 启用 Opus 压缩,设为 0 使用 PCM 无压缩
|
||||||
#define USING_OPUS 1
|
#define USING_OPUS 1
|
||||||
|
|||||||
+19
-6
@@ -36,6 +36,14 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
|
|||||||
return 0x20261013;
|
return 0x20261013;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 摄像头打开成功但格式解析失败(VIDEOINFOHEADER2 之外的媒体类型、宽高非法等):
|
||||||
|
// 结束本次会话,绝不带着空缓冲区进采帧循环——那会在第一帧 memcpy 时崩掉。
|
||||||
|
if (This->m_CapVideo.GetBmpInfor() == NULL) {
|
||||||
|
Mprintf("CVideoManager: camera format unusable, abort session\n");
|
||||||
|
This->Destroy();
|
||||||
|
return 0x20261014;
|
||||||
|
}
|
||||||
|
|
||||||
static ULONGLONG dwLastScreen = GetTickCount64();
|
static ULONGLONG dwLastScreen = GetTickCount64();
|
||||||
|
|
||||||
if (This->Initialize()) { //转到Initialize
|
if (This->Initialize()) { //转到Initialize
|
||||||
@@ -47,11 +55,7 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
|
|||||||
|
|
||||||
// 等控制端对话框打开
|
// 等控制端对话框打开
|
||||||
This->WaitForDialogOpen();
|
This->WaitForDialogOpen();
|
||||||
#if USING_ZLIB
|
|
||||||
const int fps = 8;// 帧率
|
const int fps = 8;// 帧率
|
||||||
#else
|
|
||||||
const int fps = 8;// 帧率
|
|
||||||
#endif
|
|
||||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||||
|
|
||||||
timeBeginPeriod(1);
|
timeBeginPeriod(1);
|
||||||
@@ -100,10 +104,15 @@ void CVideoManager::Destroy()
|
|||||||
|
|
||||||
void CVideoManager::SendBitMapInfor()
|
void CVideoManager::SendBitMapInfor()
|
||||||
{
|
{
|
||||||
|
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
|
||||||
|
if (bi == NULL) {
|
||||||
|
Mprintf("CVideoManager: no bitmap info, skip sending\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const int dwBytesLength = 1 + sizeof(BITMAPINFO);
|
const int dwBytesLength = 1 + sizeof(BITMAPINFO);
|
||||||
BYTE szBuffer[dwBytesLength + 3] = { 0 };
|
BYTE szBuffer[dwBytesLength + 3] = { 0 };
|
||||||
szBuffer[0] = TOKEN_WEBCAM_BITMAPINFO;
|
szBuffer[0] = TOKEN_WEBCAM_BITMAPINFO;
|
||||||
memcpy(szBuffer + 1, m_CapVideo.GetBmpInfor(), sizeof(BITMAPINFO));
|
memcpy(szBuffer + 1, bi, sizeof(BITMAPINFO));
|
||||||
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
||||||
m_ClientObject->Send2Server((char*)szBuffer, dwBytesLength, &mask);
|
m_ClientObject->Send2Server((char*)szBuffer, dwBytesLength, &mask);
|
||||||
}
|
}
|
||||||
@@ -187,9 +196,13 @@ BOOL CVideoManager::Initialize()
|
|||||||
bRet= FALSE;
|
bRet= FALSE;
|
||||||
return bRet;
|
return bRet;
|
||||||
}
|
}
|
||||||
|
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
|
||||||
|
if (bi == NULL) {
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
m_pVideoCodec = new CVideoCodec;
|
m_pVideoCodec = new CVideoCodec;
|
||||||
//这里初始化,视频压缩 ,注意这里的压缩码 m_fccHandler(到构造函数中查看)
|
//这里初始化,视频压缩 ,注意这里的压缩码 m_fccHandler(到构造函数中查看)
|
||||||
if (!m_pVideoCodec->InitCompressor(m_CapVideo.GetBmpInfor(), m_fccHandler)) {
|
if (!m_pVideoCodec->InitCompressor(bi, m_fccHandler)) {
|
||||||
delete m_pVideoCodec;
|
delete m_pVideoCodec;
|
||||||
bRet=FALSE;
|
bRet=FALSE;
|
||||||
// 置NULL, 发送时判断是否为NULL来判断是否压缩
|
// 置NULL, 发送时判断是否为NULL来判断是否压缩
|
||||||
|
|||||||
+35
-4
@@ -32,7 +32,15 @@
|
|||||||
#include <sys/mount.h> // macOS: statfs for filesystem type
|
#include <sys/mount.h> // macOS: statfs for filesystem type
|
||||||
#endif
|
#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)
|
#include <iconv.h> // Character encoding conversion (GBK <-> UTF-8)
|
||||||
|
#endif
|
||||||
|
|
||||||
// FileTransferV2 is in the same directory (common/)
|
// FileTransferV2 is in the same directory (common/)
|
||||||
#include "FileTransferV2.h"
|
#include "FileTransferV2.h"
|
||||||
@@ -47,6 +55,12 @@ class FileManager : public IOCPManager
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
FileManager(IOCPClient* client)
|
FileManager(IOCPClient* client)
|
||||||
|
: FileManager(client, false) {}
|
||||||
|
|
||||||
|
// deferredStart=true:不在构造里发 TOKEN_DRIVE_LIST,由子类准备好平台数据后
|
||||||
|
// 自己调用 SendDriveList()。Android 用它——存储根要先问 Java 要,而构造期
|
||||||
|
// 的虚函数不会分派到子类,直接发出去的是 Linux 的 "/" 根。
|
||||||
|
FileManager(IOCPClient* client, bool deferredStart)
|
||||||
: m_client(client),
|
: m_client(client),
|
||||||
m_nTransferMode(TRANSFER_MODE_NORMAL),
|
m_nTransferMode(TRANSFER_MODE_NORMAL),
|
||||||
m_nCurrentFileLength(0),
|
m_nCurrentFileLength(0),
|
||||||
@@ -54,7 +68,7 @@ public:
|
|||||||
{
|
{
|
||||||
memset(m_strCurrentFileName, 0, sizeof(m_strCurrentFileName));
|
memset(m_strCurrentFileName, 0, sizeof(m_strCurrentFileName));
|
||||||
memset(m_strCurrentUploadFile, 0, sizeof(m_strCurrentUploadFile));
|
memset(m_strCurrentUploadFile, 0, sizeof(m_strCurrentUploadFile));
|
||||||
SendDriveList();
|
if (!deferredStart) SendDriveList();
|
||||||
}
|
}
|
||||||
|
|
||||||
~FileManager()
|
~FileManager()
|
||||||
@@ -148,6 +162,7 @@ private:
|
|||||||
m_client->Send2Server((char*)&token, 1);
|
m_client->Send2Server((char*)&token, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#ifndef __ANDROID__
|
||||||
// ---- iconv encoding conversion ----
|
// ---- iconv encoding conversion ----
|
||||||
static std::string iconvConvert(const std::string& input, const char* from, const char* to)
|
static std::string iconvConvert(const std::string& input, const char* from, const char* to)
|
||||||
{
|
{
|
||||||
@@ -169,17 +184,28 @@ private:
|
|||||||
output.resize(output.size() - outLeft);
|
output.resize(output.size() - outLeft);
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
protected:
|
||||||
static std::string gbkToUtf8(const std::string& gbk)
|
static std::string gbkToUtf8(const std::string& gbk)
|
||||||
{
|
{
|
||||||
|
#ifdef __ANDROID__
|
||||||
|
return AndroidGbkToUtf8(gbk);
|
||||||
|
#else
|
||||||
return iconvConvert(gbk, "GBK", "UTF-8");
|
return iconvConvert(gbk, "GBK", "UTF-8");
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::string utf8ToGbk(const std::string& utf8)
|
static std::string utf8ToGbk(const std::string& utf8)
|
||||||
{
|
{
|
||||||
|
#ifdef __ANDROID__
|
||||||
|
return AndroidUtf8ToGbk(utf8);
|
||||||
|
#else
|
||||||
return iconvConvert(utf8, "UTF-8", "GBK");
|
return iconvConvert(utf8, "UTF-8", "GBK");
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
// ---- Windows path -> Linux path ----
|
// ---- Windows path -> Linux path ----
|
||||||
// Examples:
|
// Examples:
|
||||||
// /:\home\user\file.txt -> /home/user/file.txt
|
// /:\home\user\file.txt -> /home/user/file.txt
|
||||||
@@ -188,7 +214,8 @@ private:
|
|||||||
// /: -> /
|
// /: -> /
|
||||||
// C:\Users\file.txt -> /Users/file.txt
|
// C:\Users\file.txt -> /Users/file.txt
|
||||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
// %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)
|
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
|
||||||
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
||||||
@@ -196,7 +223,7 @@ private:
|
|||||||
|
|
||||||
// ---- Linux path -> Windows path (for sending to server) ----
|
// ---- Linux path -> Windows path (for sending to server) ----
|
||||||
// Converts /home/user/file.txt to /:\home\user\file.txt
|
// 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
|
// Start with drive letter representation /: for Linux root
|
||||||
// Linux path /home/user/file.txt should become /:\home\user\file.txt
|
// Linux path /home/user/file.txt should become /:\home\user\file.txt
|
||||||
@@ -290,8 +317,12 @@ private:
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 子类(Android)覆盖 SendDriveList 时要用到连接对象;m_client 是私有的。
|
||||||
|
IOCPClient* ClientObject() const { return m_client; }
|
||||||
|
|
||||||
// ---- Send drive list (Linux: root partition /) ----
|
// ---- Send drive list (Linux: root partition /) ----
|
||||||
void SendDriveList()
|
// Android 覆盖它:把内部存储 / SD 卡 / 应用目录当成带盘符的「驱动器」。
|
||||||
|
virtual void SendDriveList()
|
||||||
{
|
{
|
||||||
if (!m_client) return;
|
if (!m_client) return;
|
||||||
|
|
||||||
|
|||||||
+37
-1
@@ -24,7 +24,9 @@
|
|||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
#include <fcntl.h>
|
#include <fcntl.h>
|
||||||
#include <dirent.h>
|
#include <dirent.h>
|
||||||
|
#ifndef __ANDROID__
|
||||||
#include <iconv.h>
|
#include <iconv.h>
|
||||||
|
#endif
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <cctype>
|
#include <cctype>
|
||||||
#include <cerrno>
|
#include <cerrno>
|
||||||
@@ -35,8 +37,26 @@
|
|||||||
#include <set>
|
#include <set>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <functional>
|
||||||
#include <thread>
|
#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
|
class FileTransferV2
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -56,6 +76,9 @@ public:
|
|||||||
static std::string gbkToUtf8(const std::string& gbk)
|
static std::string gbkToUtf8(const std::string& gbk)
|
||||||
{
|
{
|
||||||
if (gbk.empty()) return gbk;
|
if (gbk.empty()) return gbk;
|
||||||
|
#ifdef __ANDROID__
|
||||||
|
return AndroidGbkToUtf8(gbk);
|
||||||
|
#else
|
||||||
iconv_t cd = iconv_open("UTF-8", "GBK");
|
iconv_t cd = iconv_open("UTF-8", "GBK");
|
||||||
if (cd == (iconv_t)-1) return gbk;
|
if (cd == (iconv_t)-1) return gbk;
|
||||||
|
|
||||||
@@ -72,11 +95,15 @@ public:
|
|||||||
if (ret == (size_t)-1) return gbk;
|
if (ret == (size_t)-1) return gbk;
|
||||||
output.resize(output.size() - outLeft);
|
output.resize(output.size() - outLeft);
|
||||||
return output;
|
return output;
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::string utf8ToGbk(const std::string& utf8)
|
static std::string utf8ToGbk(const std::string& utf8)
|
||||||
{
|
{
|
||||||
if (utf8.empty()) return utf8;
|
if (utf8.empty()) return utf8;
|
||||||
|
#ifdef __ANDROID__
|
||||||
|
return AndroidUtf8ToGbk(utf8);
|
||||||
|
#else
|
||||||
iconv_t cd = iconv_open("GBK", "UTF-8");
|
iconv_t cd = iconv_open("GBK", "UTF-8");
|
||||||
if (cd == (iconv_t)-1) return utf8;
|
if (cd == (iconv_t)-1) return utf8;
|
||||||
|
|
||||||
@@ -93,6 +120,7 @@ public:
|
|||||||
if (ret == (size_t)-1) return utf8;
|
if (ret == (size_t)-1) return utf8;
|
||||||
output.resize(output.size() - outLeft);
|
output.resize(output.size() - outLeft);
|
||||||
return output;
|
return output;
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// 递归创建目录
|
// 递归创建目录
|
||||||
@@ -430,11 +458,19 @@ public:
|
|||||||
closedir(d);
|
closedir(d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 平台路径映射钩子:由客户端启动时注入(Android 用盘符映射;其它平台不设,
|
||||||
|
// 保持 UnixPath 的原有语义)。只在单线程初始化阶段调用,不要求线程安全。
|
||||||
|
static void SetPathMapper(std::function<std::string(const std::string&)> mapper)
|
||||||
|
{
|
||||||
|
filetransferv2_path::Mapper() = std::move(mapper);
|
||||||
|
}
|
||||||
|
|
||||||
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
||||||
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
||||||
static std::string WinPathToLinux(const std::string& winPath)
|
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 码分类
|
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
|
||||||
|
|||||||
@@ -56,6 +56,13 @@ inline bool IsCommandAllowed(unsigned char cmd)
|
|||||||
return g_settingsVerified.load(std::memory_order_acquire) || cmd == CMD_MASTERSETTING;
|
return g_settingsVerified.load(std::memory_order_acquire) || cmd == CMD_MASTERSETTING;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 本连接是否已通过 MasterSettings 校验。转移主机用它判断「目标主控是否真的可用」:
|
||||||
|
// 连得上但校验一直不通过(对端不是主控,或不是本构建的主控)与连不上等价。
|
||||||
|
inline bool IsVerified()
|
||||||
|
{
|
||||||
|
return g_settingsVerified.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
// 处理 CMD_MASTERSETTING(payload = szBuffer + 1,payloadLen = ulLength - 1):
|
// 处理 CMD_MASTERSETTING(payload = szBuffer + 1,payloadLen = ulLength - 1):
|
||||||
// 强制要求完整 MasterSettings(包含 Signature 字段);不完整 / 签名失败 → 不更新
|
// 强制要求完整 MasterSettings(包含 Signature 字段);不完整 / 签名失败 → 不更新
|
||||||
// g_settingsVerified,让心跳循环 30s 超时自然把本次连接断开重连。
|
// g_settingsVerified,让心跳循环 30s 超时自然把本次连接断开重连。
|
||||||
|
|||||||
@@ -152,6 +152,12 @@ inline int isValid_10s()
|
|||||||
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明)
|
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明)
|
||||||
#define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位)
|
#define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位)
|
||||||
#define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明)
|
#define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明)
|
||||||
|
#define CLIENT_CAP_COMPRESS_SWITCH 0x40000 // 支持服务端远程切换线缆压缩(COMMAND_SET_COMPRESS,仅 Windows)
|
||||||
|
|
||||||
|
// TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG,
|
||||||
|
// 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。
|
||||||
|
// 值等于 mmioFOURCC('J','P','G','D')。
|
||||||
|
#define WEBCAM_FOURCC_JPEG_DIRECT 0x4447504A
|
||||||
|
|
||||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||||
|
|
||||||
@@ -380,6 +386,12 @@ enum {
|
|||||||
COMMAND_MCP_WINDOW_INFO = 179,
|
COMMAND_MCP_WINDOW_INFO = 179,
|
||||||
TOKEN_MCP_WINDOW_INFO = 180,
|
TOKEN_MCP_WINDOW_INFO = 180,
|
||||||
|
|
||||||
|
// 线缆压缩切换(服务端 → 客户端):载荷 [cmd:1]["zlib"|"zstd"]。
|
||||||
|
// 客户端写入自己配置的 settings\compress 后重启 StartClient 线程,新连接按新模式
|
||||||
|
// 重连;服务端按首包自动识别算法,无需额外握手。只有声明 CLIENT_CAP_COMPRESS_SWITCH
|
||||||
|
// 的 Windows 客户端认识;老客户端走 default 静默丢弃。
|
||||||
|
COMMAND_SET_COMPRESS = 181,
|
||||||
|
|
||||||
TOKEN_DECRYPT = 199,
|
TOKEN_DECRYPT = 199,
|
||||||
TOKEN_REGEDIT = 200, // 注册表
|
TOKEN_REGEDIT = 200, // 注册表
|
||||||
COMMAND_REG_FIND, // 注册表 管理标识
|
COMMAND_REG_FIND, // 注册表 管理标识
|
||||||
@@ -1330,6 +1342,8 @@ typedef struct LOGIN_INFOR {
|
|||||||
caps |= CLIENT_CAP_C2C_PATHS;
|
caps |= CLIENT_CAP_C2C_PATHS;
|
||||||
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
||||||
caps |= CLIENT_CAP_PROTO_SWITCH;
|
caps |= CLIENT_CAP_PROTO_SWITCH;
|
||||||
|
// 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。
|
||||||
|
caps |= CLIENT_CAP_COMPRESS_SWITCH;
|
||||||
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
|
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
|
||||||
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
|
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
|
||||||
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
|
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
|
||||||
@@ -1409,6 +1423,36 @@ typedef struct LOGIN_INFOR {
|
|||||||
{
|
{
|
||||||
return StringToVector(szReserved, '|', n);
|
return StringToVector(szReserved, '|', n);
|
||||||
}
|
}
|
||||||
|
// 按位置改写第 index 个字段(服务端用 LOGIN_RES 下标取值)。AddReserved 只能往后追加,
|
||||||
|
// 改不了已写好的字段;重连重发登录前刷新某个「当前状态」字段(RES_TLS / RES_UPTIME)
|
||||||
|
// 就得靠这个。
|
||||||
|
// 字段数按分隔符数 + 1 数,末尾空槽也算一个字段,拼回去时原样保留——否则少写一个 '|'
|
||||||
|
// 会让后面的字段整体前移,服务端把用户名读成类型。整体放不下 szReserved 时返回 false
|
||||||
|
// 且保持原值,绝不写半截。
|
||||||
|
bool SetReserved(int index, const char* v)
|
||||||
|
{
|
||||||
|
if (index < 0 || index >= (int)RES_MAX) return false;
|
||||||
|
|
||||||
|
std::vector<std::string> fields;
|
||||||
|
const char* p = szReserved;
|
||||||
|
for (;;) {
|
||||||
|
const char* bar = strchr(p, '|');
|
||||||
|
if (bar == nullptr) {
|
||||||
|
fields.push_back(p);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
fields.push_back(std::string(p, bar - p));
|
||||||
|
p = bar + 1;
|
||||||
|
}
|
||||||
|
if (fields.size() < (size_t)index + 1)
|
||||||
|
fields.resize((size_t)index + 1); // 补空槽,std::string 默认空串
|
||||||
|
fields[index] = v ? v : "";
|
||||||
|
|
||||||
|
const std::string joined = VectorJoin(fields, '|');
|
||||||
|
if (joined.size() >= sizeof(szReserved)) return false;
|
||||||
|
memcpy(szReserved, joined.c_str(), joined.size() + 1);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// 追加一个保留字段。szReserved 是「按位置」解析的(服务端用 LOGIN_RES 下标取值),
|
// 追加一个保留字段。szReserved 是「按位置」解析的(服务端用 LOGIN_RES 下标取值),
|
||||||
|
|||||||
+11
-1
@@ -43,10 +43,20 @@ inline bool ParseHeaderEnc(const std::string& s, int& out)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 端点能安全写进 CONNECT_ADDRESS 的边界。非 Windows 上 strcpy_s/sprintf_s 就是无界的
|
||||||
|
// strcpy/sprintf(见 commands.h),地址超长会直接踩坏 szPort/iType 等后续字段,
|
||||||
|
// 所以来自命令或配置文件的端点必须先过这一关。
|
||||||
|
inline bool FitsConnAddress(const Endpoint& ep)
|
||||||
|
{
|
||||||
|
return !ep.ip.empty()
|
||||||
|
&& ep.ip.size() <= sizeof(((CONNECT_ADDRESS*)nullptr)->szServerIP) - 1
|
||||||
|
&& ep.port > 0 && ep.port <= 65535;
|
||||||
|
}
|
||||||
|
|
||||||
// 把端点写进连接参数。只在连接生命周期的持有线程调用(见文件头注释)。
|
// 把端点写进连接参数。只在连接生命周期的持有线程调用(见文件头注释)。
|
||||||
inline void ApplyEndpoint(CONNECT_ADDRESS& conn, const Endpoint& ep)
|
inline void ApplyEndpoint(CONNECT_ADDRESS& conn, const Endpoint& ep)
|
||||||
{
|
{
|
||||||
if (ep.ip.empty() || ep.port <= 0)
|
if (!FitsConnAddress(ep))
|
||||||
return;
|
return;
|
||||||
conn.SetServer(ep.ip.c_str(), ep.port);
|
conn.SetServer(ep.ip.c_str(), ep.port);
|
||||||
if (ep.transport >= 0)
|
if (ep.transport >= 0)
|
||||||
|
|||||||
+2
-1
@@ -10,7 +10,8 @@
|
|||||||
// server/2015Remote/2015RemoteDlg.cpp ShareClient)。命令字节是 COMMAND_SHARE(59),
|
// server/2015Remote/2015RemoteDlg.cpp ShareClient)。命令字节是 COMMAND_SHARE(59),
|
||||||
// 不是「转移主机」用的 COMMAND_ASSIGN_MASTER(207);Windows 客户端的 case 把两者
|
// 不是「转移主机」用的 COMMAND_ASSIGN_MASTER(207);Windows 客户端的 case 把两者
|
||||||
// 并在一起、靠 buf[1] 的类型字节区分,这里同样两个都收。和「转移主机」的区别:
|
// 并在一起、靠 buf[1] 的类型字节区分,这里同样两个都收。和「转移主机」的区别:
|
||||||
// 转移改的是本实例的主连接,分享另起一条通往目标主控的连接,主连接原样保留。
|
// 转移改的是本实例的主连接(收包后立刻断开、重连到新主控,老主控那边随即离线),
|
||||||
|
// 分享另起一条通往目标主控的连接,主连接原样保留。
|
||||||
// Windows 侧是同一进程里再起一个 ClientApp 线程(client/KernelManager.cpp、
|
// Windows 侧是同一进程里再起一个 ClientApp 线程(client/KernelManager.cpp、
|
||||||
// client/ClientDll.cpp 的 m_bShared 分支);Linux 侧由主实例 fork+exec 出一个
|
// client/ClientDll.cpp 的 m_bShared 分支);Linux 侧由主实例 fork+exec 出一个
|
||||||
// 分享子进程,复用同一份登录/心跳/命令处理代码。
|
// 分享子进程,复用同一份登录/心跳/命令处理代码。
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
namespace HostTransfer {
|
namespace HostTransfer {
|
||||||
|
|
||||||
using HostEndpoint::Endpoint;
|
using HostEndpoint::Endpoint;
|
||||||
|
using HostEndpoint::FitsConnAddress;
|
||||||
using HostEndpoint::ParseTransport;
|
using HostEndpoint::ParseTransport;
|
||||||
using HostEndpoint::ParseHeaderEnc;
|
using HostEndpoint::ParseHeaderEnc;
|
||||||
using HostEndpoint::ApplyEndpoint;
|
using HostEndpoint::ApplyEndpoint;
|
||||||
@@ -28,7 +29,8 @@ struct Target {
|
|||||||
long long validTo; // <= 0 表示无效
|
long long validTo; // <= 0 表示无效
|
||||||
|
|
||||||
Target() : validTo(0) {}
|
Target() : validTo(0) {}
|
||||||
bool Valid() const { return !ep.ip.empty() && ep.port > 0 && validTo > 0; }
|
// 端点容量由 FitsConnAddress 守住:记录里存的是外部输入,直接 ApplyTarget 会越界。
|
||||||
|
bool Valid() const { return FitsConnAddress(ep) && validTo > 0; }
|
||||||
bool Active(long long now) const { return Valid() && now <= validTo; }
|
bool Active(long long now) const { return Valid() && now <= validTo; }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -54,7 +56,9 @@ inline bool ParseAssignCommand(const unsigned char* buf, unsigned long len,
|
|||||||
Target t;
|
Target t;
|
||||||
t.ep.ip = v[0];
|
t.ep.ip = v[0];
|
||||||
t.ep.port = atoi(v[1].c_str());
|
t.ep.port = atoi(v[1].c_str());
|
||||||
if (t.ep.ip.empty() || t.ep.port <= 0 || t.ep.port > 65535)
|
// 长度/端口范围都要挡住:服务端只限制整条载荷不超过 250 字节,地址本身可以顶到
|
||||||
|
// CONNECT_ADDRESS::szServerIP[100] 之外,写进 g_SETTINGS 时就是堆栈/全局越界。
|
||||||
|
if (!FitsConnAddress(t.ep))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
double days = atof(v[2].c_str());
|
double days = atof(v[2].c_str());
|
||||||
|
|||||||
+10
-1
@@ -499,6 +499,10 @@ typedef uLong FAR uLongf;
|
|||||||
|
|
||||||
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
|
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
|
||||||
# define Z_LFS64
|
# define Z_LFS64
|
||||||
|
#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \
|
||||||
|
!defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__))
|
||||||
|
# define Z_LFS64 /* native Windows has 64-bit file offsets */
|
||||||
|
# define Z_WINLFS
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
|
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
|
||||||
@@ -516,7 +520,7 @@ typedef uLong FAR uLongf;
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifndef z_off_t
|
#ifndef z_off_t
|
||||||
# define z_off_t long long
|
# define z_off_t long
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if !defined(_WIN32) && defined(Z_LARGE64)
|
#if !defined(_WIN32) && defined(Z_LARGE64)
|
||||||
@@ -531,6 +535,11 @@ typedef uLong FAR uLongf;
|
|||||||
# define z_off64_t z_off_t
|
# define z_off64_t z_off_t
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO)
|
||||||
|
# undef z_off_t
|
||||||
|
# define z_off_t z_off64_t
|
||||||
|
#endif
|
||||||
|
|
||||||
/* MVS linker does not support external names larger than 8 bytes */
|
/* MVS linker does not support external names larger than 8 bytes */
|
||||||
#if defined(__MVS__)
|
#if defined(__MVS__)
|
||||||
#pragma map(deflateInit_,"DEIN")
|
#pragma map(deflateInit_,"DEIN")
|
||||||
|
|||||||
+44
-33
@@ -1,5 +1,5 @@
|
|||||||
/* zlib.h -- interface of the 'zlib' general purpose compression library
|
/* zlib.h -- interface of the 'zlib' general purpose compression library
|
||||||
version 1.3.2, February 17th, 2026
|
version 1.4, November 4th, 2026
|
||||||
|
|
||||||
Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
|
Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
|
||||||
|
|
||||||
@@ -41,11 +41,11 @@
|
|||||||
extern "C" {
|
extern "C" {
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define ZLIB_VERSION "1.3.2"
|
#define ZLIB_VERSION "1.4"
|
||||||
#define ZLIB_VERNUM 0x1320
|
#define ZLIB_VERNUM 0x1400
|
||||||
#define ZLIB_VER_MAJOR 1
|
#define ZLIB_VER_MAJOR 1
|
||||||
#define ZLIB_VER_MINOR 3
|
#define ZLIB_VER_MINOR 4
|
||||||
#define ZLIB_VER_REVISION 2
|
#define ZLIB_VER_REVISION 0
|
||||||
#define ZLIB_VER_SUBREVISION 0
|
#define ZLIB_VER_SUBREVISION 0
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -696,7 +696,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
|
|||||||
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||||
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
||||||
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
||||||
destination.
|
destination. If deflateCopy fails and dest is not Z_NULL, then dest->state
|
||||||
|
is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can
|
||||||
|
be called safely, though dest is not a usable stream.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
|
ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
|
||||||
@@ -769,17 +771,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen);
|
|||||||
ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
|
ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
|
||||||
/*
|
/*
|
||||||
deflateBound() returns an upper bound on the compressed size after
|
deflateBound() returns an upper bound on the compressed size after
|
||||||
deflation of sourceLen bytes. It must be called after deflateInit() or
|
deflation of sourceLen bytes. It must be called after deflateInit() or
|
||||||
deflateInit2(), and after deflateSetHeader(), if used. This would be used
|
deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if
|
||||||
to allocate an output buffer for deflation in a single pass, and so would be
|
used. This would be used to allocate an output buffer for deflation in a
|
||||||
called before deflate(). If that first deflate() call is provided the
|
single pass, and so would be called before deflate(). If that first
|
||||||
sourceLen input bytes, an output buffer allocated to the size returned by
|
deflate() call is provided the sourceLen input bytes, an output buffer
|
||||||
deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
|
allocated to the size returned by deflateBound(), and the flush value
|
||||||
to return Z_STREAM_END. Note that it is possible for the compressed size to
|
Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it
|
||||||
be larger than the value returned by deflateBound() if flush options other
|
is possible for the compressed size to be larger than the value returned by
|
||||||
than Z_FINISH or Z_NO_FLUSH are used.
|
deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
|
||||||
|
|
||||||
delfateBound_z() is the same, but takes and returns a size_t length. Note
|
deflateBound_z() is the same, but takes and returns a size_t length. Note
|
||||||
that a long is 32 bits on Windows.
|
that a long is 32 bits on Windows.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -789,7 +791,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
|
|||||||
/*
|
/*
|
||||||
deflatePending() returns the number of bytes and bits of output that have
|
deflatePending() returns the number of bytes and bits of output that have
|
||||||
been generated, but not yet provided in the available output. The bytes not
|
been generated, but not yet provided in the available output. The bytes not
|
||||||
provided would be due to the available output space having being consumed.
|
provided would be due to the available output space having been consumed.
|
||||||
The number of bits of output not provided are between 0 and 7, where they
|
The number of bits of output not provided are between 0 and 7, where they
|
||||||
await more bits to join them in order to fill out a full byte. If pending
|
await more bits to join them in order to fill out a full byte. If pending
|
||||||
or bits are Z_NULL, then those values are not set.
|
or bits are Z_NULL, then those values are not set.
|
||||||
@@ -869,8 +871,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
|
|||||||
instead. windowBits must be greater than or equal to the windowBits value
|
instead. windowBits must be greater than or equal to the windowBits value
|
||||||
provided to deflateInit2() while compressing, or it must be equal to 15 if
|
provided to deflateInit2() while compressing, or it must be equal to 15 if
|
||||||
deflateInit2() was not used. If a compressed stream with a larger window
|
deflateInit2() was not used. If a compressed stream with a larger window
|
||||||
size is given as input, inflate() will return with the error code
|
size is given as input, inflate() may return with a Z_DATA_ERROR.
|
||||||
Z_DATA_ERROR instead of trying to allocate a larger window.
|
|
||||||
|
|
||||||
windowBits can also be zero to request that inflate use the window size in
|
windowBits can also be zero to request that inflate use the window size in
|
||||||
the zlib header of the compressed stream.
|
the zlib header of the compressed stream.
|
||||||
@@ -980,7 +981,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
|
|||||||
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||||
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
||||||
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
||||||
destination.
|
destination. If inflateCopy fails and dest is not Z_NULL, then dest->state
|
||||||
|
is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can
|
||||||
|
be called safely, though dest is not a usable stream.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
|
ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
|
||||||
@@ -1095,9 +1098,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
|
|||||||
a terminating zero. If any of extra, name, or comment are not present in
|
a terminating zero. If any of extra, name, or comment are not present in
|
||||||
the header, then that field's pointer is set to Z_NULL. This allows the use
|
the header, then that field's pointer is set to Z_NULL. This allows the use
|
||||||
of deflateSetHeader() with the returned structure to duplicate the header.
|
of deflateSetHeader() with the returned structure to duplicate the header.
|
||||||
Note that if those fields initially pointed to allocated memory, then the
|
Though take care that none of the fields were truncated before so using it,
|
||||||
application will need to save them elsewhere so that they can be eventually
|
lest havoc ensue. Note that if those fields initially pointed to allocated
|
||||||
freed.
|
memory, then the application will need to save them elsewhere so that they
|
||||||
|
can be eventually freed.
|
||||||
|
|
||||||
If inflateGetHeader is not used, then the header information is simply
|
If inflateGetHeader is not used, then the header information is simply
|
||||||
discarded. The header is always checked for validity, including the header
|
discarded. The header is always checked for validity, including the header
|
||||||
@@ -1394,8 +1398,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
|
|||||||
errno can be checked to determine if the reason gzopen failed was that the
|
errno can be checked to determine if the reason gzopen failed was that the
|
||||||
file could not be opened. Note that if 'N' is in mode for non-blocking, the
|
file could not be opened. Note that if 'N' is in mode for non-blocking, the
|
||||||
open() itself can fail in order to not block. In that case gzopen() will
|
open() itself can fail in order to not block. In that case gzopen() will
|
||||||
return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can
|
return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen()
|
||||||
then be re-tried. If the application would like to block on opening the
|
can then be re-tried. If the application would like to block on opening the
|
||||||
file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
|
file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
|
||||||
resulting file descriptor and 'N' in the mode, which will set it to non-
|
resulting file descriptor and 'N' in the mode, which will set it to non-
|
||||||
blocking.
|
blocking.
|
||||||
@@ -1501,9 +1505,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
|
|||||||
gzfread() returns the number of full items read of size size, or zero if
|
gzfread() returns the number of full items read of size size, or zero if
|
||||||
the end of the file was reached and a full item could not be read, or if
|
the end of the file was reached and a full item could not be read, or if
|
||||||
there was an error. gzerror() must be consulted if zero is returned in
|
there was an error. gzerror() must be consulted if zero is returned in
|
||||||
order to determine if there was an error. If the multiplication of size and
|
order to determine if there was an error. If some data was read before an
|
||||||
nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
|
error, then that data is returned until exhausted, after which the next call
|
||||||
is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
|
will return zero and gzerror() will report the error. If the multiplication
|
||||||
|
of size and nitems overflows, i.e. the product does not fit in a z_size_t,
|
||||||
|
then nothing is read, zero is returned, and the error state is set to
|
||||||
|
Z_STREAM_ERROR.
|
||||||
|
|
||||||
In the event that the end of file is reached and only a partial item is
|
In the event that the end of file is reached and only a partial item is
|
||||||
available at the end, i.e. the remaining uncompressed data length is not a
|
available at the end, i.e. the remaining uncompressed data length is not a
|
||||||
@@ -1569,7 +1576,7 @@ ZEXTERN int ZEXPORTVA gzprintf();
|
|||||||
these possibilities can be determined using zlibCompileFlags().
|
these possibilities can be determined using zlibCompileFlags().
|
||||||
|
|
||||||
If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
|
If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
|
||||||
the non-blocking write destination.
|
the non-blocking write destination. The operation can be retried.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
|
ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
|
||||||
@@ -1677,7 +1684,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
|
|||||||
gzseek returns the resulting offset location as measured in bytes from
|
gzseek returns the resulting offset location as measured in bytes from
|
||||||
the beginning of the uncompressed stream, or -1 in case of error, in
|
the beginning of the uncompressed stream, or -1 in case of error, in
|
||||||
particular if the file is opened for writing and the new starting position
|
particular if the file is opened for writing and the new starting position
|
||||||
would be before the current position.
|
would be before the current position, or if the resulting position would
|
||||||
|
not be representable in the offset type. If gzseek returns -1, the stream
|
||||||
|
position is unchanged.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
ZEXTERN int ZEXPORT gzrewind(gzFile file);
|
ZEXTERN int ZEXPORT gzrewind(gzFile file);
|
||||||
@@ -1778,7 +1787,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
|
|||||||
If errnum is not NULL, *errnum is set to zlib error number. If an error
|
If errnum is not NULL, *errnum is set to zlib error number. If an error
|
||||||
occurred in the file system and not in the compression library, *errnum is
|
occurred in the file system and not in the compression library, *errnum is
|
||||||
set to Z_ERRNO and the application may consult errno to get the exact error
|
set to Z_ERRNO and the application may consult errno to get the exact error
|
||||||
code.
|
code. The error is reported by gzerror() as soon as it is detected, which
|
||||||
|
may be before all of the data read prior to the error has been returned.
|
||||||
|
|
||||||
The application must not modify the returned string. Future calls to
|
The application must not modify the returned string. Future calls to
|
||||||
this function may invalidate the previously returned string. If file is
|
this function may invalidate the previously returned string. If file is
|
||||||
@@ -1972,7 +1982,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
|
|||||||
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
|
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
|
||||||
* both are true, the application gets the *64 functions, and the regular
|
* both are true, the application gets the *64 functions, and the regular
|
||||||
* functions are changed to 64 bits) -- in case these are set on systems
|
* functions are changed to 64 bits) -- in case these are set on systems
|
||||||
* without large file support, _LFS64_LARGEFILE must also be true
|
* without large file support, _LFS64_LARGEFILE must also be true, except on
|
||||||
|
* native Windows, where 64-bit offsets are always available
|
||||||
*/
|
*/
|
||||||
#ifdef Z_LARGE64
|
#ifdef Z_LARGE64
|
||||||
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
|
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
|
||||||
@@ -2029,7 +2040,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
|
|||||||
|
|
||||||
#endif /* !Z_SOLO */
|
#endif /* !Z_SOLO */
|
||||||
|
|
||||||
/* undocumented functions */
|
/* undocumented functions (not part of the zlib API) */
|
||||||
ZEXTERN const char * ZEXPORT zError(int);
|
ZEXTERN const char * ZEXPORT zError(int);
|
||||||
ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
|
ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
|
||||||
ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
|
ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,179 @@
|
|||||||
|
# 客户端能力矩阵
|
||||||
|
|
||||||
|
以 Windows 客户端为基线,对比 Linux、macOS、Android 客户端的实现情况。表中所有主表行在 Windows 列均为 ✓;其他平台按实际代码判断,不做推测。
|
||||||
|
|
||||||
|
- 依据:各平台客户端源码(`client/`、`linux/`、`macos/`、`android/app/src/main/`)与登录能力位(`common/commands.h` 的 `DefaultCaps()`),代码基线 `main@d9fe93f`(2026-11-19)。
|
||||||
|
- `linux/README.md` 里的「未实现」清单部分已过时(例如开机自启已由 `install.sh` 实现),以本表为准。
|
||||||
|
- 图例:✓ 已实现;△ 部分实现或依赖运行环境;— 未实现。
|
||||||
|
- 服务端侧功能(主机列表、备注/分组、上线提醒、授权管理界面、MCP、Web 控制台等)不在本表范围。
|
||||||
|
|
||||||
|
## 一、连接与传输
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| TCP 直连 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| WebSocket / WSS 传输(出包时选择) | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| TLS 加密传输 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 子连接 ConnAuth 身份校验 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 断线自动重连 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 心跳与活动窗口上报 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 服务端修改分组 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| UDP / KCP / HTTP 伪装传输 | ✓ | — | — | — |
|
||||||
|
| 并发上线(多实例并行) | ✓ | — | — | — |
|
||||||
|
| 远程切换传输协议(TCP/WS/WSS) | ✓ | — | — | — |
|
||||||
|
| 客户端 ID 重建(克隆机撞 ID) | ✓ | — | — | — |
|
||||||
|
| 分享主机 / 取消分享 | ✓ | ✓ | — | — |
|
||||||
|
| 转移主机(到期自动复原) | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- 分享/转移:Android 实现转移、不实现分享(收到分享命令会回“不支持”);macOS 同样只实现转移(收包即迁移主连接,记录存 `~/.config/ghost/config.conf` 的 `transfer` 键,连不上目标满 60 秒且连续失败 3 次后退回原主控),分享命令回“不支持”。
|
||||||
|
- **WebSocket/WSS 是“出包能力”,不是“运行时切换能力”**:四个平台的网络层(`IOCPClient` + `WsChannel.h`)都实现了 WS/WSS,生成客户端时把「协议」选为 WebSocket 或 WS+TLS 即可,客户端启动后按烘焙的 `protoType` 连接(需经反向代理入口;WSS 还需内嵌或在线下发的信任锚)。但运行时的「协议切换」菜单走 `COMMAND_SET_PROTO`,只有 Windows 客户端处理该命令并声明 `CLIENT_CAP_PROTO_SWITCH`;其他平台该菜单整组置灰,菜单里勾选 TCP 只是当前实际连接的传输,不代表客户端只能走 TCP。
|
||||||
|
- UDP/KCP/HTTP 伪装传输:只有 Windows 客户端有对应实现;Linux/macOS/Android 的网络层只处理 TCP/WS/WSS,出包时选其他协议不会生效。
|
||||||
|
- 并发上线(`RUNNING_PARALLEL`)只有 Windows 客户端实现;其他平台按单实例运行。
|
||||||
|
- 客户端 ID 重建同样仅 Windows 处理。
|
||||||
|
- TLS:macOS 复用 `client/TlsChannelLinux.cpp`,实机验证仍待补;Android/Linux 已随 TLS 开关使用。
|
||||||
|
|
||||||
|
## 二、远程桌面
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| 实时屏幕查看 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| H.264 编码与关键帧请求 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 画质档位下发(自适应/固定档) | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 帧率设置(`CMD_FPS`) | ✓ | — | — | ✓ |
|
||||||
|
| 远程桌面调优 / 硬编码 / SSE2 | ✓ | — | — | — |
|
||||||
|
| 鼠标/键盘注入 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 剪贴板同步 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 剪贴板文件同步(复制文件/路径) | ✓ | ✓ | ✓ | — |
|
||||||
|
| 锁定目标键鼠 | ✓ | — | — | ✓ |
|
||||||
|
| 隐私屏幕(独立桌面) | ✓ | — | — | — |
|
||||||
|
| 多显示器整桌面捕获 | ✓ | △ | — | — |
|
||||||
|
| 切换显示器 | ✓ | — | — | — |
|
||||||
|
| 黑白屏幕(灰度传输) | ✓ | ✓ | ✓ | — |
|
||||||
|
| 区域/窗口级截图 | ✓ | — | — | — |
|
||||||
|
| 全屏 / 远程光标视图偏好 | ✓ | ✓ | — | — |
|
||||||
|
| 滚动优化 / 多线程压缩 | ✓ | — | — | — |
|
||||||
|
| RDP 会话归位 / 虚拟桌面重置 / 窗口切换 | ✓ | — | — | — |
|
||||||
|
| 自定义光标 | ✓ | — | — | — |
|
||||||
|
| 屏幕缩略图预览 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 远程音频监听 | ✓ | — | — | ✓ |
|
||||||
|
| 远程摄像头 | ✓ | — | — | ✓ |
|
||||||
|
| 键盘记录 | ✓ | — | — | — |
|
||||||
|
| 即时消息/远程交谈 | ✓ | — | — | ✓ |
|
||||||
|
| 远程画板 | ✓ | — | — | — |
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- 剪贴板:Windows/Linux/macOS 支持读取与写入;Android 只处理服务端下发的“写入并粘贴”,不支持读取设备剪贴板。
|
||||||
|
- 剪贴板文件同步:Windows/Linux/macOS 在剪贴板里是文件时返回文件清单/内容(`COMMAND_GET_FOLDER` / `COMMAND_GET_FILE`),Android 没有文件剪贴板协议。
|
||||||
|
- 缩略图预览:Linux 需有可截图的 X11 会话,macOS 需已授予录屏权限,Android 需无障碍服务与 API 30+;条件不满足时客户端不声明对应能力位,服务端会提前拒绝。
|
||||||
|
- 画质配置表(`CMD_QUALITY_PROFILES`)仅 Windows/Android 处理;Linux/macOS 只处理单档 `CMD_QUALITY_LEVEL`。
|
||||||
|
- 关键帧请求(`COMMAND_SCREEN_KEYFRAME_REQ`):Windows/Linux/macOS 处理(Web 屏幕墙恢复用);Android 未处理该命令,只在注入手势后主动请求 IDR。
|
||||||
|
- 鼠标/键盘注入:Windows/Linux/macOS 是完整键鼠注入;Android 把鼠标映射为触摸手势,只支持 Back/Home/Apps/截图/粘贴等少量按键,没有通用键盘注入。
|
||||||
|
- 帧率设置:Android 处理 `CMD_FPS`;`CMD_SCREEN_TUNING` 在 Android 上是显式 no-op,`COMMAND_ENCODE_LEVEL`(硬编码选择)只有 Windows 处理。
|
||||||
|
- 多显示器:Windows 支持整桌面捕获和按显示器切换;Linux 总是抓 X root(含所有显示器),不能按显示器选择;macOS 只抓主显示器。
|
||||||
|
- 全屏/远程光标:Windows 与 Linux 会把主控端的视图偏好落盘并在下次打开时上报;macOS/Android 没有这两个偏好命令。
|
||||||
|
- 黑白屏幕(灰度传输):Windows/Linux/macOS 处理 `ALGORITHM_GRAY`;Android 没有该算法,收到后会忽略灰度标志。
|
||||||
|
- RDP 会话归位/虚拟桌面重置/窗口切换:均为 Windows 屏幕子连接命令,其他平台没有对应实现。
|
||||||
|
- 键盘记录仅在 Windows 客户端实现(支持实时与离线落盘、清除);其他平台没有输入钩子。
|
||||||
|
- 远程音频为单向麦克风监听(Windows/Android);双向语音对讲/麦克风回传未实现(评估后放弃)。Windows 的音频开关支持持久化(`CMD_AUDIO_CTRL`),Android 不支持。
|
||||||
|
- 远程摄像头:Windows 支持压缩开关与分辨率调整;Android 固定 1280×720@8fps JPEG。
|
||||||
|
- Android 的锁定键鼠、黑屏遮罩、锁屏(映射 `GLOBAL_ACTION_LOCK_SCREEN`)都依赖无障碍服务,客户端按运行时状态追加 `PRIVACY_OVERLAY` / `LOCK_SCREEN` 能力位;Windows 无锁屏/黑屏对应行,故未列入主表。
|
||||||
|
|
||||||
|
## 三、文件管理
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| 磁盘/目录浏览 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 上传/下载 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| V2 文件传输通道 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 断点续传 | ✓ | — | — | — |
|
||||||
|
| 删除/重命名/新建目录 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 文件搜索 | ✓ | — | — | ✓ |
|
||||||
|
| 压缩/解压 | ✓ | — | — | — |
|
||||||
|
| 客户端间 C2C 文件直传 | ✓ | △ | △ | — |
|
||||||
|
| 客户端间 C2C 剪贴板文本 | ✓ | △ | △ | — |
|
||||||
|
| 文件复制/粘贴 / 属性 / 最近文件 / 网上邻居 / 远程打开 / 强制删除 | ✓ | — | — | — |
|
||||||
|
| 文件加密/解密(经典文件管理器) | ✓ | — | — | — |
|
||||||
|
| 插件文件管理(SimplePlugins) | ✓ | — | — | — |
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- 断点续传:仅 Windows 客户端处理 `COMMAND_FILE_QUERY_RESUME` / `COMMAND_FILE_RESUME`;其他平台走 V2 普通传输,不响应续传查询。
|
||||||
|
- C2C 文件:Windows 支持发送(`CLIENT_CAP_C2C_PATHS`)与接收(`COMMAND_C2C_PREPARE/_RESP`);Linux/macOS 只做接收端并在落盘后回执(`CLIENT_CAP_C2C_RECV_ACK`);Android 未实现。C2C 需要收发两端能力配合,单端具备能力不等于任意两平台之间都能直传。
|
||||||
|
- C2C 剪贴板文本(`COMMAND_C2C_TEXT`):Windows 能发送也能接收;Linux/macOS 只处理接收端(服务端下发文本后写入本机剪贴板,Linux 需要 `xclip`/`xsel`);Android 未实现。
|
||||||
|
- 文件复制/粘贴、属性、最近文件、网上邻居、远程打开、强制删除:Windows 经典文件管理器的扩展命令;Linux/macOS/Android 的 V2 文件管理只提供目录浏览与增删改,没有这些入口。
|
||||||
|
- 文件加密/解密:Windows 客户端处理 `COMMAND_FILE_Encryption` / `COMMAND_FILE_Decrypt`;其他平台没有对应实现。
|
||||||
|
- 插件文件管理(SimplePlugins):Windows 的「实验功能 → 文件管理」走 `COMMAND_FILE_MANAGER_PLUGIN`;其他平台没有该插件入口。
|
||||||
|
|
||||||
|
## 四、系统管理
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| 进程列表 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 结束进程 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 进程冻结/解冻/删除 | ✓ | — | — | — |
|
||||||
|
| 窗口列表 | ✓ | — | △ | — |
|
||||||
|
| 窗口操作(激活/移动/置顶/关闭) | ✓ | — | — | — |
|
||||||
|
| 远程终端(PTY) | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 服务管理(启动/停止/暂停/删除) | ✓ | — | — | — |
|
||||||
|
| 计划任务管理 | ✓ | — | — | — |
|
||||||
|
| 注册表管理 | ✓ | — | — | — |
|
||||||
|
| 系统信息/机器管理 | ✓ | — | — | — |
|
||||||
|
| 已安装软件清单/卸载 | ✓ | — | — | — |
|
||||||
|
| 电源操作(关机/重启/注销) | ✓ | — | — | — |
|
||||||
|
| 下载执行 / 上传执行 / DLL 执行 | ✓ | — | — | — |
|
||||||
|
| 代理映射/端口转发 | ✓ | — | — | — |
|
||||||
|
| 提权运行(UAC) | ✓ | — | — | — |
|
||||||
|
| 进程注入(记事本 / Shellcode) | ✓ | — | — | — |
|
||||||
|
| 连接管理(连接列表/强制断开) | ✓ | — | — | — |
|
||||||
|
| 远程封禁(强制终止客户端) | ✓ | — | — | — |
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- Android 进程列表/结束进程依赖 root;非 root 设备登录时不声明 `CLIENT_CAP_PROCESS`,服务端直接返回“不支持”。
|
||||||
|
- 窗口列表:macOS 只提供应用列表(PID 当伪句柄),不是窗口级枚举;Linux 的 `COMMAND_WSLIST` 只回一个空 `TOKEN_WSLIST`(无 GUI 窗口管理),Android 仅上报当前活动窗口标题。窗口移动/置顶/关闭只有 Windows 实现。
|
||||||
|
- 机器管理(Windows)在同一面板下还提供网络连接、浏览器历史、收藏夹、HOSTS 文件、驱动服务等清单/编辑能力;其他平台没有对应面板。
|
||||||
|
- 电源操作仅 Windows 实现(MCP `power_action` 也只放行 Windows 主机)。
|
||||||
|
- 连接管理:Windows 客户端枚举本机 TCP 连接并通过 `SetTcpEntry` 强制断开;其他平台没有 `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` 处理。
|
||||||
|
- 远程封禁(`COMMAND_FORBIDDEN`)只有 Windows 客户端处理(直接 `TerminateProcess` 退出);其他平台收到命令会走 default 丢弃。
|
||||||
|
|
||||||
|
## 五、监控与审计
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| 拉取客户端运行日志 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 历史活动上报 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
|
||||||
|
## 六、升级与运维
|
||||||
|
|
||||||
|
| 功能 | Windows | Linux | macOS | Android |
|
||||||
|
|---|:---:|:---:|:---:|:---:|
|
||||||
|
| 远程升级 | ✓ | ✓ | — | ✓ |
|
||||||
|
| TLS 开关下发 | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| 自启动/服务化 | ✓ | ✓ | ✓ | △ |
|
||||||
|
| 远程卸载 | ✓ | — | — | ✓ |
|
||||||
|
| 授权/许可校验(V2) | ✓ | — | — | — |
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- 远程升级:Windows 替换 PE、Linux 替换 ELF、Android 下发 APK 并拉起系统安装器(尚未真机验收);macOS 客户端没有 `COMMAND_UPDATE` 分支,暂不支持自升级。
|
||||||
|
- 自启动:Windows 安装为系统服务;Linux 注册 XDG autostart(`install.sh`,另有 `-d` 守护进程模式);macOS 添加登录项;Android 为前台服务,但清单里没有 BOOT_COMPLETED 接收器,重启设备后需手动启动一次。
|
||||||
|
- 远程卸载:Linux/macOS 仅提供本地 `uninstall.sh`,服务端命令不会被处理。
|
||||||
|
- 授权/许可:V2 授权校验、服务端「延长授权/撤销授权」只对 Windows 客户端生效;其他平台不参与授权校验。
|
||||||
|
|
||||||
|
## 七、平台前提与已知边界
|
||||||
|
|
||||||
|
- **Windows**:功能最全;能力位未声明的终端、进程、聊天等功能实际已实现(服务端历史上按平台名放行)。
|
||||||
|
- **Linux**:抓屏与注入依赖 X11/XTest;Wayland 会话下抓屏不可用。安装脚本要求以普通桌面用户运行,以注册 autostart。
|
||||||
|
- **macOS**:屏幕录制与辅助功能需要用户在“隐私与安全性”里授权;更新二进制会导致授权失效,需要重新授权。自升级未实现。
|
||||||
|
- **Android**:屏幕预览/注入依赖无障碍服务;进程管理依赖 root;文件管理依赖全盘访问权限(MANAGE_EXTERNAL_STORAGE);远程摄像头、音频、锁屏、黑屏遮罩需相应系统权限或 API 级别;APK 在线升级已编码但尚未真机验收。
|
||||||
|
|
||||||
|
## 八、能力位对照(登录上报)
|
||||||
|
|
||||||
|
服务端从 `moduleVersion` 的 `-XXXX` 后缀解析能力位(`DefaultCaps()`):
|
||||||
|
|
||||||
|
| 平台 | 默认能力位 | 运行时追加 |
|
||||||
|
|---|---|---|
|
||||||
|
| Windows | V2、UTF8、SCREEN_PREVIEW、C2C_PATHS、PROTO_SWITCH、VIRTUAL_DESKTOP、WINDOW_INFO、SCREEN_REGION | 仅当本次连接走 TLS 且使用内嵌锚时追加 EMBEDDED_ANCHOR |
|
||||||
|
| Linux | V2、UTF8、C2C_RECV_ACK、PROCESS | SCREEN_PREVIEW(有可抓 X11 桌面时) |
|
||||||
|
| macOS | V2、UTF8、TERMINAL、SCREEN_CLIPBOARD、PROCESS、C2C_RECV_ACK | SCREEN_PREVIEW(已授录屏权限时) |
|
||||||
|
| Android | V2、UTF8、APK_UPDATE、SCREEN_CLIPBOARD、UNINSTALL、REMOTE_CHAT、TERMINAL | SCREEN_PREVIEW、LOCK_SCREEN、PRIVACY_OVERLAY、PROCESS(按无障碍/API/root 状态) |
|
||||||
|
|
||||||
|
注意:Windows 的终端、进程、聊天、剪贴板、卸载等能力虽未在能力位中声明,但客户端实际实现并被服务端按平台放行;其他平台的能力位缺失会被服务端提前拒绝。
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# 生成客户端 MCP 工具(build_client)设计
|
||||||
|
|
||||||
|
> 2026-11-15。让模型把「生成一个连 1.2.3.4:443 的 Linux 客户端」这类需求直接落成
|
||||||
|
> 服务端本机上的一个客户端文件。实现在 `server/2015Remote/McpBuildClient.{h,cpp}`。
|
||||||
|
|
||||||
|
## 1. 定位
|
||||||
|
|
||||||
|
`build_client` 是**服务端本地工具**,不针对任何在线主机:
|
||||||
|
|
||||||
|
- 入参没有 `id`,平台门禁(`CheckToolPlatform`)因拿不到主机而直接放行;
|
||||||
|
- `kToolPlatforms` 仍登记为全平台(`win|lnx|mac|apk`),与其它服务端本地工具一致;
|
||||||
|
- 工具只读模板资源、写服务端本机文件,不向任何客户端下发命令。
|
||||||
|
|
||||||
|
它复用「生成服务端」对话框(`BuildDlg.cpp::CBuildDlg::OnBnClickedOk`)的字节搬运路径:
|
||||||
|
|
||||||
|
```
|
||||||
|
读资源(res 目录优先,回退内嵌)
|
||||||
|
→ 构造 CONNECT_ADDRESS(地址/端口/类型/启动方式/分组/安装目录/主控 ID/pwdHash)
|
||||||
|
→ 模板发布日期校验(模板比主控新则拒绝)
|
||||||
|
→ 原地覆盖所有 FLAG_FINDEN 命中处
|
||||||
|
→ 内嵌 TLS 信任锚(在 UPX / 增肥之前)
|
||||||
|
→ 落盘
|
||||||
|
→ 可选 UPX / 增肥
|
||||||
|
```
|
||||||
|
|
||||||
|
对话框专属的 ShellCode AES / PE→ShellCode / 载荷伪装流程(需要额外的载荷文件与
|
||||||
|
图片容器)**不在本工具范围内**:传 `compress` 其他值会返回 `-32602` 并提示改用对话框。
|
||||||
|
|
||||||
|
## 2. 开关与错误码
|
||||||
|
|
||||||
|
| 条件 | 行为 |
|
||||||
|
|---|---|
|
||||||
|
| `McpBuild=1` 且 `McpReadonly=0` | 工具出现在 `tools/list`,可调用 |
|
||||||
|
| `McpBuild=0` | 不出现;直接调用返回 `-32006` |
|
||||||
|
| `McpReadonly=1` | 工具出现但调用返回 `-32006`(与 `host_set_remark` / `host_set_watch_level` 这类只改服务端本地数据的工具一致:列出、调用时拒绝) |
|
||||||
|
|
||||||
|
`McpBuild` 默认 `0`,改动需重启服务端生效。之所以不复用 `McpManage` / `McpFileWrite`:
|
||||||
|
生成的是**带主控凭据、可分发的客户端二进制**,风险等级与「操作在线主机」不同,需要能
|
||||||
|
单独关掉。工具同时要求只读模式关闭。
|
||||||
|
|
||||||
|
参数错误统一 `-32602`;文件已存在且 `overwrite=false`、输出路径是目录返回 `-32012`;
|
||||||
|
模板缺失 / 模板比主控新 / 找不到 `CONNECT_ADDRESS` / 写盘或 UPX 失败返回 `-32001`。
|
||||||
|
|
||||||
|
## 3. 参数
|
||||||
|
|
||||||
|
| 参数 | 必填 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `target` | 是 | `ghost` / `ghost_service` / `ghost_system` / `testrun_dll` / `testrun_memdll` / `testrun_injsc` / `testrun_service` / `testrun_system` / `serverdll` / `tinyrun` / `linux` / `macos` / `android` |
|
||||||
|
| `arch` | 否 | `x64`(默认)/ `x86`;posix 固定架构,传 `x86` 返回 `-32602`;`testrun_injsc` 只支持 x64 |
|
||||||
|
| `host` | 否 | 主控地址,可含分号分隔的多地址;省略取服务端当前有效主控地址(含上级 FRP) |
|
||||||
|
| `port` | 否 | 省略取服务端当前有效端口 |
|
||||||
|
| `protocol` | 否 | `tcp`(默认)/ `udp` / `http` / `random` / `kcp` / `ws` / `wss` |
|
||||||
|
| `header_enc` | 否 | `hell`(默认)/ `shine` |
|
||||||
|
| `running` | 否 | `random`(默认)/ `parallel` |
|
||||||
|
| `group` | 否 | 分组名,≤23 字节 ANSI |
|
||||||
|
| `install_location` | 否 | `programdata`(默认)/ `programfiles` / `systemroot` / `appdata` / `localappdata` |
|
||||||
|
| `install_dir` / `install_name` | 否 | Windows 安装子目录/程序名,≤31 字节,按 Windows 文件名规则校验 |
|
||||||
|
| `run_as_admin` | 否 | 默认 `false`;安装 Windows 服务时通常需要 |
|
||||||
|
| `encrypt_address` | 否 | 默认 `true`;`testrun_injsc` 与 `tinyrun` 与对话框一致,不加密 |
|
||||||
|
| `compress` | 否 | `none`(默认)/ `upx`;仅 Windows 目标 |
|
||||||
|
| `tls_anchor` | 否 | 默认 `true`;见 §4 |
|
||||||
|
| `padding_mb` | 否 | 0–256,仅 Windows 目标 |
|
||||||
|
| `output_dir` | 否 | 默认主控程序目录;不存在会自动创建 |
|
||||||
|
| `output_name` | 否 | 默认按 target 取 `ghost.exe` / `TestRun.exe` / `ServerDll.dll` / `TinyRun.dll` / `ghost` / `ghost.apk` |
|
||||||
|
| `overwrite` | 否 | 默认 `false`;目标已存在时返回 `-32012`,确认后传 `true` 重试 |
|
||||||
|
|
||||||
|
字符串入参按 UTF-8 接收,落到 ANSI 结构体/路径前用 `Utf8ToCpExact` 严格转换;
|
||||||
|
服务端代码页表示不了的字符直接拒绝,不用 `?` 顶替(否则会写出路径或分组名都不对的
|
||||||
|
客户端)。
|
||||||
|
|
||||||
|
## 4. 内嵌 TLS 信任锚
|
||||||
|
|
||||||
|
只有 `ghost` / `ghost_service` / `ghost_system` / `serverdll` 的 Windows 模板里有
|
||||||
|
`EmbeddedTlsAnchor` 块(`client/EmbeddedTlsAnchor.cpp`)。工具按以下顺序判定,
|
||||||
|
结果写入 `tlsAnchor`:
|
||||||
|
|
||||||
|
| 状态 | 含义 |
|
||||||
|
|---|---|
|
||||||
|
| `disabled` | 入参 `tls_anchor=false` |
|
||||||
|
| `not_applicable` | TestRun / TinyRun:模板不含客户端代码(TestRun 的锚要生成进 ServerDll.dll) |
|
||||||
|
| `unsupported_platform` | Linux / macOS / Android 模板没有锚块,信任锚由主控在线下发 |
|
||||||
|
| `skipped_protocol` | 协议不是 tcp/http(ws/wss 的锚是反代那张证书) |
|
||||||
|
| `unavailable` | 服务端未启用可用 TLS 身份 |
|
||||||
|
| `no_block` | 模板里没有锚块(资源未重编),按普通客户端生成,不视为失败 |
|
||||||
|
| `embedded` | 已写入;`tlsAnchorSummary` 给出证书摘要 |
|
||||||
|
|
||||||
|
与对话框一致:`Ambiguous` / `TooLong` / `NoAnchor` 会中止生成(`-32001`),
|
||||||
|
`NoBlock` 只提示;锚必须在 UPX / 增肥之前写入。
|
||||||
|
|
||||||
|
## 5. 其它行为
|
||||||
|
|
||||||
|
- **版本校验**:模板 `szBuildDate` 比主控 `DLL_VERSION` 新时拒绝生成。
|
||||||
|
- **输出覆盖**:默认拒绝覆盖;`overwrite=true` 时才写。输出文件名不允许包含目录分隔符。
|
||||||
|
- **并发**:模块内用 `std::mutex` 串行化。`ReleaseUPX()` 固定把 `upx.exe` 释放到服务端
|
||||||
|
目录,两个并发生成会互相踩;串行化同时避免同一输出文件的写竞争。
|
||||||
|
- **审计**:每次成功/失败写一行 `[MCP] build_client ...` 到服务端日志(路径、目标、字节数)。
|
||||||
|
- **结果 tips**:KCP 需要主控 UDP 参数为 1、WS/WSS 需要反代、macOS 需 `install.sh`/codesign、
|
||||||
|
Android 需 apksigner、TestRun 需要 ServerDll.dll、锚未内嵌等。
|
||||||
|
- **UPX 失败**:返回 `-32001`,未压缩的文件保留在原路径(与对话框一致)。
|
||||||
|
|
||||||
|
## 6. 「生成服务端」对话框的联动改进
|
||||||
|
|
||||||
|
同一批改动还修了对话框里几个平台联动问题(`BuildDlg.cpp`):
|
||||||
|
|
||||||
|
1. 选 Linux / macOS / Android 时,「安装目录」下拉框(`IDC_COMBO_INSTALL_LOC`)及其
|
||||||
|
标签(`IDC_STATIC_LOCATION`)现在与安装目录/程序名一起置灰。此前它们不在禁用清单里,
|
||||||
|
看起来仍可设置,但生成时根本不会被使用。
|
||||||
|
2. 运行模式(`IDC_COMBO_RUNTYPE`)对非 Windows 客户端无意义(`runningType` 只有
|
||||||
|
Windows `ClientDll` 消费),一并置灰。
|
||||||
|
3. 加壳选择切到非 Windows 目标时暂存并显示「无」,切回 Windows 时恢复;避免
|
||||||
|
「控件置灰但显示 ShellCode AES」与实际生成结果(强制 NONE)不一致。
|
||||||
|
4. 载荷类型 / 下载服务几行在非 Windows 目标下隐藏,而不是留下置灰的空行。
|
||||||
|
5. 「随机名称」「以管理员权限运行」两个菜单项在非 Windows 目标下置灰。
|
||||||
|
6. 内嵌 TLS 锚复选框的文案对 Linux/macOS/Android 改为「仅Windows客户端模板支持」,
|
||||||
|
不再误报「该目标不含客户端」。
|
||||||
|
|
||||||
|
## 7. 验收记录(2026-11-15,Debug 实例)
|
||||||
|
|
||||||
|
- `tools/list` 出现 `build_client`(`McpBuild=1`),关闭开关时不出现、直接调用 `-32006`。
|
||||||
|
- Linux:生成 10,285,456 字节,`tlsAnchor=unsupported_platform`;`encrypt_address=false`
|
||||||
|
时二进制里能检索到明文 host/port/分组/安装目录,原 `FLAG_FINDEN` 命中数归零。
|
||||||
|
- ghost x64:`tlsAnchor=embedded`;生成的 PE 被本机 Defender 隔离,属测试环境现象。
|
||||||
|
- Android:生成 11,929,218 字节,`tlsAnchor=unsupported_platform`,tips 提示重签。
|
||||||
|
- `arch=x86` + Linux、`testrun_injsc` + x86、未知 target、非字符串 target、显式但解析不出
|
||||||
|
的 `port`(如 `"443 "`)均返回 `-32602`;同名文件不传 `overwrite` 返回 `-32012`,
|
||||||
|
传 `true` 后 `overwritten=true`。
|
||||||
|
- 保护主控自身文件:`output_dir=Bin` + `output_name=Yama_x64d.exe` + `overwrite=true`
|
||||||
|
返回 `-32012`,不会覆盖运行中的服务端;`settings.ini` / `upx.exe` 同样受保护。
|
||||||
|
- 省略 `group` 时与对话框一致写入 `default`;`protocol` 允许数字形式(5 → ws)。
|
||||||
|
- `padding_mb=3` 的 TinyRun 产物比模板大 3 MB(分块追加,不一次性分配 256 MB);
|
||||||
|
`compress=upx` 因 Defender 拒绝读取生成的 PE 而返回 `-32001`(UPX 自身报
|
||||||
|
`IOException: Invalid argument`),错误路径符合预期;UPX 临时文件按
|
||||||
|
`upx_mcp_<pid>_<tick>.exe` 释放,测后无残留,也不会与对话框的固定 `upx.exe` 抢文件。
|
||||||
|
- `mcp/tools.json` 已用 Debug 实例的 `McpMachine=1` / `McpMachine=0` 两份抓取重新生成
|
||||||
|
(55 个工具),`check_platform_table.py` PASS。
|
||||||
@@ -263,6 +263,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
|
|||||||
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
|
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
|
||||||
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
||||||
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
||||||
|
| `McpBuild` | `0` | 生成客户端工具 `build_client` 的独立开关(见 §25);另要求 `McpReadonly=0`,改动需重启生效 |
|
||||||
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
|
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
|
||||||
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
|
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
|
||||||
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
|
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
|
||||||
@@ -1352,3 +1353,22 @@ macOS 客户端此前有大量「实现了但服务端不认」的功能,断
|
|||||||
- `remote_open` 仍拒绝 `MAC`(屏幕/注入链路的 macOS 实机验证还没做),本批不动。
|
- `remote_open` 仍拒绝 `MAC`(屏幕/注入链路的 macOS 实机验证还没做),本批不动。
|
||||||
- `mcp/tools.json` 是生成物(`tools/mcp_tools/`),平台表变更后要用跑起来的服务端
|
- `mcp/tools.json` 是生成物(`tools/mcp_tools/`),平台表变更后要用跑起来的服务端
|
||||||
重新生成。
|
重新生成。
|
||||||
|
|
||||||
|
## 25. 增补(2026-11-15:生成客户端工具 `build_client`)
|
||||||
|
|
||||||
|
服务端本地工具:按本主控的上线配置 patch 客户端模板(ghost / TestRun / ServerDll /
|
||||||
|
TinyRun / Linux / macOS / Android)并落盘,不针对任何在线主机。入参没有 `id`,平台
|
||||||
|
门禁直接放行;`kToolPlatforms` 登记为全平台。
|
||||||
|
|
||||||
|
- 独立开关 `McpBuild`(默认 `0`),并额外要求 `McpReadonly=0`。它写出的是带主控
|
||||||
|
凭据、可分发的客户端二进制,风险等级与「操作在线主机」不同,因此不复用
|
||||||
|
`McpManage` / `McpFileWrite`。
|
||||||
|
- 与「生成服务端」对话框共用同一套字节搬运路径:CONNECT_ADDRESS 原地覆盖、版本日期
|
||||||
|
校验、内嵌 TLS 锚(在 UPX / 增肥之前)。ShellCode AES / PE→ShellCode / 载荷伪装
|
||||||
|
仍只能在对话框里做。
|
||||||
|
- 默认拒绝覆盖同名文件(`overwrite=true` 才覆盖);默认 `encrypt_address=true`,
|
||||||
|
`testrun_injsc` / `tinyrun` 与对话框一致不加密。
|
||||||
|
- 生成逻辑在 `server/2015Remote/McpBuildClient.{h,cpp}`;完整参数、TLS 锚状态表、
|
||||||
|
错误码、对话框联动改进与验收记录见 `docs/Mcp_BuildClient_Design.md`。
|
||||||
|
- 同批改动:选 Linux/macOS/Android 时「安装目录」下拉框/标签、运行模式一并置灰,
|
||||||
|
载荷/下载服务行隐藏,随机名称/管理员权限菜单项置灰(`BuildDlg.cpp`)。
|
||||||
@@ -35,9 +35,15 @@ set(SOURCES
|
|||||||
add_executable(ghost ${SOURCES})
|
add_executable(ghost ${SOURCES})
|
||||||
|
|
||||||
|
|
||||||
# 设置为可以调试
|
# 默认使用 Release:无调试信息、-O3,链接时剥离符号表(ghost 约 2.5MB);
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
|
# 需要 gdb 调试时用:cmake -DCMAKE_BUILD_TYPE=Debug . && make
|
||||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g")
|
if(NOT CMAKE_BUILD_TYPE)
|
||||||
|
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# 注意:这里不要再往 CMAKE_CXX_FLAGS 里塞 -g,否则 Release 也会带上 DWARF
|
||||||
|
# (ghost 会涨到 10MB 以上,其中 75% 是 .debug_* 段)。
|
||||||
|
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-s>)
|
||||||
|
|
||||||
# 链接 ZSTD 库
|
# 链接 ZSTD 库
|
||||||
message(STATUS "链接库文件: ${CMAKE_SOURCE_DIR}/lib/libzstd.a")
|
message(STATUS "链接库文件: ${CMAKE_SOURCE_DIR}/lib/libzstd.a")
|
||||||
|
|||||||
+18
-8
@@ -30,7 +30,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
|
|||||||
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
|
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
|
||||||
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
|
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
|
||||||
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
|
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
|
||||||
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,下发后立即另起一条连接,主连接重连时生效;到期自动回原主控并收掉那条连接) |
|
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,**真的转移**:收包后立刻断开原主控、主连接连到新主控,旧主控上这台主机随即离线;新主控可正常远控/升级,但不能再转移或分享它;到期自动回原主控) |
|
||||||
| 主机分享 | `common/host_share.h` + main.cpp | `KernelManager.cpp` / `ClientDll.cpp` | ✅ 完整(每条分享记录 fork 一个 `--share` 子进程,主连接不受影响;取消分享立即断开,重启自动恢复) |
|
| 主机分享 | `common/host_share.h` + main.cpp | `KernelManager.cpp` / `ClientDll.cpp` | ✅ 完整(每条分享记录 fork 一个 `--share` 子进程,主连接不受影响;取消分享立即断开,重启自动恢复) |
|
||||||
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
|
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
|
||||||
| MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) |
|
| MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) |
|
||||||
@@ -140,6 +140,14 @@ make -j$(nproc)
|
|||||||
|
|
||||||
编译成功后生成可执行文件 `ghost`。
|
编译成功后生成可执行文件 `ghost`。
|
||||||
|
|
||||||
|
默认按 Release 构建(`-O3`,链接时 `-s` 剥离符号表,产物约 2.5MB,不含调试信息)。
|
||||||
|
需要 gdb 调试或保留 DWARF 时改用:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cmake -DCMAKE_BUILD_TYPE=Debug . # -g(未优化)
|
||||||
|
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo . # -O2 -g -DNDEBUG
|
||||||
|
```
|
||||||
|
|
||||||
## 使用方法
|
## 使用方法
|
||||||
|
|
||||||
### 基本用法
|
### 基本用法
|
||||||
@@ -219,21 +227,23 @@ Windows 客户端的同名命令没有摘要(走内存加载器/更新器)
|
|||||||
服务端选中一台主机后点「转移主机」,选目标主控和有效天数,客户端会:
|
服务端选中一台主机后点「转移主机」,选目标主控和有效天数,客户端会:
|
||||||
|
|
||||||
1. 把目标写进 `~/.config/ghost/config.conf` 的 `transfer` 键(`ip:port:transport:shine:valid_to`);
|
1. 把目标写进 `~/.config/ghost/config.conf` 的 `transfer` 键(`ip:port:transport:shine:valid_to`);
|
||||||
2. **立即另起一条通往新主控的连接**(与分享同一个 fork+exec 机制),新主控马上就能看到
|
2. **立刻断开当前主控**,主连接改连新主控——转移是把这条主连接搬走,不是另开一条。
|
||||||
这台主机上线;它与老主控之间的主连接原样保留,不会断开;
|
老主控上这台主机随即离线,`--share` 那种旁路连接在这里是不对的:新主控拿到的
|
||||||
3. 下一次重连(断线重连、客户端重启)时主连接才搬到新主控,那条临时连接随之消失;
|
会是一条不能升级、也不真正属于它的连接;
|
||||||
|
3. 新主控从此可以像自己的主机一样操作它:远控、文件、终端、**升级程序**都正常;
|
||||||
4. 过了有效天数自动回到转移前的原主控——原地址只记在内存里(启动参数或编译期默认),
|
4. 过了有效天数自动回到转移前的原主控——原地址只记在内存里(启动参数或编译期默认),
|
||||||
不写回配置,所以重启后仍然有效;到期时那条临时连接一并收掉。
|
不写回配置,所以重启后仍然有效;到期时按原地址重连。
|
||||||
|
|
||||||
第 2 步与 Windows 客户端现有的实际行为一致(`KernelManager.cpp` 的转移分支会贯穿到分享
|
转移期间(`now <= valid_to`)客户端会拒绝两件事:**再次转移**和**分享**。前者是为了防止
|
||||||
分支、额外起一个 shared 实例);差别只在到期处理:Windows 那条连接要等进程重启才消失。
|
主机被 B 转到 C、到期却按 A 复原,中间那一跳成为谁也不认的孤儿;后者是因为主机此刻只
|
||||||
|
连着新主控,新主控无权再把它分出去。两条都会回一条消息进服务端消息栏,不会静默丢弃。
|
||||||
|
|
||||||
注意事项:
|
注意事项:
|
||||||
|
|
||||||
- 目标是永久转移(天数填 0)时客户端会拒绝,避免把主机改到一个不可达的地址后无法回退;
|
- 目标是永久转移(天数填 0)时客户端会拒绝,避免把主机改到一个不可达的地址后无法回退;
|
||||||
- 有效期内重复下发会被忽略(与 Windows 客户端一致);
|
- 有效期内重复下发会被忽略(与 Windows 客户端一致);
|
||||||
- 转移期间切换传输方式(明文 / WS / WSS)会跟随服务端下发的 `transport` 段;
|
- 转移期间切换传输方式(明文 / WS / WSS)会跟随服务端下发的 `transport` 段;
|
||||||
- 「取消分享」不会影响转移建立的临时连接;
|
- 「取消分享」只收掉分享子进程,撤销不了转移;
|
||||||
- 只想把主机要回来,直接把 `transfer` 键清空并重启客户端即可。
|
- 只想把主机要回来,直接把 `transfer` 键清空并重启客户端即可。
|
||||||
|
|
||||||
## 主机分享
|
## 主机分享
|
||||||
|
|||||||
+69
-116
@@ -53,15 +53,10 @@
|
|||||||
|
|
||||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
|
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
|
||||||
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
|
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
|
||||||
// 主机分享/转移的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)
|
// 主机分享的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)。
|
||||||
// 分享子进程与转移子进程都走同一套 fork+exec 管理,只是归属不同:
|
// 转移不在这里:转移是主连接自己换地址(见下面的 g_needReconnect),不起子进程。
|
||||||
// KIND_SHARE 「取消分享」只停这些
|
|
||||||
// KIND_TRANSFER 转移到期时停这些(提前建立的那条连接)
|
|
||||||
// KIND_ALL 主实例退出时全停
|
|
||||||
enum ManagedKind { KIND_SHARE, KIND_TRANSFER, KIND_ALL };
|
|
||||||
static bool StartShareInstance(const std::string& entry);
|
static bool StartShareInstance(const std::string& entry);
|
||||||
static bool StartTransferInstance(const std::string& entry);
|
static void StopChildren();
|
||||||
static void StopChildren(ManagedKind kind);
|
|
||||||
static void StartShareInstancesFromConfig();
|
static void StartShareInstancesFromConfig();
|
||||||
|
|
||||||
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
||||||
@@ -76,8 +71,9 @@ static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重
|
|||||||
static std::atomic<bool> g_needReconnect(false);
|
static std::atomic<bool> g_needReconnect(false);
|
||||||
|
|
||||||
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
|
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
|
||||||
// 服务端「转移主机」把目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;
|
// 转移 = 主连接真的搬到新主控:收包后立刻断开当前主控、连到目标,旧主控上这台主机
|
||||||
// valid_to 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
|
// 随即离线。目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;valid_to
|
||||||
|
// 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
|
||||||
// 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。
|
// 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。
|
||||||
// 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。
|
// 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。
|
||||||
static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用
|
static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用
|
||||||
@@ -96,14 +92,11 @@ static bool g_bShareInstance = false; // 本进程是分享子
|
|||||||
static std::mutex g_shareMu; // 保护 g_shareProcs
|
static std::mutex g_shareMu; // 保护 g_shareProcs
|
||||||
// 子进程 pid 和它启动时用的那条记录:判断「同一条分享」只能比这条记录,不能比配置
|
// 子进程 pid 和它启动时用的那条记录:判断「同一条分享」只能比这条记录,不能比配置
|
||||||
// 里的——命令处理是先写配置再起进程,配置里已经是新记录了。
|
// 里的——命令处理是先写配置再起进程,配置里已经是新记录了。
|
||||||
// transfer=true 表示这是「转移主机」立即建立的那条连接(见 StartTransferInstance),
|
|
||||||
// 它不进 share_list、不受「取消分享」影响。
|
|
||||||
struct ShareProc {
|
struct ShareProc {
|
||||||
pid_t pid;
|
pid_t pid;
|
||||||
std::string entry;
|
std::string entry;
|
||||||
bool transfer;
|
|
||||||
};
|
};
|
||||||
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" / "transfer:ip:port" -> 子进程
|
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" -> 子进程
|
||||||
// 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。
|
// 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。
|
||||||
static const size_t kMaxShareEntries = 16;
|
static const size_t kMaxShareEntries = 16;
|
||||||
static std::atomic<bool> g_shareReaperStop(false);
|
static std::atomic<bool> g_shareReaperStop(false);
|
||||||
@@ -574,8 +567,8 @@ static void InitTransferState()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有
|
// 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有
|
||||||
// 跨线程同步,ConnectServer 读的就是它。只改地址、不主动断开——与 Windows 一致,
|
// 跨线程同步,ConnectServer 读的就是它。收包时已经置了 g_needReconnect,心跳循环
|
||||||
// 下一次重连才生效。
|
// 会立刻断开重连,所以这里的地址在下一秒就生效——不是「等下次自然重连」。
|
||||||
static void ApplyPendingTransfer()
|
static void ApplyPendingTransfer()
|
||||||
{
|
{
|
||||||
if (!g_transferPending.load(std::memory_order_acquire))
|
if (!g_transferPending.load(std::memory_order_acquire))
|
||||||
@@ -588,7 +581,7 @@ static void ApplyPendingTransfer()
|
|||||||
}
|
}
|
||||||
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||||
long long left = t.validTo - (long long)time(nullptr);
|
long long left = t.validTo - (long long)time(nullptr);
|
||||||
Mprintf(">>> Transfer armed: next reconnect -> %s:%d (transport=%d), %llds left\n",
|
Mprintf(">>> Transfer applied: -> %s:%d (transport=%d), %llds left\n",
|
||||||
t.ep.ip.c_str(), t.ep.port, t.ep.transport, left);
|
t.ep.ip.c_str(), t.ep.port, t.ep.transport, left);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -606,8 +599,6 @@ static void CheckTransferExpiry()
|
|||||||
g_needReconnect.store(true, std::memory_order_relaxed);
|
g_needReconnect.store(true, std::memory_order_relaxed);
|
||||||
Mprintf(">>> Transfer expired: restoring %s:%d\n",
|
Mprintf(">>> Transfer expired: restoring %s:%d\n",
|
||||||
g_transferOrig.ip.c_str(), g_transferOrig.port);
|
g_transferOrig.ip.c_str(), g_transferOrig.port);
|
||||||
// 转移时提前建立的那条连接也要收掉,否则过期后主机仍挂在新主控上。
|
|
||||||
StopChildren(KIND_TRANSFER);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
||||||
@@ -861,6 +852,14 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
|||||||
Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user);
|
Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user);
|
||||||
return TRUE;
|
return TRUE;
|
||||||
}
|
}
|
||||||
|
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
|
||||||
|
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
|
||||||
|
// 一条谁也不认的链路。
|
||||||
|
if ((long long)time(nullptr) <= g_transferValidTo.load(std::memory_order_relaxed)) {
|
||||||
|
Mprintf("** [%p] SHARE ignored: host is transferred until %lld ***\n",
|
||||||
|
user, g_transferValidTo.load(std::memory_order_relaxed));
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
HostShare::Endpoint ep;
|
HostShare::Endpoint ep;
|
||||||
if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) {
|
if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) {
|
||||||
Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user);
|
Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user);
|
||||||
@@ -898,10 +897,19 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
|||||||
}
|
}
|
||||||
// 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。
|
// 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。
|
||||||
// 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。
|
// 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。
|
||||||
|
// 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后只连着 B,B 发来的
|
||||||
|
// 转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的那一台)还有
|
||||||
|
// 机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控复原,
|
||||||
|
// 中间那一跳就成了谁也不认的孤儿。
|
||||||
long long active = g_transferValidTo.load(std::memory_order_relaxed);
|
long long active = g_transferValidTo.load(std::memory_order_relaxed);
|
||||||
if (now <= active) {
|
if (now <= active) {
|
||||||
Mprintf("** [%p] ASSIGN to %s:%d ignored: already assigned until %lld ***\n",
|
Mprintf("** [%p] ASSIGN to %s:%d ignored: already assigned until %lld ***\n",
|
||||||
user, t.ep.ip.c_str(), t.ep.port, active);
|
user, t.ep.ip.c_str(), t.ep.port, active);
|
||||||
|
// 主控那边点完看不到任何反馈会以为下发丢了,回一条消息进消息栏。
|
||||||
|
if (g_pMainClient && g_pMainClient->IsConnected()) {
|
||||||
|
ClientMsg msg("Transfer host", "Host is already transferred, ignored");
|
||||||
|
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
|
||||||
|
}
|
||||||
return TRUE;
|
return TRUE;
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
@@ -913,17 +921,18 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
|||||||
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
||||||
LinuxConfig cfg;
|
LinuxConfig cfg;
|
||||||
cfg.SetStr("transfer", HostTransfer::EncodeRecord(t));
|
cfg.SetStr("transfer", HostTransfer::EncodeRecord(t));
|
||||||
// 立即再起一条通往新主控的连接,新主控马上就能看到这台主机上线;本实例与老主控
|
// 真转移:断掉当前主控,主连接立刻连到新主控,旧主控上这台主机随即离线。
|
||||||
// 的主连接原样保留,下次重连(含重启)才轮到主连接过去。这与 Windows 客户端
|
// 不能另起一条临时连接——那只是「分享」,新主控拿到的是一条不能升级、
|
||||||
// 现有语义一致:KernelManager 的转移分支末尾没有 break,会贯穿到分享分支,
|
// 也不真正属于它的旁路连接(升级命令按设计只认主连接)。
|
||||||
// 额外起一个 shared 实例连到同一个目标地址。
|
// 目标由主线程的 ApplyPendingTransfer 落到 g_SETTINGS,本标志让它马上重连。
|
||||||
Mprintf("** [%p] ASSIGN to %s:%d for %llds, main link moves on next reconnect ***\n",
|
g_needReconnect.store(true, std::memory_order_relaxed);
|
||||||
|
Mprintf("** [%p] ASSIGN to %s:%d for %llds, moving the main link now ***\n",
|
||||||
user, t.ep.ip.c_str(), t.ep.port, t.validTo - now);
|
user, t.ep.ip.c_str(), t.ep.port, t.validTo - now);
|
||||||
StartTransferInstance(HostShare::EncodeEntry(t.ep)); // 新主控立即看到上线
|
|
||||||
} else if (szBuffer[0] == COMMAND_SHARE_CANCEL) {
|
} else if (szBuffer[0] == COMMAND_SHARE_CANCEL) {
|
||||||
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 那边是同一进程里
|
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 客户端在
|
||||||
// 的线程,取消只改配置、下次启动才生效;Linux 的分享实例本来就是独立进程,
|
// COMMAND_SHARE_CANCEL 里也改成停掉同进程的分享线程(StopSharedInstances),
|
||||||
// 可以立即断开。
|
// 两端都是立即断开;Linux 的分享实例是独立进程,直接 stop。转移不涉及子进程,
|
||||||
|
// 取消分享自然也撤销不了转移。
|
||||||
if (g_bShareInstance) {
|
if (g_bShareInstance) {
|
||||||
Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user);
|
Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user);
|
||||||
return TRUE;
|
return TRUE;
|
||||||
@@ -931,7 +940,7 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
|||||||
LinuxConfig cfg;
|
LinuxConfig cfg;
|
||||||
cfg.SetStr("share_list", "");
|
cfg.SetStr("share_list", "");
|
||||||
Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user);
|
Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user);
|
||||||
StopChildren(KIND_SHARE);
|
StopChildren();
|
||||||
} else if (szBuffer[0] == COMMAND_UPDATE) {
|
} else if (szBuffer[0] == COMMAND_UPDATE) {
|
||||||
// 服务端"升级程序"菜单下发新版本 ELF。
|
// 服务端"升级程序"菜单下发新版本 ELF。
|
||||||
// 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换
|
// 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换
|
||||||
@@ -1315,15 +1324,14 @@ static void ShareReaperLoop()
|
|||||||
int st = 0;
|
int st = 0;
|
||||||
pid_t r = waitpid(it->second.pid, &st, WNOHANG);
|
pid_t r = waitpid(it->second.pid, &st, WNOHANG);
|
||||||
if (r == it->second.pid) {
|
if (r == it->second.pid) {
|
||||||
const char* kind = it->second.transfer ? "Transfer instance" : "Share instance";
|
|
||||||
if (WIFEXITED(st))
|
if (WIFEXITED(st))
|
||||||
Mprintf(">>> %s %s exited (code %d)\n",
|
Mprintf(">>> Share instance %s exited (code %d)\n",
|
||||||
kind, it->first.c_str(), WEXITSTATUS(st));
|
it->first.c_str(), WEXITSTATUS(st));
|
||||||
else if (WIFSIGNALED(st))
|
else if (WIFSIGNALED(st))
|
||||||
Mprintf(">>> %s %s exited by signal %d\n",
|
Mprintf(">>> Share instance %s exited by signal %d\n",
|
||||||
kind, it->first.c_str(), WTERMSIG(st));
|
it->first.c_str(), WTERMSIG(st));
|
||||||
else
|
else
|
||||||
Mprintf(">>> %s %s exited\n", kind, it->first.c_str());
|
Mprintf(">>> Share instance %s exited\n", it->first.c_str());
|
||||||
it = g_shareProcs.erase(it);
|
it = g_shareProcs.erase(it);
|
||||||
} else if (r < 0 && errno == ECHILD) {
|
} else if (r < 0 && errno == ECHILD) {
|
||||||
it = g_shareProcs.erase(it); // 已被别处收走(防御)
|
it = g_shareProcs.erase(it); // 已被别处收走(防御)
|
||||||
@@ -1420,9 +1428,8 @@ static void TerminateChildLocked(pid_t pid)
|
|||||||
Mprintf(">>> Child pid %d still alive after SIGKILL, giving up on it\n", (int)pid);
|
Mprintf(">>> Child pid %d still alive after SIGKILL, giving up on it\n", (int)pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 起一个受管子进程并登记。key 在本进程内唯一:分享用 "ip:port",转移用 "transfer:ip:port",
|
// 起一个受管子进程并登记。key 是目标主控 "ip:port"。
|
||||||
// 这样转移目标与分享目标相同也不会互相顶掉。
|
static bool SpawnManagedChild(const std::string& key, const std::string& entry)
|
||||||
static bool SpawnManagedChild(const std::string& key, const std::string& entry, bool transfer)
|
|
||||||
{
|
{
|
||||||
EnsureShareReaper();
|
EnsureShareReaper();
|
||||||
|
|
||||||
@@ -1447,9 +1454,8 @@ static bool SpawnManagedChild(const std::string& key, const std::string& entry,
|
|||||||
pid_t pid = SpawnShareProcess(entry);
|
pid_t pid = SpawnShareProcess(entry);
|
||||||
if (pid <= 0)
|
if (pid <= 0)
|
||||||
return false;
|
return false;
|
||||||
g_shareProcs[key] = ShareProc{ pid, entry, transfer };
|
g_shareProcs[key] = ShareProc{ pid, entry };
|
||||||
Mprintf(">>> %s instance started: %s (pid %d)\n",
|
Mprintf(">>> Share instance started: %s (pid %d)\n", entry.c_str(), (int)pid);
|
||||||
transfer ? "Transfer" : "Share", entry.c_str(), (int)pid);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1459,61 +1465,19 @@ static bool StartShareInstance(const std::string& entry)
|
|||||||
if (!HostShare::DecodeEntry(entry, ep))
|
if (!HostShare::DecodeEntry(entry, ep))
|
||||||
return false;
|
return false;
|
||||||
const std::string shareKey = HostShare::MasterKey(ep);
|
const std::string shareKey = HostShare::MasterKey(ep);
|
||||||
{
|
return SpawnManagedChild(shareKey, entry);
|
||||||
// 同一主控上已有一条「转移」临时连接:分享是长期连接,接管它的职责。
|
|
||||||
// 不收掉的话,这个主控上会挂着同一 clientID 的两条连接,互踢。
|
|
||||||
const std::string transferKey = "transfer:" + shareKey;
|
|
||||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
|
||||||
auto it = g_shareProcs.find(transferKey);
|
|
||||||
if (it != g_shareProcs.end()) {
|
|
||||||
Mprintf(">>> Share to %s replaces the transfer instance (pid %d)\n",
|
|
||||||
shareKey.c_str(), (int)it->second.pid);
|
|
||||||
TerminateChildLocked(it->second.pid);
|
|
||||||
g_shareProcs.erase(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return SpawnManagedChild(shareKey, entry, false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 「转移主机」立即生效的那条连接:不进 share_list(重启后由主连接自己过去),
|
// 停掉所有子进程(分享实例;转移已不产生子进程):SIGTERM 让子进程走自己的
|
||||||
// 也不受「取消分享」影响;目标可以暂时不可达,子进程有自己的重连循环。
|
// signal handler 正常退出,3 秒还不走就 SIGKILL(再等 1 秒)。
|
||||||
static bool StartTransferInstance(const std::string& entry)
|
|
||||||
{
|
|
||||||
HostShare::Endpoint ep;
|
|
||||||
if (!HostShare::DecodeEntry(entry, ep))
|
|
||||||
return false;
|
|
||||||
const std::string shareKey = HostShare::MasterKey(ep);
|
|
||||||
{
|
|
||||||
// 同一个主控已经有分享连接时不必再起一条:目标那边已经能看到这台主机,
|
|
||||||
// 两条同 clientID 的连接只会互相踢。
|
|
||||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
|
||||||
auto it = g_shareProcs.find(shareKey);
|
|
||||||
if (it != g_shareProcs.end() && !it->second.transfer
|
|
||||||
&& ChildAliveLocked(it->second.pid)) {
|
|
||||||
Mprintf(">>> Transfer target %s already reachable via share instance "
|
|
||||||
"(pid %d), extra connection skipped\n",
|
|
||||||
shareKey.c_str(), (int)it->second.pid);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return SpawnManagedChild("transfer:" + shareKey, entry, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 停掉指定归属的子进程:SIGTERM 让子进程走自己的 signal handler 正常退出,
|
|
||||||
// 3 秒还不走就 SIGKILL(再等 1 秒)。
|
|
||||||
// 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。
|
// 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。
|
||||||
static void StopChildren(ManagedKind kind)
|
static void StopChildren()
|
||||||
{
|
{
|
||||||
auto match = [kind](const ShareProc& p) {
|
|
||||||
return kind == KIND_ALL || p.transfer == (kind == KIND_TRANSFER);
|
|
||||||
};
|
|
||||||
|
|
||||||
std::vector<pid_t> pids;
|
std::vector<pid_t> pids;
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
std::lock_guard<std::mutex> lk(g_shareMu);
|
||||||
for (auto& kv : g_shareProcs)
|
for (auto& kv : g_shareProcs)
|
||||||
if (match(kv.second))
|
pids.push_back(kv.second.pid);
|
||||||
pids.push_back(kv.second.pid);
|
|
||||||
for (pid_t pid : pids)
|
for (pid_t pid : pids)
|
||||||
kill(pid, SIGTERM); // 只发信号,不等待
|
kill(pid, SIGTERM); // 只发信号,不等待
|
||||||
}
|
}
|
||||||
@@ -1777,30 +1741,17 @@ static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
|
|||||||
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
||||||
static void RefreshLoginTls(LOGIN_INFOR& info)
|
static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||||
{
|
{
|
||||||
std::vector<std::string> fields;
|
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
|
||||||
std::string s(info.szReserved);
|
}
|
||||||
size_t pos = 0;
|
|
||||||
for (;;) {
|
|
||||||
size_t bar = s.find('|', pos);
|
|
||||||
if (bar == std::string::npos) {
|
|
||||||
fields.push_back(s.substr(pos));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
fields.push_back(s.substr(pos, bar - pos));
|
|
||||||
pos = bar + 1;
|
|
||||||
}
|
|
||||||
while (fields.size() <= (size_t)RES_TLS)
|
|
||||||
fields.push_back("");
|
|
||||||
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
|
|
||||||
|
|
||||||
std::string joined;
|
// 登录信息 szReserved 里的 [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端
|
||||||
for (size_t i = 0; i < fields.size(); ++i) {
|
// 再加本次上线时长才是当前运行时长。logInfo 在重连循环外只构造一次(见 main 里的注释),
|
||||||
if (i)
|
// 不刷新的话每次重连上报的仍是进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」——
|
||||||
joined += '|';
|
// vps 实测:进程从 11-14 06:33 一直跑着,浮窗却只显示 1.3h(正好是当天 09:05 那次重连到
|
||||||
joined += fields[i];
|
// 双击时刻的间隔),而启动时间本身是对的。与 RefreshLoginTls 同样只在主线程登录前调用。
|
||||||
}
|
static void RefreshLoginUptime(LOGIN_INFOR& info)
|
||||||
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
|
{
|
||||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||||
@@ -1890,6 +1841,9 @@ int main(int argc, char* argv[])
|
|||||||
char hostname[256] = {};
|
char hostname[256] = {};
|
||||||
gethostname(hostname, sizeof(hostname));
|
gethostname(hostname, sizeof(hostname));
|
||||||
|
|
||||||
|
// 只构造一次,每次连接复用它发登录。因此凡是「随连接变化」的字段都必须在发送前
|
||||||
|
// 用 RefreshLoginTls / RefreshLoginUptime / RefreshLoginCaps 刷新;反过来,属于
|
||||||
|
// 「进程启动时的事实」(szStartTime、clientID、安装时间…)就靠复用保持不变。
|
||||||
LOGIN_INFOR logInfo;
|
LOGIN_INFOR logInfo;
|
||||||
|
|
||||||
// 读取分组名称(从配置文件或 g_SETTINGS)
|
// 读取分组名称(从配置文件或 g_SETTINGS)
|
||||||
@@ -2051,15 +2005,13 @@ int main(int argc, char* argv[])
|
|||||||
Sleep(5000);
|
Sleep(5000);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一
|
|
||||||
// clientID 在这个主控上的第二条连接,服务端会互踢。
|
|
||||||
if (g_transferValidTo.load(std::memory_order_relaxed) > 0)
|
|
||||||
StopChildren(KIND_TRANSFER);
|
|
||||||
|
|
||||||
// 进入新连接,重置服务端身份校验状态
|
// 进入新连接,重置服务端身份校验状态
|
||||||
ClientAuth::OnNewConnection();
|
ClientAuth::OnNewConnection();
|
||||||
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
|
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
|
||||||
RefreshLoginTls(logInfo);
|
RefreshLoginTls(logInfo);
|
||||||
|
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
|
||||||
|
RefreshLoginUptime(logInfo);
|
||||||
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
|
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
|
||||||
RefreshLoginCaps(logInfo);
|
RefreshLoginCaps(logInfo);
|
||||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||||
@@ -2081,6 +2033,7 @@ int main(int argc, char* argv[])
|
|||||||
}
|
}
|
||||||
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
|
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
|
||||||
RefreshLoginTls(logInfo);
|
RefreshLoginTls(logInfo);
|
||||||
|
RefreshLoginUptime(logInfo);
|
||||||
RefreshLoginCaps(logInfo);
|
RefreshLoginCaps(logInfo);
|
||||||
ClientObject->SendLoginInfo(logInfo);
|
ClientObject->SendLoginInfo(logInfo);
|
||||||
Mprintf(">> Resent login info after group change\n");
|
Mprintf(">> Resent login info after group change\n");
|
||||||
@@ -2180,7 +2133,7 @@ int main(int argc, char* argv[])
|
|||||||
g_shareReaperStop.store(true, std::memory_order_relaxed);
|
g_shareReaperStop.store(true, std::memory_order_relaxed);
|
||||||
if (g_shareReaperThread.joinable())
|
if (g_shareReaperThread.joinable())
|
||||||
g_shareReaperThread.join();
|
g_shareReaperThread.join();
|
||||||
StopChildren(KIND_ALL);
|
StopChildren();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
|
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
|
||||||
|
|||||||
@@ -124,6 +124,11 @@ target_compile_options(ghost PRIVATE
|
|||||||
-fobjc-arc
|
-fobjc-arc
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Release 链接时删掉 local 符号(对应 Linux 那边的 -s;ld64 用 -x)。
|
||||||
|
# 只删 non-global 符号,external 符号保留,dyld 绑定不受影响;签名由 ld 在链接
|
||||||
|
# 末尾完成,所以改符号表不会让签名失效。ghost 目前 ~19k 个符号里 8.3k 是 local。
|
||||||
|
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-Wl,-x>)
|
||||||
|
|
||||||
# Output directory
|
# Output directory
|
||||||
set_target_properties(ghost PROPERTIES
|
set_target_properties(ghost PROPERTIES
|
||||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
||||||
|
|||||||
+327
-32
@@ -17,6 +17,7 @@
|
|||||||
#import <thread>
|
#import <thread>
|
||||||
#import <atomic>
|
#import <atomic>
|
||||||
#import <memory>
|
#import <memory>
|
||||||
|
#import <mutex>
|
||||||
#import <string>
|
#import <string>
|
||||||
#import <map>
|
#import <map>
|
||||||
#import <vector>
|
#import <vector>
|
||||||
@@ -29,6 +30,7 @@
|
|||||||
#include "../common/xxhash.h"
|
#include "../common/xxhash.h"
|
||||||
#include "../common/rtt_estimator.h"
|
#include "../common/rtt_estimator.h"
|
||||||
#include "../common/client_auth_state.h"
|
#include "../common/client_auth_state.h"
|
||||||
|
#include "../common/host_transfer.h" // 主机转移(COMMAND_ASSIGN_MASTER),与 Linux/Android 共用
|
||||||
#include "../common/posix_net_helpers.h"
|
#include "../common/posix_net_helpers.h"
|
||||||
#include "../common/sub_conn_thread.h"
|
#include "../common/sub_conn_thread.h"
|
||||||
#include "../common/ClientLogHandler.h"
|
#include "../common/ClientLogHandler.h"
|
||||||
@@ -82,6 +84,9 @@ State g_bExit = S_CLIENT_NORMAL;
|
|||||||
static std::string g_configDir;
|
static std::string g_configDir;
|
||||||
static std::string g_configPath;
|
static std::string g_configPath;
|
||||||
static std::map<std::string, std::string> g_configData;
|
static std::map<std::string, std::string> g_configData;
|
||||||
|
// 收包线程会写配置(分组变更、转移记录),主线程也会读/写(登录信息、到期清除),
|
||||||
|
// 而 g_configData 和整文件重写都不是线程安全的——所有访问都必须持有这把锁。
|
||||||
|
static std::mutex g_configMu;
|
||||||
|
|
||||||
// Initialize config paths
|
// Initialize config paths
|
||||||
static void initConfigPaths()
|
static void initConfigPaths()
|
||||||
@@ -112,6 +117,7 @@ static void mkdirRecursive(const std::string& path)
|
|||||||
// Load all config from file
|
// Load all config from file
|
||||||
static void loadConfig()
|
static void loadConfig()
|
||||||
{
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_configMu);
|
||||||
initConfigPaths();
|
initConfigPaths();
|
||||||
g_configData.clear();
|
g_configData.clear();
|
||||||
|
|
||||||
@@ -127,8 +133,8 @@ static void loadConfig()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save all config to file
|
// Save all config to file. 调用方必须持有 g_configMu(setConfigStr 已在锁内)。
|
||||||
static void saveConfig()
|
static void saveConfigLocked()
|
||||||
{
|
{
|
||||||
initConfigPaths();
|
initConfigPaths();
|
||||||
mkdirRecursive(g_configDir);
|
mkdirRecursive(g_configDir);
|
||||||
@@ -148,6 +154,7 @@ static void saveConfig()
|
|||||||
// Get config string value
|
// Get config string value
|
||||||
static std::string getConfigStr(const std::string& key, const std::string& def = "")
|
static std::string getConfigStr(const std::string& key, const std::string& def = "")
|
||||||
{
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_configMu);
|
||||||
auto it = g_configData.find(key);
|
auto it = g_configData.find(key);
|
||||||
return it != g_configData.end() ? it->second : def;
|
return it != g_configData.end() ? it->second : def;
|
||||||
}
|
}
|
||||||
@@ -155,8 +162,9 @@ static std::string getConfigStr(const std::string& key, const std::string& def =
|
|||||||
// Set config string value
|
// Set config string value
|
||||||
static void setConfigStr(const std::string& key, const std::string& value)
|
static void setConfigStr(const std::string& key, const std::string& value)
|
||||||
{
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_configMu);
|
||||||
g_configData[key] = value;
|
g_configData[key] = value;
|
||||||
saveConfig();
|
saveConfigLocked();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save group name to config file
|
// Save group name to config file
|
||||||
@@ -172,6 +180,175 @@ static std::string loadGroupName()
|
|||||||
return getConfigStr("group_name");
|
return getConfigStr("group_name");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============== 主机转移(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER)==============
|
||||||
|
// 服务端「转移主机」下发的载荷是 host:port:days:shine[:transport],解析与记录编解码在
|
||||||
|
// common/host_transfer.h(与 Linux/Android 共用)。收包线程只记「待应用」,地址切换
|
||||||
|
// 放在主连接线程——CONNECT_ADDRESS 不参与跨线程同步(同 linux/main.cpp 与 Android)。
|
||||||
|
// 语义与 Android 对齐:主连接立即搬到新主控;目标持续一分钟连不上就退回原主控;
|
||||||
|
// 新主控也能把主机「提前归还」(把到期时刻设成当时)。
|
||||||
|
// 原主控只存在内存里(启动时的地址),绝不写回配置——恢复时读到的若还是转移目标,
|
||||||
|
// 就成了原地打转。
|
||||||
|
static HostTransfer::Endpoint g_transferOrig;
|
||||||
|
static std::atomic<long long> g_transferValidTo(0); // >0 = 转移中(到期时刻)
|
||||||
|
static std::atomic<bool> g_transferPending(false); // 接收线程已写好新目标,待主线程应用
|
||||||
|
static std::atomic<bool> g_transferEndEarly(false); // true = 新主控提前归还,不是到期
|
||||||
|
static std::mutex g_transferMu;
|
||||||
|
static HostTransfer::Target g_transferPendingTarget;
|
||||||
|
static int g_transferFailStreak = 0; // 仅主连接线程访问,无需原子
|
||||||
|
static long long g_transferFailAt = 0; // 本轮连续失败的起点(主连接线程)
|
||||||
|
|
||||||
|
// 回退判据:连续失败次数和已尝试时长**同时**满足才退回原主控。只看次数会被网络抖动
|
||||||
|
// 误伤:一次正常的转移会被无声撤销。计时从「本轮第一次失败」开始而不是从转移生效
|
||||||
|
// 开始——否则转移跑满一分钟后,任何几次瞬时连不上都会立刻把主机撤回去。
|
||||||
|
static const int kTransferRevertAttempts = 3;
|
||||||
|
static const long long kTransferRevertGraceSec = 60;
|
||||||
|
|
||||||
|
static std::string FormatUnixTimeHuman(long long epochSec)
|
||||||
|
{
|
||||||
|
const time_t t = (time_t)epochSec;
|
||||||
|
struct tm tmv;
|
||||||
|
if (!localtime_r(&t, &tmv))
|
||||||
|
return std::to_string(epochSec);
|
||||||
|
char buf[32] = { 0 };
|
||||||
|
if (strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmv) == 0)
|
||||||
|
return std::to_string(epochSec);
|
||||||
|
const long off = tmv.tm_gmtoff;
|
||||||
|
const long absOff = off < 0 ? -off : off;
|
||||||
|
char zone[16] = { 0 };
|
||||||
|
snprintf(zone, sizeof(zone), "%c%02ld%02ld", off < 0 ? '-' : '+',
|
||||||
|
absOff / 3600, (absOff % 3600) / 60);
|
||||||
|
return std::string(buf) + " " + zone;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string FormatDurationHuman(long long seconds)
|
||||||
|
{
|
||||||
|
if (seconds < 0) seconds = 0;
|
||||||
|
const long long h = seconds / 3600;
|
||||||
|
const long long m = (seconds % 3600) / 60;
|
||||||
|
const long long s = seconds % 60;
|
||||||
|
char buf[48] = { 0 };
|
||||||
|
if (h > 0) snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
|
||||||
|
else if (m > 0) snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
|
||||||
|
else snprintf(buf, sizeof(buf), "%llds", s);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主连接上的提示消息(服务端消息栏 + get_audit_log)。title/text 必须是纯 ASCII:
|
||||||
|
// 服务端按 ANSI(GBK) 解释这两个定长字段。
|
||||||
|
static void SendClientNotice(const char* title, const char* text)
|
||||||
|
{
|
||||||
|
if (g_bExit != S_CLIENT_NORMAL || !g_pMainClient || !g_pMainClient->IsConnected())
|
||||||
|
return;
|
||||||
|
ClientMsg msg(title, text);
|
||||||
|
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void SaveTransferRecord(const HostTransfer::Target& t)
|
||||||
|
{
|
||||||
|
setConfigStr("transfer", HostTransfer::EncodeRecord(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ClearTransferRecord()
|
||||||
|
{
|
||||||
|
setConfigStr("transfer", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void RestoreOrigTarget()
|
||||||
|
{
|
||||||
|
HostTransfer::ApplyEndpoint(g_SETTINGS, g_transferOrig);
|
||||||
|
Mprintf("TRANSFER: restored to %s:%d\n",
|
||||||
|
g_transferOrig.ip.c_str(), g_transferOrig.port);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool TransferExpired()
|
||||||
|
{
|
||||||
|
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
|
||||||
|
return vt > 0 && (long long)time(nullptr) >= vt;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 到期(或提前归还)就恢复原主控并清记录,返回是否真的复原了。
|
||||||
|
static bool HandleTransferExpiry()
|
||||||
|
{
|
||||||
|
if (!TransferExpired())
|
||||||
|
return false;
|
||||||
|
const bool early = g_transferEndEarly.exchange(false, std::memory_order_relaxed);
|
||||||
|
g_transferValidTo.store(0, std::memory_order_relaxed);
|
||||||
|
ClearTransferRecord();
|
||||||
|
RestoreOrigTarget();
|
||||||
|
Mprintf("TRANSFER: %s, back to original master\n",
|
||||||
|
early ? "ended early" : "expired");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把接收线程记下的目标落到连接参数。只在主连接线程调用:CONNECT_ADDRESS 没有跨线程
|
||||||
|
// 同步,ConnectServer 读的就是它。
|
||||||
|
static void ApplyPendingTransfer()
|
||||||
|
{
|
||||||
|
if (!g_transferPending.load(std::memory_order_acquire))
|
||||||
|
return;
|
||||||
|
HostTransfer::Target t;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_transferMu);
|
||||||
|
t = g_transferPendingTarget;
|
||||||
|
g_transferPending.store(false, std::memory_order_release);
|
||||||
|
}
|
||||||
|
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||||
|
// 新转移生效:上一个「提前归还」若还没被 HandleTransferExpiry 消费,就作废了,
|
||||||
|
// 留着会让这次转移将来自然到期时被误报成“ended early”。
|
||||||
|
g_transferEndEarly.store(false, std::memory_order_relaxed);
|
||||||
|
g_transferFailStreak = 0;
|
||||||
|
g_transferFailAt = 0;
|
||||||
|
Mprintf("TRANSFER: applying %s:%d (transport=%d)\n",
|
||||||
|
t.ep.ip.c_str(), t.ep.port, t.ep.transport);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转移目标「不可用」的两种形态都算一次失败:连不上,以及连上了却始终通不过
|
||||||
|
// MasterSettings 校验(对端不是主控,或不是本构建的主控)。只看连不上的话,
|
||||||
|
// 一个「端口开着但不是主控」的地址会让主机一直空转,原主控那边已经看不到它了。
|
||||||
|
// 连续的失败次数和已尝试时长同时满足才退回原主控——只看次数会被网络抖动误伤。
|
||||||
|
static void NoteTransferFailure(const char* reason)
|
||||||
|
{
|
||||||
|
if (g_transferValidTo.load(std::memory_order_relaxed) <= 0)
|
||||||
|
return;
|
||||||
|
const long long now = (long long)time(nullptr);
|
||||||
|
if (g_transferFailStreak == 0)
|
||||||
|
g_transferFailAt = now; // 本轮第一次失败:60 秒窗口从这里开始
|
||||||
|
++g_transferFailStreak;
|
||||||
|
if (g_transferFailStreak < kTransferRevertAttempts
|
||||||
|
|| now - g_transferFailAt < kTransferRevertGraceSec)
|
||||||
|
return;
|
||||||
|
Mprintf("TRANSFER: target unusable for %s (%d tries, %s), reverting\n",
|
||||||
|
FormatDurationHuman(now - g_transferFailAt).c_str(), g_transferFailStreak, reason);
|
||||||
|
g_transferValidTo.store(0, std::memory_order_relaxed);
|
||||||
|
g_transferEndEarly.store(false, std::memory_order_relaxed);
|
||||||
|
g_transferFailStreak = 0;
|
||||||
|
g_transferFailAt = 0;
|
||||||
|
ClearTransferRecord();
|
||||||
|
RestoreOrigTarget();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动时读记录:未过期就切到转移目标,过期/损坏就删掉。必须在建连之前调用——
|
||||||
|
// 同时记下此刻的连接参数作为「原主控」,之后才可能被转移目标覆盖。
|
||||||
|
static void LoadTransferRecord()
|
||||||
|
{
|
||||||
|
g_transferOrig = HostTransfer::CaptureEndpoint(g_SETTINGS);
|
||||||
|
|
||||||
|
HostTransfer::Target t;
|
||||||
|
if (!HostTransfer::DecodeRecord(getConfigStr("transfer"), t))
|
||||||
|
return;
|
||||||
|
const long long now = (long long)time(nullptr);
|
||||||
|
if (!t.Active(now)) {
|
||||||
|
Mprintf("TRANSFER: record expired at %s, removed\n",
|
||||||
|
FormatUnixTimeHuman(t.validTo).c_str());
|
||||||
|
ClearTransferRecord();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
||||||
|
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||||
|
Mprintf("TRANSFER: active, target %s:%d, %s left\n",
|
||||||
|
t.ep.ip.c_str(), t.ep.port, FormatDurationHuman(t.validTo - now).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
// ============== System Information Functions ==============
|
// ============== System Information Functions ==============
|
||||||
|
|
||||||
// Get macOS version string (e.g., "macOS 14.0 Sonoma")
|
// Get macOS version string (e.g., "macOS 14.0 Sonoma")
|
||||||
@@ -662,35 +839,19 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
|||||||
|
|
||||||
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
|
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
|
||||||
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
|
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
|
||||||
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
|
// 否则列里会一直显示切换前的状态(按位置改写见 LOGIN_INFOR::SetReserved)。
|
||||||
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
|
|
||||||
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
||||||
static void RefreshLoginTls(LOGIN_INFOR& info)
|
static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||||
{
|
{
|
||||||
std::vector<std::string> fields;
|
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
|
||||||
std::string s(info.szReserved);
|
}
|
||||||
size_t pos = 0;
|
|
||||||
for (;;) {
|
|
||||||
size_t bar = s.find('|', pos);
|
|
||||||
if (bar == std::string::npos) {
|
|
||||||
fields.push_back(s.substr(pos));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
fields.push_back(s.substr(pos, bar - pos));
|
|
||||||
pos = bar + 1;
|
|
||||||
}
|
|
||||||
while (fields.size() <= (size_t)RES_TLS)
|
|
||||||
fields.push_back("");
|
|
||||||
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
|
|
||||||
|
|
||||||
std::string joined;
|
// [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端再加本次上线时长才是当前
|
||||||
for (size_t i = 0; i < fields.size(); ++i) {
|
// 运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是进程启动那一瞬的
|
||||||
if (i)
|
// 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,浮窗只显示 1.3h)。
|
||||||
joined += '|';
|
static void RefreshLoginUptime(LOGIN_INFOR& info)
|
||||||
joined += fields[i];
|
{
|
||||||
}
|
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
|
||||||
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
|
|
||||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||||
@@ -1288,6 +1449,92 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
|||||||
} else {
|
} else {
|
||||||
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
|
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
|
||||||
}
|
}
|
||||||
|
} else if (szBuffer[0] == COMMAND_SHARE || szBuffer[0] == COMMAND_SHARE_CANCEL) {
|
||||||
|
// 「分享主机」/「取消分享」:macOS 尚未实现。分享要在不改主连接的前提下再起
|
||||||
|
// 一条完整登录的连接,而登录校验状态、心跳、主连接句柄都是进程级单例,
|
||||||
|
// 第二条连接会把第一条顶掉(与 Android 的结论一致)。
|
||||||
|
// 服务端分享用的是 COMMAND_SHARE(assignFunction 用 ASSIGN + FOREVER 只发转移),
|
||||||
|
// 这里必须显式接住并回一条消息,否则主控那边以为下发成功了。
|
||||||
|
Mprintf("** [%p] SHARE not supported on macOS (%d), ignored ***\n",
|
||||||
|
user, (int)szBuffer[0]);
|
||||||
|
SendClientNotice("Share host", "macOS client does not support sharing a host");
|
||||||
|
return TRUE;
|
||||||
|
} else if (szBuffer[0] == COMMAND_ASSIGN_MASTER) {
|
||||||
|
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
|
||||||
|
// 服务端只在这个命令上发 SHARE_TYPE_YAMA_FOREVER;类型不符(老版本或异常载荷)
|
||||||
|
// 一律不按转移处理。
|
||||||
|
if (ulLength < 3) {
|
||||||
|
Mprintf("** [%p] ASSIGN too short (%lu), ignored ***\n",
|
||||||
|
user, (unsigned long)ulLength);
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
if (szBuffer[1] != SHARE_TYPE_YAMA_FOREVER) {
|
||||||
|
if (szBuffer[1] == SHARE_TYPE_YAMA) {
|
||||||
|
// 老服务端把「分享」发在同一个命令字节上(见 common/host_share.h:48)。
|
||||||
|
// 同样要回消息,否则主控那边以为这台主机的分享下发成功了。
|
||||||
|
Mprintf("** [%p] SHARE via ASSIGN (legacy), not supported on macOS ***\n", user);
|
||||||
|
SendClientNotice("Share host", "macOS client does not support sharing a host");
|
||||||
|
} else {
|
||||||
|
Mprintf("** [%p] ASSIGN type=%d not supported, ignored ***\n",
|
||||||
|
user, (int)szBuffer[1]);
|
||||||
|
}
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
HostTransfer::Target t;
|
||||||
|
const long long now = (long long)time(nullptr);
|
||||||
|
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
|
||||||
|
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的
|
||||||
|
// 主机就被改到一个不存在的地址上去了。
|
||||||
|
Mprintf("** [%p] ASSIGN malformed payload, ignored ***\n", user);
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
// 有效期内拒绝再次转移(与 Windows/Android 的 now <= valid_to 判断一致),
|
||||||
|
// 同时挡住「新主控再转一手」:主机此刻只连着新主控,它无权再改归属。
|
||||||
|
// 唯一例外:目标就是原主控——那是提前归还,把到期时刻设成「现在」,
|
||||||
|
// 走心跳循环里那条已经验证过的复原路径。
|
||||||
|
const bool toOriginal =
|
||||||
|
(t.ep.ip == g_transferOrig.ip && t.ep.port == g_transferOrig.port);
|
||||||
|
const long long active = g_transferValidTo.load(std::memory_order_relaxed);
|
||||||
|
if (now <= active) {
|
||||||
|
if (toOriginal) {
|
||||||
|
Mprintf("** [%p] ASSIGN back to original master, ending transfer early ***\n", user);
|
||||||
|
g_transferEndEarly.store(true, std::memory_order_relaxed);
|
||||||
|
g_transferValidTo.store(now, std::memory_order_relaxed);
|
||||||
|
// 记录立刻作废:主线程通常 1 秒内就会复原并再清一次,但若这期间进程
|
||||||
|
// 崩了/被杀,重启时旧记录(有效期还在)会把主机送回转移目标。
|
||||||
|
ClearTransferRecord();
|
||||||
|
SendClientNotice("Transfer host",
|
||||||
|
"Transfer ended early, returning to original master (validity ignored)");
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
Mprintf("** [%p] ASSIGN ignored, already assigned until %s ***\n",
|
||||||
|
user, FormatUnixTimeHuman(active).c_str());
|
||||||
|
char msg[192];
|
||||||
|
snprintf(msg, sizeof(msg),
|
||||||
|
"Host is already transferred until %s (%s left), ignored",
|
||||||
|
FormatUnixTimeHuman(active).c_str(),
|
||||||
|
FormatDurationHuman(active - now).c_str());
|
||||||
|
SendClientNotice("Transfer host", msg);
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
if (toOriginal) {
|
||||||
|
// 没在转移而目标就是原主控:无事可做,放行只会白白断线重连一次。
|
||||||
|
Mprintf("** [%p] ASSIGN target equals original master, ignored ***\n", user);
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
// 先把新的到期时刻和记录落下来,最后才发布「待应用」。主线程看到 pending 就会
|
||||||
|
// 应用地址并紧接着检查到期,若 validTo 还是旧的(恰好已过期),就会把刚接受的
|
||||||
|
// 这次转移当成到期撤销掉。先挡住后续重复下发,再落盘。
|
||||||
|
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
||||||
|
SaveTransferRecord(t);
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(g_transferMu);
|
||||||
|
g_transferPendingTarget = t;
|
||||||
|
g_transferPending.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
Mprintf("** [%p] ASSIGN to %s:%d for %s, moving the main link now ***\n",
|
||||||
|
user, t.ep.ip.c_str(), t.ep.port,
|
||||||
|
FormatDurationHuman(t.validTo - now).c_str());
|
||||||
} else {
|
} else {
|
||||||
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
|
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
|
||||||
}
|
}
|
||||||
@@ -1362,6 +1609,10 @@ int main(int argc, const char* argv[])
|
|||||||
loadConfig();
|
loadConfig();
|
||||||
Mprintf("Config loaded from %s\n", g_configPath.c_str());
|
Mprintf("Config loaded from %s\n", g_configPath.c_str());
|
||||||
|
|
||||||
|
// 上次的「转移主机」还没到期就改连目标主控(原地址记在内存里,到期恢复)。
|
||||||
|
// 必须在建连之前:它决定本次启动要连哪台主控。
|
||||||
|
LoadTransferRecord();
|
||||||
|
|
||||||
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
|
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
|
||||||
// 与 Linux 端在登录前 Start 的时机一致。
|
// 与 Linux 端在登录前 Start 的时机一致。
|
||||||
MacActivityHistory::Instance().Start();
|
MacActivityHistory::Instance().Start();
|
||||||
@@ -1434,9 +1685,6 @@ int main(int argc, const char* argv[])
|
|||||||
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
|
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
|
||||||
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
|
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
|
||||||
g_pMainClient = ClientObject.get();
|
g_pMainClient = ClientObject.get();
|
||||||
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
|
||||||
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
|
|
||||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
|
||||||
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
|
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
|
||||||
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
|
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
|
||||||
(int)(unsigned char)g_SETTINGS.protoType);
|
(int)(unsigned char)g_SETTINGS.protoType);
|
||||||
@@ -1455,8 +1703,19 @@ int main(int argc, const char* argv[])
|
|||||||
Mprintf("Auto-restart failed; continuing with the current process\n");
|
Mprintf("Auto-restart failed; continuing with the current process\n");
|
||||||
g_autoRestartPending = false;
|
g_autoRestartPending = false;
|
||||||
}
|
}
|
||||||
|
// 转移目标先落到连接参数;到期(或被新主控提前归还)则恢复原主控。
|
||||||
|
// 两者都只改地址/协议,真正的建连由本轮下面的 ConnectServer 完成。
|
||||||
|
ApplyPendingTransfer();
|
||||||
|
HandleTransferExpiry();
|
||||||
|
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
||||||
|
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。每轮重喂还因为转移可能把目标
|
||||||
|
// 换成另一台主控,它的入口未必和原主控同构(原 WSS、对方直连设备端口时是 TCP)。
|
||||||
|
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||||
clock_t c = clock();
|
clock_t c = clock();
|
||||||
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
|
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
|
||||||
|
// 转移目标连不上:连续失败且已持续一分钟才退回原主控并清掉记录,
|
||||||
|
// 否则一个写错的地址会让这台主机彻底失联——原主控那边已经看不到它了。
|
||||||
|
NoteTransferFailure("unreachable");
|
||||||
Sleep(5000);
|
Sleep(5000);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1469,6 +1728,8 @@ int main(int argc, const char* argv[])
|
|||||||
ClientAuth::OnNewConnection();
|
ClientAuth::OnNewConnection();
|
||||||
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
|
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
|
||||||
RefreshLoginTls(logInfo);
|
RefreshLoginTls(logInfo);
|
||||||
|
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
|
||||||
|
RefreshLoginUptime(logInfo);
|
||||||
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
|
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
|
||||||
RefreshLoginCaps(logInfo);
|
RefreshLoginCaps(logInfo);
|
||||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||||
@@ -1490,6 +1751,10 @@ int main(int argc, const char* argv[])
|
|||||||
break;
|
break;
|
||||||
if (g_autoRestartPending)
|
if (g_autoRestartPending)
|
||||||
break;
|
break;
|
||||||
|
// 转移与到期复原按 1 秒粒度判断:0.001 天(86 秒)这种短转移等满
|
||||||
|
// 一个心跳周期才动就晚了。这里只 break,断开由循环外统一做。
|
||||||
|
if (g_transferPending.load(std::memory_order_acquire) || TransferExpired())
|
||||||
|
break;
|
||||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||||
break;
|
break;
|
||||||
Sleep(1000);
|
Sleep(1000);
|
||||||
@@ -1500,6 +1765,19 @@ int main(int argc, const char* argv[])
|
|||||||
ClientObject->Disconnect();
|
ClientObject->Disconnect();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
// 转移主机:接收线程已写好新目标,先断开当前(原主控)连接,再由外层
|
||||||
|
// 循环换地址重连。地址必须在本线程、断开之后才改(见 ApplyPendingTransfer)。
|
||||||
|
if (g_transferPending.load(std::memory_order_acquire)) {
|
||||||
|
Mprintf("TRANSFER: leaving current master\n");
|
||||||
|
ClientObject->Disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 转移结束:恢复启动时记下的原主控。自然到期与新主控「提前归还」
|
||||||
|
// (它把到期时刻设成了当时,见 DataProcess 的 ASSIGN 分支)都走这里。
|
||||||
|
if (HandleTransferExpiry()) {
|
||||||
|
ClientObject->Disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
|
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
|
||||||
// 断开后由外层循环按新的传输方式重连。
|
// 断开后由外层循环按新的传输方式重连。
|
||||||
if (g_needReconnect.exchange(false)) {
|
if (g_needReconnect.exchange(false)) {
|
||||||
@@ -1511,7 +1789,8 @@ int main(int argc, const char* argv[])
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
// 30 秒内未通过 MasterSettings 校验 → 断开本连接让外层重连,
|
// 30 秒内未通过 MasterSettings 校验 → 断开本连接让外层重连,
|
||||||
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。
|
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。转移期间这类连接
|
||||||
|
// 记为一次失败(见下面心跳循环结束处),否则主机只能等到期才回原主控。
|
||||||
if (ClientAuth::IsTimedOut()) {
|
if (ClientAuth::IsTimedOut()) {
|
||||||
ClientObject->Disconnect();
|
ClientObject->Disconnect();
|
||||||
break;
|
break;
|
||||||
@@ -1530,6 +1809,22 @@ int main(int argc, const char* argv[])
|
|||||||
memcpy(buf + 1, &hb, sizeof(Heartbeat));
|
memcpy(buf + 1, &hb, sizeof(Heartbeat));
|
||||||
ClientObject->Send2Server((char*)buf, sizeof(buf));
|
ClientObject->Send2Server((char*)buf, sizeof(buf));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 一条连接结束了,按「这条连接有没有通过 MasterSettings 校验」记账:
|
||||||
|
// · 校验通过 → 转移目标确实可用,失败计数清零(原实现只在建连成功时清零,
|
||||||
|
// 等于把「连得上但校验不过」的目标排除在回退判据之外);
|
||||||
|
// · 从未通过 → 目标「连得上但不是主控」:典型是端口上跑着别的服务
|
||||||
|
// (连上就被关掉,走不到 30 秒超时分支),或对端不认本构建。
|
||||||
|
// 正常退出/自动重启触发的断开不计(条件在后半段挡住);已经到期或提前归还
|
||||||
|
// 时 transfer 已结束,NoteTransferFailure 自己会返回。
|
||||||
|
if (g_running && g_bExit == S_CLIENT_NORMAL && !g_autoRestartPending) {
|
||||||
|
if (ClientAuth::IsVerified()) {
|
||||||
|
g_transferFailStreak = 0;
|
||||||
|
g_transferFailAt = 0; // 有可用连接:60 秒窗口整体重置
|
||||||
|
} else {
|
||||||
|
NoteTransferFailure("no master auth");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 退出原因留痕:signal handler 不能直接打日志,在这里补一行。
|
// 退出原因留痕:signal handler 不能直接打日志,在这里补一行。
|
||||||
|
|||||||
+230
-2
@@ -18,7 +18,7 @@
|
|||||||
],
|
],
|
||||||
"version": 2,
|
"version": 2,
|
||||||
"protocolVersion": "2025-06-18",
|
"protocolVersion": "2025-06-18",
|
||||||
"toolCount": 54,
|
"toolCount": 55,
|
||||||
"tools": [
|
"tools": [
|
||||||
{
|
{
|
||||||
"name": "list_hosts",
|
"name": "list_hosts",
|
||||||
@@ -1207,7 +1207,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "get_server_status",
|
"name": "get_server_status",
|
||||||
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
|
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/文件写入/管理/主机管理/高风险操作/键盘记录/远程交谈/生成客户端)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
|
||||||
"gate": null,
|
"gate": null,
|
||||||
"platforms": [
|
"platforms": [
|
||||||
"win",
|
"win",
|
||||||
@@ -4995,6 +4995,234 @@
|
|||||||
"type": "object"
|
"type": "object"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "build_client",
|
||||||
|
"description": "在服务端本机生成一个客户端文件(按本主控的上线配置 patch 客户端模板后落盘)。这不会修改任何在线主机,也不依赖在线主机;生成目标是模板类型而不是某台设备。支持 Windows(ghost 单文件/服务/SYSTEM、TestRun 加载器、ServerDll.dll、TinyRun.dll)、Linux、macOS 与 Android。生成地址默认取服务端当前有效主控地址(含上级 FRP 配置),也可显式传 host/port。默认会在客户端模板存在内嵌 TLS 锚块且协议为 tcp/http 时写入服务端当前证书(首连即 TLS),其余目标如实标注 tlsAnchor 状态。输出目录默认主控程序目录,已存在同名文件时默认拒绝(传 overwrite=true 才覆盖)。Windows 目标可选 upx 压缩与 padding_mb 增肥;ShellCode AES / PE→ShellCode 等需要载荷文件的模式只能用生成对话框。需服务端开启 McpBuild 且关闭只读模式。生成后可把 path 交给用户;Windows/Linux/macOS 主机可用 upload_file 送达(文件格式需与目标平台匹配),Android 需用户自行安装。",
|
||||||
|
"gate": "build",
|
||||||
|
"write": true,
|
||||||
|
"platforms": [
|
||||||
|
"win",
|
||||||
|
"lnx",
|
||||||
|
"mac",
|
||||||
|
"apk"
|
||||||
|
],
|
||||||
|
"impl": "mfc",
|
||||||
|
"inputSchema": {
|
||||||
|
"properties": {
|
||||||
|
"arch": {
|
||||||
|
"description": "Windows 目标架构,默认 x64;x86 对 testrun_injsc 与 linux/macos/android 无效(会被拒绝)。",
|
||||||
|
"enum": [
|
||||||
|
"x64",
|
||||||
|
"x86"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"compress": {
|
||||||
|
"description": "压缩方式,默认 none;upx 仅 Windows 目标支持。ShellCode AES / PE→ShellCode 等需要载荷文件,只能在生成对话框里操作。",
|
||||||
|
"enum": [
|
||||||
|
"none",
|
||||||
|
"upx"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"encrypt_address": {
|
||||||
|
"description": "是否加密写进客户端的 CONNECT_ADDRESS(地址/端口),默认 true。testrun_injsc 与 tinyrun 与对话框一致,不加密。",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"group": {
|
||||||
|
"description": "分组名称,最长 23 字节(ANSI)。省略时与对话框一致使用 default。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"header_enc": {
|
||||||
|
"description": "包头加密方式,默认 hell。",
|
||||||
|
"enum": [
|
||||||
|
"shine",
|
||||||
|
"hell"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"description": "主控地址,可写分号分隔的多个地址(客户端随机选择)。省略时使用服务端当前有效主控地址(含上级 FRP 配置);两者都为空则报错。最长 99 字符。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"install_dir": {
|
||||||
|
"description": "Windows 安装子目录名,最长 31 字节,不能含 \\ / : * ? \" < > |。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"install_location": {
|
||||||
|
"description": "Windows 安装位置,默认 programdata。仅 Windows 目标有效。",
|
||||||
|
"enum": [
|
||||||
|
"programdata",
|
||||||
|
"programfiles",
|
||||||
|
"systemroot",
|
||||||
|
"appdata",
|
||||||
|
"localappdata"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"install_name": {
|
||||||
|
"description": "Windows 安装程序名,最长 31 字节,不能含 \\ / : * ? \" < > |。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"output_dir": {
|
||||||
|
"description": "输出目录(服务端本机路径),默认主控程序所在目录;不存在会自动创建。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"output_name": {
|
||||||
|
"description": "输出文件名(仅文件名,不含目录),默认按 target 取 ghost.exe / TestRun.exe / ServerDll.dll / TinyRun.dll / ghost / ghost.apk。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"overwrite": {
|
||||||
|
"description": "目标文件已存在时是否覆盖,默认 false。为 false 时返回 -32012,确认覆盖后再传 true 重试。",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"padding_mb": {
|
||||||
|
"description": "程序增肥的追加字节数(MB),默认 0;仅 Windows 目标支持。",
|
||||||
|
"maximum": 256,
|
||||||
|
"minimum": 0,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"port": {
|
||||||
|
"description": "主控端口,省略时使用服务端当前有效端口。",
|
||||||
|
"maximum": 65535,
|
||||||
|
"minimum": 1,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"protocol": {
|
||||||
|
"description": "传输协议,默认 tcp。ws/wss 需反向代理(如 nginx 443)转发到主控端口;kcp 需要主控 UDP 协议参数为 1。",
|
||||||
|
"enum": [
|
||||||
|
"tcp",
|
||||||
|
"udp",
|
||||||
|
"http",
|
||||||
|
"random",
|
||||||
|
"kcp",
|
||||||
|
"ws",
|
||||||
|
"wss"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"run_as_admin": {
|
||||||
|
"description": "生成的 Windows 客户端是否请求管理员权限运行,默认 false;安装 Windows 服务时通常需要 true。",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"running": {
|
||||||
|
"description": "上线方式,默认 random(随机上线)。",
|
||||||
|
"enum": [
|
||||||
|
"random",
|
||||||
|
"parallel"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"description": "生成目标:ghost(Windows 单文件 EXE)、ghost_service(Windows 服务)、ghost_system(SYSTEM 权限)、testrun_dll / testrun_memdll / testrun_injsc / testrun_service / testrun_system(TestRun 加载器)、serverdll、tinyrun、linux、macos、android。前十个是 Windows 目标;linux/macos/android 为固定架构的预编译 template,arch=x86 与 Windows 专属的 compress/padding 会被拒绝,安装目录相关参数不参与生成。",
|
||||||
|
"enum": [
|
||||||
|
"testrun_dll",
|
||||||
|
"testrun_memdll",
|
||||||
|
"testrun_injsc",
|
||||||
|
"testrun_service",
|
||||||
|
"testrun_system",
|
||||||
|
"ghost",
|
||||||
|
"ghost_service",
|
||||||
|
"ghost_system",
|
||||||
|
"serverdll",
|
||||||
|
"tinyrun",
|
||||||
|
"linux",
|
||||||
|
"macos",
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"tls_anchor": {
|
||||||
|
"description": "是否把服务端当前 TLS 证书作为信任锚写进客户端(首连即 TLS),默认 true。仅 ghost / ghost_service / ghost_system / serverdll 模板有锚块,且协议为 tcp/http;其余目标会如实标注为未内嵌,不视为失败。",
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"target"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"outputSchema": {
|
||||||
|
"properties": {
|
||||||
|
"arch": {
|
||||||
|
"description": "实际架构:x64 / x86;posix 目标为 native。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"bytes": {
|
||||||
|
"description": "最终文件字节数。",
|
||||||
|
"minimum": 0,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"clientType": {
|
||||||
|
"description": "客户端类型:EXE / DLL / MDLL / SC / LNX / MAC / APK。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"description": "写入客户端的主控地址。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"description": "输出文件名。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"ok": {
|
||||||
|
"description": "是否成功;失败时本工具返回 JSON-RPC error。",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"overwritten": {
|
||||||
|
"description": "是否覆盖了已存在的同名文件。",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"description": "生成文件的绝对路径(服务端本机)。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"port": {
|
||||||
|
"description": "写入客户端的主控端口。",
|
||||||
|
"maximum": 65535,
|
||||||
|
"minimum": 1,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"protocol": {
|
||||||
|
"description": "写入客户端的传输协议。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"description": "生成目标(与入参 target 一致)。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"targetLabel": {
|
||||||
|
"description": "生成目标的中文名,如「ghost.exe - Windows 服务」。",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"tips": {
|
||||||
|
"description": "生成后需要注意的事项(KCP/WS 端口、macOS/Android 重签、锚未内嵌等)。",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"tlsAnchor": {
|
||||||
|
"description": "内嵌 TLS 信任锚状态:embedded(已内嵌)/ disabled(未请求)/ not_applicable(该目标模板不含客户端代码)/ unsupported_platform(Linux/macOS/Android 模板没有锚块)/ skipped_protocol(该协议不走设备端口 TLS)/ unavailable(服务端未启用TLS)/ no_block(模板里没有锚块,已按普通客户端生成)。",
|
||||||
|
"enum": [
|
||||||
|
"embedded",
|
||||||
|
"disabled",
|
||||||
|
"not_applicable",
|
||||||
|
"unsupported_platform",
|
||||||
|
"skipped_protocol",
|
||||||
|
"unavailable",
|
||||||
|
"no_block"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"tlsAnchorSummary": {
|
||||||
|
"description": "内嵌成功时的证书摘要(如 builtin 2036-11-01 sha1:...)。",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "list_processes",
|
"name": "list_processes",
|
||||||
"description": "获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。仅在 McpMachine=0(主机管理工具关闭)时出现——那是本服务端唯一能列进程的路径;开启主机管理后改用 host_inspect 的 processes 项(字段更全、支持 arch 过滤)。",
|
"description": "获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。仅在 McpMachine=0(主机管理工具关闭)时出现——那是本服务端唯一能列进程的路径;开启主机管理后改用 host_inspect 的 processes 项(字段更全、支持 arch 过滤)。",
|
||||||
|
|||||||
@@ -328,6 +328,18 @@ static BOOL IsAgentMode()
|
|||||||
return cmdLine.Find(_T("-agent")) != -1;
|
return cmdLine.Find(_T("-agent")) != -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 是否为服务相关的命令行。
|
||||||
|
// 这几个分支由 HandleServiceCommandLine 自己处理,低完整性检查必须放行 ——
|
||||||
|
// 否则服务装不上也卸不掉,等于把唯一的补救手段也堵死了。
|
||||||
|
static bool IsServiceRelatedCommand()
|
||||||
|
{
|
||||||
|
CString cmdLine = ::GetCommandLine();
|
||||||
|
cmdLine.MakeLower();
|
||||||
|
return cmdLine.Find(_T("-service")) != -1
|
||||||
|
|| cmdLine.Find(_T("-install")) != -1
|
||||||
|
|| cmdLine.Find(_T("-uninstall")) != -1;
|
||||||
|
}
|
||||||
|
|
||||||
// CMy2015RemoteApp 初始化
|
// CMy2015RemoteApp 初始化
|
||||||
|
|
||||||
BOOL IsRunningAsAdmin()
|
BOOL IsRunningAsAdmin()
|
||||||
@@ -373,6 +385,116 @@ BOOL LaunchAsAdmin(const char* szFilePath, const char* verb)
|
|||||||
return ShellExecuteExA(&shExecInfo);
|
return ShellExecuteExA(&shExecInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 取当前进程的完整性级别 RID(Low=0x1000 / Medium=0x2000 / High=0x3000)
|
||||||
|
// 失败返回 0(此时调用方按"未知"处理,不做任何提示)
|
||||||
|
static DWORD GetProcessIntegrityRid()
|
||||||
|
{
|
||||||
|
DWORD dwRid = 0;
|
||||||
|
HANDLE hToken = NULL;
|
||||||
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
BYTE buf[256] = { 0 };
|
||||||
|
DWORD cbSize = sizeof(buf);
|
||||||
|
if (GetTokenInformation(hToken, TokenIntegrityLevel, buf, cbSize, &cbSize)) {
|
||||||
|
TOKEN_MANDATORY_LABEL* pTml = (TOKEN_MANDATORY_LABEL*)buf;
|
||||||
|
if (pTml->Label.Sid != NULL) {
|
||||||
|
DWORD nSub = *GetSidSubAuthorityCount(pTml->Label.Sid);
|
||||||
|
if (nSub > 0) {
|
||||||
|
dwRid = *GetSidSubAuthority(pTml->Label.Sid, nSub - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CloseHandle(hToken);
|
||||||
|
return dwRid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把文本放进剪贴板(工程是 MultiByte,用 CF_TEXT)
|
||||||
|
static void CopyTextToClipboard(const CString& text)
|
||||||
|
{
|
||||||
|
if (!::OpenClipboard(NULL)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
::EmptyClipboard();
|
||||||
|
|
||||||
|
int nLen = (text.GetLength() + 1) * sizeof(TCHAR);
|
||||||
|
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, nLen);
|
||||||
|
if (hMem != NULL) {
|
||||||
|
void* pDst = ::GlobalLock(hMem);
|
||||||
|
if (pDst != NULL) {
|
||||||
|
memcpy(pDst, (LPCTSTR)text, nLen);
|
||||||
|
::GlobalUnlock(hMem);
|
||||||
|
if (::SetClipboardData(CF_TEXT, hMem) != NULL) {
|
||||||
|
hMem = NULL; // 所有权已交给剪贴板,不能再释放
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (hMem != NULL) {
|
||||||
|
::GlobalFree(hMem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
::CloseClipboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 低完整性自检
|
||||||
|
//
|
||||||
|
// 返回值:true = 允许继续启动;false = 应当中止启动
|
||||||
|
//
|
||||||
|
// 现象:exe 文件带 Low 完整性标签时,Windows 会把进程 IL 压到 Low,
|
||||||
|
// 即使「以管理员身份运行」也一样(服务+代理模式同样无效),
|
||||||
|
// 表现为「设置全是默认值、保存无效」。
|
||||||
|
//
|
||||||
|
// 为什么程序自己修不了:
|
||||||
|
// 进程 IL 在创建后不可更改,Low 进程又受 no-write-up 限制,连自己
|
||||||
|
// exe 的标签都改不了(实测报「指明特定的安全 ID 可能不能作为对象
|
||||||
|
// 的标签分配」);runas 提权同样无效(UAC 批准模式关闭时是空操作,
|
||||||
|
// 子进程继承 Low)。所以只能把修复命令交给用户在管理员命令行执行。
|
||||||
|
//
|
||||||
|
// 为什么返回 false 而不是继续启动:带着 Low IL 进主界面没有任何意义 ——
|
||||||
|
// 配置全是默认值、改了也存不下来,用户只会以为是别的 bug。
|
||||||
|
//
|
||||||
|
// 服务实例(-service)走不到这里:它在 HandleServiceCommandLine 就返回了。
|
||||||
|
// 代理模式(-agent-asuser)由服务每 10 秒拉起一次,弹窗会变成弹窗轰炸,
|
||||||
|
// 所以只记日志、直接退出。
|
||||||
|
static bool CheckLowIntegrity(bool bAgentMode)
|
||||||
|
{
|
||||||
|
DWORD dwRid = GetProcessIntegrityRid();
|
||||||
|
if (dwRid == 0 || dwRid >= SECURITY_MANDATORY_MEDIUM_RID) {
|
||||||
|
return true; // Medium 及以上,正常
|
||||||
|
}
|
||||||
|
|
||||||
|
char exePath[MAX_PATH] = { 0 };
|
||||||
|
GetModuleFileNameA(NULL, exePath, MAX_PATH);
|
||||||
|
Mprintf("[完整性] 警告:进程完整性级别为 Low(RID=0x%X),"
|
||||||
|
"注册表与日志写入会失败。exe=%s\n", dwRid, exePath);
|
||||||
|
|
||||||
|
if (bAgentMode) {
|
||||||
|
return false; // 服务拉起的实例:静默退出,避免反复弹窗
|
||||||
|
}
|
||||||
|
|
||||||
|
CString fixCmd;
|
||||||
|
fixCmd.Format(_T("icacls \"%s\" /setintegritylevel M"), exePath);
|
||||||
|
|
||||||
|
CString msg;
|
||||||
|
msg.Format(_TR(
|
||||||
|
"本程序运行在「低完整性」模式下,部分功能会异常。\n\n"
|
||||||
|
"请以管理员身份打开命令提示符,执行:\n\n"
|
||||||
|
" %s\n\n"
|
||||||
|
"执行后重新启动本程序。\n\n"
|
||||||
|
"点「是」复制上面的命令,点「否」关闭。"), (LPCTSTR)fixCmd);
|
||||||
|
|
||||||
|
if (::MessageBox(NULL, msg, _TR("完整性级别受限"),
|
||||||
|
MB_ICONWARNING | MB_YESNO) == IDYES) {
|
||||||
|
CopyTextToClipboard(fixCmd);
|
||||||
|
::MessageBox(NULL,
|
||||||
|
_TR("修复命令已复制到剪贴板。\n\n"
|
||||||
|
"请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。"),
|
||||||
|
_TR("已复制"), MB_ICONINFORMATION | MB_OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false; // 无论点是还是否,都不继续启动
|
||||||
|
}
|
||||||
|
|
||||||
BOOL CMy2015RemoteApp::ProcessZstaCmd()
|
BOOL CMy2015RemoteApp::ProcessZstaCmd()
|
||||||
{
|
{
|
||||||
// 检查是否已注册右键菜单
|
// 检查是否已注册右键菜单
|
||||||
@@ -510,6 +632,35 @@ BOOL CMy2015RemoteApp::InitInstance()
|
|||||||
// 代理模式由服务管理,不应再次请求管理员权限提升
|
// 代理模式由服务管理,不应再次请求管理员权限提升
|
||||||
// 否则会导致:1) 原进程正常退出(exitCode=0)不被视为崩溃 2) 被提升的进程脱离服务监控
|
// 否则会导致:1) 原进程正常退出(exitCode=0)不被视为崩溃 2) 被提升的进程脱离服务监控
|
||||||
BOOL isAgentMode = IsAgentMode();
|
BOOL isAgentMode = IsAgentMode();
|
||||||
|
|
||||||
|
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
|
||||||
|
// 必须在创建任何对话框之前调用
|
||||||
|
SetChineseThreadLocale();
|
||||||
|
|
||||||
|
// 加载语言包(必须在显示任何文本之前)
|
||||||
|
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
|
||||||
|
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
|
||||||
|
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
|
||||||
|
langDir = langDir.empty() ? "./lang" : langDir;
|
||||||
|
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
|
||||||
|
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
|
||||||
|
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
|
||||||
|
|
||||||
|
// 低完整性自检 —— 必须排在「提权」和「服务自愈」之前。
|
||||||
|
// 1) 排在 HandleServiceCommandLine 之后:双击时程序会先把服务装好/启动,
|
||||||
|
// 然后自己 return FALSE 退出,提示只能由服务拉起的 -agent-asuser 弹出来;
|
||||||
|
// 而 agent 为了防轰炸是静默的,结果就是「双击没反应、一个字都不提示」。
|
||||||
|
// 2) 排在 LaunchAsAdmin 之后:Low 下 runas 是空操作,提权出来的子进程依然是
|
||||||
|
// Low,会陷入「弹 UAC → 还是 Low → 再弹 UAC」的死循环。
|
||||||
|
// 服务相关命令行(-service/-install/-uninstall)放行,交给下面处理。
|
||||||
|
if (!IsServiceRelatedCommand()) {
|
||||||
|
if (!CheckLowIntegrity(isAgentMode != FALSE)) {
|
||||||
|
Mprintf("[InitInstance] 低完整性,已中止启动。\n");
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 普通用户提权(低完整性已在上面拦下,走到这里说明 IL 正常)
|
||||||
if (runNormal != 1 && !isAgentMode && !IsRunningAsAdmin() && LaunchAsAdmin(curFile, "runas")) {
|
if (runNormal != 1 && !isAgentMode && !IsRunningAsAdmin() && LaunchAsAdmin(curFile, "runas")) {
|
||||||
Mprintf("[InitInstance] 程序没有管理员权限,用户选择以管理员身份重新运行。\n");
|
Mprintf("[InitInstance] 程序没有管理员权限,用户选择以管理员身份重新运行。\n");
|
||||||
return FALSE;
|
return FALSE;
|
||||||
@@ -534,19 +685,6 @@ BOOL CMy2015RemoteApp::InitInstance()
|
|||||||
if (pfn) pfn(L"YAMA");
|
if (pfn) pfn(L"YAMA");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
|
|
||||||
// 必须在创建任何对话框之前调用
|
|
||||||
SetChineseThreadLocale();
|
|
||||||
|
|
||||||
// 加载语言包(必须在显示任何文本之前)
|
|
||||||
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
|
|
||||||
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
|
|
||||||
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
|
|
||||||
langDir = langDir.empty() ? "./lang" : langDir;
|
|
||||||
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
|
|
||||||
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
|
|
||||||
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
|
|
||||||
|
|
||||||
// 创建并显示启动画面
|
// 创建并显示启动画面
|
||||||
CSplashDlg* pSplash = new CSplashDlg();
|
CSplashDlg* pSplash = new CSplashDlg();
|
||||||
pSplash->Create(NULL);
|
pSplash->Create(NULL);
|
||||||
|
|||||||
@@ -363,35 +363,70 @@ static UINT Indicators[] = {
|
|||||||
IDR_STATUSBAR_EXPIRE
|
IDR_STATUSBAR_EXPIRE
|
||||||
};
|
};
|
||||||
|
|
||||||
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下两种取值的实际文本宽度取大者,
|
// 状态栏分区宽度:按当前语言/DPI 下的实际文本宽度加左右边距。硬编码像素在
|
||||||
// 再留出左右边距。硬编码像素在不同语言/DPI 下容易被截断或浪费空间。
|
// 125%/150% 缩放或换字体时会把文字截掉(「到期: ... (41天)」只剩日期就是这个原因)。
|
||||||
|
//
|
||||||
|
// 文本按宽字符测量:状态栏控件内部是 Unicode,ANSI 串会先按系统代码页转成宽字符再
|
||||||
|
// 绘制。中文串两种方式差可达 10%(本机 134 vs 153px),按 ANSI 测会偏窄。
|
||||||
|
static int MeasureStatusTextWide(HDC dc, const CString& text)
|
||||||
|
{
|
||||||
|
const int len = text.GetLength();
|
||||||
|
if (len <= 0)
|
||||||
|
return 0;
|
||||||
|
const int n = ::MultiByteToWideChar(CP_ACP, 0, text, len, nullptr, 0);
|
||||||
|
if (n <= 0)
|
||||||
|
return 0;
|
||||||
|
std::wstring w((size_t)n, L'\0');
|
||||||
|
::MultiByteToWideChar(CP_ACP, 0, text, len, &w[0], n);
|
||||||
|
SIZE sz = {};
|
||||||
|
::GetTextExtentPoint32W(dc, w.c_str(), n, &sz);
|
||||||
|
return (int)sz.cx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 难点是「控件到底用哪个字体画」。状态栏没有显式设过字体时,MFC 自己按 DC 默认字体
|
||||||
|
// (SYSTEM_FONT)计算分区宽度,而系统「状态栏字体」(lfStatusFont)往往更窄——本机
|
||||||
|
// 实测同一串文字 SYSTEM_FONT 134px、状态栏字体 109px。只按后者测就会把分区算窄、
|
||||||
|
// 把文字截掉,所以这里几种候选字体都测一遍取最大值。
|
||||||
|
static int CalcStatusPaneWidth(const CStatusBar& bar, const CString& text)
|
||||||
|
{
|
||||||
|
if (text.IsEmpty())
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
CClientDC dc((CWnd*)&bar);
|
||||||
|
HGDIOBJ candidates[5] = {};
|
||||||
|
int count = 0;
|
||||||
|
|
||||||
|
if (CFont* pFont = bar.GetFont()) // 应用显式设过字体:控件就用它
|
||||||
|
candidates[count++] = (HGDIOBJ)pFont->GetSafeHandle();
|
||||||
|
candidates[count++] = ::GetStockObject(SYSTEM_FONT); // 无字体时的绘制/测量默认
|
||||||
|
candidates[count++] = ::GetStockObject(DEFAULT_GUI_FONT); // 另一种常见的默认
|
||||||
|
|
||||||
|
CFont statusFont, messageFont; // 系统字体表里的两种可能
|
||||||
|
NONCLIENTMETRICS ncm = {};
|
||||||
|
ncm.cbSize = sizeof(ncm);
|
||||||
|
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)) {
|
||||||
|
if (statusFont.CreateFontIndirect(&ncm.lfStatusFont))
|
||||||
|
candidates[count++] = (HGDIOBJ)statusFont.GetSafeHandle();
|
||||||
|
if (messageFont.CreateFontIndirect(&ncm.lfMessageFont))
|
||||||
|
candidates[count++] = (HGDIOBJ)messageFont.GetSafeHandle();
|
||||||
|
}
|
||||||
|
|
||||||
|
int width = 0;
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
HGDIOBJ old = dc.SelectObject(candidates[i]);
|
||||||
|
width = max(width, MeasureStatusTextWide(dc, text));
|
||||||
|
if (old != nullptr)
|
||||||
|
dc.SelectObject(old);
|
||||||
|
}
|
||||||
|
return width + 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下各取值的实际文本宽度取大者。
|
||||||
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
|
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
|
||||||
const CString& c = CString())
|
const CString& c = CString())
|
||||||
{
|
{
|
||||||
CClientDC dc((CWnd*)&bar);
|
return max(max(CalcStatusPaneWidth(bar, a), CalcStatusPaneWidth(bar, b)),
|
||||||
CFont* pOld = nullptr;
|
CalcStatusPaneWidth(bar, c));
|
||||||
CFont* pFont = bar.GetFont();
|
|
||||||
// 状态栏没有显式设过字体时,绘制用的是系统的「状态栏字体」(Segoe UI 9pt),
|
|
||||||
// 比 DEFAULT_GUI_FONT 宽约 8%:100% 缩放下靠边距还能兜住,缩放比更高就会截断,
|
|
||||||
// 所以这里直接按状态栏字体测量。
|
|
||||||
CFont statusFont;
|
|
||||||
if (pFont == nullptr) {
|
|
||||||
NONCLIENTMETRICS ncm = {};
|
|
||||||
ncm.cbSize = sizeof(ncm);
|
|
||||||
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)
|
|
||||||
&& statusFont.CreateFontIndirect(&ncm.lfStatusFont))
|
|
||||||
pFont = &statusFont;
|
|
||||||
}
|
|
||||||
if (pFont == nullptr)
|
|
||||||
pFont = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT));
|
|
||||||
if (pFont != nullptr)
|
|
||||||
pOld = dc.SelectObject(pFont);
|
|
||||||
CSize szA = dc.GetTextExtent(a);
|
|
||||||
CSize szB = dc.GetTextExtent(b);
|
|
||||||
CSize szC = c.IsEmpty() ? CSize(0, 0) : dc.GetTextExtent(c);
|
|
||||||
if (pOld != nullptr)
|
|
||||||
dc.SelectObject(pOld);
|
|
||||||
return max(max(szA.cx, szB.cx), szC.cx) + 16;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string EventName()
|
std::string EventName()
|
||||||
@@ -1142,6 +1177,8 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
|
|||||||
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
|
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
|
||||||
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
|
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
|
||||||
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
|
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
|
||||||
|
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZSTD, &CMy2015RemoteDlg::OnExperimentCompressZstd)
|
||||||
|
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZLIB, &CMy2015RemoteDlg::OnExperimentCompressZlib)
|
||||||
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
|
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
|
||||||
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
|
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
|
||||||
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
|
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
|
||||||
@@ -2580,6 +2617,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
|||||||
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
|
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
|
||||||
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
|
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
|
||||||
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
|
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
|
||||||
|
// 生成客户端(build_client):独立开关默认关;写客户端二进制,要求只读关。
|
||||||
|
McpServer().SetBuildEnabled(THIS_CFG.GetInt("settings", "McpBuild", 0) != 0);
|
||||||
// 平台门禁:默认开。调用前拦掉目标客户端根本没实现的工具(立刻 -32005),
|
// 平台门禁:默认开。调用前拦掉目标客户端根本没实现的工具(立刻 -32005),
|
||||||
// 否则会照常下发命令然后白等超时。关掉它只影响这道拦截,不改任何工具的执行路径。
|
// 否则会照常下发命令然后白等超时。关掉它只影响这道拦截,不改任何工具的执行路径。
|
||||||
McpServer().SetPlatformGuardEnabled(
|
McpServer().SetPlatformGuardEnabled(
|
||||||
@@ -3570,10 +3609,12 @@ void CMy2015RemoteDlg::StartFrpcAuto(const FrpAutoConfig& cfg)
|
|||||||
|
|
||||||
// 设置状态栏显示的 FRP 地址 (IP:Port)
|
// 设置状态栏显示的 FRP 地址 (IP:Port)
|
||||||
m_strFrpAddr.Format(_T("%hs:%d"), cfg.serverAddr.c_str(), cfg.remotePort);
|
m_strFrpAddr.Format(_T("%hs:%d"), cfg.serverAddr.c_str(), cfg.remotePort);
|
||||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
|
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度与 UpdateStatusBarStats
|
||||||
|
// 一致,按实际地址文本实测:硬编码 250px 在高缩放比机器上会截掉端口。
|
||||||
if (m_StatusBar.GetSafeHwnd()) {
|
if (m_StatusBar.GetSafeHwnd()) {
|
||||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 250);
|
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, m_strFrpAddr));
|
||||||
m_StatusBar.SetPaneText(3, m_strFrpAddr);
|
m_StatusBar.SetPaneText(3, m_strFrpAddr);
|
||||||
|
LayoutStatusPanes();
|
||||||
}
|
}
|
||||||
|
|
||||||
Mprintf("[FRP-Auto] 启动自动代理: %s:%d -> frps:%d\n",
|
Mprintf("[FRP-Auto] 启动自动代理: %s:%d -> frps:%d\n",
|
||||||
@@ -3600,10 +3641,12 @@ void CMy2015RemoteDlg::StopFrpcAuto()
|
|||||||
|
|
||||||
// 清除状态栏 FRP 地址
|
// 清除状态栏 FRP 地址
|
||||||
m_strFrpAddr.Empty();
|
m_strFrpAddr.Empty();
|
||||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
|
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度归零隐藏,下一次
|
||||||
|
// UpdateStatusBarStats 会按 FRPS/WAN/LAN 回退地址重新实测。
|
||||||
if (m_StatusBar.GetSafeHwnd()) {
|
if (m_StatusBar.GetSafeHwnd()) {
|
||||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 0);
|
m_nPaneFrpWidth = 0;
|
||||||
m_StatusBar.SetPaneText(3, _T(""));
|
m_StatusBar.SetPaneText(3, _T(""));
|
||||||
|
LayoutStatusPanes();
|
||||||
}
|
}
|
||||||
|
|
||||||
Mprintf("[FRP-Auto] 已停止\n");
|
Mprintf("[FRP-Auto] 已停止\n");
|
||||||
@@ -3942,20 +3985,9 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
|
|||||||
Rect.right=cx;
|
Rect.right=cx;
|
||||||
Rect.bottom=cy;
|
Rect.bottom=cy;
|
||||||
m_StatusBar.MoveWindow(Rect);
|
m_StatusBar.MoveWindow(Rect);
|
||||||
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址(250px)、运行统计(180px)、到期时间(180px)
|
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址、运行统计、到期时间。
|
||||||
int paneExpire = m_strExpireDate.IsEmpty() ? 0 : 180; // 无到期信息时隐藏
|
// 宽度由 UpdateStatusBarStats 按实测文本算好,这里只负责按当前窗口宽度摆位。
|
||||||
// 优先显示上级 FRPC,其次显示本机 FRPS
|
LayoutStatusPanes();
|
||||||
int paneFrp = 250;
|
|
||||||
int paneRuntime = 180;
|
|
||||||
int paneTls = max(0, m_nPaneTlsWidth);
|
|
||||||
int paneMcp = max(0, m_nPaneMcpWidth);
|
|
||||||
int paneMsg = max(0, cx - paneTls - paneMcp - paneFrp - paneRuntime - paneExpire - 20);
|
|
||||||
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
|
|
||||||
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, paneTls);
|
|
||||||
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, paneMcp);
|
|
||||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrp);
|
|
||||||
m_StatusBar.SetPaneInfo(4, m_StatusBar.GetItemID(4), SBPS_NORMAL, paneRuntime);
|
|
||||||
m_StatusBar.SetPaneInfo(5, m_StatusBar.GetItemID(5), SBPS_NORMAL, paneExpire);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(m_ToolBar.m_hWnd!=NULL) { //工具条
|
if(m_ToolBar.m_hWnd!=NULL) { //工具条
|
||||||
@@ -4238,9 +4270,7 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
|||||||
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
|
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
|
||||||
_TR("TLS: 内置"));
|
_TR("TLS: 内置"));
|
||||||
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
|
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
|
||||||
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, m_nPaneTlsWidth);
|
|
||||||
m_StatusBar.SetPaneText(1, strTls);
|
m_StatusBar.SetPaneText(1, strTls);
|
||||||
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, m_nPaneMcpWidth);
|
|
||||||
m_StatusBar.SetPaneText(2, strMcp);
|
m_StatusBar.SetPaneText(2, strMcp);
|
||||||
|
|
||||||
// === 分区4:运行统计 ===
|
// === 分区4:运行统计 ===
|
||||||
@@ -4324,12 +4354,21 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
|||||||
strFrpDisplay.Format(_T("LAN %s:%d"), m_localPrivateIP.c_str(), THIS_CFG.Get1Int("settings", "ghost", ';', 6543));
|
strFrpDisplay.Format(_T("LAN %s:%d"), m_localPrivateIP.c_str(), THIS_CFG.Get1Int("settings", "ghost", ';', 6543));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 根据是否有内容设置分区宽度
|
// 分区宽度按实际地址文本实测,但**不小于**改动前的固定宽度:250/180/180 在
|
||||||
int paneFrpWidth = 250;
|
// 100% 缩放下是验证过的,实测值只用于在高缩放比/大字体机器上把它们撑大。
|
||||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrpWidth);
|
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, strFrpDisplay));
|
||||||
m_StatusBar.SetPaneText(3, strFrpDisplay);
|
m_StatusBar.SetPaneText(3, strFrpDisplay);
|
||||||
|
|
||||||
// === 分区4:运行统计 ===
|
// === 分区4:运行统计 ===
|
||||||
|
// 宽度取「当前文本」与「可能出现的最长格式」的较大者:数字随时间增长时分区
|
||||||
|
// 不会每分钟跳一次,缩放比高的机器上也不会把 MTBF/运行时长截掉。
|
||||||
|
CString strRuntimeWidest =
|
||||||
|
_TR("运行:") + CString(_T(" 99999d 23h ")) + _TR("(无崩溃)");
|
||||||
|
m_nPaneRuntimeWidth = max(180,
|
||||||
|
max(CalcStatusPaneWidth(m_StatusBar, strRuntime),
|
||||||
|
CalcStatusPaneWidth(m_StatusBar, strRuntimeWidest)));
|
||||||
|
m_nPaneRuntimeWidth = max(m_nPaneRuntimeWidth,
|
||||||
|
CalcStatusPaneWidth(m_StatusBar, CString(_T("MTBF: 999d23h | 100.0%"))));
|
||||||
m_StatusBar.SetPaneText(4, strRuntime);
|
m_StatusBar.SetPaneText(4, strRuntime);
|
||||||
|
|
||||||
// === 分区5:到期时间 ===
|
// === 分区5:到期时间 ===
|
||||||
@@ -4381,8 +4420,52 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
|||||||
strDays.Format(_T("(%lld"), diffDays);
|
strDays.Format(_T("(%lld"), diffDays);
|
||||||
strExpire = _TR("到期:") + CString(_T(" ")) + strDate + _T(" ") + strDays + _TR("天") + _T(")");
|
strExpire = _TR("到期:") + CString(_T(" ")) + strDate + _T(" ") + strDays + _TR("天") + _T(")");
|
||||||
}
|
}
|
||||||
|
// 宽度按文本实测,再多留一层富余:不同系统对英文字形("Expires:" 里的西文)
|
||||||
|
// 的字体回退和 GetTextExtent 有出入,多留 20px 总比截断好。下限 220 保证
|
||||||
|
// 「Expires: 2026-12-31 (41d)」这类比中文更长的串有足够空间。
|
||||||
|
m_nPaneExpireWidth = max(220, CalcStatusPaneWidth(m_StatusBar, strExpire) + 20);
|
||||||
m_StatusBar.SetPaneText(5, strExpire);
|
m_StatusBar.SetPaneText(5, strExpire);
|
||||||
|
} else {
|
||||||
|
// 无授权信息:分区宽度归零(隐藏)
|
||||||
|
m_nPaneExpireWidth = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 各分区宽度都已按当前语言/DPI 算好,统一交给布局函数落位:窗口不够宽时
|
||||||
|
// 它会按优先级收掉低价值分区,保证「到期时间」不会被挤出右边缘。
|
||||||
|
LayoutStatusPanes();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按状态栏实际宽度布置分区。所有分区宽度之和(加上消息区下限)超过窗口时,按
|
||||||
|
// 运行统计 → FRP → MCP → TLS 的顺序隐藏,避免最后一个分区被窗口右边缘裁掉——
|
||||||
|
// 英文串比中文长、缩放比更高、窗口更窄,都会把总宽度顶上去,这里统一兜底。
|
||||||
|
void CMy2015RemoteDlg::LayoutStatusPanes()
|
||||||
|
{
|
||||||
|
if (!m_StatusBar.GetSafeHwnd())
|
||||||
|
return;
|
||||||
|
|
||||||
|
CRect rc;
|
||||||
|
m_StatusBar.GetClientRect(&rc);
|
||||||
|
|
||||||
|
int widths[6] = { 0, m_nPaneTlsWidth, m_nPaneMcpWidth, m_nPaneFrpWidth,
|
||||||
|
m_nPaneRuntimeWidth, m_nPaneExpireWidth };
|
||||||
|
static const int kDropOrder[] = { 4, 3, 2, 1 };
|
||||||
|
const int kMinMessageWidth = 120;
|
||||||
|
|
||||||
|
int fixedWidth = 0;
|
||||||
|
for (int i = 1; i <= 5; ++i)
|
||||||
|
fixedWidth += max(0, widths[i]);
|
||||||
|
|
||||||
|
for (int i = 0; i < (int)(sizeof(kDropOrder) / sizeof(kDropOrder[0]))
|
||||||
|
&& fixedWidth + kMinMessageWidth > rc.Width(); ++i) {
|
||||||
|
const int idx = kDropOrder[i];
|
||||||
|
fixedWidth -= max(0, widths[idx]);
|
||||||
|
widths[idx] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int paneMsg = max(0, rc.Width() - fixedWidth - 20);
|
||||||
|
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
|
||||||
|
for (int i = 1; i <= 5; ++i)
|
||||||
|
m_StatusBar.SetPaneInfo(i, m_StatusBar.GetItemID(i), SBPS_NORMAL, max(0, widths[i]));
|
||||||
}
|
}
|
||||||
|
|
||||||
void CMy2015RemoteDlg::DeletePopupWindow(BOOL bForce)
|
void CMy2015RemoteDlg::DeletePopupWindow(BOOL bForce)
|
||||||
@@ -4898,6 +4981,13 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
|||||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND);
|
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND);
|
||||||
if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE))
|
if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE))
|
||||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND);
|
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND);
|
||||||
|
// 线缆压缩切换:放在实验功能末尾。仅当该组仍有可见项时追加——被功能位整组
|
||||||
|
// 隐藏时既不泄露,也不影响下面「空组摘除」的逻辑。
|
||||||
|
if (!IsPopupEmptyOfItems(pExperimentMenu)) {
|
||||||
|
pExperimentMenu->AppendMenu(MF_SEPARATOR);
|
||||||
|
pExperimentMenu->AppendMenuL(MF_STRING, ID_EXPERIMENT_COMPRESS_ZSTD, "线缆压缩:ZSTD");
|
||||||
|
pExperimentMenu->AppendMenuL(MF_STRING, ID_EXPERIMENT_COMPRESS_ZLIB, "线缆压缩:ZLIB");
|
||||||
|
}
|
||||||
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
|
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
|
||||||
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
|
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
|
||||||
protoInsertPos = (int)i + 1;
|
protoInsertPos = (int)i + 1;
|
||||||
@@ -5245,6 +5335,36 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
|
|||||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 线缆压缩切换(在线列表右键 → 实验功能 → 线缆压缩:ZSTD / ZLIB)----
|
||||||
|
void CMy2015RemoteDlg::OnExperimentCompressZstd() { SwitchSelectedCompression("zstd"); }
|
||||||
|
void CMy2015RemoteDlg::OnExperimentCompressZlib() { SwitchSelectedCompression("zlib"); }
|
||||||
|
|
||||||
|
VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode)
|
||||||
|
{
|
||||||
|
// 老客户端不认识 COMMAND_SET_COMPRESS,收到只会丢弃;先按能力位过滤。
|
||||||
|
int selected = 0, unsupported = 0;
|
||||||
|
EnterCriticalSection(&m_cs);
|
||||||
|
for (context* ctx : ResolveCommandTargets()) {
|
||||||
|
if (!ctx->IsLogin()) continue;
|
||||||
|
++selected;
|
||||||
|
if (!ctx->SupportsCompressSwitch()) ++unsupported;
|
||||||
|
}
|
||||||
|
LeaveCriticalSection(&m_cs);
|
||||||
|
if (selected == 0) return;
|
||||||
|
if (unsupported > 0) {
|
||||||
|
MessageBoxL(_T("选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)"),
|
||||||
|
_T("提示"), MB_ICONWARNING);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 载荷 [cmd]["zstd"|"zlib"]。客户端写入 settings\compress 后重启 StartClient 线程,
|
||||||
|
// 新连接按新模式重连;服务端按每个连接的首包自动识别算法,不影响其它主机。
|
||||||
|
std::string pkt(1, (char)COMMAND_SET_COMPRESS);
|
||||||
|
pkt += mode;
|
||||||
|
Mprintf("[compress-switch] send %s to %d host(s)\n", mode, selected);
|
||||||
|
SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size());
|
||||||
|
}
|
||||||
|
|
||||||
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
|
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
|
||||||
//
|
//
|
||||||
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
|
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
|
||||||
@@ -5755,6 +5875,28 @@ VOID CMy2015RemoteDlg::OnOnlineCmdManager()
|
|||||||
|
|
||||||
VOID CMy2015RemoteDlg::OnOnlineProcessManager()
|
VOID CMy2015RemoteDlg::OnOnlineProcessManager()
|
||||||
{
|
{
|
||||||
|
// Android 只有 root(su)设备才声明 CLIENT_CAP_PROCESS:Android 7 起 /proc 是
|
||||||
|
// hidepid=2 + SELinux,普通 APK 枚举不到其它进程。提前拦下,别让用户以为
|
||||||
|
// 点了没反应(客户端兜底会回一条消息,但主控这边先说清楚更快)。
|
||||||
|
bool blocked = false;
|
||||||
|
EnterCriticalSection(&m_cs);
|
||||||
|
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||||
|
while (pos) {
|
||||||
|
int iItem = m_CList_Online.GetNextSelectedItem(pos);
|
||||||
|
context* ctx = GetContextByListIndex(iItem);
|
||||||
|
if (ctx && ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" && !ctx->SupportsProcess()) {
|
||||||
|
blocked = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LeaveCriticalSection(&m_cs);
|
||||||
|
if (blocked) {
|
||||||
|
MessageBoxL("该 Android 主机未取得 root,无法查看进程列表。\n\n"
|
||||||
|
"Android 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。",
|
||||||
|
"提示", MB_ICONINFORMATION);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
BYTE bToken = COMMAND_SYSTEM;
|
BYTE bToken = COMMAND_SYSTEM;
|
||||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||||
}
|
}
|
||||||
@@ -10254,6 +10396,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
|||||||
{FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"},
|
{FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"},
|
||||||
{FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"},
|
{FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"},
|
||||||
};
|
};
|
||||||
|
// 压缩算法标注:服务端按连接自动识别(首个压缩包解压时定型),追加在加密协议后面。
|
||||||
|
// 不改 FormatL 的格式串,避免影响多语言翻译 key。
|
||||||
|
CString typeText = typMap[type].c_str();
|
||||||
|
switch (ctx->GetCompressMethod()) {
|
||||||
|
case COMPRESS_ZSTD: typeText += " [ZSTD]"; break;
|
||||||
|
case COMPRESS_ZLIB: typeText += " [ZLIB]"; break;
|
||||||
|
case COMPRESS_NONE: typeText += " [NONE]"; break;
|
||||||
|
default: break; // COMPRESS_UNKNOWN:不标注
|
||||||
|
}
|
||||||
CString processInfo;
|
CString processInfo;
|
||||||
if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) {
|
if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) {
|
||||||
processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]);
|
processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]);
|
||||||
@@ -10274,7 +10425,7 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
|||||||
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
|
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
|
||||||
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
|
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
|
||||||
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed,
|
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed,
|
||||||
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typeText.GetString(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
||||||
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
|
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
|
||||||
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
|
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
|
||||||
// 且结果不会被显示——跳过可消除双击浮窗的弹出延时。
|
// 且结果不会被显示——跳过可消除双击浮窗的弹出延时。
|
||||||
@@ -13556,6 +13707,22 @@ context* CMy2015RemoteDlg::FindHostByClientID(uint64_t clientID)
|
|||||||
return ctx;
|
return ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool CMy2015RemoteDlg::GetHostClientType(uint64_t clientID, CString& clientType)
|
||||||
|
{
|
||||||
|
clientType.Empty();
|
||||||
|
bool found = false;
|
||||||
|
EnterCriticalSection(&m_cs);
|
||||||
|
auto it = m_ClientIndex.find(clientID);
|
||||||
|
if (it != m_ClientIndex.end() && it->second < m_HostList.size()) {
|
||||||
|
if (context* ctx = m_HostList[it->second]) {
|
||||||
|
clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||||
|
found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LeaveCriticalSection(&m_cs);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
uint64_t CMy2015RemoteDlg::FindClientIDByIP(const std::string& ip)
|
uint64_t CMy2015RemoteDlg::FindClientIDByIP(const std::string& ip)
|
||||||
{
|
{
|
||||||
CString clientIP(ip.c_str());
|
CString clientIP(ip.c_str());
|
||||||
|
|||||||
@@ -479,12 +479,19 @@ public:
|
|||||||
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
|
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
|
||||||
int m_nPaneTlsWidth = 60; // 状态栏 TLS 分区宽度(按当前语言实测文本宽度)
|
int m_nPaneTlsWidth = 60; // 状态栏 TLS 分区宽度(按当前语言实测文本宽度)
|
||||||
int m_nPaneMcpWidth = 60; // 状态栏 MCP 分区宽度(按当前语言实测文本宽度)
|
int m_nPaneMcpWidth = 60; // 状态栏 MCP 分区宽度(按当前语言实测文本宽度)
|
||||||
|
int m_nPaneFrpWidth = 250; // 状态栏 FRP 分区宽度(按当前文本实测)
|
||||||
|
int m_nPaneRuntimeWidth = 180; // 运行统计分区宽度(按最长可能文本实测)
|
||||||
|
int m_nPaneExpireWidth = 0; // 到期时间分区宽度(按当前文本实测;0 = 无授权/隐藏)
|
||||||
void UpdateStatusBarStats(); // 更新状态栏统计信息
|
void UpdateStatusBarStats(); // 更新状态栏统计信息
|
||||||
|
void LayoutStatusPanes(); // 按窗口宽度布置状态栏分区(空间不足时按优先级隐藏)
|
||||||
CTrueColorToolBar m_ToolBar;
|
CTrueColorToolBar m_ToolBar;
|
||||||
CGridDialog * m_gridDlg = NULL;
|
CGridDialog * m_gridDlg = NULL;
|
||||||
std::vector<DllInfo*> m_DllList;
|
std::vector<DllInfo*> m_DllList;
|
||||||
context* FindHostByIP(const std::string& ip);
|
context* FindHostByIP(const std::string& ip);
|
||||||
context* FindHostByClientID(uint64_t clientID); // 线程安全:通过 clientID 精确查主连接
|
context* FindHostByClientID(uint64_t clientID); // 线程安全:通过 clientID 精确查主连接
|
||||||
|
// 线程安全:在 m_cs 内读取并返回值,避免调用方拿到裸指针后再访问附加数据;
|
||||||
|
// 找不到主连接时返回 false。
|
||||||
|
bool GetHostClientType(uint64_t clientID, CString& clientType);
|
||||||
uint64_t FindClientIDByIP(const std::string& ip); // 线程安全:在锁内获取ID
|
uint64_t FindClientIDByIP(const std::string& ip); // 线程安全:在锁内获取ID
|
||||||
void InjectTinyRunDll(const std::string& ip, int pid);
|
void InjectTinyRunDll(const std::string& ip, int pid);
|
||||||
NOTIFYICONDATA m_Nid;
|
NOTIFYICONDATA m_Nid;
|
||||||
@@ -590,6 +597,10 @@ public:
|
|||||||
afx_msg void OnExperimentDrawingBoard();
|
afx_msg void OnExperimentDrawingBoard();
|
||||||
afx_msg void OnExperimentTlsEnable();
|
afx_msg void OnExperimentTlsEnable();
|
||||||
afx_msg void OnExperimentTlsDisable();
|
afx_msg void OnExperimentTlsDisable();
|
||||||
|
// 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib)
|
||||||
|
afx_msg void OnExperimentCompressZstd();
|
||||||
|
afx_msg void OnExperimentCompressZlib();
|
||||||
|
VOID SwitchSelectedCompression(const char* mode);
|
||||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
||||||
afx_msg void OnProtoSwitchTcp();
|
afx_msg void OnProtoSwitchTcp();
|
||||||
afx_msg void OnProtoSwitchWs();
|
afx_msg void OnProtoSwitchWs();
|
||||||
|
|||||||
@@ -107,6 +107,7 @@
|
|||||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
<Link>
|
<Link>
|
||||||
|
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||||
<SubSystem>Windows</SubSystem>
|
<SubSystem>Windows</SubSystem>
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||||
@@ -142,6 +143,7 @@
|
|||||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
<Link>
|
<Link>
|
||||||
|
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||||
<SubSystem>Windows</SubSystem>
|
<SubSystem>Windows</SubSystem>
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||||
@@ -177,6 +179,7 @@
|
|||||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
<Link>
|
<Link>
|
||||||
|
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||||
<SubSystem>Windows</SubSystem>
|
<SubSystem>Windows</SubSystem>
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||||
@@ -214,6 +217,7 @@
|
|||||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
<Link>
|
<Link>
|
||||||
|
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||||
<SubSystem>Windows</SubSystem>
|
<SubSystem>Windows</SubSystem>
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||||
@@ -239,6 +243,7 @@
|
|||||||
<None Include="..\..\macos\ghost" />
|
<None Include="..\..\macos\ghost" />
|
||||||
<None Include="..\..\Release\ghost.exe" />
|
<None Include="..\..\Release\ghost.exe" />
|
||||||
<None Include="..\..\Release\SCLoader.exe" />
|
<None Include="..\..\Release\SCLoader.exe" />
|
||||||
|
<None Include="server_exports.def" />
|
||||||
<None Include="..\..\Release\ServerDll.dll" />
|
<None Include="..\..\Release\ServerDll.dll" />
|
||||||
<None Include="..\..\Release\TestRun.exe" />
|
<None Include="..\..\Release\TestRun.exe" />
|
||||||
<None Include="..\..\Release\TinyRun.dll" />
|
<None Include="..\..\Release\TinyRun.dll" />
|
||||||
@@ -330,6 +335,7 @@
|
|||||||
<ClInclude Include="McpServer.h" />
|
<ClInclude Include="McpServer.h" />
|
||||||
<ClInclude Include="McpTlsProxy.h" />
|
<ClInclude Include="McpTlsProxy.h" />
|
||||||
<ClInclude Include="McpChat.h" />
|
<ClInclude Include="McpChat.h" />
|
||||||
|
<ClInclude Include="McpBuildClient.h" />
|
||||||
<ClInclude Include="McpInternal.h" />
|
<ClInclude Include="McpInternal.h" />
|
||||||
<ClInclude Include="McpMachine.h" />
|
<ClInclude Include="McpMachine.h" />
|
||||||
<ClInclude Include="McpSettingsDlg.h" />
|
<ClInclude Include="McpSettingsDlg.h" />
|
||||||
@@ -403,6 +409,7 @@
|
|||||||
<ClCompile Include="McpServer.cpp" />
|
<ClCompile Include="McpServer.cpp" />
|
||||||
<ClCompile Include="McpTlsProxy.cpp" />
|
<ClCompile Include="McpTlsProxy.cpp" />
|
||||||
<ClCompile Include="McpChat.cpp" />
|
<ClCompile Include="McpChat.cpp" />
|
||||||
|
<ClCompile Include="McpBuildClient.cpp" />
|
||||||
<ClCompile Include="McpInternal.cpp" />
|
<ClCompile Include="McpInternal.cpp" />
|
||||||
<ClCompile Include="McpMachine.cpp" />
|
<ClCompile Include="McpMachine.cpp" />
|
||||||
<ClCompile Include="McpSettingsDlg.cpp" />
|
<ClCompile Include="McpSettingsDlg.cpp" />
|
||||||
|
|||||||
@@ -92,6 +92,7 @@
|
|||||||
<ClCompile Include="HostJson.cpp" />
|
<ClCompile Include="HostJson.cpp" />
|
||||||
<ClCompile Include="McpServer.cpp" />
|
<ClCompile Include="McpServer.cpp" />
|
||||||
<ClCompile Include="McpChat.cpp" />
|
<ClCompile Include="McpChat.cpp" />
|
||||||
|
<ClCompile Include="McpBuildClient.cpp" />
|
||||||
<ClCompile Include="McpInternal.cpp" />
|
<ClCompile Include="McpInternal.cpp" />
|
||||||
<ClCompile Include="McpMachine.cpp" />
|
<ClCompile Include="McpMachine.cpp" />
|
||||||
<ClCompile Include="McpSettingsDlg.cpp" />
|
<ClCompile Include="McpSettingsDlg.cpp" />
|
||||||
@@ -210,6 +211,7 @@
|
|||||||
<ClInclude Include="TriggerSettingsDlg.h" />
|
<ClInclude Include="TriggerSettingsDlg.h" />
|
||||||
<ClInclude Include="McpServer.h" />
|
<ClInclude Include="McpServer.h" />
|
||||||
<ClInclude Include="McpChat.h" />
|
<ClInclude Include="McpChat.h" />
|
||||||
|
<ClInclude Include="McpBuildClient.h" />
|
||||||
<ClInclude Include="McpInternal.h" />
|
<ClInclude Include="McpInternal.h" />
|
||||||
<ClInclude Include="McpMachine.h" />
|
<ClInclude Include="McpMachine.h" />
|
||||||
<ClInclude Include="McpSettingsDlg.h" />
|
<ClInclude Include="McpSettingsDlg.h" />
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ enum FCCHandler {
|
|||||||
ENCODER_MJPEG = mmioFOURCC('M', 'J', 'P', 'G'),
|
ENCODER_MJPEG = mmioFOURCC('M', 'J', 'P', 'G'),
|
||||||
// 安装x264vfw编解码器: https://sourceforge.net/projects/x264vfw/
|
// 安装x264vfw编解码器: https://sourceforge.net/projects/x264vfw/
|
||||||
ENCODER_H264 = mmioFOURCC('X', '2', '6', '4'),
|
ENCODER_H264 = mmioFOURCC('X', '2', '6', '4'),
|
||||||
|
// Android 客户端直接发 JPEG(Camera2 ImageReader 输出)。服务端用 turbojpeg
|
||||||
|
// 解码,不经过 VFW ICM——目标机不需要安装任何编解码器。
|
||||||
|
// 值必须与 common/commands.h 的 WEBCAM_FOURCC_JPEG_DIRECT 一致。
|
||||||
|
ENCODER_JPEG_DIRECT = mmioFOURCC('J', 'P', 'G', 'D'),
|
||||||
};
|
};
|
||||||
|
|
||||||
/************************************************************************
|
/************************************************************************
|
||||||
|
|||||||
@@ -47,6 +47,12 @@ enum Payload {
|
|||||||
Payload_PDF,
|
Payload_PDF,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Linux / macOS / Android 是固定架构的预编译模板,没有 Windows 的安装/加壳/增肥语义。
|
||||||
|
static bool IsWindowsTarget(int index)
|
||||||
|
{
|
||||||
|
return !(index == IndexLinuxGhost || index == IndexMacGhost || index == IndexAndroidGhost);
|
||||||
|
}
|
||||||
|
|
||||||
// CBuildDlg 对话框
|
// CBuildDlg 对话框
|
||||||
|
|
||||||
IMPLEMENT_DYNAMIC(CBuildDlg, CDialog)
|
IMPLEMENT_DYNAMIC(CBuildDlg, CDialog)
|
||||||
@@ -223,9 +229,9 @@ CBuildDlg::CBuildDlg(CWnd* pParent)
|
|||||||
, m_sInstallDir(_T(""))
|
, m_sInstallDir(_T(""))
|
||||||
, m_sInstallName(_T(""))
|
, m_sInstallName(_T(""))
|
||||||
, m_sDownloadUrl(_T(""))
|
, m_sDownloadUrl(_T(""))
|
||||||
|
, m_nWindowsCompress(CLIENT_COMPRESS_SC_AES_OLD)
|
||||||
, m_nAnchorUserCheck(-1)
|
, m_nAnchorUserCheck(-1)
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
CBuildDlg::~CBuildDlg()
|
CBuildDlg::~CBuildDlg()
|
||||||
@@ -904,6 +910,7 @@ BOOL CBuildDlg::OnInitDialog()
|
|||||||
m_ComboCompress.InsertStringL(CLIENT_SHELLCODE_BINARY, "ShellCode BIN");
|
m_ComboCompress.InsertStringL(CLIENT_SHELLCODE_BINARY, "ShellCode BIN");
|
||||||
m_ComboCompress.InsertStringL(CLIENT_COMP_SC_AES_OLD_UPX, "SC AES<Old> + UPX");
|
m_ComboCompress.InsertStringL(CLIENT_COMP_SC_AES_OLD_UPX, "SC AES<Old> + UPX");
|
||||||
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_SC_AES_OLD);
|
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_SC_AES_OLD);
|
||||||
|
m_nWindowsCompress = m_ComboCompress.GetCurSel(); // 与上面的默认值保持一致
|
||||||
|
|
||||||
m_ComboLocation.InsertStringL(0, "ProgramData");
|
m_ComboLocation.InsertStringL(0, "ProgramData");
|
||||||
m_ComboLocation.InsertStringL(1, "ProgramFiles - Admin");
|
m_ComboLocation.InsertStringL(1, "ProgramFiles - Admin");
|
||||||
@@ -995,10 +1002,12 @@ CString CBuildDlg::GetFilePath(CString type, CString filter, BOOL isOpen)
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 选 Linux / macOS 客户端时禁用对它们不适用的 Windows-only 选项:
|
// 选 Linux / macOS / Android 客户端时禁用对它们不适用的 Windows-only 选项:
|
||||||
// - 架构 (m_ComboBits):Linux/macOS binary 是固定架构的预编译资源
|
// - 架构 (m_ComboBits):这些 binary 是固定架构的预编译资源
|
||||||
// - 加壳 (m_ComboCompress):UPX / ShellCode AES 等都是 Windows PE 概念
|
// - 加壳 (m_ComboCompress):UPX / ShellCode AES 等都是 Windows PE 概念
|
||||||
// - 高级 group:安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,全是 Windows 安装/伪装相关
|
// - 运行模式 (m_ComboRunType):runningType 只有 Windows 客户端(ClientDll)消费
|
||||||
|
// - 高级 group:安装位置 / 安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,
|
||||||
|
// 全是 Windows 安装/伪装相关
|
||||||
void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
||||||
{
|
{
|
||||||
static const int ids[] = {
|
static const int ids[] = {
|
||||||
@@ -1006,8 +1015,11 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
|||||||
IDC_COMBO_BITS, IDC_STATIC_BUILD_ARCH,
|
IDC_COMBO_BITS, IDC_STATIC_BUILD_ARCH,
|
||||||
// 加壳
|
// 加壳
|
||||||
IDC_COMBO_COMPRESS, IDC_STATIC_BUILD_PACK,
|
IDC_COMBO_COMPRESS, IDC_STATIC_BUILD_PACK,
|
||||||
// 高级 group + 内部所有控件
|
// 运行模式
|
||||||
|
IDC_COMBO_RUNTYPE, IDC_STATIC_BUILD_MODE,
|
||||||
|
// 高级 group + 内部所有控件(含「安装目录」下拉框与它的标签)
|
||||||
IDC_STATIC_BUILD_ADVANCED,
|
IDC_STATIC_BUILD_ADVANCED,
|
||||||
|
IDC_STATIC_LOCATION, IDC_COMBO_INSTALL_LOC,
|
||||||
IDC_STATIC_PAYLOAD, IDC_STATIC_PAYLOAD2, IDC_STATIC_PAYLOAD3,
|
IDC_STATIC_PAYLOAD, IDC_STATIC_PAYLOAD2, IDC_STATIC_PAYLOAD3,
|
||||||
IDC_STATIC_BUILD_PADDING, IDC_STATIC_DOWNLOAD,
|
IDC_STATIC_BUILD_PADDING, IDC_STATIC_DOWNLOAD,
|
||||||
IDC_EDIT_INSTALL_DIR, IDC_EDIT_INSTALL_NAME,
|
IDC_EDIT_INSTALL_DIR, IDC_EDIT_INSTALL_NAME,
|
||||||
@@ -1019,6 +1031,41 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 载荷类型 / 下载服务几行的可见性。非 Windows 目标一律隐藏:这些控件虽然已经被
|
||||||
|
// EnableWindowsOnlyControls 置灰,但「置灰却还占着版面」会让人以为它们仍会生效。
|
||||||
|
void CBuildDlg::UpdatePayloadControls()
|
||||||
|
{
|
||||||
|
const int index = m_ComboExe.GetCurSel();
|
||||||
|
if (!IsWindowsTarget(index)) {
|
||||||
|
m_ComboPayload.ShowWindow(SW_HIDE);
|
||||||
|
m_StaticPayload.ShowWindow(SW_HIDE);
|
||||||
|
m_BtnFileServer.ShowWindow(SW_HIDE);
|
||||||
|
m_StaticDownload.ShowWindow(SW_HIDE);
|
||||||
|
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool scAes = m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES;
|
||||||
|
m_ComboPayload.ShowWindow(scAes ? SW_SHOW : SW_HIDE);
|
||||||
|
m_StaticPayload.ShowWindow(scAes ? SW_SHOW : SW_HIDE);
|
||||||
|
|
||||||
|
const bool fileServer = scAes && m_ComboPayload.GetCurSel() > Payload_Self;
|
||||||
|
m_BtnFileServer.ShowWindow(fileServer ? SW_SHOW : SW_HIDE);
|
||||||
|
const bool downloading = fileServer && m_BtnFileServer.GetCheck() == BST_CHECKED;
|
||||||
|
m_StaticDownload.ShowWindow(downloading ? SW_SHOW : SW_HIDE);
|
||||||
|
m_EditDownloadUrl.ShowWindow(downloading ? SW_SHOW : SW_HIDE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 菜单项联动:随机名称只影响安装目录/程序名,以管理员权限运行只有 Windows 客户端消费。
|
||||||
|
void CBuildDlg::UpdateTargetMenuState(BOOL windowsTarget)
|
||||||
|
{
|
||||||
|
CMenu* sub = m_MainMenu.GetSubMenu(0);
|
||||||
|
if (!sub || !GetSafeHwnd()) return;
|
||||||
|
sub->EnableMenuItem(ID_RANDOM_NAME, windowsTarget ? MF_ENABLED : MF_GRAYED);
|
||||||
|
sub->EnableMenuItem(ID_CLIENT_RUNAS_ADMIN, windowsTarget ? MF_ENABLED : MF_GRAYED);
|
||||||
|
::DrawMenuBar(GetSafeHwnd());
|
||||||
|
}
|
||||||
|
|
||||||
// 「内嵌 TLS 信任锚」复选框的可用性与文案。三个条件缺一不可(设计文档 §4.7):
|
// 「内嵌 TLS 信任锚」复选框的可用性与文案。三个条件缺一不可(设计文档 §4.7):
|
||||||
// 1. 生成目标里真的有客户端代码(ghost.exe / ServerDll.dll);
|
// 1. 生成目标里真的有客户端代码(ghost.exe / ServerDll.dll);
|
||||||
// 2. 协议会用到这份锚(TCP / HTTP;WS 走明文,WSS 的锚是反代那张证书);
|
// 2. 协议会用到这份锚(TCP / HTTP;WS 走明文,WSS 的锚是反代那张证书);
|
||||||
@@ -1036,13 +1083,22 @@ void CBuildDlg::UpdateTlsAnchorState()
|
|||||||
const bool testRun = (index == IndexTestRun_DLL || index == IndexTestRun_MemDLL ||
|
const bool testRun = (index == IndexTestRun_DLL || index == IndexTestRun_MemDLL ||
|
||||||
index == IndexTestRun_InjSC || index == IndexTestRunMsc ||
|
index == IndexTestRun_InjSC || index == IndexTestRunMsc ||
|
||||||
index == IndexTestRunSystem);
|
index == IndexTestRunSystem);
|
||||||
|
// Linux/macOS/Android 模板里没有锚块(只有 Windows 的 client/ 侧编译了
|
||||||
|
// common/tls_anchor.h),它们的信任锚由主控在线下发;文案要说清这一点,
|
||||||
|
// 不能笼统写成「不含客户端」。
|
||||||
|
const bool posixTarget = (index == IndexLinuxGhost || index == IndexMacGhost ||
|
||||||
|
index == IndexAndroidGhost);
|
||||||
|
|
||||||
CString label;
|
CString label;
|
||||||
bool usable = false;
|
bool usable = false;
|
||||||
if (!embeddable) {
|
if (!embeddable) {
|
||||||
// TestRun 只是加载器,锚要生成进 ServerDll.dll —— 这条提示比「不含客户端」有用。
|
// TestRun 只是加载器,锚要生成进 ServerDll.dll —— 这条提示比「不含客户端」有用。
|
||||||
label = testRun ? _TR("内嵌TLS信任锚(锚在ServerDll.dll里)")
|
if (testRun)
|
||||||
: _TR("内嵌TLS信任锚(该目标不含客户端)");
|
label = _TR("内嵌TLS信任锚(锚在ServerDll.dll里)");
|
||||||
|
else if (posixTarget)
|
||||||
|
label = _TR("内嵌TLS信任锚(仅Windows客户端模板支持)");
|
||||||
|
else
|
||||||
|
label = _TR("内嵌TLS信任锚(该目标不含客户端)");
|
||||||
} else if (proto != PROTO_TCP && proto != PROTO_HTTP) {
|
} else if (proto != PROTO_TCP && proto != PROTO_HTTP) {
|
||||||
label = _TR("内嵌TLS信任锚(该协议不走TLS)");
|
label = _TR("内嵌TLS信任锚(该协议不走TLS)");
|
||||||
} else if (!ServerTlsIdentity::IsReady()) {
|
} else if (!ServerTlsIdentity::IsReady()) {
|
||||||
@@ -1078,9 +1134,31 @@ void CBuildDlg::OnCbnSelchangeComboProto()
|
|||||||
|
|
||||||
void CBuildDlg::OnCbnSelchangeComboExe()
|
void CBuildDlg::OnCbnSelchangeComboExe()
|
||||||
{
|
{
|
||||||
auto n = m_ComboExe.GetCurSel();
|
const int n = m_ComboExe.GetCurSel();
|
||||||
EnableWindowsOnlyControls(!(n == IndexLinuxGhost || n == IndexMacGhost || n == IndexAndroidGhost));
|
const BOOL windowsTarget = IsWindowsTarget(n);
|
||||||
|
|
||||||
|
EnableWindowsOnlyControls(windowsTarget);
|
||||||
UpdateTlsAnchorState();
|
UpdateTlsAnchorState();
|
||||||
|
|
||||||
|
// 加壳:非 Windows 目标切到「无」并记住 Windows 下的选择,切回时恢复。否则控件
|
||||||
|
// 已置灰却还显示「ShellCode AES」,会让人以为生成时仍按它处理(生成代码其实会强制
|
||||||
|
// 改成 NONE,界面和实际行为对不上)。
|
||||||
|
if (!windowsTarget) {
|
||||||
|
const int cur = m_ComboCompress.GetCurSel();
|
||||||
|
if (cur != CLIENT_COMPRESS_NONE) {
|
||||||
|
m_nWindowsCompress = cur;
|
||||||
|
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_NONE);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_NONE &&
|
||||||
|
m_nWindowsCompress != CLIENT_COMPRESS_NONE) {
|
||||||
|
m_ComboCompress.SetCurSel(m_nWindowsCompress);
|
||||||
|
}
|
||||||
|
m_nWindowsCompress = m_ComboCompress.GetCurSel();
|
||||||
|
}
|
||||||
|
UpdateTargetMenuState(windowsTarget);
|
||||||
|
UpdatePayloadControls();
|
||||||
|
|
||||||
if (n == OTHER_ITEM) {
|
if (n == OTHER_ITEM) {
|
||||||
CString name = GetFilePath(_T("dll"), _T("All Files (*.*)|*.*|DLL Files (*.dll)|*.dll|EXE Files (*.exe)|*.exe|"));
|
CString name = GetFilePath(_T("dll"), _T("All Files (*.*)|*.*|DLL Files (*.dll)|*.dll|EXE Files (*.exe)|*.exe|"));
|
||||||
if (!name.IsEmpty()) {
|
if (!name.IsEmpty()) {
|
||||||
@@ -1150,14 +1228,13 @@ void CBuildDlg::OnClientRunasAdmin()
|
|||||||
|
|
||||||
void CBuildDlg::OnCbnSelchangeComboCompress()
|
void CBuildDlg::OnCbnSelchangeComboCompress()
|
||||||
{
|
{
|
||||||
m_ComboPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
|
// 记下用户在当前 Windows 目标下的加壳选择;切到 Linux/macOS/Android 时控件会置灰、
|
||||||
m_StaticPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
|
// 显示值切到「无」,切回来时恢复这个值。
|
||||||
m_ComboPayload.SetFocus();
|
if (IsWindowsTarget(m_ComboExe.GetCurSel()))
|
||||||
m_BtnFileServer.ShowWindow(
|
m_nWindowsCompress = m_ComboCompress.GetCurSel();
|
||||||
m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && m_ComboPayload.GetCurSel() ? SW_SHOW : SW_HIDE);
|
|
||||||
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
||||||
m_StaticDownload.ShowWindow(SW_HIDE);
|
UpdatePayloadControls();
|
||||||
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
m_ComboPayload.SetFocus();
|
||||||
static bool warned = false;
|
static bool warned = false;
|
||||||
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && !warned) {
|
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && !warned) {
|
||||||
warned = true;
|
warned = true;
|
||||||
@@ -1313,9 +1390,6 @@ void CBuildDlg::OnBnClickedCheckFileserver()
|
|||||||
|
|
||||||
void CBuildDlg::OnCbnSelchangeComboPayload()
|
void CBuildDlg::OnCbnSelchangeComboPayload()
|
||||||
{
|
{
|
||||||
m_BtnFileServer.ShowWindow(
|
|
||||||
m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && m_ComboPayload.GetCurSel() ? SW_SHOW : SW_HIDE);
|
|
||||||
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
||||||
m_StaticDownload.ShowWindow(SW_HIDE);
|
UpdatePayloadControls();
|
||||||
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,8 @@ namespace ResFileName {
|
|||||||
extern const char* GHOST_X86;
|
extern const char* GHOST_X86;
|
||||||
extern const char* GHOST_X64;
|
extern const char* GHOST_X64;
|
||||||
extern const char* GHOST_LINUX;
|
extern const char* GHOST_LINUX;
|
||||||
extern const char* GHOST_MACOS; // 预留
|
extern const char* GHOST_MACOS;
|
||||||
|
extern const char* GHOST_ANDROID;
|
||||||
// TestRun 加载器
|
// TestRun 加载器
|
||||||
extern const char* TESTRUN_X86;
|
extern const char* TESTRUN_X86;
|
||||||
extern const char* TESTRUN_X64;
|
extern const char* TESTRUN_X64;
|
||||||
@@ -109,6 +110,14 @@ public:
|
|||||||
void EnableWindowsOnlyControls(BOOL enable);
|
void EnableWindowsOnlyControls(BOOL enable);
|
||||||
CComboBox m_ComboLocation;
|
CComboBox m_ComboLocation;
|
||||||
|
|
||||||
|
// 载荷/下载服务几行的可见性(由「目标是否 Windows」+「加壳方式」+「载荷类型」共同决定)
|
||||||
|
void UpdatePayloadControls();
|
||||||
|
// 菜单项联动:随机名称 / 以管理员权限运行只对 Windows 目标有意义
|
||||||
|
void UpdateTargetMenuState(BOOL windowsTarget);
|
||||||
|
// 非 Windows 目标期间暂存的加壳选择:控件置灰后仍显示旧值会让人误以为会按它生成,
|
||||||
|
// 所以切到 Linux/macOS/Android 时先切到「无」,切回 Windows 时恢复。
|
||||||
|
int m_nWindowsCompress;
|
||||||
|
|
||||||
// 内嵌服务端 TLS 信任锚(动态创建:不改 .rc,避免 GBK 资源文件的字节级编辑)。
|
// 内嵌服务端 TLS 信任锚(动态创建:不改 .rc,避免 GBK 资源文件的字节级编辑)。
|
||||||
// 可用性三条件见 UpdateTlsAnchorState;生成时由 OnBnClickedOk 调用 EmbedTlsAnchorInto。
|
// 可用性三条件见 UpdateTlsAnchorState;生成时由 OnBnClickedOk 调用 EmbedTlsAnchorInto。
|
||||||
CButton m_ChkTlsAnchor;
|
CButton m_ChkTlsAnchor;
|
||||||
|
|||||||
@@ -1410,8 +1410,10 @@ BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOr
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD;
|
bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD;
|
||||||
|
// zlib 用 compressBound:1.001n+12 对小于约 1KB 的包会比 compressBound 少
|
||||||
|
// 1 字节,compress() 返回 Z_BUF_ERROR,小包(心跳 ACK、控制命令)被静默丢弃。
|
||||||
unsigned long ulCompressedLength = usingZstd ?
|
unsigned long ulCompressedLength = usingZstd ?
|
||||||
ZSTD_compressBound(ulOriginalLength) : (unsigned long)((double)ulOriginalLength * 1.001 + 12);
|
ZSTD_compressBound(ulOriginalLength) : compressBound(ulOriginalLength);
|
||||||
// 使用预分配缓冲区替代每次 new
|
// 使用预分配缓冲区替代每次 new
|
||||||
LPBYTE CompressedBuffer = ContextObject->GetSendCompressBuffer(ulCompressedLength);
|
LPBYTE CompressedBuffer = ContextObject->GetSendCompressBuffer(ulCompressedLength);
|
||||||
Buffer tmp(szBuffer, ulOriginalLength);
|
Buffer tmp(szBuffer, ulOriginalLength);
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,34 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// MCP「生成客户端」工具族:build_client。
|
||||||
|
//
|
||||||
|
// 这是服务端本地工具,不针对任何在线主机:把 res 目录里的客户端模板(ghost / TestRun /
|
||||||
|
// ServerDll / Linux / macOS / Android)patch 成本主控的上线信息并落盘。生成结果与
|
||||||
|
// 「生成服务端」对话框(BuildDlg.cpp)走同一套字节搬运路径:
|
||||||
|
// 资源读取 → CONNECT_ADDRESS 原地覆盖 → 版本日期校验 → 内嵌 TLS 信任锚 → 落盘
|
||||||
|
// 对话框专属的 ShellCode AES / PE→ShellCode / 载荷伪装流程不在 MCP 范围内。
|
||||||
|
//
|
||||||
|
// 独立开关 McpBuild(默认关):生成客户端会用主控的 pwdHash / 主控 ID 写出可分发的
|
||||||
|
// 二进制,属于会留下持久产物的高风险写操作,必须由管理员显式打开。
|
||||||
|
//
|
||||||
|
// 见 docs/Mcp_BuildClient_Design.md。
|
||||||
|
|
||||||
|
#include "jsoncpp/json.h"
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class CMy2015RemoteDlg;
|
||||||
|
|
||||||
|
namespace McpBuildClient {
|
||||||
|
|
||||||
|
// 是否由本模块处理(AppendTools 与 Call 必须保持一致)。
|
||||||
|
bool Handles(const std::string& toolName);
|
||||||
|
|
||||||
|
// 按当前开关(McpBuild)追加可见工具。
|
||||||
|
void AppendTools(Json::Value& tools);
|
||||||
|
|
||||||
|
// 执行工具;返回完整 JSON-RPC 响应字符串(成功 = BuildResult,失败 = BuildError)。
|
||||||
|
std::string Call(const Json::Value& id, const std::string& toolName,
|
||||||
|
const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||||
|
|
||||||
|
} // namespace McpBuildClient
|
||||||
@@ -599,6 +599,9 @@ const ToolHints kToolHints[] = {
|
|||||||
{ "chat_send", false, false, false, true },
|
{ "chat_send", false, false, false, true },
|
||||||
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
|
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
|
||||||
{ "chat_close", false, false, true, true },
|
{ "chat_close", false, false, true, true },
|
||||||
|
// --- 生成客户端(McpBuild)---
|
||||||
|
// 写服务端本机文件(可覆盖),会留下可分发的客户端二进制;不触达任何外部主机。
|
||||||
|
{ "build_client", false, true, false, false },
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
#include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用)
|
#include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用)
|
||||||
#include "McpMachine.h" // 主机管理 / 连接管理工具族
|
#include "McpMachine.h" // 主机管理 / 连接管理工具族
|
||||||
#include "McpChat.h" // 远程交谈工具族
|
#include "McpChat.h" // 远程交谈工具族
|
||||||
|
#include "McpBuildClient.h" // 生成客户端工具族(build_client)
|
||||||
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
@@ -283,12 +284,12 @@ const char* kServerInstructions =
|
|||||||
u8"2) 工具的可见性与开关\n"
|
u8"2) 工具的可见性与开关\n"
|
||||||
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
|
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
|
||||||
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
|
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
|
||||||
u8"远程交谈(chat)各有独立开关。工具不在列表里通常就不可用,直接调用会被拒(-32006 或 -32005);"
|
u8"远程交谈(chat)、生成客户端(build)各有独立开关。工具不在列表里通常就不可用,直接调用会被拒(-32006 或 -32005);"
|
||||||
u8"例外是下文提到的降级别名(list_processes / list_windows / list_services、operate_window / "
|
u8"例外是下文提到的降级别名(list_processes / list_windows / list_services、operate_window / "
|
||||||
u8"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——"
|
u8"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——"
|
||||||
u8"它们不在列表里但仍可调用。"
|
u8"它们不在列表里但仍可调用。"
|
||||||
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
|
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
|
||||||
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;"
|
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level / build_client 仍会列出,调用时才被拒;"
|
||||||
u8"get_keylog 只受 McpKeylog 开关控制(与只读模式无关):开关关闭时它不在列表里;只读模式下"
|
u8"get_keylog 只受 McpKeylog 开关控制(与只读模式无关):开关关闭时它不在列表里;只读模式下"
|
||||||
u8"只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
|
u8"只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
|
||||||
u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / "
|
u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / "
|
||||||
@@ -350,6 +351,10 @@ const char* kServerInstructions =
|
|||||||
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
|
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
|
||||||
u8"不跟随重定向,响应体上限 64KB),不要为此自己写 Invoke-WebRequest / curl;Windows 与 Linux 可用,"
|
u8"不跟随重定向,响应体上限 64KB),不要为此自己写 Invoke-WebRequest / curl;Windows 与 Linux 可用,"
|
||||||
u8"macOS 与 Android 不支持。\n"
|
u8"macOS 与 Android 不支持。\n"
|
||||||
|
u8"生成客户端:用户说「生成一个连某地址的 Linux/Windows 客户端」时用 build_client(需开启 build 开关且关闭只读)。"
|
||||||
|
u8"它把模板 patch 成本主控的上线配置后写到服务端本机,结果里 path 是服务端路径;要送到目标机再用 upload_file"
|
||||||
|
u8"(Windows/Linux/macOS 可用,Android 需用户自行安装),但 macOS/Android 的产物还需要重签(结果 tips 会给出命令)。"
|
||||||
|
u8"host/port 省略时取服务端当前有效主控地址。已存在同名文件默认拒绝,需要覆盖时显式传 overwrite=true。\n"
|
||||||
u8"\n"
|
u8"\n"
|
||||||
u8"5) 客户端平台差异\n"
|
u8"5) 客户端平台差异\n"
|
||||||
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
|
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
|
||||||
@@ -381,9 +386,13 @@ const char* kServerInstructions =
|
|||||||
u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内,"
|
u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内,"
|
||||||
u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK)、远程终端(exec_command / terminal_open / "
|
u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK)、远程终端(exec_command / terminal_open / "
|
||||||
u8"terminal_exec / terminal_close,PTY 里跑 /system/bin/sh(mksh),命令由 toybox 提供,"
|
u8"terminal_exec / terminal_close,PTY 里跑 /system/bin/sh(mksh),命令由 toybox 提供,"
|
||||||
u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005),以及 "
|
u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005)、文件管理"
|
||||||
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持"
|
u8"(list_files / download_file / upload_file / read_file;路径是盘符形式 I:\\、S:\\、P:\\,"
|
||||||
u8"(客户端未实现 SYSTEM 等命令)。\n"
|
u8"I 是内部存储、S 起是 SD 卡/U 盘、P 是应用私有目录;未授予「所有文件访问」时"
|
||||||
|
u8"I/S 下的文件可能读不了,只能正常使用 P:\\)、进程列表与杀进程"
|
||||||
|
u8"(list_processes / kill_process,仅限取得 root 的设备:Android 7+ 的 /proc 受 "
|
||||||
|
u8"hidepid=2 + SELinux 限制,非 root 设备不声明 CLIENT_CAP_PROCESS,直接返回 -32005),以及 "
|
||||||
|
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持。\n"
|
||||||
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
|
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
|
||||||
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
|
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
|
||||||
u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)"
|
u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)"
|
||||||
@@ -2410,7 +2419,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
|||||||
{
|
{
|
||||||
Json::Value tool(Json::objectValue);
|
Json::Value tool(Json::objectValue);
|
||||||
tool["name"] = "get_server_status";
|
tool["name"] = "get_server_status";
|
||||||
tool["description"] = u8"获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。";
|
tool["description"] = u8"获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/文件写入/管理/主机管理/高风险操作/键盘记录/远程交谈/生成客户端)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。";
|
||||||
|
|
||||||
Json::Value inputSchema(Json::objectValue);
|
Json::Value inputSchema(Json::objectValue);
|
||||||
inputSchema["type"] = "object";
|
inputSchema["type"] = "object";
|
||||||
@@ -2812,6 +2821,10 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
|||||||
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
|
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
|
||||||
McpChat::AppendTools(tools);
|
McpChat::AppendTools(tools);
|
||||||
|
|
||||||
|
// 20b) 生成客户端(build_client):服务端本地工具,独立开关 McpBuild(默认关),
|
||||||
|
// 另要求 McpReadonly=0;关闭时不追加任何工具。
|
||||||
|
McpBuildClient::AppendTools(tools);
|
||||||
|
|
||||||
// 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。
|
// 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。
|
||||||
// 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁,
|
// 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁,
|
||||||
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
|
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
|
||||||
@@ -3143,6 +3156,15 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C
|
|||||||
if (!ctx)
|
if (!ctx)
|
||||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||||
|
|
||||||
|
// Android 只有取得 root(su)时才声明 CLIENT_CAP_PROCESS——Android 7+ 的 /proc
|
||||||
|
// 是 hidepid=2 + SELinux,普通 APK 枚举不到其它进程。没有能力位就提前拒绝,
|
||||||
|
// 否则客户端不认 COMMAND_SYSTEM,这里会白等到超时。
|
||||||
|
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||||
|
if (clientType == "APK" && !ctx->SupportsProcess())
|
||||||
|
return BuildError(id, -32005,
|
||||||
|
"process management requires root on Android: this host has no su, "
|
||||||
|
"so it does not declare CLIENT_CAP_PROCESS");
|
||||||
|
|
||||||
CMcpServer& mcp = CMcpServer::Instance();
|
CMcpServer& mcp = CMcpServer::Instance();
|
||||||
if (!mcp.BeginPending(devId, "list_processes"))
|
if (!mcp.BeginPending(devId, "list_processes"))
|
||||||
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
|
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
|
||||||
@@ -3158,10 +3180,9 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C
|
|||||||
return BuildError(id, -32001, "Timeout waiting for process list");
|
return BuildError(id, -32001, "Timeout waiting for process list");
|
||||||
|
|
||||||
// 进程名/路径编码按 clientType 判定:Windows 走 A 接口(QueryFullProcessImageNameA 等)
|
// 进程名/路径编码按 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 进程名。
|
// 不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 进程名。
|
||||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
UINT cp = (clientType == "LNX" || clientType == "MAC" || clientType == "APK") ? CP_UTF8 : 936;
|
||||||
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
|
|
||||||
|
|
||||||
Json::Value procs = ParseProcessList(data, cp);
|
Json::Value procs = ParseProcessList(data, cp);
|
||||||
|
|
||||||
@@ -3678,7 +3699,9 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
|||||||
// (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。
|
// (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。
|
||||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||||
const bool posixFs = (clientType == "LNX" || clientType == "MAC");
|
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 上 "/" 是真实目录
|
// Windows 上 "."、"/"、"\\" 是「列盘」的历史写法;POSIX 上 "/" 是真实目录
|
||||||
// (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。
|
// (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。
|
||||||
@@ -4580,6 +4603,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
|||||||
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
|
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
|
||||||
switches["keylog"] = srv.IsKeylogEnabled();
|
switches["keylog"] = srv.IsKeylogEnabled();
|
||||||
switches["chat"] = srv.IsChatEnabled();
|
switches["chat"] = srv.IsChatEnabled();
|
||||||
|
switches["build"] = srv.IsBuildEnabled();
|
||||||
status["switches"] = switches;
|
status["switches"] = switches;
|
||||||
|
|
||||||
int onlineCount = 0, offlineCount = 0;
|
int onlineCount = 0, offlineCount = 0;
|
||||||
@@ -9816,8 +9840,11 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
|||||||
return BuildError(id, -32005,
|
return BuildError(id, -32005,
|
||||||
"macOS client is too old for kill_process: "
|
"macOS client is too old for kill_process: "
|
||||||
"it does not declare CLIENT_CAP_PROCESS; upgrade the client first");
|
"it does not declare CLIENT_CAP_PROCESS; upgrade the client first");
|
||||||
if (clientType == "APK")
|
// Android:只有 root(su)设备才声明 CLIENT_CAP_PROCESS(hidepid=2 + SELinux)
|
||||||
return BuildError(id, -32005, "kill_process is only supported on Windows, Linux and macOS hosts");
|
if (clientType == "APK" && !ctx->SupportsProcess())
|
||||||
|
return BuildError(id, -32005,
|
||||||
|
"kill_process requires root on Android: this host has no su, "
|
||||||
|
"so it does not declare CLIENT_CAP_PROCESS");
|
||||||
|
|
||||||
CMcpServer& mcp = CMcpServer::Instance();
|
CMcpServer& mcp = CMcpServer::Instance();
|
||||||
if (mcp.IsReadonly())
|
if (mcp.IsReadonly())
|
||||||
@@ -9868,7 +9895,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
|||||||
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
|
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
|
||||||
return BuildError(id, -32001, "Timeout waiting for process list (dry run)");
|
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 procs = ParseProcessList(data, cp);
|
||||||
|
|
||||||
Json::Value targets(Json::arrayValue);
|
Json::Value targets(Json::arrayValue);
|
||||||
@@ -9929,7 +9956,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
|||||||
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
|
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
|
||||||
return BuildError(id, -32001, "Timeout waiting for process list after kill");
|
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 procs = ParseProcessList(data, cp);
|
||||||
|
|
||||||
Json::Value remaining(Json::arrayValue);
|
Json::Value remaining(Json::arrayValue);
|
||||||
@@ -11991,14 +12018,21 @@ const ToolPlatform kToolPlatforms[] = {
|
|||||||
{ "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
{ "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
{ "host_set_remark", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
{ "host_set_remark", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
{ "host_set_watch_level", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
{ "host_set_watch_level", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
|
// 生成客户端只在服务端本机写文件,不触达任何主机;平台表按「全平台」登记,
|
||||||
|
// 门禁因入参没有 id 而直接放行(与其它服务端本地工具相同)。
|
||||||
|
{ "build_client", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
// ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输
|
// ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输
|
||||||
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac },
|
// Android 只在 root 设备上声明 CLIENT_CAP_PROCESS;工具内部按能力位提前拒绝
|
||||||
{ "list_files", kPlatWin|kPlatLnx|kPlatMac },
|
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
|
// 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 子连接上报
|
// Android 客户端同样实现了 COMMAND_QUERY_LOG → TOKEN_REPORT_LOG 子连接上报
|
||||||
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
{ "download_file", kPlatWin|kPlatLnx|kPlatMac },
|
{ "download_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
{ "read_file", kPlatWin|kPlatLnx|kPlatMac },
|
{ "read_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
|
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
|
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
|
||||||
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
|
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
|
||||||
// macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW
|
// macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW
|
||||||
@@ -12025,7 +12059,8 @@ const ToolPlatform kToolPlatforms[] = {
|
|||||||
{ "terminal_close", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
{ "terminal_close", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL),
|
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL),
|
||||||
// 新版声明 CLIENT_CAP_PROCESS;老构建按能力位提前拒绝。
|
// 新版声明 CLIENT_CAP_PROCESS;老构建按能力位提前拒绝。
|
||||||
{ "kill_process", kPlatWin|kPlatLnx|kPlatMac },
|
// 同上:Android 需要 root,工具内部按 CLIENT_CAP_PROCESS 提前拒绝
|
||||||
|
{ "kill_process", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||||
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl)。
|
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl)。
|
||||||
// macOS 终端已开放,但这里的 POSIX 命令用了 `base64 -w`(GNU 专有),BSD base64
|
// macOS 终端已开放,但这里的 POSIX 命令用了 `base64 -w`(GNU 专有),BSD base64
|
||||||
// 没有这个开关,头和体都会解不出来——等换成两平台通用的折行写法再放行。
|
// 没有这个开关,头和体都会解不出来——等换成两平台通用的折行写法再放行。
|
||||||
@@ -12397,6 +12432,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
|||||||
// P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。
|
// P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。
|
||||||
if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent);
|
if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent);
|
||||||
|
|
||||||
|
// 生成客户端(独立开关 McpBuild + !McpReadonly;门控在 Call 内复核)。
|
||||||
|
if (McpBuildClient::Handles(toolName)) return McpBuildClient::Call(id, toolName, args, parent);
|
||||||
|
|
||||||
// P1-1:list_hosts 与三个旧别名共用一个 handler;list_all_hosts 默认为「在线 + 离线」。
|
// P1-1:list_hosts 与三个旧别名共用一个 handler;list_all_hosts 默认为「在线 + 离线」。
|
||||||
if (toolName == "list_hosts") return BuildListHosts(id, args, parent, false);
|
if (toolName == "list_hosts") return BuildListHosts(id, args, parent, false);
|
||||||
if (toolName == "list_online_hosts") return BuildListHosts(id, args, parent, false);
|
if (toolName == "list_online_hosts") return BuildListHosts(id, args, parent, false);
|
||||||
|
|||||||
@@ -566,6 +566,13 @@ public:
|
|||||||
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
|
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
|
||||||
bool IsKeylogEnabled() const { return m_keylogEnabled; }
|
bool IsKeylogEnabled() const { return m_keylogEnabled; }
|
||||||
|
|
||||||
|
// ===== 生成客户端(build_client)=====
|
||||||
|
// 服务端本地工具:按本主控配置 patch 客户端模板并落盘。不是远程操作,但会写出
|
||||||
|
// 可分发的二进制(含 pwdHash / 主控 ID),独立开关 McpBuild(默认关)且要求
|
||||||
|
// McpReadonly=0。见 docs/Mcp_BuildClient_Design.md。
|
||||||
|
void SetBuildEnabled(bool enabled) { m_buildEnabled = enabled; }
|
||||||
|
bool IsBuildEnabled() const { return m_buildEnabled; }
|
||||||
|
|
||||||
// ===== 工具默认等待超时([settings] McpToolTimeoutMs,ini-only 键)=====
|
// ===== 工具默认等待超时([settings] McpToolTimeoutMs,ini-only 键)=====
|
||||||
// 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 600000]。
|
// 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 600000]。
|
||||||
// 改动需重启服务端生效(与其它 Mcp* 开关一致)。
|
// 改动需重启服务端生效(与其它 Mcp* 开关一致)。
|
||||||
@@ -999,6 +1006,7 @@ private:
|
|||||||
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
|
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
|
||||||
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
|
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
|
||||||
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
|
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
|
||||||
|
bool m_buildEnabled = false; // 生成客户端开关(默认关;build_client)
|
||||||
// 平台门禁(默认开):调用前拦掉「该客户端根本没实现」的工具,立刻返回 -32005。
|
// 平台门禁(默认开):调用前拦掉「该客户端根本没实现」的工具,立刻返回 -32005。
|
||||||
// 关闭后这类调用会照常下发命令,通常表现为白等超时。判据表见 McpServer.cpp 的
|
// 关闭后这类调用会照常下发命令,通常表现为白等超时。判据表见 McpServer.cpp 的
|
||||||
// kToolPlatforms,与 mcp/tools.json 的 platforms 字段对应。
|
// kToolPlatforms,与 mcp/tools.json 的 platforms 字段对应。
|
||||||
|
|||||||
@@ -181,6 +181,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
|||||||
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
|
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
|
||||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||||
r0, this, IDC_MCP_KEYLOG);
|
r0, this, IDC_MCP_KEYLOG);
|
||||||
|
m_btnBuild.Create(_TR("启用客户端生成(AI 生成客户端文件,要求只读关)"),
|
||||||
|
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||||
|
r0, this, IDC_MCP_BUILD);
|
||||||
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||||
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
|
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
|
||||||
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
|
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
|
||||||
@@ -217,6 +220,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
|||||||
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
|
m_btnBuild.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||||
@@ -239,6 +243,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
|||||||
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
|
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
|
||||||
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
|
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
|
||||||
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
|
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
|
||||||
|
int build = THIS_CFG.GetInt("settings", "McpBuild", 0);
|
||||||
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
|
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
|
||||||
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
|
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
|
||||||
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
|
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
|
||||||
@@ -265,6 +270,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
|||||||
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
|
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
|
||||||
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
|
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
|
||||||
m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
|
m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
|
||||||
|
m_btnBuild.SetCheck(build ? BST_CHECKED : BST_UNCHECKED);
|
||||||
// 白名单存储为逗号分隔,展示为每行一条。
|
// 白名单存储为逗号分隔,展示为每行一条。
|
||||||
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
|
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
|
||||||
|
|
||||||
@@ -339,6 +345,7 @@ void CMcpSettingsDlg::OnOK()
|
|||||||
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
|
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
|
||||||
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
|
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
|
||||||
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
|
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
|
||||||
|
bool build = (m_btnBuild.GetCheck() == BST_CHECKED);
|
||||||
bool https = (m_btnHttps.GetCheck() == BST_CHECKED);
|
bool https = (m_btnHttps.GetCheck() == BST_CHECKED);
|
||||||
|
|
||||||
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
|
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
|
||||||
@@ -401,6 +408,7 @@ void CMcpSettingsDlg::OnOK()
|
|||||||
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
|
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
|
||||||
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
|
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
|
||||||
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
|
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
|
||||||
|
THIS_CFG.SetInt("settings", "McpBuild", build ? 1 : 0);
|
||||||
std::string whitelist = CT2A(sWhitelist);
|
std::string whitelist = CT2A(sWhitelist);
|
||||||
whitelist = NormalizeWhitelist(whitelist);
|
whitelist = NormalizeWhitelist(whitelist);
|
||||||
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
|
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
|
||||||
@@ -416,6 +424,7 @@ void CMcpSettingsDlg::OnOK()
|
|||||||
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
|
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
|
||||||
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
|
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
|
||||||
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
|
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
|
||||||
|
_TR("客户端生成开关的改动需重启程序生效;它还会写出带主控凭据的客户端文件,请谨慎开启。") + _T("\r\n") +
|
||||||
_TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
|
_TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
|
||||||
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
|
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
|
||||||
_TR("提示"), MB_ICONINFORMATION);
|
_TR("提示"), MB_ICONINFORMATION);
|
||||||
@@ -494,6 +503,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
|||||||
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
|
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||||
y += 30;
|
y += 30;
|
||||||
|
|
||||||
|
m_btnBuild.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||||
|
y += 30;
|
||||||
|
|
||||||
const int whitelistH = 90;
|
const int whitelistH = 90;
|
||||||
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
|
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
|
||||||
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
|
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ private:
|
|||||||
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
|
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
|
||||||
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
|
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
|
||||||
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
|
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
|
||||||
|
IDC_MCP_BUILD = 1021, // 「启用客户端生成」复选框(build_client,要求只读关)
|
||||||
};
|
};
|
||||||
|
|
||||||
CButton m_btnEnable;
|
CButton m_btnEnable;
|
||||||
@@ -61,6 +62,7 @@ private:
|
|||||||
CButton m_btnMachineDangerous;
|
CButton m_btnMachineDangerous;
|
||||||
CButton m_btnChat;
|
CButton m_btnChat;
|
||||||
CButton m_btnKeylog;
|
CButton m_btnKeylog;
|
||||||
|
CButton m_btnBuild;
|
||||||
CStatic m_lblWhitelist;
|
CStatic m_lblWhitelist;
|
||||||
CEdit m_editWhitelist;
|
CEdit m_editWhitelist;
|
||||||
CButton m_btnHttps;
|
CButton m_btnHttps;
|
||||||
|
|||||||
@@ -452,7 +452,7 @@ namespace {
|
|||||||
const int kStatusInfoMinWidth = 170;
|
const int kStatusInfoMinWidth = 170;
|
||||||
const int kStatusInfoHeight = 24;
|
const int kStatusInfoHeight = 24;
|
||||||
const int kStatusInfoPadX = 16; // 文本左右留白
|
const int kStatusInfoPadX = 16; // 文本左右留白
|
||||||
// 宽度按 16px 取整:FPS / KB/s 每秒都在变,位数进位会让窗口每秒抖动一两个像素
|
// 宽度按 16px 取整,避免质量名变化时窗口左右微挪
|
||||||
const int kStatusInfoWidthStep = 16;
|
const int kStatusInfoWidthStep = 16;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -497,15 +497,20 @@ BOOL CStatusInfoWnd::Create(CWnd* pParent)
|
|||||||
|
|
||||||
int CStatusInfoWnd::MeasureWidth()
|
int CStatusInfoWnd::MeasureWidth()
|
||||||
{
|
{
|
||||||
if (m_strInfo.IsEmpty())
|
|
||||||
return kStatusInfoMinWidth;
|
|
||||||
|
|
||||||
CClientDC dc(this);
|
CClientDC dc(this);
|
||||||
CFont* pOldFont = dc.SelectObject(&m_infoFont);
|
CFont* pOldFont = dc.SelectObject(&m_infoFont);
|
||||||
CSize sz = dc.GetTextExtent(m_strInfo);
|
|
||||||
|
// 用最宽的数字占位测宽,而不是实际文本:FPS / 速率每秒都在变,按实际文本
|
||||||
|
// 量宽会让窗口在位数进位、KB/MB 单位切换时每秒 resize 一次,分层窗口 resize
|
||||||
|
// 会闪。这样宽度只随质量名变化。
|
||||||
|
CString kbSample, mbSample;
|
||||||
|
kbSample.Format(_T("888 FPS | 8888 KB/s | %s"), m_strQuality.GetString());
|
||||||
|
mbSample.Format(_T("888 FPS | 888.8 MB/s | %s"), m_strQuality.GetString());
|
||||||
|
int cx = max(dc.GetTextExtent(kbSample).cx, dc.GetTextExtent(mbSample).cx);
|
||||||
|
|
||||||
dc.SelectObject(pOldFont);
|
dc.SelectObject(pOldFont);
|
||||||
|
|
||||||
int w = sz.cx + kStatusInfoPadX * 2;
|
int w = cx + kStatusInfoPadX * 2;
|
||||||
if (w < kStatusInfoMinWidth)
|
if (w < kStatusInfoMinWidth)
|
||||||
w = kStatusInfoMinWidth;
|
w = kStatusInfoMinWidth;
|
||||||
w = (w + kStatusInfoWidthStep - 1) / kStatusInfoWidthStep * kStatusInfoWidthStep;
|
w = (w + kStatusInfoWidthStep - 1) / kStatusInfoWidthStep * kStatusInfoWidthStep;
|
||||||
@@ -538,6 +543,8 @@ void CStatusInfoWnd::UpdateInfo(double fps, double kbps, const CString& quality)
|
|||||||
else
|
else
|
||||||
m_strInfo.Format(_T("%.0f FPS | %.0f KB/s | %s"), fps, kbps, quality.GetString());
|
m_strInfo.Format(_T("%.0f FPS | %.0f KB/s | %s"), fps, kbps, quality.GetString());
|
||||||
|
|
||||||
|
m_strQuality = quality;
|
||||||
|
|
||||||
// 文本变了宽度就可能变(切档原因的四种文案长度不同),隐藏时也算,
|
// 文本变了宽度就可能变(切档原因的四种文案长度不同),隐藏时也算,
|
||||||
// 免得下次 Show 出来先窄一帧再撑开。
|
// 免得下次 Show 出来先窄一帧再撑开。
|
||||||
ResizeToFit();
|
ResizeToFit();
|
||||||
@@ -698,16 +705,27 @@ void CStatusInfoWnd::OnPaint()
|
|||||||
CPaintDC dc(this);
|
CPaintDC dc(this);
|
||||||
CRect rc;
|
CRect rc;
|
||||||
GetClientRect(&rc);
|
GetClientRect(&rc);
|
||||||
|
if (rc.IsRectEmpty())
|
||||||
|
return;
|
||||||
|
|
||||||
// 背景
|
// 分层窗口上分两步画(先擦背景再写字),合成器可能采到中间的纯色帧,
|
||||||
dc.FillSolidRect(rc, RGB(40, 40, 40));
|
// 每秒刷新一次就表现为闪。整帧画进内存 DC,一次 BitBlt 上屏。
|
||||||
|
CDC memDC;
|
||||||
|
memDC.CreateCompatibleDC(&dc);
|
||||||
|
CBitmap bmp;
|
||||||
|
bmp.CreateCompatibleBitmap(&dc, rc.Width(), rc.Height());
|
||||||
|
CBitmap* pOldBmp = memDC.SelectObject(&bmp);
|
||||||
|
|
||||||
// 文字
|
memDC.FillSolidRect(rc, RGB(40, 40, 40));
|
||||||
dc.SetBkMode(TRANSPARENT);
|
memDC.SetBkMode(TRANSPARENT);
|
||||||
dc.SetTextColor(RGB(220, 220, 220));
|
memDC.SetTextColor(RGB(220, 220, 220));
|
||||||
CFont* pOldFont = dc.SelectObject(&m_infoFont);
|
CFont* pOldFont = memDC.SelectObject(&m_infoFont);
|
||||||
dc.DrawText(m_strInfo, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
memDC.DrawText(m_strInfo, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
||||||
dc.SelectObject(pOldFont);
|
memDC.SelectObject(pOldFont);
|
||||||
|
|
||||||
|
dc.BitBlt(0, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY);
|
||||||
|
|
||||||
|
memDC.SelectObject(pOldBmp);
|
||||||
}
|
}
|
||||||
|
|
||||||
BOOL CStatusInfoWnd::OnEraseBkgnd(CDC* pDC)
|
BOOL CStatusInfoWnd::OnEraseBkgnd(CDC* pDC)
|
||||||
@@ -3442,7 +3460,21 @@ BOOL CScreenSpyDlg::PreTranslateMessage(MSG* pMsg)
|
|||||||
case WM_MBUTTONDBLCLK:
|
case WM_MBUTTONDBLCLK:
|
||||||
case WM_MBUTTONDOWN:
|
case WM_MBUTTONDOWN:
|
||||||
case WM_MBUTTONUP:
|
case WM_MBUTTONUP:
|
||||||
|
SendScaledMouseMessage(pMsg, true);
|
||||||
|
break;
|
||||||
case WM_MOUSEMOVE:
|
case WM_MOUSEMOVE:
|
||||||
|
// Android(含 TV/盒子)把悬停的 mousemove 翻译成焦点移动;MFC 控制端只在
|
||||||
|
// 按住左键拖动时转发,避免鼠标划过画面时远程焦点乱跳。触摸屏浏览器的输入
|
||||||
|
// 走 Web 前端的 touch 处理器,不经过这里。
|
||||||
|
if (m_bIsCtrl) {
|
||||||
|
if (m_androidHost < 0 && m_ClientID != 0 && g_2015RemoteDlg) {
|
||||||
|
CString clientType;
|
||||||
|
if (g_2015RemoteDlg->GetHostClientType(m_ClientID, clientType))
|
||||||
|
m_androidHost = clientType.CompareNoCase(_T("APK")) == 0 ? 1 : 0;
|
||||||
|
}
|
||||||
|
if (m_androidHost == 1 && !(pMsg->wParam & MK_LBUTTON))
|
||||||
|
break;
|
||||||
|
}
|
||||||
SendScaledMouseMessage(pMsg, true);
|
SendScaledMouseMessage(pMsg, true);
|
||||||
break;
|
break;
|
||||||
case WM_MOUSEWHEEL: {
|
case WM_MOUSEWHEEL: {
|
||||||
|
|||||||
@@ -181,14 +181,15 @@ protected:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
CString m_strInfo;
|
CString m_strInfo;
|
||||||
|
CString m_strQuality; // 最近一次的质量名,测宽时按最宽数字占位用它拼样本
|
||||||
int m_nOpacityLevel;
|
int m_nOpacityLevel;
|
||||||
bool m_bVisible;
|
bool m_bVisible;
|
||||||
|
|
||||||
// 宽度按文本自适应。原来写死 170,档位名后面跟出「(链路改善)」这类切档原因时
|
// 宽度按质量名自适应。原来写死 170,档位名后面跟出「(链路改善)」这类切档原因时
|
||||||
// 会被截断;170 现在只是下限。
|
// 会被截断;170 只是下限。FPS / 速率的位数变化不再影响宽度,避免每秒 resize。
|
||||||
int m_nWidth = 170;
|
int m_nWidth = 170;
|
||||||
CFont m_infoFont; // 绘制与测量共用,Create 里建一次
|
CFont m_infoFont; // 绘制与测量共用,Create 里建一次
|
||||||
int MeasureWidth(); // 当前文本的窗口宽度(不小于下限,按 16px 取整)
|
int MeasureWidth(); // 按最宽占位算窗口宽度(不小于下限,按 16px 取整)
|
||||||
void ResizeToFit(); // 宽度有变化时改窗口大小,保持中心不动
|
void ResizeToFit(); // 宽度有变化时改窗口大小,保持中心不动
|
||||||
|
|
||||||
// 拖动支持
|
// 拖动支持
|
||||||
@@ -208,6 +209,9 @@ class CScreenSpyDlg : public DialogBase
|
|||||||
DECLARE_DYNAMIC(CScreenSpyDlg)
|
DECLARE_DYNAMIC(CScreenSpyDlg)
|
||||||
CToolbarDlg* m_pToolbar = nullptr;
|
CToolbarDlg* m_pToolbar = nullptr;
|
||||||
CMy2015RemoteDlg* m_pParent = nullptr;
|
CMy2015RemoteDlg* m_pParent = nullptr;
|
||||||
|
// -1=尚未解析, 0=非 Android, 1=Android(APK)。只在 UI 线程读写:PreTranslateMessage
|
||||||
|
// 首次用到时解析并缓存,避免每次 mousemove 都查主连接。
|
||||||
|
int m_androidHost = -1;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
CStatusInfoWnd* m_pStatusInfoWnd = nullptr;
|
CStatusInfoWnd* m_pStatusInfoWnd = nullptr;
|
||||||
|
|||||||
@@ -741,6 +741,10 @@ public:
|
|||||||
{
|
{
|
||||||
return Parser.m_nFlagType;
|
return Parser.m_nFlagType;
|
||||||
}
|
}
|
||||||
|
virtual int GetCompressMethod() const override
|
||||||
|
{
|
||||||
|
return CompressMethod;
|
||||||
|
}
|
||||||
// Write compressed buffer.
|
// Write compressed buffer.
|
||||||
void WriteBuffer(LPBYTE data, ULONG dataLen, ULONG originLen, int cmd = -1)
|
void WriteBuffer(LPBYTE data, ULONG dataLen, ULONG originLen, int cmd = -1)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,6 +5,9 @@
|
|||||||
#include "2015Remote.h"
|
#include "2015Remote.h"
|
||||||
#include "VideoDlg.h"
|
#include "VideoDlg.h"
|
||||||
#include "afxdialogex.h"
|
#include "afxdialogex.h"
|
||||||
|
// Android 客户端直接发 JPEG:用项目已在用的 libjpeg(HideScreenSpyDlg.cpp 的
|
||||||
|
// JPG_BMP 走同一套 API 与同一份库),不再引入 turbojpeg 的 tj* 运行时符号。
|
||||||
|
#include "../common/jpeglib.h"
|
||||||
|
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
@@ -194,6 +197,11 @@ void CVideoDlg::DrawDIB(void)
|
|||||||
}
|
}
|
||||||
SysMenu->CheckMenuItem(IDM_ENABLECOMPRESS, MF_UNCHECKED);
|
SysMenu->CheckMenuItem(IDM_ENABLECOMPRESS, MF_UNCHECKED);
|
||||||
memcpy(m_BitmapData_Full, szBuffer + nHeadLen, ulBufferLen - nHeadLen);
|
memcpy(m_BitmapData_Full, szBuffer + nHeadLen, ulBufferLen - nHeadLen);
|
||||||
|
} else if (*(LPDWORD)(szBuffer + 2) == ENCODER_JPEG_DIRECT) {
|
||||||
|
// Android(Camera2)直接发 JPEG:不经过 VFW ICM,turbojpeg 直解
|
||||||
|
if (DecodeJpegFrame(szBuffer + nHeadLen, ulBufferLen - nHeadLen)) {
|
||||||
|
SysMenu->CheckMenuItem(IDM_ENABLECOMPRESS, MF_CHECKED);
|
||||||
|
}
|
||||||
} else { // 解码
|
} else { // 解码
|
||||||
////这里缓冲区里的的第二个字符正好是是否视频解码
|
////这里缓冲区里的的第二个字符正好是是否视频解码
|
||||||
InitCodec(*(LPDWORD)(szBuffer + 2)); //判断
|
InitCodec(*(LPDWORD)(szBuffer + 2)); //判断
|
||||||
@@ -210,6 +218,95 @@ void CVideoDlg::DrawDIB(void)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// libjpeg 的默认 error_exit 会调 exit():一帧畸形 JPEG 就能结束整个服务端。
|
||||||
|
// 与 HideScreenSpyDlg.cpp 的 JPG_BMP 同一套 setjmp/longjmp 兜底。
|
||||||
|
struct VideoJpegErrorMgr {
|
||||||
|
jpeg_error_mgr pub; // 必须是第一个成员
|
||||||
|
jmp_buf jb;
|
||||||
|
};
|
||||||
|
|
||||||
|
void VideoJpegErrorExit(j_common_ptr cinfo)
|
||||||
|
{
|
||||||
|
longjmp(reinterpret_cast<VideoJpegErrorMgr*>(cinfo->err)->jb, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void VideoJpegSilentMessage(j_common_ptr /*cinfo*/)
|
||||||
|
{
|
||||||
|
// 畸形/截断的 JPEG 可能被反复发送,保持静默避免刷屏
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// Android 客户端(COMMAND_WEBCAM → Camera2 JPEG)的帧解码。
|
||||||
|
// BITMAPINFO 描述的是解码后的位图(BI_RGB / 24bpp / bottom-up),与 Windows
|
||||||
|
// 摄像头的 DIB 布局一致,DrawDib 和「保存 AVI」两条路径都不用改。
|
||||||
|
bool CVideoDlg::DecodeJpegFrame(const BYTE* data, UINT len)
|
||||||
|
{
|
||||||
|
if (!data || len == 0 || !m_BitmapInfor_Full || !m_BitmapData_Full)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const int dw = m_BitmapInfor_Full->bmiHeader.biWidth;
|
||||||
|
const int dh = abs(m_BitmapInfor_Full->bmiHeader.biHeight);
|
||||||
|
if (dw <= 0 || dh <= 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// 值初始化:longjmp 回来后要 destroy,不能是栈上的垃圾指针
|
||||||
|
struct jpeg_decompress_struct jds = {};
|
||||||
|
VideoJpegErrorMgr jem;
|
||||||
|
jds.err = jpeg_std_error(&jem.pub);
|
||||||
|
jem.pub.error_exit = VideoJpegErrorExit;
|
||||||
|
jem.pub.output_message = VideoJpegSilentMessage;
|
||||||
|
|
||||||
|
volatile bool created = false;
|
||||||
|
if (setjmp(jem.jb) != 0) {
|
||||||
|
if (created) jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
jpeg_create_decompress(&jds);
|
||||||
|
created = true;
|
||||||
|
jpeg_mem_src(&jds, const_cast<unsigned char*>(data), len);
|
||||||
|
|
||||||
|
if (jpeg_read_header(&jds, TRUE) != JPEG_HEADER_OK) {
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ((int)jds.image_width != dw || (int)jds.image_height != dh) {
|
||||||
|
// BITMAPINFO 与相机分辨率在同一会话里固定;尺寸对不上宁可丢帧
|
||||||
|
Mprintf("[Video] JPEG %ux%u != bitmap %dx%d, frame dropped\n",
|
||||||
|
jds.image_width, jds.image_height, dw, dh);
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
jds.out_color_space = JCS_EXT_BGR;
|
||||||
|
if (!jpeg_start_decompress(&jds)) {
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// BITMAPINFO 的 biSizeImage 按 DWORD 对齐的 stride 计算(见 Android 客户端
|
||||||
|
// SendBitmapInfo),这里逐行写回 bottom-up:第 0 行是图像最底部。
|
||||||
|
const int stride = (dw * 3 + 3) & ~3;
|
||||||
|
while (jds.output_scanline < jds.output_height) {
|
||||||
|
const int y = (int)jds.output_scanline;
|
||||||
|
JSAMPROW row = m_BitmapData_Full + (size_t)(dh - 1 - y) * stride;
|
||||||
|
if (jpeg_read_scanlines(&jds, &row, 1) != 1) {
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!jpeg_finish_decompress(&jds)) {
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
jpeg_destroy_decompress(&jds);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void CVideoDlg::InitCodec(DWORD fccHandler)
|
void CVideoDlg::InitCodec(DWORD fccHandler)
|
||||||
{
|
{
|
||||||
if (m_pVideoCodec != NULL)
|
if (m_pVideoCodec != NULL)
|
||||||
|
|||||||
@@ -146,6 +146,9 @@ public:
|
|||||||
|
|
||||||
void SaveAvi(void);
|
void SaveAvi(void);
|
||||||
void InitCodec(DWORD fccHandler);
|
void InitCodec(DWORD fccHandler);
|
||||||
|
// Android 客户端直接发 JPEG(ENCODER_JPEG_DIRECT):turbojpeg 解到
|
||||||
|
// m_BitmapData_Full(bottom-up BGR24,与 Windows 摄像头一致)。
|
||||||
|
bool DecodeJpegFrame(const BYTE* data, UINT len);
|
||||||
|
|
||||||
CString m_aviFile; // 如果文件名不为空就写入
|
CString m_aviFile; // 如果文件名不为空就写入
|
||||||
CBmpToAvi m_aviStream;
|
CBmpToAvi m_aviStream;
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ public:
|
|||||||
virtual std::string GetProtocol() const = 0;
|
virtual std::string GetProtocol() const = 0;
|
||||||
virtual int GetServerPort() const = 0;
|
virtual int GetServerPort() const = 0;
|
||||||
virtual FlagType GetFlagType() const = 0;
|
virtual FlagType GetFlagType() const = 0;
|
||||||
|
virtual int GetCompressMethod() const = 0; // COMPRESS_ZSTD / COMPRESS_ZLIB / COMPRESS_NONE
|
||||||
virtual std::string GetGroupName() const = 0;
|
virtual std::string GetGroupName() const = 0;
|
||||||
virtual uint64_t GetAliveTime()const = 0;
|
virtual uint64_t GetAliveTime()const = 0;
|
||||||
virtual void SetLastHeartbeat(uint64_t time) = 0;
|
virtual void SetLastHeartbeat(uint64_t time) = 0;
|
||||||
@@ -199,6 +200,14 @@ public:
|
|||||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
|
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 检查客户端是否支持远程切换线缆压缩(COMMAND_SET_COMPRESS,zstd / zlib)。
|
||||||
|
// 只有声明 CLIENT_CAP_COMPRESS_SWITCH 的 Windows 客户端认识。
|
||||||
|
bool SupportsCompressSwitch() const {
|
||||||
|
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||||
|
if (caps.IsEmpty()) return false;
|
||||||
|
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_COMPRESS_SWITCH) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
// 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。
|
// 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。
|
||||||
// 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃,
|
// 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃,
|
||||||
// 服务端据此提示「先手动装一次新版」。
|
// 服务端据此提示「先手动装一次新版」。
|
||||||
|
|||||||
@@ -2058,6 +2058,8 @@ MCPԶ
|
|||||||
远程交谈开关的改动需重启程序生效。=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam.
|
远程交谈开关的改动需重启程序生效。=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam.
|
||||||
启用键盘记录(AI 采集击键)=Keylogger aktivieren (KI-Tastenaufzeichnung)
|
启用键盘记录(AI 采集击键)=Keylogger aktivieren (KI-Tastenaufzeichnung)
|
||||||
键盘记录开关的改动需重启程序生效。=Aenderungen am Keylogger-Schalter werden erst nach einem Neustart wirksam.
|
键盘记录开关的改动需重启程序生效。=Aenderungen am Keylogger-Schalter werden erst nach einem Neustart wirksam.
|
||||||
|
启用客户端生成(AI 生成客户端文件,要求只读关)=Client-Erstellung aktivieren (KI erzeugt Clientdateien; Nur-Lesen aus)
|
||||||
|
客户端生成开关的改动需重启程序生效;它还会写出带主控凭据的客户端文件,请谨慎开启。=Aenderungen am Client-Erstellungs-Schalter werden nach einem Neustart wirksam; er schreibt Clientdateien mit Master-Anmeldedaten, daher bitte vorsichtig aktivieren.
|
||||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Schreiboperationen der Maschinenverwaltung erfordern deaktivierten Nur-Lesen-Modus; Einfrieren/Auftauen von Prozessen und Stoppen/Neustarten von Diensten erfordern zusaetzlich gefaehrliche Maschinenoperationen.
|
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Schreiboperationen der Maschinenverwaltung erfordern deaktivierten Nur-Lesen-Modus; Einfrieren/Auftauen von Prozessen und Stoppen/Neustarten von Diensten erfordern zusaetzlich gefaehrliche Maschinenoperationen.
|
||||||
第 %d 个钱包地址不合法!=Wallet-Adresse #%d ist ungueltig!
|
第 %d 个钱包地址不合法!=Wallet-Adresse #%d ist ungueltig!
|
||||||
%d 新连接\r\n=%d Neue Verbindung\r\n
|
%d 新连接\r\n=%d Neue Verbindung\r\n
|
||||||
@@ -2225,6 +2227,7 @@ HTTPS
|
|||||||
内嵌TLS信任锚(首连即加密)=TLS-Vertrauensanker einbetten (TLS von Anfang an)
|
内嵌TLS信任锚(首连即加密)=TLS-Vertrauensanker einbetten (TLS von Anfang an)
|
||||||
内嵌TLS信任锚(锚在ServerDll.dll里)=TLS-Vertrauensanker einbetten (in ServerDll.dll)
|
内嵌TLS信任锚(锚在ServerDll.dll里)=TLS-Vertrauensanker einbetten (in ServerDll.dll)
|
||||||
内嵌TLS信任锚(该目标不含客户端)=TLS-Vertrauensanker einbetten (Ziel ohne Client)
|
内嵌TLS信任锚(该目标不含客户端)=TLS-Vertrauensanker einbetten (Ziel ohne Client)
|
||||||
|
内嵌TLS信任锚(仅Windows客户端模板支持)=TLS-Vertrauensanker einbetten (nur Windows-Clientvorlagen)
|
||||||
内嵌TLS信任锚(该协议不走TLS)=TLS-Vertrauensanker einbetten (Protokoll ohne TLS)
|
内嵌TLS信任锚(该协议不走TLS)=TLS-Vertrauensanker einbetten (Protokoll ohne TLS)
|
||||||
内嵌TLS信任锚(服务端未启用TLS)=TLS-Vertrauensanker einbetten (Server-TLS aus)
|
内嵌TLS信任锚(服务端未启用TLS)=TLS-Vertrauensanker einbetten (Server-TLS aus)
|
||||||
内嵌 TLS 信任锚失败,已取消生成:=TLS-Vertrauensanker konnte nicht eingebettet werden, Generierung abgebrochen:
|
内嵌 TLS 信任锚失败,已取消生成:=TLS-Vertrauensanker konnte nicht eingebettet werden, Generierung abgebrochen:
|
||||||
@@ -2252,3 +2255,9 @@ APK
|
|||||||
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=Dieses APK enthaelt keine Kennung dieses Masters; nach der Installation kann es sich sehr wahrscheinlich nicht mit diesem Server verbinden.\n\nStellen Sie sicher, dass es ueber "Client erstellen -> Android" exportiert und mit android/sign_apk.bat neu signiert wurde (ein nicht neu signiertes Paket behaelt die alte Signatur, und das System verweigert die Neuinstallation).\n\nDatei:\n%s\n\nTrotzdem senden?
|
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=Dieses APK enthaelt keine Kennung dieses Masters; nach der Installation kann es sich sehr wahrscheinlich nicht mit diesem Server verbinden.\n\nStellen Sie sicher, dass es ueber "Client erstellen -> Android" exportiert und mit android/sign_apk.bat neu signiert wurde (ein nicht neu signiertes Paket behaelt die alte Signatur, und das System verweigert die Neuinstallation).\n\nDatei:\n%s\n\nTrotzdem senden?
|
||||||
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=Das APK wurde gesendet.\n\nDie restlichen Schritte muessen am Geraet ausgefuehrt werden:\n1. Erscheint kein Installationsdialog, ist "Unbekannte Apps installieren" fuer YAMA vermutlich nicht erlaubt - in den App-Einstellungen des Geraets aktivieren;\n2. Auf "Installieren" tippen, um die Neuinstallation zu bestaetigen;\n3. Nach der Installation YAMA oeffnen und die Bildschirmaufnahme erneut erlauben (die Berechtigung geht bei jedem Update verloren).
|
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=Das APK wurde gesendet.\n\nDie restlichen Schritte muessen am Geraet ausgefuehrt werden:\n1. Erscheint kein Installationsdialog, ist "Unbekannte Apps installieren" fuer YAMA vermutlich nicht erlaubt - in den App-Einstellungen des Geraets aktivieren;\n2. Auf "Installieren" tippen, um die Neuinstallation zu bestaetigen;\n3. Nach der Installation YAMA oeffnen und die Bildschirmaufnahme erneut erlauben (die Berechtigung geht bei jedem Update verloren).
|
||||||
确认=Bestaetigen
|
确认=Bestaetigen
|
||||||
|
; === 完整性级别自检(Low Integrity 提示) ===
|
||||||
|
本程序运行在「低完整性」模式下,部分功能会异常。\n\n请以管理员身份打开命令提示符,执行:\n\n %s\n\n执行后重新启动本程序。\n\n点「是」复制上面的命令,点「否」关闭。=Dieses Programm laeuft mit niedriger Integritaetsstufe, daher funktionieren einige Funktionen nicht ordnungsgemaess.\n\nOeffnen Sie eine Eingabeaufforderung als Administrator und fuehren Sie aus:\n\n %s\n\nStarten Sie danach das Programm neu.\n\nJa kopiert den Befehl, Nein schliesst das Fenster.
|
||||||
|
完整性级别受限=Integritaetsstufe eingeschraenkt
|
||||||
|
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=Der Reparaturbefehl wurde in die Zwischenablage kopiert.\n\nDruecken Sie Win+X, oeffnen Sie Terminal (Administrator), fuegen Sie den Befehl ein und starten Sie das Programm danach neu.
|
||||||
|
已复制=Kopiert
|
||||||
|
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=Dieser Android-Host hat kein Root, daher ist die Prozessliste nicht verfuegbar.\n\nAb Android 7 ist /proc durch hidepid/SELinux eingeschraenkt; eine normale App kann keine anderen Prozesse auflisten.
|
||||||
@@ -2059,6 +2059,8 @@ MCPԶ
|
|||||||
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
|
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
|
||||||
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
|
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
|
||||||
键盘记录开关的改动需重启程序生效。=Changes to the keylogger switch take effect after restart.
|
键盘记录开关的改动需重启程序生效。=Changes to the keylogger switch take effect after restart.
|
||||||
|
启用客户端生成(AI 生成客户端文件,要求只读关)=Enable client build (AI generates client files; requires read-only mode off)
|
||||||
|
客户端生成开关的改动需重启程序生效;它还会写出带主控凭据的客户端文件,请谨慎开启。=Changes to the client build switch take effect after restart; it also writes client files containing master credentials, so enable it with care.
|
||||||
启用 HTTPS(本端口同时接受 TLS 连接)=Enable HTTPS (this port also accepts TLS connections)
|
启用 HTTPS(本端口同时接受 TLS 连接)=Enable HTTPS (this port also accepts TLS connections)
|
||||||
HTTPS 开关与证书路径的改动需重启程序生效。=Changes to the HTTPS switch and certificate paths take effect after restart.
|
HTTPS 开关与证书路径的改动需重启程序生效。=Changes to the HTTPS switch and certificate paths take effect after restart.
|
||||||
证书或私钥文件不存在,请检查路径。=Certificate or private key file not found; check the path.
|
证书或私钥文件不存在,请检查路径。=Certificate or private key file not found; check the path.
|
||||||
@@ -2237,6 +2239,7 @@ MCP:
|
|||||||
内嵌TLS信任锚(首连即加密)=Embed TLS trust anchor (TLS on first connect)
|
内嵌TLS信任锚(首连即加密)=Embed TLS trust anchor (TLS on first connect)
|
||||||
内嵌TLS信任锚(锚在ServerDll.dll里)=Embed TLS trust anchor (use ServerDll.dll)
|
内嵌TLS信任锚(锚在ServerDll.dll里)=Embed TLS trust anchor (use ServerDll.dll)
|
||||||
内嵌TLS信任锚(该目标不含客户端)=Embed TLS trust anchor (no client code here)
|
内嵌TLS信任锚(该目标不含客户端)=Embed TLS trust anchor (no client code here)
|
||||||
|
内嵌TLS信任锚(仅Windows客户端模板支持)=Embed TLS trust anchor (Windows client templates only)
|
||||||
内嵌TLS信任锚(该协议不走TLS)=Embed TLS trust anchor (protocol is not TLS)
|
内嵌TLS信任锚(该协议不走TLS)=Embed TLS trust anchor (protocol is not TLS)
|
||||||
内嵌TLS信任锚(服务端未启用TLS)=Embed TLS trust anchor (server TLS is off)
|
内嵌TLS信任锚(服务端未启用TLS)=Embed TLS trust anchor (server TLS is off)
|
||||||
内嵌 TLS 信任锚失败,已取消生成:=Failed to embed the TLS trust anchor, generation cancelled:
|
内嵌 TLS 信任锚失败,已取消生成:=Failed to embed the TLS trust anchor, generation cancelled:
|
||||||
@@ -2264,3 +2267,9 @@ APK
|
|||||||
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=This APK does not contain the identifier of this master, so once installed it very likely cannot connect back to this server.\n\nMake sure it was exported by "Build Client -> Android" and re-signed with android/sign_apk.bat (a package that was not re-signed keeps the old signature and the system will refuse to overwrite the installed app).\n\nFile:\n%s\n\nSend anyway?
|
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=This APK does not contain the identifier of this master, so once installed it very likely cannot connect back to this server.\n\nMake sure it was exported by "Build Client -> Android" and re-signed with android/sign_apk.bat (a package that was not re-signed keeps the old signature and the system will refuse to overwrite the installed app).\n\nFile:\n%s\n\nSend anyway?
|
||||||
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=The APK has been sent.\n\nThe remaining steps must be done on the device:\n1. If no installer dialog appears, the system may not allow "install unknown apps" - enable it for YAMA in the device's app settings;\n2. Tap "Install" to confirm the overwrite install;\n3. After installing, open YAMA and grant screen capture again (the grant is always lost after an upgrade).
|
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=The APK has been sent.\n\nThe remaining steps must be done on the device:\n1. If no installer dialog appears, the system may not allow "install unknown apps" - enable it for YAMA in the device's app settings;\n2. Tap "Install" to confirm the overwrite install;\n3. After installing, open YAMA and grant screen capture again (the grant is always lost after an upgrade).
|
||||||
确认=Confirm
|
确认=Confirm
|
||||||
|
; === 完整性级别自检(Low Integrity 提示) ===
|
||||||
|
本程序运行在「低完整性」模式下,部分功能会异常。\n\n请以管理员身份打开命令提示符,执行:\n\n %s\n\n执行后重新启动本程序。\n\n点「是」复制上面的命令,点「否」关闭。=This program is running at Low integrity, so some features will not work properly.\n\nOpen a command prompt as administrator and run:\n\n %s\n\nThen restart this program.\n\nClick Yes to copy the command, No to close.
|
||||||
|
完整性级别受限=Integrity Level Restricted
|
||||||
|
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=The fix command has been copied to the clipboard.\n\nPress Win+X to open Terminal (Admin), paste and run it, then restart this program.
|
||||||
|
已复制=Copied
|
||||||
|
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=This Android host is not rooted, so the process list is unavailable.\n\nAndroid 7+ restricts /proc with hidepid/SELinux, so a normal app cannot enumerate other processes.
|
||||||
@@ -2052,6 +2052,8 @@ MCPԶ
|
|||||||
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
|
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
|
||||||
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
|
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
|
||||||
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
|
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
|
||||||
|
启用客户端生成(AI 生成客户端文件,要求只读关)=啟用客戶端生成(AI 生成客戶端檔案,要求唯讀關閉)
|
||||||
|
客户端生成开关的改动需重启程序生效;它还会写出带主控凭据的客户端文件,请谨慎开启。=客戶端生成開關的變更需重新啟動程式生效;它還會寫出帶主控憑證的客戶端檔案,請謹慎開啟。
|
||||||
启用 HTTPS(本端口同时接受 TLS 连接)=啟用 HTTPS(本連接埠同時接受 TLS 連線)
|
启用 HTTPS(本端口同时接受 TLS 连接)=啟用 HTTPS(本連接埠同時接受 TLS 連線)
|
||||||
HTTPS 开关与证书路径的改动需重启程序生效。=HTTPS 開關與憑證路徑的改動需重啟程式生效。
|
HTTPS 开关与证书路径的改动需重启程序生效。=HTTPS 開關與憑證路徑的改動需重啟程式生效。
|
||||||
证书或私钥文件不存在,请检查路径。=憑證或私鑰檔案不存在,請檢查路徑。
|
证书或私钥文件不存在,请检查路径。=憑證或私鑰檔案不存在,請檢查路徑。
|
||||||
@@ -2230,6 +2232,7 @@ MCP:
|
|||||||
内嵌TLS信任锚(首连即加密)=內嵌TLS信任錨(首連即加密)
|
内嵌TLS信任锚(首连即加密)=內嵌TLS信任錨(首連即加密)
|
||||||
内嵌TLS信任锚(锚在ServerDll.dll里)=內嵌TLS信任錨(錨在ServerDll.dll裡)
|
内嵌TLS信任锚(锚在ServerDll.dll里)=內嵌TLS信任錨(錨在ServerDll.dll裡)
|
||||||
内嵌TLS信任锚(该目标不含客户端)=內嵌TLS信任錨(該目標不含客戶端)
|
内嵌TLS信任锚(该目标不含客户端)=內嵌TLS信任錨(該目標不含客戶端)
|
||||||
|
内嵌TLS信任锚(仅Windows客户端模板支持)=內嵌TLS信任錨(僅Windows客戶端模板支援)
|
||||||
内嵌TLS信任锚(该协议不走TLS)=內嵌TLS信任錨(該協議不走TLS)
|
内嵌TLS信任锚(该协议不走TLS)=內嵌TLS信任錨(該協議不走TLS)
|
||||||
内嵌TLS信任锚(服务端未启用TLS)=內嵌TLS信任錨(服務端未啟用TLS)
|
内嵌TLS信任锚(服务端未启用TLS)=內嵌TLS信任錨(服務端未啟用TLS)
|
||||||
内嵌 TLS 信任锚失败,已取消生成:=內嵌 TLS 信任錨失敗,已取消生成:
|
内嵌 TLS 信任锚失败,已取消生成:=內嵌 TLS 信任錨失敗,已取消生成:
|
||||||
@@ -2257,3 +2260,9 @@ APK
|
|||||||
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=這個 APK 裡沒有找到本主控的標識,裝上去很可能連不回本伺服器。\n\n請確認它是「生成客戶端 → 安卓」匯出的包,並且已經用 android/sign_apk.bat 重新簽名(未重簽的包簽名對不上,系統會拒絕覆寫安裝)。\n\n檔案:\n%s\n\n仍然下發嗎?
|
这个 APK 里没有找到本主控的标识,装上去很可能连不回本服务器。\n\n请确认它是「生成客户端 → 安卓」导出的包,并且已经用 android/sign_apk.bat 重新签名(未重签的包签名对不上,系统会拒绝覆盖安装)。\n\n文件:\n%s\n\n仍然下发吗?=這個 APK 裡沒有找到本主控的標識,裝上去很可能連不回本伺服器。\n\n請確認它是「生成客戶端 → 安卓」匯出的包,並且已經用 android/sign_apk.bat 重新簽名(未重簽的包簽名對不上,系統會拒絕覆寫安裝)。\n\n檔案:\n%s\n\n仍然下發嗎?
|
||||||
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=APK 已下發。\n\n接下來的操作需要在裝置上完成:\n1. 若沒彈出安裝框,可能是系統未授權「安裝未知應用」——在裝置的應用設定裡給 YAMA 打開;\n2. 點「安裝」確認覆寫安裝;\n3. 安裝完成後打開 YAMA,重新授權錄屏(升級後授權一定會失效)。
|
APK 已下发。\n\n接下来的操作需要在设备上完成:\n1. 若没弹出安装框,可能是系统未授权「安装未知应用」——在设备的应用设置里给 YAMA 打开;\n2. 点「安装」确认覆盖安装;\n3. 安装完成后打开 YAMA,重新授权录屏(升级后授权一定会失效)。=APK 已下發。\n\n接下來的操作需要在裝置上完成:\n1. 若沒彈出安裝框,可能是系統未授權「安裝未知應用」——在裝置的應用設定裡給 YAMA 打開;\n2. 點「安裝」確認覆寫安裝;\n3. 安裝完成後打開 YAMA,重新授權錄屏(升級後授權一定會失效)。
|
||||||
确认=確認
|
确认=確認
|
||||||
|
; === 完整性级别自检(Low Integrity 提示) ===
|
||||||
|
本程序运行在「低完整性」模式下,部分功能会异常。\n\n请以管理员身份打开命令提示符,执行:\n\n %s\n\n执行后重新启动本程序。\n\n点「是」复制上面的命令,点「否」关闭。=本程式執行在「低完整性」模式下,部分功能會異常。\n\n請以系統管理員身分開啟命令提示字元,執行:\n\n %s\n\n執行後重新啟動本程式。\n\n點「是」複製上面的命令,點「否」關閉。
|
||||||
|
完整性级别受限=完整性層級受限
|
||||||
|
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=修復命令已複製到剪貼簿。\n\n請按 Win+X 開啟「終端機(系統管理員)」,貼上執行後再重新啟動本程式。
|
||||||
|
已复制=已複製
|
||||||
|
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=該 Android 主機未取得 root,無法查看處理程序清單。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,一般應用程式無法列舉其他處理程序。
|
||||||
@@ -1123,6 +1123,8 @@
|
|||||||
#define ID_PROTO_SWITCH_WSS 33100
|
#define ID_PROTO_SWITCH_WSS 33100
|
||||||
// 高级菜单开关:把服务端 TLS 证书内嵌进下发给客户端的 ServerDll
|
// 高级菜单开关:把服务端 TLS 证书内嵌进下发给客户端的 ServerDll
|
||||||
#define ID_TOOL_EMBED_TLS_ANCHOR 33101
|
#define ID_TOOL_EMBED_TLS_ANCHOR 33101
|
||||||
|
#define ID_EXPERIMENT_COMPRESS_ZSTD 33107
|
||||||
|
#define ID_EXPERIMENT_COMPRESS_ZLIB 33108
|
||||||
// 高级 → 运行测试程序:把内存里的 ServerDll 在主控进程内加载,本机上线一台测试主机
|
// 高级 → 运行测试程序:把内存里的 ServerDll 在主控进程内加载,本机上线一台测试主机
|
||||||
#define ID_TOOL_RUN_TEST 33106
|
#define ID_TOOL_RUN_TEST 33106
|
||||||
#define ID_EXIT_FULLSCREEN 40001
|
#define ID_EXIT_FULLSCREEN 40001
|
||||||
@@ -1132,7 +1134,7 @@
|
|||||||
#ifdef APSTUDIO_INVOKED
|
#ifdef APSTUDIO_INVOKED
|
||||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||||
#define _APS_NEXT_RESOURCE_VALUE 418
|
#define _APS_NEXT_RESOURCE_VALUE 418
|
||||||
#define _APS_NEXT_COMMAND_VALUE 33107
|
#define _APS_NEXT_COMMAND_VALUE 33109
|
||||||
#define _APS_NEXT_CONTROL_VALUE 2621
|
#define _APS_NEXT_CONTROL_VALUE 2621
|
||||||
#define _APS_NEXT_SYMED_VALUE 105
|
#define _APS_NEXT_SYMED_VALUE 105
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
; Host identity block for auxiliary tooling/diagnostics.
|
||||||
|
EXPORTS
|
||||||
|
HostIdentityBlock=?g_MasterID@@3PADA
|
||||||
@@ -72,6 +72,7 @@ Web 应用能力 (Phase 3-7):
|
|||||||
- **鼠标 / 键盘输入**: Win32 消息映射 (`WM_*` / `VK_*` / `MK_*`),MSG64 48 字节布局直传客户端
|
- **鼠标 / 键盘输入**: Win32 消息映射 (`WM_*` / `VK_*` / `MK_*`),MSG64 48 字节布局直传客户端
|
||||||
- **Web 终端**: xterm.js + Windows ConPTY / 旧 cmd 管道双模式;二进制 "TRM1" 帧分流;尺寸自适应;单设备单 viewer
|
- **Web 终端**: xterm.js + Windows ConPTY / 旧 cmd 管道双模式;二进制 "TRM1" 帧分流;尺寸自适应;单设备单 viewer
|
||||||
- **用户与分组**: admin 可创建/删除 viewer 账号、配置 allowed_groups,users.json 原子写入
|
- **用户与分组**: admin 可创建/删除 viewer 账号、配置 allowed_groups,users.json 原子写入
|
||||||
|
- **转移主机**: 把主机临时交给另一台 master(通常是 MFC 服务端)做客户端升级,到期由客户端自动连回本机;转移状态持久化并在设备卡片上倒计时显示。仅 Go 服务端下发 `device_list.transfer`,MFC 共用同一份页面但不会出现该入口
|
||||||
|
|
||||||
## 支持的命令
|
## 支持的命令
|
||||||
|
|
||||||
@@ -102,6 +103,7 @@ Web 应用能力 (Phase 3-7):
|
|||||||
| `COMMAND_SHELL` | 40 | 请求开启 shell 子连接 |
|
| `COMMAND_SHELL` | 40 | 请求开启 shell 子连接 |
|
||||||
| `CMD_TERMINAL_RESIZE` | 81 | PTY 尺寸 (cols / rows int16 LE) |
|
| `CMD_TERMINAL_RESIZE` | 81 | PTY 尺寸 (cols / rows int16 LE) |
|
||||||
| `COMMAND_BYE` | 204 | 优雅断开屏幕 / 终端 |
|
| `COMMAND_BYE` | 204 | 优雅断开屏幕 / 终端 |
|
||||||
|
| `COMMAND_ASSIGN_MASTER` | 207 | 转移主机:`host:port:days::transport` + `SHARE_TYPE_YAMA_FOREVER`(transport:0=TCP / 5=WS / 6=WSS),客户端到期自动连回本机 |
|
||||||
| `CMD_MASTERSETTING` | 215 | 主控配置 + HMAC 签名 (1000B) |
|
| `CMD_MASTERSETTING` | 215 | 主控配置 + HMAC 签名 (1000B) |
|
||||||
| `CMD_HEARTBEAT_ACK` | 216 | 心跳响应(携带 Authorized 字段) |
|
| `CMD_HEARTBEAT_ACK` | 216 | 心跳响应(携带 Authorized 字段) |
|
||||||
| `TOKEN_CONN_AUTH` | 246 | 子连接身份握手响应 (256B) |
|
| `TOKEN_CONN_AUTH` | 246 | 子连接身份握手响应 (256B) |
|
||||||
@@ -172,6 +174,9 @@ VSCode F5 调试时由 `sync-web-assets` preLaunchTask 自动同步。
|
|||||||
| `YAMA_WEB_TRUST_PROXY` | Set to `1` only when running behind a reverse proxy you control (caddy / nginx / cloudflare). Switches client-IP extraction to use the last entry of `X-Forwarded-For` instead of `RemoteAddr`, so per-IP login rate limit sees the real client. Direct-exposure deployments MUST leave this unset — otherwise attackers can spoof the header to evade rate limits. | `1` |
|
| `YAMA_WEB_TRUST_PROXY` | Set to `1` only when running behind a reverse proxy you control (caddy / nginx / cloudflare). Switches client-IP extraction to use the last entry of `X-Forwarded-For` instead of `RemoteAddr`, so per-IP login rate limit sees the real client. Direct-exposure deployments MUST leave this unset — otherwise attackers can spoof the header to evade rate limits. | `1` |
|
||||||
| `YAMA_AUDIT_LOG` | 安全审计日志路径(JSON lines)。默认 `logs/audit.log`;设为 `off` / `none` / `0` / `-` 关闭独立文件(审计记录仍会写入 `logs/server.log`)。审计记录带 `audit=true` 和稳定的 `event` 名,便于告警与检索。 | `/var/log/yama/audit.log` |
|
| `YAMA_AUDIT_LOG` | 安全审计日志路径(JSON lines)。默认 `logs/audit.log`;设为 `off` / `none` / `0` / `-` 关闭独立文件(审计记录仍会写入 `logs/server.log`)。审计记录带 `audit=true` 和稳定的 `event` 名,便于告警与检索。 | `/var/log/yama/audit.log` |
|
||||||
| `YAMA_SSO_JWT_SECRET` | **[SSO]** Shared HS256 secret for bridging the parent portal's `auth_token` JWT into a YAMA web session via `/sso`. Must equal the upstream portal's signing key (FMS: `SERVER_PRIVATE_KEY`). **Only `admin` portal users are auto-logged-in**; other roles still need YAMA's own web login. Unset → SSO disabled, `/sso` returns 401. | `<shared-secret>` |
|
| `YAMA_SSO_JWT_SECRET` | **[SSO]** Shared HS256 secret for bridging the parent portal's `auth_token` JWT into a YAMA web session via `/sso`. Must equal the upstream portal's signing key (FMS: `SERVER_PRIVATE_KEY`). **Only `admin` portal users are auto-logged-in**; other roles still need YAMA's own web login. Unset → SSO disabled, `/sso` returns 401. | `<shared-secret>` |
|
||||||
|
| `YAMA_TRANSFER_TARGET` | **[转移主机]** 预填 Web UI「转移主机」弹窗的目标 `host:port`。仅作默认值,操作员仍可改填其它地址;留空则按钮照常可用、输入框为空。 | `mfc.example.com:6543` |
|
||||||
|
| `YAMA_TRANSFER_DAYS` | **[转移主机]** 预填的转移天数(到期后客户端自动连回本机),默认 `1`。取值 `(0, 365]`,弹窗输入框下限为 `0.5`;非正数或无法解析时忽略并沿用默认值。 | `2` |
|
||||||
|
| `YAMA_TRANSFER_TRANSPORT` | **[转移主机]** 转移后主机连接目标主控所用的传输方式:`0`=TCP(默认,MFC 主控直连端口)、`5`=WS、`6`=WSS。命令里始终携带该段——缺省时客户端会沿用当前链路的传输方式,WSS 主机转移到直连主控会一直连不上。 | `0` |
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Linux/macOS
|
# Linux/macOS
|
||||||
@@ -347,6 +352,7 @@ Web 端与设备端的认证、授权、远程控制操作会额外写入**独
|
|||||||
| `remote.clipboard.get` / `.set` | 剪贴板读取 / 写入(只记字节数,**不记内容**) |
|
| `remote.clipboard.get` / `.set` | 剪贴板读取 / 写入(只记字节数,**不记内容**) |
|
||||||
| `remote.rdp_reset` | 远程 RDP 会话归位操作 |
|
| `remote.rdp_reset` | 远程 RDP 会话归位操作 |
|
||||||
| `admin.user.create` / `admin.user.delete` / `admin.device.delete` | 管理操作(`target` / `device_id` / `mode`) |
|
| `admin.user.create` / `admin.user.delete` / `admin.device.delete` | 管理操作(`target` / `device_id` / `mode`) |
|
||||||
|
| `admin.device.transfer` | 转移主机(`device_id` / `target` / `days` / `until`);被拒时带 `ok:false` 与 `reason`(`invalid_target`、`already_transferred`、`offline`、`send_failed`),并以 `WARN` 级别记录 |
|
||||||
| `admin.audit.query` | 管理员在网页查询审计日志(记录筛选条件与命中数) |
|
| `admin.audit.query` | 管理员在网页查询审计日志(记录筛选条件与命中数) |
|
||||||
| `device.online` / `device.offline` | 受控设备上线 / 下线 |
|
| `device.online` / `device.offline` | 受控设备上线 / 下线 |
|
||||||
| `device.auth.success` / `.failure` / `.throttled` / `.heartbeat.success` | 设备 TCP 授权结果(**只记 passcode 长度,不记 passcode**) |
|
| `device.auth.success` / `.failure` / `.throttled` / `.heartbeat.success` | 设备 TCP 授权结果(**只记 passcode 长度,不记 passcode**) |
|
||||||
|
|||||||
@@ -50,6 +50,12 @@ type Query struct {
|
|||||||
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
|
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
|
||||||
WarnOnly bool `json:"warn_only"` // only level=warn records
|
WarnOnly bool `json:"warn_only"` // only level=warn records
|
||||||
|
|
||||||
|
// DeviceAllowed, when non-nil, drops records that carry a device_id the
|
||||||
|
// predicate rejects. The MCP endpoint uses it to hide devices bound to a
|
||||||
|
// web user; the web audit page leaves it nil. Not serialisable: it is a
|
||||||
|
// server-side policy hook, not a client filter.
|
||||||
|
DeviceAllowed func(deviceID string) bool `json:"-"`
|
||||||
|
|
||||||
// EventContains is a case-insensitive substring match on the event column.
|
// EventContains is a case-insensitive substring match on the event column.
|
||||||
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
|
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
|
||||||
// exposes a "type contains" filter, which maps here.
|
// exposes a "type contains" filter, which maps here.
|
||||||
@@ -219,6 +225,13 @@ func recordMatches(rec map[string]any, line string, q Query, from time.Time, has
|
|||||||
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
|
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if q.DeviceAllowed != nil {
|
||||||
|
for _, id := range RecordDeviceIDs(rec) {
|
||||||
|
if !q.DeviceAllowed(id) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if q.WarnOnly && StringField(rec, "level") != "warn" {
|
if q.WarnOnly && StringField(rec, "level") != "warn" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -256,6 +269,39 @@ func eventFilterMatches(filter, event string) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RecordDeviceIDs returns every device identifier an audit record names.
|
||||||
|
// Producers spell the target differently: web remote-control events use
|
||||||
|
// device_id, MCP tool calls use device, and admin bind/unbind records use a
|
||||||
|
// devices array. A device record written by the MCP audit path uses "-" for
|
||||||
|
// "no device"; that sentinel is not an id.
|
||||||
|
func RecordDeviceIDs(rec map[string]any) []string {
|
||||||
|
var ids []string
|
||||||
|
add := func(v any) {
|
||||||
|
s, ok := v.(string)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if s == "" || s == "-" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ids = append(ids, s)
|
||||||
|
}
|
||||||
|
add(rec["device_id"])
|
||||||
|
add(rec["device"])
|
||||||
|
switch list := rec["devices"].(type) {
|
||||||
|
case []any:
|
||||||
|
for _, item := range list {
|
||||||
|
add(item)
|
||||||
|
}
|
||||||
|
case []string:
|
||||||
|
for _, item := range list {
|
||||||
|
add(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
// StringField returns rec[key] when it is a string, else "".
|
// StringField returns rec[key] when it is a string, else "".
|
||||||
func StringField(rec map[string]any, key string) string {
|
func StringField(rec map[string]any, key string) string {
|
||||||
s, _ := rec[key].(string)
|
s, _ := rec[key].(string)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
@@ -1173,6 +1174,20 @@ func main() {
|
|||||||
log.Warn("Failed to load %s: %v (continuing with admin only)", usersFile, err)
|
log.Warn("Failed to load %s: %v (continuing with admin only)", usersFile, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Per-device owner bindings live next to users.json. A malformed file is
|
||||||
|
// fatal: silently starting with an empty table would make every private
|
||||||
|
// device public to all admin-role users.
|
||||||
|
aclFile := os.Getenv("YAMA_DEVICE_ACL_FILE")
|
||||||
|
if aclFile == "" {
|
||||||
|
aclFile = filepath.Join(filepath.Dir(usersFile), "device_acl.json")
|
||||||
|
rememberDefault("YAMA_DEVICE_ACL_FILE", aclFile)
|
||||||
|
}
|
||||||
|
deviceACL := web.NewDeviceACL(aclFile)
|
||||||
|
if err := deviceACL.Load(); err != nil {
|
||||||
|
log.Fatal("Failed to load device ACL: %v", err)
|
||||||
|
}
|
||||||
|
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
||||||
|
|
||||||
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
|
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
|
||||||
// (the real TCP peer — there is no X-Forwarded-For on the device port).
|
// (the real TCP peer — there is no X-Forwarded-For on the device port).
|
||||||
// Generous enough that a NAT office whose devices all re-auth at once is
|
// Generous enough that a NAT office whose devices all re-auth at once is
|
||||||
@@ -1259,6 +1274,8 @@ func main() {
|
|||||||
AuditPath: auditFile,
|
AuditPath: auditFile,
|
||||||
Port: *httpPort,
|
Port: *httpPort,
|
||||||
Bind: bindAddr,
|
Bind: bindAddr,
|
||||||
|
// Devices bound to a web user are invisible/unreachable through MCP.
|
||||||
|
DeviceACL: deviceACL,
|
||||||
})
|
})
|
||||||
if mcpSrv.Enabled() {
|
if mcpSrv.Enabled() {
|
||||||
// Terminal tools need the hub's shell events (ready/data/closed).
|
// Terminal tools need the hub's shell events (ready/data/closed).
|
||||||
@@ -1358,6 +1375,38 @@ func main() {
|
|||||||
} else {
|
} else {
|
||||||
log.Info("SSO disabled (YAMA_SSO_JWT_SECRET not set) — web login only")
|
log.Info("SSO disabled (YAMA_SSO_JWT_SECRET not set) — web login only")
|
||||||
}
|
}
|
||||||
|
// "Transfer host": the web UI hands a host over to another master (the MFC
|
||||||
|
// server) so that master can push a client upgrade to it; the host returns
|
||||||
|
// to this server on its own once the days run out. The target only
|
||||||
|
// pre-fills the dialog — the operator can still type another one, and an
|
||||||
|
// empty value keeps the feature available with an empty field.
|
||||||
|
transferTarget := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TARGET"))
|
||||||
|
transferDays := 1.0
|
||||||
|
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_DAYS")); v != "" {
|
||||||
|
if d, err := strconv.ParseFloat(v, 64); err == nil && d > 0 {
|
||||||
|
transferDays = d
|
||||||
|
} else {
|
||||||
|
log.Info("Ignoring YAMA_TRANSFER_DAYS=%q (want a positive number)", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The link the transferred host uses to reach the target. It is always in
|
||||||
|
// the command: clients keep their current link when it is missing, so a
|
||||||
|
// WSS-managed host would try WSS against a plain-TCP master. Default TCP
|
||||||
|
// matches what an MFC master listens on.
|
||||||
|
transferTransport := protocol.TransferTransportTCP
|
||||||
|
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TRANSPORT")); v != "" {
|
||||||
|
switch v {
|
||||||
|
case "0", "5", "6":
|
||||||
|
transferTransport, _ = strconv.Atoi(v)
|
||||||
|
default:
|
||||||
|
log.Info("Ignoring YAMA_TRANSFER_TRANSPORT=%q (want 0=TCP, 5=WS, 6=WSS)", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if transferTarget != "" {
|
||||||
|
log.Info("Host transfer dialog pre-filled with %s (%.1f days, transport=%d)",
|
||||||
|
transferTarget, transferDays, transferTransport)
|
||||||
|
}
|
||||||
|
|
||||||
webCfg := web.Config{
|
webCfg := web.Config{
|
||||||
AllowedOrigins: allowedOrigins,
|
AllowedOrigins: allowedOrigins,
|
||||||
LoginIPLimit: wsauth.NewRateLimiter(10, time.Minute),
|
LoginIPLimit: wsauth.NewRateLimiter(10, time.Minute),
|
||||||
@@ -1366,6 +1415,10 @@ func main() {
|
|||||||
BasePath: basePath,
|
BasePath: basePath,
|
||||||
BrandName: brandName,
|
BrandName: brandName,
|
||||||
SSO: ssoDetector,
|
SSO: ssoDetector,
|
||||||
|
DeviceACL: deviceACL,
|
||||||
|
TransferTarget: transferTarget,
|
||||||
|
TransferDays: transferDays,
|
||||||
|
TransferTransport: transferTransport,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start HTTP server for web UI. Hub gives it read-only access to the
|
// Start HTTP server for web UI. Hub gives it read-only access to the
|
||||||
|
|||||||
@@ -58,6 +58,14 @@ type Record struct {
|
|||||||
|
|
||||||
FirstSeen int64 `json:"first_seen"`
|
FirstSeen int64 `json:"first_seen"`
|
||||||
LastSeen int64 `json:"last_seen"`
|
LastSeen int64 `json:"last_seen"`
|
||||||
|
|
||||||
|
// TransferTo / TransferUntil mark a host that was handed over to another
|
||||||
|
// master (COMMAND_ASSIGN_MASTER): target is "host:port", until is the unix
|
||||||
|
// second the client goes back to its original master on its own. The store
|
||||||
|
// only remembers it for display — it never acts on the deadline, and a
|
||||||
|
// login here clears it because that means the host is back.
|
||||||
|
TransferTo string `json:"transfer_to,omitempty"`
|
||||||
|
TransferUntil int64 `json:"transfer_until,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type fileShape struct {
|
type fileShape struct {
|
||||||
@@ -165,6 +173,13 @@ func (s *Store) upsertAt(d hub.DeviceInfo, at time.Time) {
|
|||||||
rec.IP = d.IP
|
rec.IP = d.IP
|
||||||
rec.Screen = d.Screen
|
rec.Screen = d.Screen
|
||||||
rec.LastSeen = now
|
rec.LastSeen = now
|
||||||
|
// A login on this server means the host is here, not at the master it was
|
||||||
|
// handed to: either it came back early (the upgrade finished, or the target
|
||||||
|
// was unreachable) or the deadline passed while this server was down. In
|
||||||
|
// both cases the marker would label an online card as "transferred" and
|
||||||
|
// keep the operator from transferring it again until the deadline.
|
||||||
|
rec.TransferTo = ""
|
||||||
|
rec.TransferUntil = 0
|
||||||
s.online[d.ID] = true
|
s.online[d.ID] = true
|
||||||
|
|
||||||
s.pruneLocked()
|
s.pruneLocked()
|
||||||
@@ -244,6 +259,59 @@ func (s *Store) Offline(online map[string]struct{}) []hub.DeviceInfo {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetTransfer marks id as handed over to target ("host:port") until the given
|
||||||
|
// unix second. Reports false when the device has no history record — only a
|
||||||
|
// device that logged in at least once can be transferred, and the marker has
|
||||||
|
// nowhere to live otherwise.
|
||||||
|
func (s *Store) SetTransfer(id, target string, until int64) bool {
|
||||||
|
if id == "" || target == "" || until <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
rec, ok := s.devices[id]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
rec.TransferTo = target
|
||||||
|
rec.TransferUntil = until
|
||||||
|
s.markDirtyLocked()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearTransfer forgets the handover marker and reports whether one was set.
|
||||||
|
func (s *Store) ClearTransfer(id string) bool {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
rec, ok := s.devices[id]
|
||||||
|
if !ok || rec.TransferUntil == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
rec.TransferTo = ""
|
||||||
|
rec.TransferUntil = 0
|
||||||
|
s.markDirtyLocked()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transfer returns the current handover marker, dropping it once the deadline
|
||||||
|
// has passed: the client returns to its original master by itself, so an
|
||||||
|
// expired marker would only mislabel the card forever.
|
||||||
|
func (s *Store) Transfer(id string) (target string, until int64, ok bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
rec, found := s.devices[id]
|
||||||
|
if !found || rec.TransferUntil == 0 {
|
||||||
|
return "", 0, false
|
||||||
|
}
|
||||||
|
if time.Now().Unix() >= rec.TransferUntil {
|
||||||
|
rec.TransferTo = ""
|
||||||
|
rec.TransferUntil = 0
|
||||||
|
s.markDirtyLocked()
|
||||||
|
return "", 0, false
|
||||||
|
}
|
||||||
|
return rec.TransferTo, rec.TransferUntil, true
|
||||||
|
}
|
||||||
|
|
||||||
// Remove deletes the persisted record for id and reports whether one existed.
|
// Remove deletes the persisted record for id and reports whether one existed.
|
||||||
// This is the web UI's explicit "delete" for an offline device: an offline
|
// This is the web UI's explicit "delete" for an offline device: an offline
|
||||||
// record has no live agent to uninstall, so forgetting it is all "delete" can
|
// record has no live agent to uninstall, so forgetting it is all "delete" can
|
||||||
|
|||||||
@@ -261,3 +261,48 @@ func TestFlushLeavesNoTempFiles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A transfer marker is dropped once its deadline passes — the client is back on
|
||||||
|
// its original master by then, so keeping the label would be a lie — and also
|
||||||
|
// as soon as the device logs in here again, because that means it is back
|
||||||
|
// early (upgrade done, or the target was unreachable).
|
||||||
|
func TestTransferMarkerLifecycle(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "devices.json")
|
||||||
|
s, err := Open(path, 1000, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Open: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = s.Close() })
|
||||||
|
|
||||||
|
h := hub.New()
|
||||||
|
h.Subscribe(s)
|
||||||
|
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5000"})
|
||||||
|
|
||||||
|
if _, _, ok := s.Transfer("dev-1"); ok {
|
||||||
|
t.Fatal("fresh device already reports a transfer")
|
||||||
|
}
|
||||||
|
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
|
||||||
|
t.Fatal("SetTransfer on a known device failed")
|
||||||
|
}
|
||||||
|
if target, _, ok := s.Transfer("dev-1"); !ok || target != "mfc.example:6544" {
|
||||||
|
t.Fatalf("marker not visible: %q/%v", target, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expired marker is dropped on read.
|
||||||
|
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(-time.Second).Unix()) {
|
||||||
|
t.Fatal("SetTransfer with a past deadline failed")
|
||||||
|
}
|
||||||
|
if _, _, ok := s.Transfer("dev-1"); ok {
|
||||||
|
t.Fatal("expired transfer marker still reported")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A login on this server means the host is back, so the marker goes away.
|
||||||
|
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
|
||||||
|
t.Fatal("SetTransfer after expiry failed")
|
||||||
|
}
|
||||||
|
h.Unregister("dev-1")
|
||||||
|
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5001"})
|
||||||
|
if target, until, ok := s.Transfer("dev-1"); ok {
|
||||||
|
t.Fatalf("marker survived a reconnect: %q/%d", target, until)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
package mcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeOwners stands in for web.DeviceACL: a device with a non-empty owner is
|
||||||
|
// bound to that web user and must be invisible to MCP.
|
||||||
|
type fakeOwners map[string]string
|
||||||
|
|
||||||
|
func (f fakeOwners) Owner(deviceID string) string { return f[deviceID] }
|
||||||
|
|
||||||
|
func bindOwners(s *Server, owners fakeOwners) { s.cfg.DeviceACL = owners }
|
||||||
|
|
||||||
|
func hasID(hosts []map[string]any, id string) bool {
|
||||||
|
for _, h := range hosts {
|
||||||
|
if h["id"] == id {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func wantNoID(t *testing.T, hosts []map[string]any, id string) {
|
||||||
|
t.Helper()
|
||||||
|
if hasID(hosts, id) {
|
||||||
|
t.Fatalf("ids = %v, must not contain bound device %s", hostIDs(hosts), id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestACLListHostsHidesBoundDevices covers the listing paths: online and
|
||||||
|
// offline entries whose owner is set are dropped before paging and counting,
|
||||||
|
// so they affect neither the page nor total/totalAll.
|
||||||
|
func TestACLListHostsHidesBoundDevices(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"})
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
|
||||||
|
hosts := hostList(t, sc)
|
||||||
|
wantIDs(t, hosts, "1002", "1003")
|
||||||
|
wantNoID(t, hosts, "1001")
|
||||||
|
if got := intField(t, sc, "total"); got != 2 {
|
||||||
|
t.Fatalf("total = %d, want 2 public hosts", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 2 {
|
||||||
|
t.Fatalf("totalAll = %d, want 2 public hosts", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`)
|
||||||
|
hosts = hostList(t, sc)
|
||||||
|
wantNoID(t, hosts, "1001")
|
||||||
|
wantNoID(t, hosts, "2001") // bound device that is now offline
|
||||||
|
if !hasID(hosts, "2002") {
|
||||||
|
t.Fatalf("ids = %v, want unbound offline device 2002", hostIDs(hosts))
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "total"); got != 3 {
|
||||||
|
t.Fatalf("total = %d, want 3 public hosts (2 online + 1 offline)", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtering by the bound device's own name or group must not reveal it
|
||||||
|
// through an empty-but-otherwise-valid result either: the filters apply to
|
||||||
|
// the public snapshot, so the answer is simply nothing.
|
||||||
|
for _, q := range []string{`{"name":"ALPHA"}`, `{"query":"ALPHA"}`, `{"group":"Legacy"}`} {
|
||||||
|
if _, sc = mustCallLocal(t, f.srv, "list_hosts", q); len(hostList(t, sc)) != 0 {
|
||||||
|
t.Fatalf("%s returned bound hosts: %v", q, hostIDs(hostList(t, sc)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestACLDeniesBoundDeviceByID checks the per-device tools: a bound device is
|
||||||
|
// answered exactly like an offline host, so MCP callers cannot tell it exists
|
||||||
|
// at all (policy C: bound devices are unreachable even by id).
|
||||||
|
func TestACLDeniesBoundDeviceByID(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
bindOwners(f.srv, fakeOwners{"1001": "alice"})
|
||||||
|
|
||||||
|
single := []struct{ tool, args string }{
|
||||||
|
{"get_host_detail", `{"id":"1001"}`},
|
||||||
|
{"get_screenshot", `{"id":"1001"}`},
|
||||||
|
{"list_files", `{"id":"1001"}`},
|
||||||
|
{"read_file", `{"id":"1001","path":"/etc/hostname"}`},
|
||||||
|
{"terminal_exec", `{"id":"1001","command":"dir"}`},
|
||||||
|
}
|
||||||
|
for _, c := range single {
|
||||||
|
if _, _, rerr := callLocal(t, f.srv, c.tool, c.args); rerr == nil || rerr.Code != CodeOffline {
|
||||||
|
t.Fatalf("%s on bound device = %+v, want -32002", c.tool, rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The batch form reports a per-id failure, not a leak.
|
||||||
|
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","1002"]}`)
|
||||||
|
if got := intField(t, sc, "succeeded"); got != 1 {
|
||||||
|
t.Fatalf("succeeded = %d, want only the public host", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "failed"); got != 1 {
|
||||||
|
t.Fatalf("failed = %d, want the bound host", got)
|
||||||
|
}
|
||||||
|
if strings.Contains(text, "ALPHA") {
|
||||||
|
t.Fatalf("text leaks the bound host: %q", text)
|
||||||
|
}
|
||||||
|
first := sc["results"].([]any)[0].(map[string]any)
|
||||||
|
if ok, _ := first["ok"].(bool); ok {
|
||||||
|
t.Fatalf("bound id reported ok: %v", first)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files batch listing: every bound id fails, public ids still succeed.
|
||||||
|
_, sc = mustCallLocal(t, f.srv, "list_files", `{"ids":["1001"]}`)
|
||||||
|
raw, _ := json.Marshal(sc["results"])
|
||||||
|
if !strings.Contains(string(raw), `"ok":false`) || strings.Contains(string(raw), "ALPHA") {
|
||||||
|
t.Fatalf("list_files batch = %s, want one opaque failure", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The gate is the owner map, not the device's online state: an unbound id
|
||||||
|
// must still pass it (the later "is it online" check rejects 9999).
|
||||||
|
if f.srv.denyPrivateDevice("1002") != nil {
|
||||||
|
t.Fatal("unbound device denied")
|
||||||
|
}
|
||||||
|
if f.srv.denyPrivateDevice("9999") != nil {
|
||||||
|
t.Fatal("unknown device denied as private")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestACLServerStatusCounts verifies the status tool counts only public
|
||||||
|
// devices, so bound hosts do not inflate the fleet summary.
|
||||||
|
func TestACLServerStatusCounts(t *testing.T) {
|
||||||
|
f := newLocalFixture(t)
|
||||||
|
bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"})
|
||||||
|
|
||||||
|
_, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`)
|
||||||
|
hosts, ok := sc["hosts"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("hosts = %v", sc["hosts"])
|
||||||
|
}
|
||||||
|
if got := intField(t, hosts, "online"); got != 2 {
|
||||||
|
t.Fatalf("online = %d, want 2 public online hosts", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, hosts, "offline"); got != 1 {
|
||||||
|
t.Fatalf("offline = %d, want 1 public offline host", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestACLAuditHidesBoundDeviceRecords checks that audit records carrying a
|
||||||
|
// bound device_id are filtered out of get_audit_log, including through
|
||||||
|
// keyword/type filters, while the pre-filter total stays honest.
|
||||||
|
func TestACLAuditHidesBoundDeviceRecords(t *testing.T) {
|
||||||
|
path := writeAuditFile(t,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"web.login.success","actor":"admin","ip":"1.2.3.4"}`,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:01:00Z","level":"info","event":"device.online","device_id":"1001","name":"ALPHA"}`,
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:02:00Z","level":"info","event":"device.online","device_id":"1002","name":"BETA"}`,
|
||||||
|
// MCP tool calls spell the target as "device".
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"mcp.tool.call","device":"1001","args":"{}"}`,
|
||||||
|
// Bind/unbind records carry a devices array.
|
||||||
|
`{"audit":true,"time":"2026-11-12T10:04:00Z","level":"info","event":"admin.device.bind","devices":["1001","1002"],"owner":"alice"}`,
|
||||||
|
)
|
||||||
|
s := New(Config{Token: "test-token", AuditPath: path})
|
||||||
|
bindOwners(s, fakeOwners{"1001": "alice"})
|
||||||
|
|
||||||
|
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
|
||||||
|
// Public: login, device.online 1002. Hidden: device_id 1001, MCP device
|
||||||
|
// 1001, and the bind record because its devices array names 1001.
|
||||||
|
if got := intField(t, sc, "total"); got != 2 {
|
||||||
|
t.Fatalf("total = %d, want the two public records", got)
|
||||||
|
}
|
||||||
|
if got := intField(t, sc, "totalAll"); got != 5 {
|
||||||
|
t.Fatalf("totalAll = %d, want unfiltered 5", got)
|
||||||
|
}
|
||||||
|
for _, leak := range []string{"ALPHA", `"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"`} {
|
||||||
|
if strings.Contains(text, leak) {
|
||||||
|
t.Fatalf("text leaks bound-device record %s: %q", leak, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A keyword carried only by the bound device's record finds nothing.
|
||||||
|
if _, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"ALPHA"}`); intField(t, sc, "total") != 0 {
|
||||||
|
t.Fatalf("keyword ALPHA total = %d, want 0", intField(t, sc, "total"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without an owner map (MCP-only deployments) nothing is filtered.
|
||||||
|
plain := New(Config{Token: "test-token", AuditPath: path})
|
||||||
|
if _, sc = mustCallLocal(t, plain, "get_audit_log", `{}`); intField(t, sc, "total") != 5 {
|
||||||
|
t.Fatalf("no-ACL total = %d, want 5", intField(t, sc, "total"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -511,6 +511,9 @@ func (s *Server) listFilesOne(ctx context.Context, args listFilesArgs) (toolResu
|
|||||||
if !isDecimalID(args.ID) {
|
if !isDecimalID(args.ID) {
|
||||||
return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||||
}
|
}
|
||||||
|
if rerr := s.denyPrivateDevice(args.ID); rerr != nil {
|
||||||
|
return toolResult{}, rerr
|
||||||
|
}
|
||||||
// NUL and newlines would truncate or split the client's C string field.
|
// NUL and newlines would truncate or split the client's C string field.
|
||||||
if strings.ContainsAny(args.Path, "\x00\r\n") {
|
if strings.ContainsAny(args.Path, "\x00\r\n") {
|
||||||
return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed")
|
return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed")
|
||||||
|
|||||||
@@ -36,6 +36,34 @@ const (
|
|||||||
termSweepInterval = 30 * time.Second
|
termSweepInterval = 30 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// DeviceOwner reports the owner of a device. The web console's DeviceACL
|
||||||
|
// implements it; declared here as an interface so the MCP package does not
|
||||||
|
// import the web package.
|
||||||
|
type DeviceOwner interface {
|
||||||
|
Owner(deviceID string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the
|
||||||
|
// whole binding table lets a long operation (the audit scan) apply the policy
|
||||||
|
// without a read-lock acquisition per record. Implemented by web.DeviceACL.
|
||||||
|
type deviceOwnerSnapshotter interface {
|
||||||
|
Owners() map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownerChecker returns a predicate for "is this device public?" that borrows a
|
||||||
|
// single snapshot when the ACL supports it, so scanning thousands of audit
|
||||||
|
// records does not contend with an in-flight bind's write lock.
|
||||||
|
func (s *Server) ownerChecker() func(deviceID string) bool {
|
||||||
|
if s.cfg.DeviceACL == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if snap, ok := s.cfg.DeviceACL.(deviceOwnerSnapshotter); ok {
|
||||||
|
owners := snap.Owners()
|
||||||
|
return func(id string) bool { return owners[id] == "" }
|
||||||
|
}
|
||||||
|
return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" }
|
||||||
|
}
|
||||||
|
|
||||||
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
|
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
|
||||||
// the package itself never reads the environment, so tests are deterministic.
|
// the package itself never reads the environment, so tests are deterministic.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@@ -56,6 +84,12 @@ type Config struct {
|
|||||||
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
|
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
|
||||||
Port int // web/MCP listening port, for get_server_status
|
Port int // web/MCP listening port, for get_server_status
|
||||||
Bind string // listening address, for get_server_status
|
Bind string // listening address, for get_server_status
|
||||||
|
|
||||||
|
// DeviceACL, when non-nil, hides devices bound to a web user. MCP only
|
||||||
|
// operates public devices (product decision): a bound device is invisible
|
||||||
|
// in list_hosts/get_host_detail and unreachable by ID in every device-
|
||||||
|
// targeted tool, even if its ID is known.
|
||||||
|
DeviceACL DeviceOwner
|
||||||
}
|
}
|
||||||
|
|
||||||
// toolFunc implements one tools/call. It returns either a result value or a
|
// toolFunc implements one tools/call. It returns either a result value or a
|
||||||
@@ -145,6 +179,36 @@ func New(cfg Config) *Server {
|
|||||||
// unknown path.
|
// unknown path.
|
||||||
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
|
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
|
||||||
|
|
||||||
|
// devicePrivate reports whether the device is bound to a web user. MCP only
|
||||||
|
// operates public devices; bound devices are hidden and unreachable here even
|
||||||
|
// though the endpoint's static token is effectively an admin credential.
|
||||||
|
func (s *Server) devicePrivate(deviceID string) bool {
|
||||||
|
return s.cfg.DeviceACL != nil && s.cfg.DeviceACL.Owner(deviceID) != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// denyPrivateDevice returns the same error shape as an offline host so a
|
||||||
|
// private device is indistinguishable from one that does not exist.
|
||||||
|
func (s *Server) denyPrivateDevice(deviceID string) *rpcError {
|
||||||
|
if s.devicePrivate(deviceID) {
|
||||||
|
return errf(CodeOffline, "Host not found or offline: %s", deviceID)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// publicDevices filters a device snapshot down to the ones MCP may expose.
|
||||||
|
func (s *Server) publicDevices(devices []hub.DeviceInfo) []hub.DeviceInfo {
|
||||||
|
if s.cfg.DeviceACL == nil {
|
||||||
|
return devices
|
||||||
|
}
|
||||||
|
out := make([]hub.DeviceInfo, 0, len(devices))
|
||||||
|
for _, d := range devices {
|
||||||
|
if s.cfg.DeviceACL.Owner(d.ID) == "" {
|
||||||
|
out = append(out, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// Close releases resources held by long-lived tool state: the reaper stops and
|
// Close releases resources held by long-lived tool state: the reaper stops and
|
||||||
// every terminal session MCP owns is torn down and the shell told to exit.
|
// every terminal session MCP owns is torn down and the shell told to exit.
|
||||||
func (s *Server) Close() {
|
func (s *Server) Close() {
|
||||||
@@ -344,6 +408,13 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any,
|
|||||||
// a temporary state between milestones, not a client mistake.
|
// a temporary state between milestones, not a client mistake.
|
||||||
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
|
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
|
||||||
}
|
}
|
||||||
|
// A device bound to a web user is invisible to MCP (product policy). Enforce
|
||||||
|
// it once here for every single-host tool so a new tool cannot forget the
|
||||||
|
// check; batch id[] spellings are checked by their per-host handler
|
||||||
|
// (listFilesOne / hostMaps).
|
||||||
|
if rerr := s.denyPrivateDevice(deviceID); rerr != nil {
|
||||||
|
return nil, rerr
|
||||||
|
}
|
||||||
|
|
||||||
// Global slot first: a call that would be rejected for concurrency must
|
// Global slot first: a call that would be rejected for concurrency must
|
||||||
// not squat on a device lock while it fails.
|
// not squat on a device lock while it fails.
|
||||||
|
|||||||
@@ -106,12 +106,17 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
|||||||
}
|
}
|
||||||
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
|
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
|
||||||
|
|
||||||
onlineDevices := s.cfg.Hub.ListDevices()
|
// The offline history must be computed from the FULL online set, not the
|
||||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
// ACL-filtered one: otherwise a private device that is currently online
|
||||||
for _, d := range onlineDevices {
|
// would reappear as an "offline" entry until the outer filter drops it.
|
||||||
|
// Filter once, at the end.
|
||||||
|
onlineAll := s.cfg.Hub.ListDevices()
|
||||||
|
onlineSet := make(map[string]struct{}, len(onlineAll))
|
||||||
|
for _, d := range onlineAll {
|
||||||
onlineSet[d.ID] = struct{}{}
|
onlineSet[d.ID] = struct{}{}
|
||||||
}
|
}
|
||||||
offlineDevices := s.offlineDevices(onlineSet)
|
onlineDevices := s.publicDevices(onlineAll)
|
||||||
|
offlineDevices := s.publicDevices(s.offlineDevices(onlineSet))
|
||||||
|
|
||||||
var pool []hub.DeviceInfo
|
var pool []hub.DeviceInfo
|
||||||
switch {
|
switch {
|
||||||
@@ -347,14 +352,19 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
|
|||||||
// hostMaps indexes the online devices and offline history by ID. Building both
|
// hostMaps indexes the online devices and offline history by ID. Building both
|
||||||
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
|
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
|
||||||
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
|
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
|
||||||
onlineDevices := s.cfg.Hub.ListDevices()
|
onlineAll := s.cfg.Hub.ListDevices()
|
||||||
|
onlineSet := make(map[string]struct{}, len(onlineAll))
|
||||||
|
onlineDevices := s.publicDevices(onlineAll)
|
||||||
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
|
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
|
||||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
|
||||||
for _, d := range onlineDevices {
|
for _, d := range onlineDevices {
|
||||||
online[d.ID] = d
|
online[d.ID] = d
|
||||||
|
}
|
||||||
|
// Derive offline entries from the full online set (see callListHosts):
|
||||||
|
// a private online device must not be mistaken for an offline one.
|
||||||
|
for _, d := range onlineAll {
|
||||||
onlineSet[d.ID] = struct{}{}
|
onlineSet[d.ID] = struct{}{}
|
||||||
}
|
}
|
||||||
offlineDevices := s.offlineDevices(onlineSet)
|
offlineDevices := s.publicDevices(s.offlineDevices(onlineSet))
|
||||||
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
|
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
|
||||||
for _, d := range offlineDevices {
|
for _, d := range offlineDevices {
|
||||||
offline[d.ID] = d
|
offline[d.ID] = d
|
||||||
@@ -483,12 +493,13 @@ func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any,
|
|||||||
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
|
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
|
||||||
}
|
}
|
||||||
if s.cfg.Hub != nil {
|
if s.cfg.Hub != nil {
|
||||||
onlineDevices := s.cfg.Hub.ListDevices()
|
onlineAll := s.cfg.Hub.ListDevices()
|
||||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
onlineSet := make(map[string]struct{}, len(onlineAll))
|
||||||
for _, d := range onlineDevices {
|
for _, d := range onlineAll {
|
||||||
onlineSet[d.ID] = struct{}{}
|
onlineSet[d.ID] = struct{}{}
|
||||||
}
|
}
|
||||||
offline := len(s.offlineDevices(onlineSet))
|
onlineDevices := s.publicDevices(onlineAll)
|
||||||
|
offline := len(s.publicDevices(s.offlineDevices(onlineSet)))
|
||||||
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
|
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
|
||||||
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
|
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
|
||||||
}
|
}
|
||||||
@@ -530,6 +541,9 @@ func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *
|
|||||||
// event name; the web UI's exact/prefix Event filter does not fit.
|
// event name; the web UI's exact/prefix Event filter does not fit.
|
||||||
EventContains: args.Type,
|
EventContains: args.Type,
|
||||||
}
|
}
|
||||||
|
// Audit records name their target device. A device bound to a web user is
|
||||||
|
// invisible to MCP, so its activity must not leak through the log either.
|
||||||
|
q.DeviceAllowed = s.ownerChecker()
|
||||||
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
|
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
|
||||||
q.Offset = auditquery.ClampOffset(args.Offset)
|
q.Offset = auditquery.ClampOffset(args.Offset)
|
||||||
|
|
||||||
|
|||||||
@@ -131,7 +131,6 @@ func (s *Server) callTerminalExec(ctx context.Context, raw json.RawMessage) (any
|
|||||||
if !isDecimalID(args.ID) {
|
if !isDecimalID(args.ID) {
|
||||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||||
}
|
}
|
||||||
|
|
||||||
command := strings.TrimSpace(args.Command)
|
command := strings.TrimSpace(args.Command)
|
||||||
isPoll := command == ""
|
isPoll := command == ""
|
||||||
if isPoll && args.SessionID == "" {
|
if isPoll && args.SessionID == "" {
|
||||||
|
|||||||
@@ -155,6 +155,21 @@ const (
|
|||||||
CommandBye byte = 204 // COMMAND_BYE - disconnect
|
CommandBye byte = 204 // COMMAND_BYE - disconnect
|
||||||
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
|
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
|
||||||
|
|
||||||
|
// CommandAssignMaster moves a host to another master (COMMAND_ASSIGN_MASTER).
|
||||||
|
// Payload: [cmd][ShareTypeYamaForever]host:port:days[:shine[:transport]]\0
|
||||||
|
// The client stores the target plus a deadline and goes back to the master it
|
||||||
|
// captured at startup when the deadline passes — the Go server does not take
|
||||||
|
// part in the restore. See common/host_transfer.h.
|
||||||
|
CommandAssignMaster byte = 207
|
||||||
|
ShareTypeYamaForever byte = 100 // SHARE_TYPE_YAMA_FOREVER — "transfer", not "share"
|
||||||
|
|
||||||
|
// TransferTransport* are the clients' CONNECT_ADDRESS.protoType values
|
||||||
|
// (common/commands.h): PROTO_TCP=0, PROTO_WS=5, PROTO_WSS=6. They travel in
|
||||||
|
// the assign-master payload's transport segment.
|
||||||
|
TransferTransportTCP int = 0
|
||||||
|
TransferTransportWS int = 5
|
||||||
|
TransferTransportWSS int = 6
|
||||||
|
|
||||||
// Client -> Server tokens
|
// Client -> Server tokens
|
||||||
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
|
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
|
||||||
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
|
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
|
||||||
@@ -705,3 +720,29 @@ func BuildValidation(days float64, admin string, port int, maxDepth uint16) []by
|
|||||||
|
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BuildAssignMasterPacket encodes a "transfer this host to another master"
|
||||||
|
// command, byte-compatible with the MFC server's assignFunction
|
||||||
|
// (server/2015Remote/2015RemoteDlg.cpp):
|
||||||
|
//
|
||||||
|
// [COMMAND_ASSIGN_MASTER][SHARE_TYPE_YAMA_FOREVER]host:port:days::transport\0
|
||||||
|
//
|
||||||
|
// The shine segment stays empty: the header-encryption variant is not
|
||||||
|
// something this server can know better than the host, and clients rotate it
|
||||||
|
// when a login is rejected (client/IOCPClient.h). The transport segment is
|
||||||
|
// always sent, because an absent segment does **not** mean "plain TCP" to the
|
||||||
|
// clients — they keep the link they run today (client/ClientDll.cpp
|
||||||
|
// ApplyAssignedMaster, common/host_endpoint.h ApplyEndpoint). A host that
|
||||||
|
// talks WSS to this server would then try WSS against the MFC master's raw TCP
|
||||||
|
// port and never connect. The caller picks the transport; TCP (0) matches what
|
||||||
|
// an MFC master listens on. days is formatted without trailing zeros so "0.5"
|
||||||
|
// survives the round trip.
|
||||||
|
func BuildAssignMasterPacket(host string, port int, days float64, transport int) []byte {
|
||||||
|
payload := host + ":" + strconv.Itoa(port) + ":" + strconv.FormatFloat(days, 'f', -1, 64) +
|
||||||
|
"::" + strconv.Itoa(transport)
|
||||||
|
pkt := make([]byte, 0, 2+len(payload)+1)
|
||||||
|
pkt = append(pkt, CommandAssignMaster, ShareTypeYamaForever)
|
||||||
|
pkt = append(pkt, payload...)
|
||||||
|
pkt = append(pkt, 0) // clients parse the payload as a C string
|
||||||
|
return pkt
|
||||||
|
}
|
||||||
@@ -103,3 +103,35 @@ func isCommandTokenName(name string) bool {
|
|||||||
strings.HasPrefix(name, "Token") ||
|
strings.HasPrefix(name, "Token") ||
|
||||||
strings.HasPrefix(name, "Cmd")
|
strings.HasPrefix(name, "Cmd")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The assign-master payload must stay byte-compatible with the MFC master's
|
||||||
|
// assignFunction, otherwise the client parses the wrong fields: days keeps
|
||||||
|
// fractions ("0.5" for a half-day handover) and the string is NUL-terminated
|
||||||
|
// because both clients read it as a C string. The shine segment is empty
|
||||||
|
// (clients then keep their header-encryption variant) while the transport
|
||||||
|
// segment is always present — without it the clients would keep the link they
|
||||||
|
// run today, which is exactly the WSS-vs-TCP mismatch that made the transfer
|
||||||
|
// unreachable.
|
||||||
|
func TestBuildAssignMasterPacket(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
host string
|
||||||
|
port int
|
||||||
|
days float64
|
||||||
|
transport int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"mfc.example", 6544, 1, TransferTransportTCP, "mfc.example:6544:1::0\x00"},
|
||||||
|
{"10.0.0.5", 6543, 0.5, TransferTransportTCP, "10.0.0.5:6543:0.5::0\x00"},
|
||||||
|
{"mfc.example", 6544, 2.25, TransferTransportWS, "mfc.example:6544:2.25::5\x00"},
|
||||||
|
{"mfc.example", 6544, 1, TransferTransportWSS, "mfc.example:6544:1::6\x00"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
got := BuildAssignMasterPacket(tc.host, tc.port, tc.days, tc.transport)
|
||||||
|
if len(got) < 2 || got[0] != CommandAssignMaster || got[1] != ShareTypeYamaForever {
|
||||||
|
t.Fatalf("header = %v, want [%d %d]", got[:2], CommandAssignMaster, ShareTypeYamaForever)
|
||||||
|
}
|
||||||
|
if string(got[2:]) != tc.want {
|
||||||
|
t.Fatalf("payload = %q, want %q", got[2:], tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,10 +32,13 @@ const (
|
|||||||
auditClipGet = "remote.clipboard.get"
|
auditClipGet = "remote.clipboard.get"
|
||||||
auditRdpReset = "remote.rdp_reset"
|
auditRdpReset = "remote.rdp_reset"
|
||||||
|
|
||||||
auditUserCreate = "admin.user.create"
|
auditUserCreate = "admin.user.create"
|
||||||
auditUserDelete = "admin.user.delete"
|
auditUserDelete = "admin.user.delete"
|
||||||
auditDeviceAdmin = "admin.device.delete"
|
auditDeviceAdmin = "admin.device.delete"
|
||||||
auditQuery = "admin.audit.query"
|
auditDeviceTransfer = "admin.device.transfer"
|
||||||
|
auditDeviceBind = "admin.device.bind"
|
||||||
|
auditDeviceUnbind = "admin.device.unbind"
|
||||||
|
auditQuery = "admin.audit.query"
|
||||||
)
|
)
|
||||||
|
|
||||||
// audit emits one audit record for a WebSocket client. Identity fields are
|
// audit emits one audit record for a WebSocket client. Identity fields are
|
||||||
|
|||||||
@@ -32,6 +32,19 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
|||||||
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
|
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
|
||||||
in.Offset = auditquery.ClampOffset(in.Offset)
|
in.Offset = auditquery.ClampOffset(in.Offset)
|
||||||
|
|
||||||
|
// The audit trail is another visibility channel for devices. An admin-role
|
||||||
|
// user may see public devices and their own, but not another user's bound
|
||||||
|
// devices; the superadmin sees everything. One owner snapshot per query
|
||||||
|
// keeps the scanner off the ACL lock per record.
|
||||||
|
if h.acl != nil && !c.isSuperAdmin() {
|
||||||
|
owners := h.acl.Owners()
|
||||||
|
user := c.user
|
||||||
|
in.DeviceAllowed = func(deviceID string) bool {
|
||||||
|
owner := owners[deviceID]
|
||||||
|
return owner == "" || owner == user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
path := h.log.AuditPath()
|
path := h.log.AuditPath()
|
||||||
if path == "" {
|
if path == "" {
|
||||||
h.audit(c, true, auditQuery, map[string]any{
|
h.audit(c, true, auditQuery, map[string]any{
|
||||||
|
|||||||
@@ -100,6 +100,75 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An admin-role user may read public-device audit records and their own, but
|
||||||
|
// not records naming another user's bound device. The superadmin sees all.
|
||||||
|
func TestQueryAuditHandlerFiltersBoundDevices(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
lg := logger.New(logger.Config{
|
||||||
|
Level: logger.LevelInfo,
|
||||||
|
Console: false,
|
||||||
|
File: filepath.Join(dir, "server.log"),
|
||||||
|
AuditFile: filepath.Join(dir, "audit.log"),
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { _ = lg.Close() })
|
||||||
|
|
||||||
|
acl := NewDeviceACL(filepath.Join(dir, "device_acl.json"))
|
||||||
|
if err := acl.Bind([]string{"1001"}, "alice@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind 1001: %v", err)
|
||||||
|
}
|
||||||
|
if err := acl.Bind([]string{"1002"}, "bob@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind 1002: %v", err)
|
||||||
|
}
|
||||||
|
wh := newWSHub(wsauth.New(), hub.New(), nil, lg).withDeviceACL(acl)
|
||||||
|
t.Cleanup(wh.stop)
|
||||||
|
|
||||||
|
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1001"})
|
||||||
|
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1002"})
|
||||||
|
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1003"}) // public
|
||||||
|
wh.log.Audit("mcp.tool.call", map[string]any{"device": "1001"})
|
||||||
|
wh.log.Audit("admin.device.bind", map[string]any{"devices": []string{"1001"}, "owner": "alice@corp.com"})
|
||||||
|
|
||||||
|
query := func(user string) string {
|
||||||
|
t.Helper()
|
||||||
|
c, tok := aclTestClient(t, wh, user, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "limit": 50})
|
||||||
|
wh.handleQueryAudit(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "audit_result")
|
||||||
|
if msg["ok"] != true {
|
||||||
|
t.Fatalf("%s: reply = %+v", user, msg)
|
||||||
|
}
|
||||||
|
events, _ := json.Marshal(msg["events"])
|
||||||
|
return string(events)
|
||||||
|
}
|
||||||
|
|
||||||
|
alice := query("alice@corp.com")
|
||||||
|
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1003"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||||
|
if !strings.Contains(alice, want) {
|
||||||
|
t.Fatalf("alice events missing %s: %s", want, alice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(alice, `"device_id":"1002"`) {
|
||||||
|
t.Fatalf("alice saw bob's bound device: %s", alice)
|
||||||
|
}
|
||||||
|
|
||||||
|
bob := query("bob@corp.com")
|
||||||
|
if !strings.Contains(bob, `"device_id":"1002"`) {
|
||||||
|
t.Fatalf("bob events missing his own device: %s", bob)
|
||||||
|
}
|
||||||
|
for _, leak := range []string{`"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||||
|
if strings.Contains(bob, leak) {
|
||||||
|
t.Fatalf("bob saw alice's bound device record %s: %s", leak, bob)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
super := query("admin")
|
||||||
|
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1002"`, `"device":"1001"`, `"devices":["1001"]`} {
|
||||||
|
if !strings.Contains(super, want) {
|
||||||
|
t.Fatalf("superadmin events missing %s: %s", want, super)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestQueryAuditHandlerDisabledFile(t *testing.T) {
|
func TestQueryAuditHandlerDisabledFile(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
wh, _ := newAuditTestHubWithoutAuditFile(t, dir)
|
wh, _ := newAuditTestHubWithoutAuditFile(t, dir)
|
||||||
|
|||||||
@@ -0,0 +1,252 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeviceACLEntry is one device-to-owner binding.
|
||||||
|
type DeviceACLEntry struct {
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
UpdatedBy string `json:"updated_by,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceACLFile is the on-disk shape of device_acl.json. Version is reserved
|
||||||
|
// for future migrations; v1 is a flat deviceID -> owner map.
|
||||||
|
type deviceACLFile struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Devices map[string]DeviceACLEntry `json:"devices"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeviceACL is the per-device owner table used by the web console. A device
|
||||||
|
// with no entry is "public": admin-role users may see and control it, viewers
|
||||||
|
// may not. A device with an owner is visible/controllable only by that owner
|
||||||
|
// (plus the built-in superadmin).
|
||||||
|
//
|
||||||
|
// The table is process-local and persisted atomically to Path. An empty Path
|
||||||
|
// disables persistence (tests).
|
||||||
|
type DeviceACL struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
path string
|
||||||
|
entries map[string]DeviceACLEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDeviceACL returns an empty table backed by path.
|
||||||
|
func NewDeviceACL(path string) *DeviceACL {
|
||||||
|
return &DeviceACL{path: path, entries: make(map[string]DeviceACLEntry)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads Path into memory. A missing file is an empty table. A malformed
|
||||||
|
// file is returned as an error: silently starting with no bindings would turn
|
||||||
|
// every private device public, so the caller must fail closed.
|
||||||
|
func (a *DeviceACL) Load() error {
|
||||||
|
if a.path == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(a.path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("read %s: %w", a.path, err)
|
||||||
|
}
|
||||||
|
var f deviceACLFile
|
||||||
|
if err := json.Unmarshal(data, &f); err != nil {
|
||||||
|
return fmt.Errorf("parse %s: %w", a.path, err)
|
||||||
|
}
|
||||||
|
entries := make(map[string]DeviceACLEntry, len(f.Devices))
|
||||||
|
for id, e := range f.Devices {
|
||||||
|
id = strings.TrimSpace(id)
|
||||||
|
e.Owner = strings.TrimSpace(e.Owner)
|
||||||
|
if id == "" || e.Owner == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entries[id] = e
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
a.entries = entries
|
||||||
|
a.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceAllowed is the single visibility rule shared by the WebSocket handlers
|
||||||
|
// and the REST device list:
|
||||||
|
//
|
||||||
|
// acl == nil -> legacy: every authenticated session
|
||||||
|
// username == admin -> superadmin: every device
|
||||||
|
// unbound device -> admin role only (shared public pool)
|
||||||
|
// bound device -> its owner only (plus superadmin)
|
||||||
|
func deviceAllowed(acl *DeviceACL, username, role, deviceID string) bool {
|
||||||
|
if deviceID == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if acl == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if role == "admin" && username == "admin" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
owner := acl.Owner(deviceID)
|
||||||
|
if owner == "" {
|
||||||
|
return role == "admin"
|
||||||
|
}
|
||||||
|
return username != "" && username == owner
|
||||||
|
}
|
||||||
|
|
||||||
|
// Owner returns the owner of deviceID, or "" when the device is public.
|
||||||
|
func (a *DeviceACL) Owner(deviceID string) string {
|
||||||
|
if a == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
a.mu.RLock()
|
||||||
|
defer a.mu.RUnlock()
|
||||||
|
return a.entries[deviceID].Owner
|
||||||
|
}
|
||||||
|
|
||||||
|
// Owners returns a copy of the deviceID -> owner map. Callers that check many
|
||||||
|
// ids in a loop (the audit scanner walks up to 32 MB of records) take this
|
||||||
|
// snapshot once instead of taking the read lock per record, so a concurrent
|
||||||
|
// bind's file fsync cannot sit between their checks.
|
||||||
|
func (a *DeviceACL) Owners() map[string]string {
|
||||||
|
if a == nil {
|
||||||
|
return map[string]string{}
|
||||||
|
}
|
||||||
|
a.mu.RLock()
|
||||||
|
defer a.mu.RUnlock()
|
||||||
|
out := make(map[string]string, len(a.entries))
|
||||||
|
for id, e := range a.entries {
|
||||||
|
out[id] = e.Owner
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot returns a copy of the table (for admin listings/tests).
|
||||||
|
func (a *DeviceACL) Snapshot() map[string]DeviceACLEntry {
|
||||||
|
if a == nil {
|
||||||
|
return map[string]DeviceACLEntry{}
|
||||||
|
}
|
||||||
|
a.mu.RLock()
|
||||||
|
defer a.mu.RUnlock()
|
||||||
|
out := make(map[string]DeviceACLEntry, len(a.entries))
|
||||||
|
for id, e := range a.entries {
|
||||||
|
out[id] = e
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bind assigns owner to every device in ids. On persistence failure the
|
||||||
|
// in-memory table is rolled back so it never claims a binding that would not
|
||||||
|
// survive a restart.
|
||||||
|
func (a *DeviceACL) Bind(ids []string, owner, actor string) error {
|
||||||
|
owner = strings.TrimSpace(owner)
|
||||||
|
if owner == "" {
|
||||||
|
return fmt.Errorf("empty owner")
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
prev := make(map[string]DeviceACLEntry, len(ids))
|
||||||
|
now := time.Now().UTC()
|
||||||
|
changed := false
|
||||||
|
for _, id := range ids {
|
||||||
|
id = strings.TrimSpace(id)
|
||||||
|
if id == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
prev[id] = a.entries[id]
|
||||||
|
a.entries[id] = DeviceACLEntry{Owner: owner, UpdatedAt: now, UpdatedBy: actor}
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return fmt.Errorf("no device ids")
|
||||||
|
}
|
||||||
|
if err := a.saveLocked(); err != nil {
|
||||||
|
for id, e := range prev {
|
||||||
|
if e.Owner == "" {
|
||||||
|
delete(a.entries, id)
|
||||||
|
} else {
|
||||||
|
a.entries[id] = e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unbind removes the binding for every device in ids (idempotent).
|
||||||
|
func (a *DeviceACL) Unbind(ids []string) error {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
prev := make(map[string]DeviceACLEntry, len(ids))
|
||||||
|
for _, id := range ids {
|
||||||
|
id = strings.TrimSpace(id)
|
||||||
|
if id == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e, ok := a.entries[id]; ok {
|
||||||
|
prev[id] = e
|
||||||
|
delete(a.entries, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(prev) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := a.saveLocked(); err != nil {
|
||||||
|
for id, e := range prev {
|
||||||
|
a.entries[id] = e
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove drops the binding for one device (called when the device record is
|
||||||
|
// deleted, so a future client reusing the same ID cannot inherit it).
|
||||||
|
func (a *DeviceACL) Remove(deviceID string) error {
|
||||||
|
return a.Unbind([]string{deviceID})
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveLocked writes the table via a temp file + rename. Caller holds a.mu.
|
||||||
|
func (a *DeviceACL) saveLocked() error {
|
||||||
|
if a.path == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
f := deviceACLFile{Version: 1, Devices: a.entries}
|
||||||
|
data, err := json.MarshalIndent(f, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode device acl: %w", err)
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(a.path)
|
||||||
|
if dir == "" {
|
||||||
|
dir = "."
|
||||||
|
}
|
||||||
|
tmp, err := os.CreateTemp(dir, ".device_acl-*.tmp")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create temp acl: %w", err)
|
||||||
|
}
|
||||||
|
tmpName := tmp.Name()
|
||||||
|
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
|
||||||
|
|
||||||
|
if _, err := tmp.Write(data); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return fmt.Errorf("write temp acl: %w", err)
|
||||||
|
}
|
||||||
|
if err := tmp.Sync(); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return fmt.Errorf("sync temp acl: %w", err)
|
||||||
|
}
|
||||||
|
if err := tmp.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close temp acl: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmpName, a.path); err != nil {
|
||||||
|
return fmt.Errorf("rename acl: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeviceACLPersistAndReload(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "device_acl.json")
|
||||||
|
a := NewDeviceACL(path)
|
||||||
|
if err := a.Bind([]string{"dev1", "dev2"}, "a@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("Bind: %v", err)
|
||||||
|
}
|
||||||
|
if got := a.Owner("dev1"); got != "a@corp.com" {
|
||||||
|
t.Fatalf("Owner(dev1) = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
reloaded := NewDeviceACL(path)
|
||||||
|
if err := reloaded.Load(); err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if got := reloaded.Owner("dev2"); got != "a@corp.com" {
|
||||||
|
t.Fatalf("reloaded Owner(dev2) = %q", got)
|
||||||
|
}
|
||||||
|
if got := reloaded.Owner("dev3"); got != "" {
|
||||||
|
t.Fatalf("reloaded Owner(dev3) = %q, want empty", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := reloaded.Unbind([]string{"dev1"}); err != nil {
|
||||||
|
t.Fatalf("Unbind: %v", err)
|
||||||
|
}
|
||||||
|
again := NewDeviceACL(path)
|
||||||
|
if err := again.Load(); err != nil {
|
||||||
|
t.Fatalf("Load after unbind: %v", err)
|
||||||
|
}
|
||||||
|
if got := again.Owner("dev1"); got != "" {
|
||||||
|
t.Fatalf("Owner(dev1) after unbind = %q", got)
|
||||||
|
}
|
||||||
|
if got := again.Owner("dev2"); got != "a@corp.com" {
|
||||||
|
t.Fatalf("Owner(dev2) after unbind = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := again.Remove("dev2"); err != nil {
|
||||||
|
t.Fatalf("Remove: %v", err)
|
||||||
|
}
|
||||||
|
final := NewDeviceACL(path)
|
||||||
|
if err := final.Load(); err != nil {
|
||||||
|
t.Fatalf("Load after remove: %v", err)
|
||||||
|
}
|
||||||
|
if got := final.Snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("snapshot = %+v, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeviceACLMalformedFileIsAnError(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "device_acl.json")
|
||||||
|
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
if err := NewDeviceACL(path).Load(); err == nil {
|
||||||
|
t.Fatal("Load accepted a malformed file; private devices would become public")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeviceAllowedMatrix(t *testing.T) {
|
||||||
|
acl := NewDeviceACL("")
|
||||||
|
if err := acl.Bind([]string{"a-dev"}, "a@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("Bind: %v", err)
|
||||||
|
}
|
||||||
|
if err := acl.Bind([]string{"b-dev"}, "b@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("Bind: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
acl *DeviceACL
|
||||||
|
username string
|
||||||
|
role string
|
||||||
|
device string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"nil acl legacy allows all", nil, "any", "viewer", "pub", true},
|
||||||
|
{"superadmin sees public", acl, "admin", "admin", "pub", true},
|
||||||
|
{"superadmin sees bound", acl, "admin", "admin", "a-dev", true},
|
||||||
|
{"admin sees public", acl, "c@corp.com", "admin", "pub", true},
|
||||||
|
{"admin blocked on other's device", acl, "c@corp.com", "admin", "a-dev", false},
|
||||||
|
{"owner sees own device", acl, "a@corp.com", "admin", "a-dev", true},
|
||||||
|
{"owner blocked on other's device", acl, "a@corp.com", "admin", "b-dev", false},
|
||||||
|
{"viewer sees no public device", acl, "v@corp.com", "viewer", "pub", false},
|
||||||
|
{"viewer sees own device", acl, "a@corp.com", "viewer", "a-dev", true},
|
||||||
|
{"empty username blocked", acl, "", "viewer", "a-dev", false},
|
||||||
|
{"empty device blocked", acl, "admin", "admin", "", false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := deviceAllowed(tt.acl, tt.username, tt.role, tt.device); got != tt.want {
|
||||||
|
t.Fatalf("deviceAllowed(%q,%q,%q) = %v, want %v",
|
||||||
|
tt.username, tt.role, tt.device, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
-5
@@ -32,6 +32,7 @@ type Server struct {
|
|||||||
hub *hub.Hub
|
hub *hub.Hub
|
||||||
auth *wsauth.Authenticator
|
auth *wsauth.Authenticator
|
||||||
history *devicehistory.Store // nil → no offline devices
|
history *devicehistory.Store // nil → no offline devices
|
||||||
|
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||||
ws *wsHub
|
ws *wsHub
|
||||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||||
loginIPLimit *wsauth.RateLimiter
|
loginIPLimit *wsauth.RateLimiter
|
||||||
@@ -39,6 +40,9 @@ type Server struct {
|
|||||||
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
|
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
|
||||||
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
|
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
|
||||||
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
|
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
|
||||||
|
transferTarget string // pre-filled "transfer host" target, "host:port"
|
||||||
|
transferDays float64 // pre-filled "transfer host" days
|
||||||
|
transferTransport int // link to the target: protocol.TransferTransport*
|
||||||
sso SSODetector // nil = SSO disabled
|
sso SSODetector // nil = SSO disabled
|
||||||
mcp mcpEndpoint // nil = no /mcp route
|
mcp mcpEndpoint // nil = no /mcp route
|
||||||
sweepDone chan struct{} // closes to stop the login-limiter sweeper
|
sweepDone chan struct{} // closes to stop the login-limiter sweeper
|
||||||
@@ -88,6 +92,24 @@ type Config struct {
|
|||||||
// session (cookie/header) into a YAMA web session via /sso. nil disables
|
// session (cookie/header) into a YAMA web session via /sso. nil disables
|
||||||
// SSO and the front-end falls back to the built-in login form.
|
// SSO and the front-end falls back to the built-in login form.
|
||||||
SSO SSODetector
|
SSO SSODetector
|
||||||
|
// DeviceACL is the per-device owner table. nil disables filtering (legacy
|
||||||
|
// behaviour: every authenticated session sees every device). The shipped
|
||||||
|
// server always wires one; tests may omit it.
|
||||||
|
DeviceACL *DeviceACL
|
||||||
|
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
|
||||||
|
// "transfer host" dialog. Reporting them is also what tells the shared
|
||||||
|
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
|
||||||
|
// serves the same page but never reports it, so no transfer button appears
|
||||||
|
// where the command would be dropped. Empty target = the operator types
|
||||||
|
// the address; days <= 0 falls back to 1.
|
||||||
|
//
|
||||||
|
// TransferTransport is the link the transferred host must use to reach the
|
||||||
|
// target (protocol.TransferTransportTCP/WS/WSS; zero value = TCP, what an
|
||||||
|
// MFC master listens on). It is always sent to the client: leaving it out
|
||||||
|
// would make a host that currently talks WSS keep WSS against the target.
|
||||||
|
TransferTarget string
|
||||||
|
TransferDays float64
|
||||||
|
TransferTransport int
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates an HTTP server bound to the given port. port=0 disables the server.
|
// New creates an HTTP server bound to the given port. port=0 disables the server.
|
||||||
@@ -115,6 +137,10 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
|||||||
s.basePath = cfg.BasePath
|
s.basePath = cfg.BasePath
|
||||||
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||||
s.sso = cfg.SSO
|
s.sso = cfg.SSO
|
||||||
|
s.deviceACL = cfg.DeviceACL
|
||||||
|
s.transferTarget = cfg.TransferTarget
|
||||||
|
s.transferDays = cfg.TransferDays
|
||||||
|
s.transferTransport = cfg.TransferTransport
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +164,9 @@ func (s *Server) Start() error {
|
|||||||
s.ws = newWSHub(s.auth, s.hub, s.history, s.log).
|
s.ws = newWSHub(s.auth, s.hub, s.history, s.log).
|
||||||
withOriginAllowlist(s.allowedOrigins).
|
withOriginAllowlist(s.allowedOrigins).
|
||||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||||
withTrustForwardedFor(s.trustForwardedFor)
|
withTrustForwardedFor(s.trustForwardedFor).
|
||||||
|
withDeviceACL(s.deviceACL).
|
||||||
|
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/", s.handleIndex)
|
mux.HandleFunc("/", s.handleIndex)
|
||||||
@@ -280,8 +308,17 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|||||||
// handleDevices returns a JSON snapshot of currently-online devices. Empty
|
// handleDevices returns a JSON snapshot of currently-online devices. Empty
|
||||||
// array (not null) when no clients are connected — matches what the front-end
|
// array (not null) when no clients are connected — matches what the front-end
|
||||||
// will eventually expect. Auth-gated via requireBearer.
|
// will eventually expect. Auth-gated via requireBearer.
|
||||||
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request, sess *wsauth.Session) {
|
||||||
devices := s.hub.ListDevices()
|
devices := s.hub.ListDevices()
|
||||||
|
if s.deviceACL != nil {
|
||||||
|
visible := make([]hub.DeviceInfo, 0, len(devices))
|
||||||
|
for _, d := range devices {
|
||||||
|
if deviceAllowed(s.deviceACL, sess.Username, sess.Role, d.ID) {
|
||||||
|
visible = append(visible, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
devices = visible
|
||||||
|
}
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
if err := json.NewEncoder(w).Encode(devices); err != nil {
|
if err := json.NewEncoder(w).Encode(devices); err != nil {
|
||||||
@@ -294,7 +331,7 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
|
|||||||
// missing / invalid / expired tokens. Used to gate REST endpoints that
|
// missing / invalid / expired tokens. Used to gate REST endpoints that
|
||||||
// previously fell through with no auth (notably /api/devices, which
|
// previously fell through with no auth (notably /api/devices, which
|
||||||
// otherwise leaks the full online-device list to anyone on the internet).
|
// otherwise leaks the full online-device list to anyone on the internet).
|
||||||
func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
|
func (s *Server) requireBearer(next func(http.ResponseWriter, *http.Request, *wsauth.Session)) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
const prefix = "Bearer "
|
const prefix = "Bearer "
|
||||||
hdr := r.Header.Get("Authorization")
|
hdr := r.Header.Get("Authorization")
|
||||||
@@ -307,11 +344,12 @@ func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
|
|||||||
s.unauthorized(w)
|
s.unauthorized(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err := s.auth.ValidateToken(token); err != nil {
|
sess, err := s.auth.ValidateToken(token)
|
||||||
|
if err != nil {
|
||||||
s.unauthorized(w)
|
s.unauthorized(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next(w, r)
|
next(w, r, sess)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,19 @@ func (s *Server) handleSSO(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.unauthorized(w)
|
s.unauthorized(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// "admin" is the built-in superadmin account and must never be minted by
|
||||||
|
// SSO: any portal identity with that name would inherit bind/unbind and
|
||||||
|
// unrestricted device access. Portal usernames are email addresses, so a
|
||||||
|
// real portal user can never legitimately hit this.
|
||||||
|
if username == "admin" {
|
||||||
|
fields := requestFields(r, s.trustForwardedFor)
|
||||||
|
fields["method"] = "sso"
|
||||||
|
fields["actor"] = username
|
||||||
|
fields["reason"] = "reserved_username"
|
||||||
|
s.log.AuditWarn(auditLoginFail, fields)
|
||||||
|
s.unauthorized(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
// Only the "admin" role may skip the login form via SSO. Every other role
|
// Only the "admin" role may skip the login form via SSO. Every other role
|
||||||
// (viewer, unknown) must authenticate against YAMA's own login, even with
|
// (viewer, unknown) must authenticate against YAMA's own login, even with
|
||||||
// a valid portal session. A valid portal identity being refused here is
|
// a valid portal session. A valid portal identity being refused here is
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ func TestHandleSSOAdminOnly(t *testing.T) {
|
|||||||
wantStatus int
|
wantStatus int
|
||||||
}{
|
}{
|
||||||
{"admin is bridged", &fakeSSODetector{"alice", "admin", true}, http.StatusOK},
|
{"admin is bridged", &fakeSSODetector{"alice", "admin", true}, http.StatusOK},
|
||||||
|
{"built-in username is rejected", &fakeSSODetector{"admin", "admin", true}, http.StatusUnauthorized},
|
||||||
{"viewer is rejected", &fakeSSODetector{"bob", "viewer", true}, http.StatusUnauthorized},
|
{"viewer is rejected", &fakeSSODetector{"bob", "viewer", true}, http.StatusUnauthorized},
|
||||||
{"unknown role is rejected", &fakeSSODetector{"carol", "operator", true}, http.StatusUnauthorized},
|
{"unknown role is rejected", &fakeSSODetector{"carol", "operator", true}, http.StatusUnauthorized},
|
||||||
{"no credential is rejected", &fakeSSODetector{ok: false}, http.StatusUnauthorized},
|
{"no credential is rejected", &fakeSSODetector{ok: false}, http.StatusUnauthorized},
|
||||||
|
|||||||
@@ -0,0 +1,278 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
// transferReply drains queued messages until the transfer result arrives. The
|
||||||
|
// handler also broadcasts devices_changed to every authenticated client, so
|
||||||
|
// the reply is not necessarily the first message on the channel.
|
||||||
|
func transferReply(t *testing.T, c *wsClient) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
select {
|
||||||
|
case m := <-c.send:
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(m.data, &out); err != nil {
|
||||||
|
t.Fatalf("decode reply: %v", err)
|
||||||
|
}
|
||||||
|
if out["cmd"] == "transfer_device_result" {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Fatal("no transfer_device_result reply")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("transfer_device_result not queued")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransferDeviceSendsAssignMaster(t *testing.T) {
|
||||||
|
wh, h, hist := deleteTestHub(t)
|
||||||
|
var sent []byte
|
||||||
|
h.SetSender(func(_ *connection.Context, data []byte) error {
|
||||||
|
sent = append([]byte(nil), data...)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.9:1000"})
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 2,
|
||||||
|
})
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
rep := transferReply(t, c)
|
||||||
|
if rep["ok"] != true {
|
||||||
|
t.Fatalf("reply = %+v, want ok", rep)
|
||||||
|
}
|
||||||
|
if rep["target"] != "mfc.example:6544" {
|
||||||
|
t.Fatalf("target = %v, want mfc.example:6544", rep["target"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wire format must match the MFC master byte for byte: command, transfer
|
||||||
|
// type, then host:port:days::transport as a NUL-terminated string. The
|
||||||
|
// empty shine segment keeps the host's header-encryption variant; the
|
||||||
|
// transport segment must always be present (TCP unless configured), or a
|
||||||
|
// host that currently talks WSS would keep WSS against the target.
|
||||||
|
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
|
||||||
|
"mfc.example:6544:2::0\x00"
|
||||||
|
if string(sent) != want {
|
||||||
|
t.Fatalf("sent = %q, want %q", sent, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The marker is what the card renders as "transferred → …".
|
||||||
|
target, until, ok := hist.Transfer("live")
|
||||||
|
if !ok || target != "mfc.example:6544" || until <= 0 {
|
||||||
|
t.Fatalf("history marker = %q/%d/%v, want mfc.example:6544 with a deadline", target, until, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The configured transport must reach the device: the clients keep their
|
||||||
|
// current link when the segment is missing, so a WSS-managed host handed to a
|
||||||
|
// plain-TCP master would retry WSS forever.
|
||||||
|
func TestTransferDeviceSendsConfiguredTransport(t *testing.T) {
|
||||||
|
wh, h, _ := deleteTestHub(t)
|
||||||
|
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportWSS)
|
||||||
|
var sent []byte
|
||||||
|
h.SetSender(func(_ *connection.Context, data []byte) error {
|
||||||
|
sent = append([]byte(nil), data...)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.14:1000"})
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
|
||||||
|
})
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
if rep := transferReply(t, c); rep["ok"] != true {
|
||||||
|
t.Fatalf("reply = %+v, want ok", rep)
|
||||||
|
}
|
||||||
|
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
|
||||||
|
"mfc.example:6544:1::6\x00"
|
||||||
|
if string(sent) != want {
|
||||||
|
t.Fatalf("sent = %q, want %q", sent, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransferDeviceRequiresAdmin(t *testing.T) {
|
||||||
|
wh, h, hist := deleteTestHub(t)
|
||||||
|
sent := false
|
||||||
|
h.SetSender(func(_ *connection.Context, _ []byte) error {
|
||||||
|
sent = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.10:1000"})
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "viewer")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
|
||||||
|
})
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
if rep := transferReply(t, c); rep["ok"] != false {
|
||||||
|
t.Fatalf("reply = %+v, want ok:false", rep)
|
||||||
|
}
|
||||||
|
if sent {
|
||||||
|
t.Fatal("viewer's transfer command reached the device")
|
||||||
|
}
|
||||||
|
if _, _, ok := hist.Transfer("live"); ok {
|
||||||
|
t.Fatal("viewer's transfer left a marker")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransferDeviceOffline(t *testing.T) {
|
||||||
|
wh, _, _ := deleteTestHub(t)
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "never-seen", "host": "mfc.example", "port": 6544, "days": 1,
|
||||||
|
})
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
if rep := transferReply(t, c); rep["ok"] != false || rep["msg"] != "Host is offline" {
|
||||||
|
t.Fatalf("reply = %+v, want offline failure", rep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransferDeviceRejectsBadTarget(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
in map[string]any
|
||||||
|
}{
|
||||||
|
{"empty host", map[string]any{"host": "", "port": 6544, "days": 1}},
|
||||||
|
{"colon in host", map[string]any{"host": "mfc:6544", "port": 6544, "days": 1}},
|
||||||
|
{"port zero", map[string]any{"host": "mfc.example", "port": 0, "days": 1}},
|
||||||
|
{"port too big", map[string]any{"host": "mfc.example", "port": 70000, "days": 1}},
|
||||||
|
{"zero days", map[string]any{"host": "mfc.example", "port": 6544, "days": 0}},
|
||||||
|
{"too many days", map[string]any{"host": "mfc.example", "port": 6544, "days": 400}},
|
||||||
|
{"no id", map[string]any{"id": "", "host": "mfc.example", "port": 6544, "days": 1}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
wh, h, _ := deleteTestHub(t)
|
||||||
|
sent := false
|
||||||
|
h.SetSender(func(_ *connection.Context, _ []byte) error {
|
||||||
|
sent = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.11:1000"})
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
args := map[string]any{"token": tok, "id": "live"}
|
||||||
|
for k, v := range tc.in {
|
||||||
|
args[k] = v
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(args)
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
if rep := transferReply(t, c); rep["ok"] != false {
|
||||||
|
t.Fatalf("reply = %+v, want ok:false", rep)
|
||||||
|
}
|
||||||
|
if sent {
|
||||||
|
t.Fatal("invalid target still reached the device")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A second assignment while the first one is live would be ignored by the
|
||||||
|
// Windows client ("Avoid assign again"), so the server must not report success
|
||||||
|
// for it.
|
||||||
|
func TestTransferDeviceRefusesSecondTransfer(t *testing.T) {
|
||||||
|
wh, h, hist := deleteTestHub(t)
|
||||||
|
sends := 0
|
||||||
|
h.SetSender(func(_ *connection.Context, _ []byte) error {
|
||||||
|
sends++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.12:1000"})
|
||||||
|
if !hist.SetTransfer("live", "mfc.example:6544", 1<<62) {
|
||||||
|
t.Fatal("SetTransfer on a live device failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "live", "host": "other.example", "port": 6544, "days": 1,
|
||||||
|
})
|
||||||
|
wh.handleTransferDevice(c, raw)
|
||||||
|
|
||||||
|
rep := transferReply(t, c)
|
||||||
|
if rep["ok"] != false {
|
||||||
|
t.Fatalf("reply = %+v, want ok:false", rep)
|
||||||
|
}
|
||||||
|
if sends != 0 {
|
||||||
|
t.Fatalf("device received %d commands, want 0", sends)
|
||||||
|
}
|
||||||
|
if target, _, _ := hist.Transfer("live"); target != "mfc.example:6544" {
|
||||||
|
t.Fatalf("marker overwritten to %q", target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The shared page decides whether to show the transfer button by the presence
|
||||||
|
// of the "transfer" object in device_list, and reads the card marker from
|
||||||
|
// transferTo/transferUntil. Both are part of the contract with index.html.
|
||||||
|
func TestDeviceListReportsTransferContract(t *testing.T) {
|
||||||
|
wh, h, hist := deleteTestHub(t)
|
||||||
|
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportTCP)
|
||||||
|
|
||||||
|
h.Register(&hub.Device{ID: "live", Name: "Live"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.13:1000"})
|
||||||
|
if !hist.SetTransfer("live", "mfc.example:6544", 4102444800) { // year 2100
|
||||||
|
t.Fatal("SetTransfer failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
c, tok := deleteTestClient(wh, "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok})
|
||||||
|
wh.handleGetDevices(c, raw)
|
||||||
|
|
||||||
|
var out struct {
|
||||||
|
Cmd string `json:"cmd"`
|
||||||
|
Transfer *struct {
|
||||||
|
Target string `json:"target"`
|
||||||
|
Days float64 `json:"days"`
|
||||||
|
} `json:"transfer"`
|
||||||
|
Devices []struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
TransferTo string `json:"transferTo"`
|
||||||
|
TransferUntil int64 `json:"transferUntil"`
|
||||||
|
} `json:"devices"`
|
||||||
|
}
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
select {
|
||||||
|
case m := <-c.send:
|
||||||
|
if err := json.Unmarshal(m.data, &out); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Fatal("no device_list reply")
|
||||||
|
}
|
||||||
|
if out.Cmd == "device_list" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out.Transfer == nil {
|
||||||
|
t.Fatal("device_list carries no transfer config — the page would hide the button")
|
||||||
|
}
|
||||||
|
if out.Transfer.Target != "mfc.example:6544" || out.Transfer.Days != 2 {
|
||||||
|
t.Fatalf("transfer config = %+v", *out.Transfer)
|
||||||
|
}
|
||||||
|
if len(out.Devices) != 1 {
|
||||||
|
t.Fatalf("devices = %d, want 1", len(out.Devices))
|
||||||
|
}
|
||||||
|
if d := out.Devices[0]; d.TransferTo != "mfc.example:6544" || d.TransferUntil == 0 {
|
||||||
|
t.Fatalf("device marker = %+v, want mfc.example:6544 with a deadline", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
+69
-3
@@ -131,7 +131,15 @@ func (c *wsClient) close() {
|
|||||||
// challengeCaps advertises optional protocol features. It is appended to every
|
// challengeCaps advertises optional protocol features. It is appended to every
|
||||||
// challenge, including the rotation after a failed login, because the browser
|
// challenge, including the rotation after a failed login, because the browser
|
||||||
// overwrites its capability state on each challenge. Old frontends ignore it.
|
// overwrites its capability state on each challenge. Old frontends ignore it.
|
||||||
const challengeCaps = `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true}`
|
// deviceAcl is only advertised when the hub actually has a binding table;
|
||||||
|
// embedders that leave it nil keep the old "everyone sees everything" model.
|
||||||
|
func (h *wsHub) challengeCaps() string {
|
||||||
|
deviceAcl := "false"
|
||||||
|
if h.acl != nil {
|
||||||
|
deviceAcl = "true"
|
||||||
|
}
|
||||||
|
return `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true,"deviceAcl":` + deviceAcl + `}`
|
||||||
|
}
|
||||||
|
|
||||||
// maxWatchPerClient bounds the number of devices one WebSocket may stream at
|
// maxWatchPerClient bounds the number of devices one WebSocket may stream at
|
||||||
// once. The wall tops out at 25 tiles; the slack covers a focus switch racing
|
// once. The wall tops out at 25 tiles; the slack covers a focus switch racing
|
||||||
@@ -152,6 +160,7 @@ type wsHub struct {
|
|||||||
auth *wsauth.Authenticator
|
auth *wsauth.Authenticator
|
||||||
devices *hub.Hub
|
devices *hub.Hub
|
||||||
history *devicehistory.Store // nil → device_list stays online-only
|
history *devicehistory.Store // nil → device_list stays online-only
|
||||||
|
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||||
log *logger.Logger
|
log *logger.Logger
|
||||||
|
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
@@ -172,6 +181,16 @@ type wsHub struct {
|
|||||||
loginIPLimit *wsauth.RateLimiter
|
loginIPLimit *wsauth.RateLimiter
|
||||||
loginUserLimit *wsauth.RateLimiter
|
loginUserLimit *wsauth.RateLimiter
|
||||||
trustForwardedFor bool // honor X-Forwarded-For (only when behind a trusted proxy)
|
trustForwardedFor bool // honor X-Forwarded-For (only when behind a trusted proxy)
|
||||||
|
|
||||||
|
// transferTarget / transferDays pre-fill the "transfer host" dialog and,
|
||||||
|
// by being reported to the browser, tell the shared page that this backend
|
||||||
|
// implements COMMAND_ASSIGN_MASTER at all (see withTransferDefaults).
|
||||||
|
// transferTransport is the link the transferred host uses to reach the
|
||||||
|
// target (protocol.TransferTransport*); it is sent in the command because
|
||||||
|
// the clients keep their current link when it is missing.
|
||||||
|
transferTarget string
|
||||||
|
transferDays float64
|
||||||
|
transferTransport int
|
||||||
}
|
}
|
||||||
|
|
||||||
func newWSHub(auth *wsauth.Authenticator, devices *hub.Hub, history *devicehistory.Store, log *logger.Logger) *wsHub {
|
func newWSHub(auth *wsauth.Authenticator, devices *hub.Hub, history *devicehistory.Store, log *logger.Logger) *wsHub {
|
||||||
@@ -210,6 +229,50 @@ func (h *wsHub) withTrustForwardedFor(trust bool) *wsHub {
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// withDeviceACL wires the per-device owner table. nil keeps the legacy
|
||||||
|
// "every authenticated session may access every device" behaviour, which is
|
||||||
|
// what embedders/tests without the ACL set up get.
|
||||||
|
func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
||||||
|
h.acl = acl
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// withTransferDefaults installs the pre-filled target/days and the link type
|
||||||
|
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
|
||||||
|
// empty target still enables the feature: the operator types the address in
|
||||||
|
// the dialog. The front-end keys the button's visibility off this being
|
||||||
|
// reported at all, so the shared page shows no transfer button on the MFC
|
||||||
|
// server (which never reports it).
|
||||||
|
func (h *wsHub) withTransferDefaults(target string, days float64, transport int) *wsHub {
|
||||||
|
h.transferTarget = target
|
||||||
|
if days <= 0 {
|
||||||
|
days = 1 // one day is enough for an upgrade round-trip
|
||||||
|
}
|
||||||
|
h.transferDays = days
|
||||||
|
h.transferTransport = transport
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// isSuperAdmin reports whether this session is the built-in admin account
|
||||||
|
// (username "admin" + role admin). Other admin-role users — local accounts
|
||||||
|
// created in the user panel or portal admins bridged by SSO — are device-
|
||||||
|
// scoped by the ACL and must NOT be treated as superadmins.
|
||||||
|
//
|
||||||
|
// The "admin" username cannot be minted elsewhere: wsauth.CreateUser rejects
|
||||||
|
// it, the users.json loader skips it, local password login rejects '@' names,
|
||||||
|
// and handleSSO refuses a portal identity named "admin".
|
||||||
|
func (c *wsClient) isSuperAdmin() bool {
|
||||||
|
return c != nil && c.role == "admin" && c.user == "admin"
|
||||||
|
}
|
||||||
|
|
||||||
|
// canAccessDevice applies the visibility matrix from deviceAllowed.
|
||||||
|
func (h *wsHub) canAccessDevice(c *wsClient, deviceID string) bool {
|
||||||
|
if c == nil || deviceID == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return deviceAllowed(h.acl, c.user, c.role, deviceID)
|
||||||
|
}
|
||||||
|
|
||||||
// checkOrigin decides whether to accept a WebSocket upgrade based on
|
// checkOrigin decides whether to accept a WebSocket upgrade based on
|
||||||
// the request's Origin header. Same-origin (Origin host == Host) is
|
// the request's Origin header. Same-origin (Origin host == Host) is
|
||||||
// always accepted; explicit allowlist entries cover the
|
// always accepted; explicit allowlist entries cover the
|
||||||
@@ -512,7 +575,10 @@ func (h *wsHub) OnDeviceUpdate(id string, rtt int, activeWindow string) {
|
|||||||
h.mu.RLock()
|
h.mu.RLock()
|
||||||
defer h.mu.RUnlock()
|
defer h.mu.RUnlock()
|
||||||
for c := range h.clients {
|
for c := range h.clients {
|
||||||
if c.token != "" {
|
// Heartbeat data includes the device's foreground-window text. Sending
|
||||||
|
// it to clients that cannot access the device would leak both its
|
||||||
|
// existence and what its user is doing.
|
||||||
|
if c.token != "" && deviceAllowed(h.acl, c.user, c.role, id) {
|
||||||
c.queue(payload)
|
c.queue(payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -673,7 +739,7 @@ func (h *wsHub) serve(w http.ResponseWriter, r *http.Request) {
|
|||||||
go h.writeLoop(client)
|
go h.writeLoop(client)
|
||||||
|
|
||||||
// Greet with a challenge nonce so the browser can compute the login response.
|
// Greet with a challenge nonce so the browser can compute the login response.
|
||||||
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + challengeCaps + `}`))
|
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + h.challengeCaps() + `}`))
|
||||||
|
|
||||||
h.readLoop(client)
|
h.readLoop(client)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,494 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||||
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// aclTestHub builds a hub with one public device and two owner-bound devices.
|
||||||
|
func aclTestHub(t *testing.T) (*wsHub, *hub.Hub, *DeviceACL) {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
lg := logger.New(logger.Config{
|
||||||
|
Level: logger.LevelInfo,
|
||||||
|
Console: false,
|
||||||
|
File: filepath.Join(dir, "server.log"),
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { _ = lg.Close() })
|
||||||
|
|
||||||
|
devices := hub.New()
|
||||||
|
devices.SetSender(func(*connection.Context, []byte) error { return nil })
|
||||||
|
devices.Register(&hub.Device{ID: "pub", Name: "Public", Group: "shared"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
|
||||||
|
devices.Register(&hub.Device{ID: "a-dev", Name: "A", Group: "private-a"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.2:1000"})
|
||||||
|
devices.Register(&hub.Device{ID: "b-dev", Name: "B", Group: "private-b"},
|
||||||
|
&connection.Context{RemoteAddr: "10.0.0.3:1000"})
|
||||||
|
|
||||||
|
acl := NewDeviceACL(filepath.Join(dir, "device_acl.json"))
|
||||||
|
if err := acl.Bind([]string{"a-dev"}, "a@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind a-dev: %v", err)
|
||||||
|
}
|
||||||
|
if err := acl.Bind([]string{"b-dev"}, "b@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind b-dev: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
wh := newWSHub(wsauth.New(), devices, nil, lg).withDeviceACL(acl)
|
||||||
|
t.Cleanup(wh.stop)
|
||||||
|
return wh, devices, acl
|
||||||
|
}
|
||||||
|
|
||||||
|
func aclTestClient(t *testing.T, wh *wsHub, username, role string) (*wsClient, string) {
|
||||||
|
t.Helper()
|
||||||
|
tok, err := wh.auth.IssueToken(username, role)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("IssueToken(%q): %v", username, err)
|
||||||
|
}
|
||||||
|
c := &wsClient{
|
||||||
|
send: make(chan wsMsg, 64),
|
||||||
|
closed: make(chan struct{}),
|
||||||
|
id: newConnID(),
|
||||||
|
addr: "203.0.113.5",
|
||||||
|
peerAddr: "203.0.113.5",
|
||||||
|
connectedAt: time.Now(),
|
||||||
|
// Simulate an already-authenticated connection: in production these
|
||||||
|
// fields are installed by requireAuth on the first command.
|
||||||
|
token: tok,
|
||||||
|
user: username,
|
||||||
|
role: role,
|
||||||
|
watchIDs: make(map[string]struct{}),
|
||||||
|
watchStartedAt: make(map[string]time.Time),
|
||||||
|
keyframeAt: make(map[string]int64),
|
||||||
|
}
|
||||||
|
wh.register(c)
|
||||||
|
return c, tok
|
||||||
|
}
|
||||||
|
|
||||||
|
// readUntilCmd drains queued messages until cmd arrives. Handlers may also
|
||||||
|
// queue broadcasts (devices_changed) or revocations on the same channel.
|
||||||
|
func readUntilCmd(t *testing.T, c *wsClient, cmd string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.After(2 * time.Second)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case m := <-c.send:
|
||||||
|
var v map[string]any
|
||||||
|
if err := json.Unmarshal(m.data, &v); err != nil {
|
||||||
|
t.Fatalf("decode queued message: %v", err)
|
||||||
|
}
|
||||||
|
if v["cmd"] == cmd {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
case <-deadline:
|
||||||
|
t.Fatalf("timed out waiting for %q", cmd)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeviceListACL(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
tests := []struct {
|
||||||
|
user string
|
||||||
|
role string
|
||||||
|
want []string
|
||||||
|
owner string // owner of a-dev as exposed to this caller
|
||||||
|
}{
|
||||||
|
{"admin", "admin", []string{"pub", "a-dev", "b-dev"}, "a@corp.com"},
|
||||||
|
{"a@corp.com", "admin", []string{"pub", "a-dev"}, ""},
|
||||||
|
{"b@corp.com", "admin", []string{"pub", "b-dev"}, ""},
|
||||||
|
{"v@corp.com", "viewer", nil, ""},
|
||||||
|
{"a@corp.com", "viewer", []string{"a-dev"}, ""},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.user+"/"+tt.role, func(t *testing.T) {
|
||||||
|
c, tok := aclTestClient(t, wh, tt.user, tt.role)
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok})
|
||||||
|
wh.handleGetDevices(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "device_list")
|
||||||
|
rawDevices, _ := json.Marshal(msg["devices"])
|
||||||
|
var items []deviceListItem
|
||||||
|
if err := json.Unmarshal(rawDevices, &items); err != nil {
|
||||||
|
t.Fatalf("decode devices: %v", err)
|
||||||
|
}
|
||||||
|
got := make(map[string]string, len(items))
|
||||||
|
for _, it := range items {
|
||||||
|
got[it.ID] = it.Owner
|
||||||
|
}
|
||||||
|
if len(got) != len(tt.want) {
|
||||||
|
t.Fatalf("visible = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
for _, id := range tt.want {
|
||||||
|
if _, ok := got[id]; !ok {
|
||||||
|
t.Fatalf("visible = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tt.owner != "" && got["a-dev"] != tt.owner {
|
||||||
|
t.Fatalf("a-dev owner = %q, want %q", got["a-dev"], tt.owner)
|
||||||
|
}
|
||||||
|
if tt.owner == "" && got["a-dev"] != "" {
|
||||||
|
t.Fatalf("non-superadmin saw owner %q", got["a-dev"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectDeniedForOtherOwnersDevice(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
c, tok := aclTestClient(t, wh, "b@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev", "multiWatch": true})
|
||||||
|
wh.handleConnect(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "connect_result")
|
||||||
|
if msg["ok"] != false {
|
||||||
|
t.Fatalf("connect allowed: %+v", msg)
|
||||||
|
}
|
||||||
|
wh.mu.RLock()
|
||||||
|
_, watching := c.watchIDs["a-dev"]
|
||||||
|
wh.mu.RUnlock()
|
||||||
|
if watching {
|
||||||
|
t.Fatal("denied connect still subscribed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectAllowedForOwner(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
c, tok := aclTestClient(t, wh, "a@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev", "multiWatch": true})
|
||||||
|
wh.handleConnect(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "connect_result")
|
||||||
|
if msg["ok"] != true {
|
||||||
|
t.Fatalf("owner connect denied: %+v", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTerminalDeniedForOtherOwnersDevice(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
c, tok := aclTestClient(t, wh, "b@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"})
|
||||||
|
wh.handleTermOpen(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "term_closed")
|
||||||
|
if msg["ok"] != false {
|
||||||
|
t.Fatalf("terminal allowed: %+v", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInputChannelsDeniedByACL(t *testing.T) {
|
||||||
|
wh, devices, _ := aclTestHub(t)
|
||||||
|
var sent int
|
||||||
|
devices.SetSender(func(*connection.Context, []byte) error {
|
||||||
|
sent++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
c, tok := aclTestClient(t, wh, "b@corp.com", "admin")
|
||||||
|
// Simulate a subscription established before the device became private.
|
||||||
|
wh.mu.Lock()
|
||||||
|
c.watchIDs["a-dev"] = struct{}{}
|
||||||
|
c.watchStartedAt["a-dev"] = time.Now()
|
||||||
|
wh.mu.Unlock()
|
||||||
|
|
||||||
|
mouse, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "a-dev", "type": "move", "x": 10, "y": 20,
|
||||||
|
})
|
||||||
|
wh.handleMouse(c, mouse)
|
||||||
|
if sent != 0 {
|
||||||
|
t.Fatal("mouse event reached a device the caller does not own")
|
||||||
|
}
|
||||||
|
|
||||||
|
key, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "a-dev", "keyCode": 65, "down": true,
|
||||||
|
})
|
||||||
|
wh.handleKey(c, key)
|
||||||
|
if sent != 0 {
|
||||||
|
t.Fatal("key event reached a device the caller does not own")
|
||||||
|
}
|
||||||
|
|
||||||
|
clip, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "id": "a-dev", "text": "secret",
|
||||||
|
})
|
||||||
|
wh.handleClipboardSet(c, clip)
|
||||||
|
if sent != 0 {
|
||||||
|
t.Fatal("clipboard write reached a device the caller does not own")
|
||||||
|
}
|
||||||
|
|
||||||
|
kf, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"})
|
||||||
|
wh.handleKeyframe(c, kf)
|
||||||
|
reply := readUntilCmd(t, c, "keyframe_result")
|
||||||
|
if reply["ok"] != false {
|
||||||
|
t.Fatalf("keyframe allowed: %+v", reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
rdp, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"})
|
||||||
|
wh.handleRdpReset(c, rdp)
|
||||||
|
if sent != 0 {
|
||||||
|
t.Fatal("rdp reset reached a device the caller does not own")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindDeviceRequiresSuperadmin(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
c, tok := aclTestClient(t, wh, "a@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "ids": []string{"pub"}, "username": "a@corp.com",
|
||||||
|
})
|
||||||
|
wh.handleBindDevice(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "bind_device_result")
|
||||||
|
if msg["ok"] != false || msg["msg"] != "Superadmin only" {
|
||||||
|
t.Fatalf("non-superadmin bind reply = %+v", msg)
|
||||||
|
}
|
||||||
|
if acl.Owner("pub") != "" {
|
||||||
|
t.Fatal("non-superadmin changed the ACL")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindDeviceAndRevoke(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
b, btok := aclTestClient(t, wh, "b@corp.com", "admin")
|
||||||
|
// b was legitimately watching/terminalling b-dev before it became private.
|
||||||
|
wh.mu.Lock()
|
||||||
|
b.watchIDs["b-dev"] = struct{}{}
|
||||||
|
b.watchStartedAt["b-dev"] = time.Now()
|
||||||
|
b.termWatching = "b-dev"
|
||||||
|
b.termStartedAt = time.Now()
|
||||||
|
wh.mu.Unlock()
|
||||||
|
_ = btok
|
||||||
|
|
||||||
|
admin, atok := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": atok, "ids": []string{"b-dev"}, "username": "a@corp.com",
|
||||||
|
})
|
||||||
|
wh.handleBindDevice(admin, raw)
|
||||||
|
msg := readUntilCmd(t, admin, "bind_device_result")
|
||||||
|
if msg["ok"] != true {
|
||||||
|
t.Fatalf("bind reply = %+v", msg)
|
||||||
|
}
|
||||||
|
if got := acl.Owner("b-dev"); got != "a@corp.com" {
|
||||||
|
t.Fatalf("owner = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
wh.mu.RLock()
|
||||||
|
_, watching := b.watchIDs["b-dev"]
|
||||||
|
term := b.termWatching
|
||||||
|
wh.mu.RUnlock()
|
||||||
|
if watching {
|
||||||
|
t.Fatal("revoked viewer still subscribed")
|
||||||
|
}
|
||||||
|
if term != "" {
|
||||||
|
t.Fatal("revoked viewer still holds the terminal")
|
||||||
|
}
|
||||||
|
|
||||||
|
// b gets device_revoked and term_closed; both may be preceded by
|
||||||
|
// devices_changed broadcasts.
|
||||||
|
_ = readUntilCmd(t, b, "device_revoked")
|
||||||
|
_ = readUntilCmd(t, b, "term_closed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindRejectsBadTargets(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
admin, tok := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
username string
|
||||||
|
}{
|
||||||
|
{"built-in admin", "admin"},
|
||||||
|
{"unknown local", "nobody"},
|
||||||
|
{"empty", ""},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "ids": []string{"pub"}, "username": tt.username,
|
||||||
|
})
|
||||||
|
wh.handleBindDevice(admin, raw)
|
||||||
|
msg := readUntilCmd(t, admin, "bind_device_result")
|
||||||
|
if msg["ok"] != false {
|
||||||
|
t.Fatalf("bind(%q) accepted: %+v", tt.username, msg)
|
||||||
|
}
|
||||||
|
if acl.Owner("pub") != "" {
|
||||||
|
t.Fatalf("bind(%q) changed the ACL", tt.username)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A local account is accepted…
|
||||||
|
if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil {
|
||||||
|
t.Fatalf("CreateUser: %v", err)
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"token": tok, "ids": []string{"pub"}, "username": "alice",
|
||||||
|
})
|
||||||
|
wh.handleBindDevice(admin, raw)
|
||||||
|
msg := readUntilCmd(t, admin, "bind_device_result")
|
||||||
|
if msg["ok"] != true {
|
||||||
|
t.Fatalf("bind to local user denied: %+v", msg)
|
||||||
|
}
|
||||||
|
if acl.Owner("pub") != "alice" {
|
||||||
|
t.Fatalf("owner = %q", acl.Owner("pub"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteDeviceDropsBinding(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
c, tok := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"})
|
||||||
|
wh.handleDeleteDevice(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "delete_device_result")
|
||||||
|
if msg["ok"] != true {
|
||||||
|
t.Fatalf("delete reply = %+v", msg)
|
||||||
|
}
|
||||||
|
if got := acl.Owner("a-dev"); got != "" {
|
||||||
|
t.Fatalf("binding survived device deletion: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginRejectsAtSignUsername(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
c := &wsClient{
|
||||||
|
send: make(chan wsMsg, 8),
|
||||||
|
closed: make(chan struct{}),
|
||||||
|
addr: "203.0.113.5",
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{
|
||||||
|
"username": "alice@corp.com", "response": "x", "nonce": "n",
|
||||||
|
})
|
||||||
|
wh.handleLogin(c, raw)
|
||||||
|
msg := readUntilCmd(t, c, "login_result")
|
||||||
|
if msg["ok"] != false {
|
||||||
|
t.Fatalf("password login accepted an SSO-shaped username: %+v", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeviceUpdateDoesNotLeakBoundDevices(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
super, _ := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
other, _ := aclTestClient(t, wh, "c@corp.com", "admin")
|
||||||
|
|
||||||
|
wh.OnDeviceUpdate("a-dev", 12, "Bank - Chrome")
|
||||||
|
|
||||||
|
msg := readUntilCmd(t, super, "device_update")
|
||||||
|
if msg["activeWindow"] != "Bank - Chrome" {
|
||||||
|
t.Fatalf("superadmin update = %+v", msg)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case m := <-other.send:
|
||||||
|
t.Fatalf("device_update for a bound device leaked: %s", m.data)
|
||||||
|
case <-time.After(200 * time.Millisecond):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetGroupsFiltersHiddenDevices(t *testing.T) {
|
||||||
|
wh, _, _ := aclTestHub(t)
|
||||||
|
other, tok := aclTestClient(t, wh, "c@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok})
|
||||||
|
wh.handleGetGroups(other, raw)
|
||||||
|
msg := readUntilCmd(t, other, "groups")
|
||||||
|
got, _ := msg["groups"].([]any)
|
||||||
|
for _, g := range got {
|
||||||
|
if g == "private-a" || g == "private-b" {
|
||||||
|
t.Fatalf("group of a hidden device leaked: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnbindRevokesViewerKeepsAdmin(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
if err := acl.Bind([]string{"a-dev"}, "v@corp.com", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind: %v", err)
|
||||||
|
}
|
||||||
|
viewer, _ := aclTestClient(t, wh, "v@corp.com", "viewer")
|
||||||
|
adminWhilePublic, _ := aclTestClient(t, wh, "c@corp.com", "admin")
|
||||||
|
super, stok := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
|
||||||
|
// Both sessions predate the unbind (simulated directly).
|
||||||
|
wh.mu.Lock()
|
||||||
|
viewer.watchIDs["a-dev"] = struct{}{}
|
||||||
|
viewer.watchStartedAt["a-dev"] = time.Now()
|
||||||
|
adminWhilePublic.watchIDs["a-dev"] = struct{}{}
|
||||||
|
adminWhilePublic.watchStartedAt["a-dev"] = time.Now()
|
||||||
|
wh.mu.Unlock()
|
||||||
|
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": stok, "ids": []string{"a-dev"}})
|
||||||
|
wh.handleUnbindDevice(super, raw)
|
||||||
|
if rep := readUntilCmd(t, super, "unbind_device_result"); rep["ok"] != true {
|
||||||
|
t.Fatalf("unbind = %+v", rep)
|
||||||
|
}
|
||||||
|
|
||||||
|
wh.mu.RLock()
|
||||||
|
_, viewerWatching := viewer.watchIDs["a-dev"]
|
||||||
|
_, adminWatching := adminWhilePublic.watchIDs["a-dev"]
|
||||||
|
wh.mu.RUnlock()
|
||||||
|
if viewerWatching {
|
||||||
|
t.Fatal("viewer kept watching a device that became admin-only")
|
||||||
|
}
|
||||||
|
if !adminWatching {
|
||||||
|
t.Fatal("admin-role watcher was dropped from a now-public device")
|
||||||
|
}
|
||||||
|
_ = readUntilCmd(t, viewer, "device_revoked")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteUserUnbindsDevices(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil {
|
||||||
|
t.Fatalf("CreateUser: %v", err)
|
||||||
|
}
|
||||||
|
if err := acl.Bind([]string{"a-dev"}, "alice", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind: %v", err)
|
||||||
|
}
|
||||||
|
super, tok := aclTestClient(t, wh, "admin", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "username": "alice"})
|
||||||
|
wh.handleDeleteUser(super, raw)
|
||||||
|
rep := readUntilCmd(t, super, "delete_user_result")
|
||||||
|
if rep["ok"] != true {
|
||||||
|
t.Fatalf("delete_user = %+v", rep)
|
||||||
|
}
|
||||||
|
if got := acl.Owner("a-dev"); got != "" {
|
||||||
|
t.Fatalf("binding survived user deletion: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A non-superadmin admin may not delete an account that owns bound devices:
|
||||||
|
// releasing those bindings would hand another user's private device to the
|
||||||
|
// public pool, which only the superadmin may decide.
|
||||||
|
func TestDeleteUserWithBoundDevicesRequiresSuperadmin(t *testing.T) {
|
||||||
|
wh, _, acl := aclTestHub(t)
|
||||||
|
if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil {
|
||||||
|
t.Fatalf("CreateUser: %v", err)
|
||||||
|
}
|
||||||
|
if err := acl.Bind([]string{"a-dev"}, "alice", "admin"); err != nil {
|
||||||
|
t.Fatalf("bind: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
eve, tok := aclTestClient(t, wh, "eve@corp.com", "admin")
|
||||||
|
raw, _ := json.Marshal(map[string]any{"token": tok, "username": "alice"})
|
||||||
|
wh.handleDeleteUser(eve, raw)
|
||||||
|
rep := readUntilCmd(t, eve, "delete_user_result")
|
||||||
|
if rep["ok"] != false {
|
||||||
|
t.Fatalf("delete_user = %+v, want refusal", rep)
|
||||||
|
}
|
||||||
|
if _, exists := wh.auth.GetSalt("alice"); !exists {
|
||||||
|
t.Fatal("alice was deleted by a non-superadmin admin")
|
||||||
|
}
|
||||||
|
if got := acl.Owner("a-dev"); got != "alice" {
|
||||||
|
t.Fatalf("binding changed: %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An account without bound devices is still deletable by any admin.
|
||||||
|
if err := wh.auth.CreateUser("carol", "pw", "admin", nil); err != nil {
|
||||||
|
t.Fatalf("CreateUser: %v", err)
|
||||||
|
}
|
||||||
|
raw, _ = json.Marshal(map[string]any{"token": tok, "username": "carol"})
|
||||||
|
wh.handleDeleteUser(eve, raw)
|
||||||
|
rep = readUntilCmd(t, eve, "delete_user_result")
|
||||||
|
if rep["ok"] != true {
|
||||||
|
t.Fatalf("delete_user(carol) = %+v, want success", rep)
|
||||||
|
}
|
||||||
|
if _, exists := wh.auth.GetSalt("carol"); exists {
|
||||||
|
t.Fatal("carol was not deleted")
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user