5 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 7172ab376d Feature: add build_client MCP tool and improve build dialog linkage
Add a service-local MCP tool, build_client, that patches a client template
with this master's connect settings and writes the binary on the server.
It covers ghost/TestRun/ServerDll/TinyRun plus Linux, macOS and Android,
reusing the same byte path as CBuildDlg::OnBnClickedOk (CONNECT_ADDRESS
overwrite, build-date check, embedded TLS anchor before UPX/padding).
ShellCode AES and payload impersonation stay dialog-only.

The tool is gated by a new McpBuild switch (default 0) and McpReadonly=0.
It refuses to overwrite an existing file unless overwrite=true, protects
the server binaries/settings.ini/upx.exe, validates names strictly and
uses a unique UPX temp file so it cannot race the dialog. Results report
the path, size, target, TLS-anchor status and follow-up tips.

In the build dialog, Linux/macOS/Android targets now also grey out the
install-location combo/label and run mode, save and restore the Windows
compress choice, hide payload/download rows, grey the random-name and
run-as-admin menu items, and fix the TLS-anchor label for posix targets.
OnBnClickedOk is untouched; generated output is unchanged for every target.

New UI strings were added to the en_US, zh_TW and de_DE language packs.
McpBuild is off by default and changes require a server restart.
Verified on a Debug x64 instance: MCP generation for Linux is patched
correctly, Android and ghost anchor/error paths behave, and dialog-driven
Linux/TestRun/SC_AES generation still succeeds. mcp/tools.json regenerated
(55 tools); check_platform_table.py passes.

Co-Authored-By: deepseek-flash
2026-11-15 20:43:28 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash 1401ff0a4c Feat(android): support the assign-master command
The Android client now handles COMMAND_ASSIGN_MASTER (SHARE_TYPE_YAMA_FOREVER)
and reuses common/host_transfer.h for the parsing and for the on-disk record -
the same code the Linux and macOS clients already use.

Windows and Linux keep the main link where it is and spawn a second instance so
the new master sees the host right away, moving the main link only on the next
reconnect. Android cannot do that: the login state (ClientAuth verification,
the heartbeat ACK watchdog, the main client handle, g_bExit) is process-wide,
so a second login connection would reset the first one's verification and make
it drop every command it receives. Sharing has the same problem and stays
unimplemented. Android therefore switches immediately: change the target,
disconnect, reconnect. The new master sees the host at once and the old one
loses it at once.

Four cases, each exercised against two real masters:

  not transferred, target elsewhere        transfer
  not transferred, target is the original  ignored - it would only cost a
                                           reconnect and leave a record that
                                           "expires back to itself"
  transferred, target elsewhere            refused with a ClientMsg; this is
                                           what stops B from chaining the host
                                           to C, which would orphan the middle
                                           hop because expiry always restores
                                           to A
  transferred, target is the original      early return: the expiry time is set
                                           to now and the verified expiry path
                                           does the restore, so a master can
                                           hand the host back instead of
                                           waiting out the term

The record lives in filesDir/yama_transfer; the original master is captured
once at init and never written back, because restoring from a record that
points at the transfer target is a no-op loop. A target that stays unreachable
for 60 s (and at least 3 attempts) reverts to the original master so a typo
does not lose the host; the 60 s floor exists because a Wi-Fi hiccup would
otherwise cancel a perfectly good transfer.

Both the switch and the expiry are checked once a second rather than once per
heartbeat. With the 30 s cycle a 0.001 day (86 s) transfer took effect 14 s
late and restored 20 s late, measured; now both are under a second.

g_serverIp/g_serverPort moved behind a mutex and every connect site takes a
snapshot first: the transfer rewrites them at runtime while the screen, log,
chat, audio and terminal threads read them to connect, and assigning a
std::string frees the buffer another thread may still be holding.

ClientMsg titles are ASCII. The controller decodes title/text as ANSI/GBK, so a
Chinese literal from this UTF-8 source reaches the message pane as mojibake.

Verified on an API 35 x86_64 emulator: 443 -> 6543 -> back, refused chaining,
unreachable-target revert, natural expiry, and restart from a record.
host_transfer.h is covered by a standalone test (24 assertions: with and
without the transport field, share type rejected, port 0 / days 0 / empty IP /
bad transport, record round-trip, expiry). Sharing is answered with "Android
client does not support sharing a host" instead of being ignored.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 17:51:44 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash 3ae54c808e Fix(audio): keep audio packets block-aligned end to end
waveOut only converts whole 65-byte GSM610 blocks; a trailing partial block is
dropped, never carried over. Windows hosts record into a 1000-byte buffer but
the driver fills only 975 (15 blocks) - the last 25 bytes are stale heap the
driver never wrote. Clients ship all 1000 bytes anyway, so PlayBuffer has to
truncate each packet to whole blocks and throw that tail away.

Accumulating the remainder across packets instead - the first attempt at this
fix - inserted 25 bytes of garbage every 1000 bytes and shifted the block
boundary, turning voice monitoring of existing Windows clients into pure noise
while Android stayed fine. Both symptoms are the same "per packet" versus
"across packets" opposition, and per packet is the one that matches the wire.

So the invariant is: one packet carries a whole number of 65-byte blocks, and
nothing is ever carried into the next packet. Windows hosts satisfy it for
free. Android now packs 15 blocks (975 bytes) and pads the rest with zeros to
keep the 1000-byte length that older controllers expect - see AudioHandler.h.

GetRecordBuffer keeps returning the full 1000 bytes on purpose: shortening the
packet would make a v1.4.2 controller memcpy m_ulBufferLength and read past the
end, which is real garbage rather than harmless stale bytes.

Measured against the real waveOut API with a 2 s 1 kHz tone (3250 bytes = 50
blocks = 16000 samples): one 3250-byte buffer played 16000 samples, four
1000-byte buffers played 15360 (25 bytes lost per packet), four 975-byte
buffers played 16000. The encoder was never at fault - the same libgsm WAV49
stream decodes through Windows ACM with a correlation of 0.9999 when handed
over whole.

Also check WHDR_INQUEUE before reusing a header and honour the waveOutWrite
return value, since the old code dropped data silently on WAVERR_BUSY; size the
playback buffers for the largest packet; and unprepare the waveOut headers in
the destructor, which was unpreparing the waveIn headers after they had already
been freed.

Android APKs built before this commit still send unaligned 1000-byte packets
and will sound noisy against this controller - rebuild the APK.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 17:05:41 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash d987941e57 Fix(server): stop at startup when the process runs at Low integrity
An exe carrying a Low integrity label makes Windows downgrade the process
token, so HKCU reads/writes and %TEMP% logging all fail silently: the
settings dialog shows defaults, saving does nothing, and no log file is
ever written. Nothing in the UI hints at the real cause.

- Read TokenIntegrityLevel on startup and abort when below Medium
- Print the icacls fix command; Yes copies it to the clipboard
- Never fall through into the main window: running at Low IL is useless
- Keep the service-spawned agent silent, otherwise the 10-second relaunch
  loop turns the dialog into a flood
- Do not try runas: with UAC approval mode off it is a no-op and the child
  inherits Low, so icacls fails with "cannot assign the specified label"
- Add en_US / zh_TW / de_DE translations

The check has to run before both the UAC relaunch and the service self-heal.
Placed after HandleServiceCommandLine, a double-click installs/starts the
service, returns TRUE and exits, so the dialog could only come from the
service-spawned agent - which stays silent to avoid a flood, and the user
saw nothing at all. Placed after LaunchAsAdmin, a Low process without admin
rights loops forever, because runas spawns a child that is still Low.
Service commands (-service/-install/-uninstall) are exempted so the service
can still be installed and removed.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 11:21:58 +01:00
yuanyuanxiang 7faca2c01b Fix(android): keep encoder operating rate at 30 to restore screen streaming
3ab5154 tied KEY_OPERATING_RATE to the tuned fps, so any profile below 30 (Good=20, Medium=15, Low=12, Minimal=8) pushed it under 30. Some hardware encoders, notably TV SoCs, then drop into a low-power mode that accepts configure/createInputSurface/start without error but never emits a single buffer. The controller receives BITMAPINFO and waits forever on the first decoded frame.

Confirmed on a Changhong Android TV: with operating rate 20 the log stopped right after SendBitmapInfo with no H.264 output at all; clamping to maxOf(fps, 30) produced a first IDR within the same second. KEY_OPERATING_RATE is a resource-planning hint, not a frame limiter - the actual rate is driven by KEY_FRAME_RATE and scene content.

Harden the capture lifecycle while here: fail loudly when createVirtualDisplay returns null instead of advertising a dead surface; downgrade the foreground type back to dataSync before stopping that projection, otherwise Android 14+ tears down a service still declaring mediaProjection and the controller loses the connection entirely; release the previous capture when MainActivity is reopened, including the projection-only state left behind when encoder creation throws before mediaCodec is assigned; ignore stale MediaProjection onStop callbacks that would otherwise tear down a fresh encoder; zero the native screen size on teardown; and make SendLoop's wait timeout so a silent zero-output encoder is reported instead of hanging.
2026-11-14 20:09:14 +01:00
29 changed files with 2406 additions and 113 deletions

No files matched your search

+27 -11
View File
@@ -4,17 +4,19 @@
// 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp):
// 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START]
// → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节 GSM 流](服务端 CAudio::PlayBuffer 固定按
// 1000 字节一块拷贝,包长必须正好 1000,且不能短——短了服务端会越界读)
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节]。前 975 字节是 15 个完整 GSM 块,
// 后 25 字节补零。
// waveOut 只转换整数个 65 字节块,末尾不足一块的字节既不转换也不保留,
// 所以 65 字节块绝不能跨包切开 —— 切开的半块会被直接丢掉,块边界一错位
// 整条流就是噪声。服务端 CAudio::PlayBuffer 按包截断到整块,那 25 个零
// 正好被丢掉。包长仍保持 1000:老版本服务端按 m_ulBufferLength 整块
// 拷贝,包长小于 1000 会越界读。
// 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块
//
// 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道,
// 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包
// (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。
// 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。
//
// 语音流是连续的:1000 不是 65 的整数倍,65 字节块会跨包切开,这是允许的——
// 服务端把每个 1000 字节缓冲按顺序写给 waveOut,编解码状态跨缓冲延续。
#include "common/commands.h"
#include "common/logger.h"
#include "client/IOCPClient.h"
@@ -30,6 +32,12 @@
#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__)
// 上行包: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" {
#include "gsm.h"
}
@@ -125,18 +133,26 @@ private:
gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节
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;
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);
m_pktFill += n;
off += n;
if (m_pktFill == 1000) {
m_client->Send2Server((char*)m_pkt, 1 + 1000);
if (m_pktFill == AUDIO_PKT_BLOCKS) {
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;
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;
uint8_t m_frameBuf[65];
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;
unsigned m_pktsSent;
+29 -2
View File
@@ -5,6 +5,7 @@
#include "common/logger.h"
#include "client/IOCPClient.h"
#include <atomic>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <queue>
@@ -113,7 +114,12 @@ public:
memcpy(&buf[off + 16], &ss, sizeof(ss));
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 才开始发帧。
// 服务端在 auth 通过瞬间发 COMMAND_NEXT,此时 setManagerCallBack 尚未注册,
@@ -267,11 +273,32 @@ private:
std::thread m_sendThread;
void SendLoop() {
// "一帧都没进来"是 Android 侧「请等待」最常见的成因:MediaProjection 被系统停掉、
// createVirtualDisplay 返回 null、硬件编码器不接受当前尺寸,都会让 MediaCodec
// 零输出。原先这里无限期阻塞在 wait 上,队列一直空就什么日志都不打,服务端只能
// 干等。改成带超时的等待,把「没有帧」和「帧被当 P 帧丢弃」区分开。
const auto startTick = std::chrono::steady_clock::now();
bool noFrameWarned = false;
while (m_running) {
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_queue.empty() || !m_started) {
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
if (!noFrameWarned && m_started && !m_firstSent &&
std::chrono::steady_clock::now() - startTick > std::chrono::seconds(5)) {
noFrameWarned = true;
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);
}
continue;
}
Frame f = std::move(m_queue.front());
m_queue.pop();
lk.unlock();
+335 -24
View File
@@ -11,6 +11,7 @@
#include <cstring>
#include <cinttypes>
#include <cstdio>
#include <ctime>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
@@ -28,6 +29,7 @@
#include "ChatHandler.h"
#include "AudioHandler.h"
#include "common/PTYHandler.h" // 远程终端(COMMAND_SHELL):与 Linux/macOS 共用 PTY 实现
#include "common/host_transfer.h" // 主机转移(COMMAND_ASSIGN_MASTER):与 Linux/macOS 共用解析与记录编解码
#define XXH_INLINE_ALL
#include "common/xxhash.h"
#include "common/logger.h"
@@ -689,10 +691,29 @@ static LinuxActivity::ProbeResult ProbeActivityFromJava()
return r;
}
// 服务器连接参数
// 服务器连接参数。平时只在 nativeInit 里写一次,但「转移主机」会在运行期改写它,
// 而抓屏/日志/交谈/音频/终端这些子连接线程都是在自己的循环里读它去建连——std::string
// 赋值会释放旧缓冲,别的线程正拿着 c_str() 就成了悬空读。所以读写统一走下面这对
// 函数(持锁拷贝一份再连),不要直接碰这两个全局量。
static std::mutex g_targetMu;
static std::string g_serverIp;
static int g_serverPort = 443;
// 取一份目标快照。子连接与主连接建连前都先拷一份,避免读到改写中的字符串。
static void GetServerTarget(std::string& ip, int& port)
{
std::lock_guard<std::mutex> lk(g_targetMu);
ip = g_serverIp;
port = g_serverPort;
}
static void SetServerTarget(const std::string& ip, int port)
{
std::lock_guard<std::mutex> lk(g_targetMu);
g_serverIp = ip;
g_serverPort = port;
}
// 设备信息(nativeInit 传入)
static std::string g_androidId;
static std::string g_deviceModel;
@@ -825,7 +846,9 @@ static void ScreenSpyThread()
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
return;
}
LOGI("ScreenSpyThread start → %s:%d size=%dx%d", g_serverIp.c_str(), g_serverPort, w, h);
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ScreenSpyThread start → %s:%d size=%dx%d", ip.c_str(), port, w, h);
// 服务端只发一次 COMMAND_SCREEN_SPY 就等子连接,子连接失败必须自己重试
for (int attempt = 1; attempt <= 20 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
@@ -840,8 +863,9 @@ static void ScreenSpyThread()
// 配成 WS/WSS 时连不上反代(主连接在 ConnectionThread 里已经这么做了)
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
LOGI("SST[%d]: connecting %s:%d", attempt, g_serverIp.c_str(), g_serverPort);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
GetServerTarget(ip, port); // 转移主机后目标会变,每轮重取
LOGI("SST[%d]: connecting %s:%d", attempt, ip.c_str(), port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGI("ScreenSpyThread: connect failed (attempt %d/20), retry 2s", attempt);
Sleep(2000);
continue;
@@ -898,7 +922,9 @@ static void ScreenSpyThread()
// 被关掉的就是主连接本身(客户端当场掉线)。
static void ClientLogThread()
{
LOGI("ClientLogThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ClientLogThread start → %s:%d", ip.c_str(), port);
for (int attempt = 1; attempt <= 3 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
std::unique_ptr<IOCPClient> client;
std::unique_ptr<ClientLogHandler> handler;
@@ -907,7 +933,8 @@ static void ClientLogThread()
client->EnableSubConnAuth(true, g_myClientID);
// 同上:子连接必须继承配置的传输方式,否则 WS/WSS 部署下 get_client_log 连不上
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("ClientLogThread: connect failed (attempt %d/3)", attempt);
Sleep(1000);
continue;
@@ -947,7 +974,9 @@ static void ChatThread()
~InFlightGuard() { g_chatInFlight.store(false); }
} guard;
LOGI("ChatThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ChatThread start → %s:%d", ip.c_str(), port);
for (int attempt = 1; attempt <= 3 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
std::unique_ptr<IOCPClient> client;
std::unique_ptr<AndroidChatHandler> handler;
@@ -956,7 +985,8 @@ static void ChatThread()
client->EnableSubConnAuth(true, g_myClientID);
// 与屏幕/日志子连接相同:必须继承配置的传输方式,否则 WS/WSS 部署下连不上反代
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("ChatThread: connect failed (attempt %d/3)", attempt);
Sleep(1000);
continue;
@@ -1015,7 +1045,9 @@ static void AudioThread()
~InFlightGuard() { g_audioInFlight.store(false); }
} guard;
LOGI("AudioThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("AudioThread start → %s:%d", ip.c_str(), port);
std::unique_ptr<IOCPClient> client;
std::unique_ptr<AndroidAudioHandler> handler;
bool started = false;
@@ -1024,7 +1056,8 @@ static void AudioThread()
client->EnableSubConnAuth(true, g_myClientID);
// 与屏幕/日志/交谈子连接一致:必须继承配置的传输方式(WS/WSS 部署)
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("AudioThread: connect failed");
return;
}
@@ -1083,13 +1116,16 @@ static void TerminalThread()
~InFlightGuard() { g_termInFlight.store(false); }
} guard;
LOGI("TerminalThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("TerminalThread start → %s:%d", ip.c_str(), port);
try {
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
client->EnableSubConnAuth(true, g_myClientID);
// 与屏幕/日志/交谈子连接一致:继承配置的传输方式,WS/WSS 部署下直连会连不上反代
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("TerminalThread: connect failed");
return;
}
@@ -1315,6 +1351,11 @@ static void ScreenPreviewThread(ScreenPreviewReq req)
// 所以统一截断后 memcpy。
static void sendClientMsg(const char* title, const char* text)
{
// title / text 必须是纯 ASCII。ClientMsg 的两个字段在服务端按 ANSI(GBK) 解释
// (2015RemoteDlg.cpp 的 `_L(msg->title)`),而本文件是 UTF-8 源码——直接传中文
// 字面量过去,主控的消息栏里就是「杞Щ涓绘満」这种乱码。要发中文得先转 GBK,
// 而 Android 的 iconv 只在 API 28+ 才有,minSdk 21 上不能依赖它。
//
// Java 安装线程也会走这里;连接检查与发送必须用同一份句柄,否则中间被收掉就崩
auto mc = GetMainClient();
if (!mc || !mc->IsConnected()) return;
@@ -1451,6 +1492,111 @@ static void RefreshLoginTls(LOGIN_INFOR& info)
}
#endif // YAMA_TLS_CHANNEL
// ============== 主机转移(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER)==============
// 服务端「转移主机」下发的载荷是 host:port:days:shine[:transport](见
// server/2015Remote/2015RemoteDlg.cpp assignFunction),解析与记录编解码在
// common/host_transfer.h,与 Linux/macOS 共用同一份代码。
//
// 与 Windows/Linux 的语义差别:那两个平台上主连接留在原主控不动、只在下次重连时
// 才过去,另起一个实例让新主控「立刻」看到这台主机。Android 的连接状态
// (ClientAuth 的校验态、心跳 ACK 看门狗、主连接句柄、g_bExit)全是进程级单例,
// 起第二条登录连接等于把这些全部参数化——这正是「分享主机」没做的原因。所以这里
// 用「立即切换」:改目标 → 断开 → 按新地址重连。新主控立刻看到主机,代价是原主控
// 立刻失去它;为防目标写错把主机彻底弄丢,持续一分钟连不上就退回原主控。
//
// 原主控是出包时烘焙的地址,只存在内存里(g_transferOrig),绝不写回记录——恢复时
// 读到的若还是转移目标,就成了原地打转(同 linux/main.cpp 的注释)。
static std::atomic<long long> g_transferValidTo{0}; // >0 = 处于转移状态(到期时刻)
static std::atomic<bool> g_transferPending{false}; // 接收线程已写下新目标,待主循环应用
static std::atomic<long long> g_transferAppliedAt{0}; // 切到转移目标的时刻,回退判据用
static std::atomic<bool> g_transferEndEarly{false};// true = 目标主控提前归还,不是到期
static std::mutex g_transferMu;
static HostTransfer::Target g_transferPendingTarget;
static HostTransfer::Endpoint g_transferOrig; // 烘焙的主控,到期/失败时恢复用
static std::once_flag g_transferOrigOnce;
static int g_transferFailStreak = 0; // 仅连接线程访问,无需原子
// 回退判据:连续失败次数 + 已尝试时长**同时**满足才退回原主控。只看次数会被网络
// 抖动误伤——Wi-Fi 卡一下就是连续几次失败,一次正常的转移会被无声撤销。加上 60 秒
// 下限后,只有「持续一分钟都连不上」才认定目标不可用。
static const int kTransferRevertAttempts = 3;
static const long long kTransferRevertGraceSec = 60;
static std::string TransferRecordPath()
{
return g_filesDir.empty() ? std::string() : g_filesDir + "/yama_transfer";
}
// 记录只有一行 ip:port:transport:headerEnc:valid_to(见 HostTransfer::EncodeRecord)。
// 用文件而不是 SharedPreferences:native 侧没有 JNI 上下文,分组名也是这么存的。
static void SaveTransferRecord(const HostTransfer::Target& t)
{
const std::string path = TransferRecordPath();
if (path.empty()) return;
FILE* f = fopen(path.c_str(), "w");
if (!f) { LOGI("TRANSFER: cannot write %s", path.c_str()); return; }
fputs(HostTransfer::EncodeRecord(t).c_str(), f);
fclose(f);
}
static void ClearTransferRecord()
{
const std::string path = TransferRecordPath();
if (!path.empty()) unlink(path.c_str());
}
// 把端点应用到连接参数:g_serverIp/Port 给建连用,g_SETTINGS.protoType 给子连接继承
// (子连接在各自线程里 SetDefaultProto(g_SETTINGS.protoType))。Android 没有 SHINE/HELL
// 头加密,headerEnc 段忽略。
static void ApplyEndpointToTarget(const HostTransfer::Endpoint& ep)
{
SetServerTarget(ep.ip, ep.port);
if (ep.transport >= 0)
g_SETTINGS.protoType = (char)ep.transport;
}
static void RestoreOrigTarget()
{
ApplyEndpointToTarget(g_transferOrig);
LOGI("TRANSFER: restored to %s:%d", 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;
}
// 启动时读记录:未过期就切到转移目标,过期/损坏就删掉。只在 nativeInit 调用。
static void LoadTransferRecord()
{
const std::string path = TransferRecordPath();
if (path.empty()) return;
FILE* f = fopen(path.c_str(), "r");
if (!f) return;
char buf[512] = {};
const size_t n = fread(buf, 1, sizeof(buf) - 1, f);
fclose(f);
HostTransfer::Target t;
if (n == 0 || !HostTransfer::DecodeRecord(std::string(buf, n), t)) {
LOGI("TRANSFER: bad record, ignored and removed");
ClearTransferRecord();
return;
}
const long long now = (long long)time(nullptr);
if (!t.Active(now)) {
LOGI("TRANSFER: record expired at %lld, removed", t.validTo);
ClearTransferRecord();
return;
}
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
g_transferAppliedAt.store(now, std::memory_order_relaxed);
ApplyEndpointToTarget(t.ep);
LOGI("TRANSFER: active, target %s:%d, %llds left", t.ep.ip.c_str(), t.ep.port, t.validTo - now);
}
// ------------------------------------------------------------------ DataProcess
int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
{
@@ -1693,6 +1839,90 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
}
#endif
case COMMAND_ASSIGN_MASTER: {
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
// 同一个命令字节也承载「分享主机」(buf[1] = SHARE_TYPE_YAMA,见下面单独的 case)。
if (ulLength < 3) {
LOGI("cmd: ASSIGN too short (%lu), ignored", (unsigned long)ulLength);
break;
}
if (szBuffer[1] != SHARE_TYPE_YAMA_FOREVER) {
LOGI("cmd: ASSIGN type=%d not supported on Android", (int)szBuffer[1]);
sendClientMsg("Share host", "Android client does not support sharing a host");
break;
}
HostTransfer::Target t;
const long long now = (long long)time(nullptr);
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的
// 主机就被改到一个不存在的地址上去了。
LOGI("cmd: ASSIGN malformed payload, ignored");
break;
}
// 有效期内拒绝再次转移,与 Windows KernelManager 的 now <= valid_to 判断一致。
// 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后,和它相连的只有 B,
// 于是 B 发来的转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的
// 那一台)还有机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控
// 复原,中间那一跳就成了谁也不认的孤儿。
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) {
// 唯一的例外:目标就是原主控。那是「提前归还」,不是再转一手——B 有权把
// 主机还给 A,否则一旦转错或临时用完,只能干等到期。
// 实现上不新增状态:把到期时刻设成「现在」,走心跳循环里那条已经验证过的
// 复原路径(清记录 → 换回原地址 → 重连)。代价是 A 不可达时主机会一直重试
// A,这与自然到期完全一致,没有引入新的失败形态。
//
// 注意这里**丢弃**了命令里的天数(t.validTo):有效期描述的是「多久之后回到
// 原主控」,已经回到原主控就没有倒计时可言了。服务端对话框强制天数 > 0,
// 所以操作员必然填了一个值,日志里把它记下来免得事后对不上。
if (toOriginal) {
LOGI("cmd: ASSIGN back to original master %s:%d, ending transfer early "
"(requested validity %llds ignored)",
t.ep.ip.c_str(), t.ep.port, t.validTo - now);
g_transferEndEarly.store(true, std::memory_order_relaxed);
g_transferValidTo.store(now, std::memory_order_relaxed);
sendClientMsg("Transfer host",
"Transfer ended early, returning to original master (validity ignored)");
break;
}
LOGI("cmd: ASSIGN ignored, already assigned until %lld", active);
char msg[128];
snprintf(msg, sizeof(msg),
"Host is already transferred until %lld, ignored", active);
sendClientMsg("Transfer host", msg);
break;
}
// 当前没在转移,而目标就是原主控自己:无事可做。放行只会白白断线重连一次,
// 还留下一条「到期复原到自己」的记录。
if (toOriginal) {
LOGI("cmd: ASSIGN target equals original master, ignored");
break;
}
{
std::lock_guard<std::mutex> lk(g_transferMu);
g_transferPendingTarget = t;
g_transferPending.store(true, std::memory_order_release);
}
// 先挡住后续重复下发,再落盘:落盘失败也不至于被第二条命令覆盖。
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
SaveTransferRecord(t);
LOGI("cmd: ASSIGN → %s:%d for %llds", t.ep.ip.c_str(), t.ep.port, t.validTo - now);
PostStatus("transfer: switching master");
break;
}
case COMMAND_SHARE:
case COMMAND_SHARE_CANCEL:
// 「分享主机」/「取消分享」:Android 尚未实现。分享要在不改主连接的前提下
// 再起一条**完整登录**的连接,而登录相关的状态(ClientAuth 校验态、心跳 ACK
// 看门狗、主连接句柄)都是进程级单例,第二条连接会把第一条的状态顶掉——
// 要做得先把它们整体参数化,属另一件事。这里明确回一条消息,别让主控那边
// 以为下发成功了(Windows 客户端在无权限时也是这么回的)。
LOGI("cmd: SHARE not supported on Android (%d)", (int)szBuffer[0]);
sendClientMsg("Share host", "Android client does not support sharing a host");
break;
default:
LOGI("cmd: unhandled cmd=%d len=%lu", (int)szBuffer[0], (unsigned long)ulLength);
break;
@@ -1712,7 +1942,11 @@ static std::atomic<uint64_t> g_connGeneration{0};
static void ConnectionThread(uint64_t gen)
{
LOGI("ConnectionThread → %s:%d", g_serverIp.c_str(), g_serverPort);
{
std::string ip0; int port0;
GetServerTarget(ip0, port0);
LOGI("ConnectionThread → %s:%d", ip0.c_str(), port0);
}
PostStatus("geo: fetching...");
std::string g_pubIp, g_location;
@@ -1767,11 +2001,6 @@ static void ConnectionThread(uint64_t gen)
std::shared_ptr<IOCPClient> client = std::make_shared<IOCPClient>(g_bExit, false);
client->setManagerCallBack(nullptr, DataProcess, nullptr);
SetMainClient(client); // 升级失败回报用;线程退出前撤回
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 现已有 TLS 通道(OpenSSL),WSS
// 在有信任锚时正常握手,无锚时按明文 WS 回退、待服务端下发后升级(见 IOCPClient)。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
int g_connAttempt = 0;
// 每次循环判断都带上代号:nativeStop 后 2 秒内进程被 nativeInit 重新拉起时,
// g_bExit/g_running 会被新一轮重置成「运行中」,旧线程醒来会再连一条主连接
@@ -1780,17 +2009,54 @@ static void ConnectionThread(uint64_t gen)
return gen == g_connGeneration.load(std::memory_order_acquire);
};
while (S_CLIENT_NORMAL == g_bExit && g_running.load() && currentGen()) {
// 转移主机:接收线程只写「待应用」,地址切换必须在本线程做——g_serverIp 是
// 建连用的全局量,只能在连接生命周期的持有线程改(同 linux/main.cpp)。
// 上一轮的连接已由心跳循环 Disconnect 掉,这里换地址再连。
if (g_transferPending.exchange(false, std::memory_order_acq_rel)) {
HostTransfer::Target t;
{
std::lock_guard<std::mutex> lk(g_transferMu);
t = g_transferPendingTarget;
}
ApplyEndpointToTarget(t.ep);
g_transferFailStreak = 0;
g_transferAppliedAt.store((long long)time(nullptr), std::memory_order_relaxed);
LOGI("TRANSFER: applying %s:%d", t.ep.ip.c_str(), t.ep.port);
}
std::string ip; int port;
GetServerTarget(ip, port);
char connMsg[64];
snprintf(connMsg, sizeof(connMsg), "connect #%d → %s:%d",
++g_connAttempt, g_serverIp.c_str(), g_serverPort);
snprintf(connMsg, sizeof(connMsg), "connect #%d → %s:%d", ++g_connAttempt, ip.c_str(), port);
PostStatus(connMsg);
clock_t c = clock();
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
// 传输方式每轮重喂。两个原因:一是不传 conn 的构造路径拿不到注入的
// CONNECT_ADDRESS,协议不显式喂进去就会静默按明文 TCP 直连;二是转移主机
// 可能把目标换成另一台主控,它的前端未必和原主控同构(本主控走反代的 WSS、
// 对方直连设备端口时就得是 TCP)。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(ip.c_str(), port)) {
snprintf(connMsg, sizeof(connMsg), "connect #%d failed errno=%d", g_connAttempt, errno);
PostStatus(connMsg);
// 转移目标连不上:连续失败且已持续一分钟,才退回原主控并清掉记录,否则一个
// 写错的地址会让这台主机彻底失联——原主控那边此时已经看不到它了。
if (g_transferValidTo.load(std::memory_order_relaxed) > 0) {
++g_transferFailStreak;
const long long tried = (long long)time(nullptr)
- g_transferAppliedAt.load(std::memory_order_relaxed);
if (g_transferFailStreak >= kTransferRevertAttempts && tried >= kTransferRevertGraceSec) {
LOGI("TRANSFER: unreachable for %llds (%d tries), reverting", tried, g_transferFailStreak);
g_transferValidTo.store(0, std::memory_order_relaxed);
g_transferFailStreak = 0;
ClearTransferRecord();
RestoreOrigTarget();
PostStatus("transfer: unreachable, reverted");
}
}
Sleep(5000);
continue;
}
g_transferFailStreak = 0;
PostStatus("connected! sending login...");
ClientAuth::OnNewConnection();
@@ -1833,6 +2099,12 @@ static void ConnectionThread(uint64_t gen)
PostStatus(dbg);
break;
}
// 转移主机与到期复原按 1 秒粒度判断。放在心跳周期(30 秒)之外是有原因的:
// 这两件事都是「到点就该动」的,等满一个周期会让 0.001 天(86 秒)这种短
// 转移晚二十多秒才生效、晚二十多秒才复原。这里只 break,真正的断开与恢复
// 由循环外的检查统一做(避免 Disconnect 被调两次)。
if (g_transferPending.load(std::memory_order_acquire) || TransferExpired())
break;
Sleep(1000);
}
#ifdef YAMA_TLS_CHANNEL
@@ -1845,6 +2117,31 @@ static void ConnectionThread(uint64_t gen)
break;
}
#endif
// 转移主机:接收线程已写好新目标,先断开当前(原主控)连接,再由外层循环
// 换地址重连。顺序不能反——地址必须在本线程、断开之后才改。
if (g_transferPending.load(std::memory_order_acquire)) {
PostStatus("transfer: leaving current master");
client->Disconnect();
break;
}
// 转移结束:恢复出包时烘焙的主控。Windows/Linux 由 StartClient 的 assigned
// 分支做同一件事;Android 没有重启入口,就地改回并重连。
// 两种情况都会走到这里:自然到期,以及目标主控「提前归还」(它把到期时刻设成
// 了当时,见 DataProcess 的 COMMAND_ASSIGN_MASTER 分支)。
{
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
if (TransferExpired()) {
const bool early = g_transferEndEarly.exchange(false, std::memory_order_relaxed);
LOGI("TRANSFER: %s at %lld, restoring original master",
early ? "ended early" : "expired", vt);
g_transferValidTo.store(0, std::memory_order_relaxed);
ClearTransferRecord();
RestoreOrigTarget();
PostStatus(early ? "transfer: returned by new master" : "transfer: expired, back to original");
client->Disconnect();
break;
}
}
if (!client->IsRunning() || !client->IsConnected()
|| g_bExit != S_CLIENT_NORMAL || !g_running.load() || !currentGen()) break;
@@ -1942,8 +2239,7 @@ Java_com_yama_client_YamaBridge_nativeInit(
return s;
};
g_serverIp = g_SETTINGS.ServerIP();
g_serverPort = g_SETTINGS.ServerPort();
SetServerTarget(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort());
g_androidId = toStr(androidId);
g_deviceModel = toStr(deviceModel);
g_androidVersion = toStr(androidVersion);
@@ -1956,6 +2252,17 @@ Java_com_yama_client_YamaBridge_nativeInit(
g_versionCode = (int)versionCode;
LoadGroupName(); // 若文件存在则覆盖 g_SETTINGS.szGroupName(优先级高于编译时 patch)
// 转移主机:先抓一次出包时烘焙的主控(只抓第一次——之后 g_SETTINGS.protoType 可能
// 已被转移改写,再抓就把转移目标当成原主控了),再按落盘记录切到转移目标。
// 顺序不能反:LoadTransferRecord 会改 g_SETTINGS.protoType。
std::call_once(g_transferOrigOnce, []() {
g_transferOrig.ip = g_SETTINGS.ServerIP();
g_transferOrig.port = g_SETTINGS.ServerPort();
g_transferOrig.transport = (int)(unsigned char)g_SETTINGS.protoType;
g_transferOrig.headerEnc = g_SETTINGS.iHeaderEnc;
});
LoadTransferRecord();
#ifdef YAMA_TLS_CHANNEL
// 信任锚目录注入 App 私有 filesDir,必须在连接线程首次 TlsEnabled() 之前。
if (!g_filesDir.empty()) TlsSetAnchorDir(g_filesDir);
@@ -2111,7 +2418,11 @@ Java_com_yama_client_YamaBridge_nativeInit(
// g_running 已在 CAS 中设为 true,不重复 store
const uint64_t gen = g_connGeneration.fetch_add(1, std::memory_order_acq_rel) + 1;
std::thread(ConnectionThread, gen).detach();
LOGI("nativeInit OK server=%s:%d", g_serverIp.c_str(), g_serverPort);
{
std::string ip0; int port0;
GetServerTarget(ip0, port0);
LOGI("nativeInit OK server=%s:%d", ip0.c_str(), port0);
}
return 0;
}
@@ -253,6 +253,22 @@ class CaptureService : Service() {
// Android 14+: upgrade foreground type to MEDIA_PROJECTION in the same
// start command that calls getMediaProjection(), as required by API 34+.
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) {
Log.i(TAG, "onStartCommand: releasing previous capture before restart")
stopCapture()
}
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val mp = pm.getMediaProjection(projResult, projData)
mediaProjection = mp
@@ -345,6 +361,14 @@ class CaptureService : Service() {
// Android 14+ requires callback registered before createVirtualDisplay()
mp.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
if (mediaProjection !== mp) {
Log.i(TAG, "stale MediaProjection onStop ignored")
return
}
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
stopCapture()
// Android 14+: system auto-kills a foreground service whose mediaProjection
@@ -353,12 +377,40 @@ class CaptureService : Service() {
}
}, null)
virtualDisplay = mp.createVirtualDisplay(
val vd = mp.createVirtualDisplay(
"YAMA",
encW, encH, dpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
surface, null, null
)
// 返回 null 不会抛异常。原实现直接往下走并调用 nativeSetScreenSize,于是
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
if (vd == null) {
Log.e(TAG, "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)
@@ -379,7 +431,13 @@ class CaptureService : Service() {
setInteger(MediaFormat.KEY_FRAME_RATE, fps)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
setInteger(MediaFormat.KEY_LATENCY, 0)
@@ -423,6 +481,13 @@ class CaptureService : Service() {
virtualDisplay = null
mediaCodec = null
mediaProjection = null
// 编码器已经没了,必须把 native 侧记录的尺寸一起清零。ScreenSpyThread 只靠
// g_screenWidth != 0 判断「投屏就绪」,不清零就会出现:MediaProjection 被系统
// 停掉(电视待机/切走/系统回收都会触发 onStop)后编码器已释放,但尺寸还是旧值,
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
YamaBridge.nativeSetScreenSize(0, 0)
}
// ---------------------------------------------------------------- 辅助函数
+34 -6
View File
@@ -1,17 +1,31 @@
@echo off
:: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
:: 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 publish Same, plus UPX --best compression
:: server-linux Cross-compile Go server for Linux -> Bin\server_linux_amd64
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe
:: server-linux Cross-compile Go server for Linux - Bin\server_linux_amd64
:: serverd Debug server only (x64) - Bin\Yama_x64d.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
:: 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 PLATFORM=x64
set EXTRA_ARGS=
set SERVER_NAME=
:parse_args
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
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"=="-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
shift
goto :parse_args
@@ -35,9 +59,13 @@ goto :parse_args
:run
echo.
echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM%
if not "%SERVER_NAME%"=="" echo Server name: %SERVER_NAME%
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 (
echo.
+44 -8
View File
@@ -1,5 +1,5 @@
# 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:
# - Visual Studio 2019 or 2022
@@ -19,7 +19,12 @@ param(
[switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[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"
@@ -28,6 +33,23 @@ $rootDir = $PSScriptRoot
$binDir = Join-Path $rootDir "Bin"
$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.
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
function Build-GoServer {
@@ -289,7 +311,9 @@ function Build-Project {
[string]$Project,
[string]$Configuration,
[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
@@ -307,6 +331,10 @@ function Build-Project {
"/v:minimal" # Minimal verbosity
)
if ($ExtraProps.Count -gt 0) {
$buildArgs += $ExtraProps
}
if ($Clean -or $ForceClean) {
# Use :Rebuild target for single 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 " VS: $vsYear" -ForegroundColor Cyan
Write-Host " Clean: $Clean" -ForegroundColor Cyan
if ($ServerName) {
Write-Host " Server: $serverTargetName" -ForegroundColor Cyan
}
if ($Publish) {
Write-Host " UPX: Yes" -ForegroundColor Cyan
}
@@ -426,10 +457,15 @@ if (-not $ServerOnly) {
}
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) {
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
@@ -438,7 +474,7 @@ if ($Publish) {
Write-Host ""
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)) {
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)
$suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" }
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" }
if ($Config -eq "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
$outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null }
+73 -11
View File
@@ -44,7 +44,9 @@ CAudio::CAudio()
m_InAudioData[i] = new BYTE[m_ulBufferLength];
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;
}
}
@@ -88,9 +90,12 @@ CAudio::~CAudio()
if (m_bIsWaveOutUsed) {
waveOutReset(m_hWaveOut);
// 这里原来 unprepare 的是 m_InAudioHeader —— 那是录音侧的头,而且上面
// 已经 delete 掉了(悬垂指针),unprepare 的对象完全错了。播放侧要收的是
// m_OutAudioHeader。
for (int i = 0; i < 2; ++i) {
if (m_InAudioHeader[i])
waveOutUnprepareHeader(m_hWaveOut, m_InAudioHeader[i], sizeof(WAVEHDR));
if (m_OutAudioHeader[i])
waveOutUnprepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
}
waveOutClose(m_hWaveOut);
}
@@ -150,6 +155,13 @@ LPBYTE CAudio::GetRecordBuffer(LPDWORD dwBufferSize)
SetEvent(m_hStartRecord);
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;
return m_InAudioData[m_nWaveInIndex]; //返出真正数据
}
@@ -196,14 +208,60 @@ DWORD WINAPI CAudio::waveInCallBack(LPVOID lParam)
BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize)
{
if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备
return NULL;
return FALSE;
if (!szBuffer || !dwBufferSize)
return FALSE;
for (int i = 0; i < dwBufferSize; i += m_ulBufferLength) {
memcpy(m_OutAudioData[m_nWaveOutIndex], szBuffer, m_ulBufferLength);
waveOutWrite(m_hWaveOut, m_OutAudioHeader[m_nWaveOutIndex], sizeof(WAVEHDR));
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
// 按包截断到整数个 65 字节块,余数直接丢弃 —— 不能攒到下一包。
//
// waveOut 只转换整块,末尾不足一块的字节既不转换也不保留。曾经的写法是把
// 余数攒起来跨包拼接(当成一条连续的流处理),在 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()
@@ -212,16 +270,20 @@ BOOL CAudio::InitializeWaveOut()
return FALSE;
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 = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL);
if (mmResult != MMSYSERR_NOERROR)
return false;
m_nWaveOutIndex = 0;
for (int i = 0; i < 2; ++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]->dwLoops = 0;
waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
+12
View File
@@ -11,6 +11,16 @@
#include <MMSYSTEM.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
{
@@ -40,6 +50,8 @@ public:
LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续
BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize);
BOOL InitializeWaveOut();
// 把整块数据交给 waveOut。两个缓冲轮转,还在队列里的不能复用
BOOL WriteAligned(LPBYTE p, DWORD len);
};
#endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_)
+135
View File
@@ -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。
+20
View File
@@ -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`)以支持远程 |
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
| `McpBuild` | `0` | 生成客户端工具 `build_client` 的独立开关(见 §25);另要求 `McpReadonly=0`,改动需重启生效 |
| `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」复选框设置,改动需重启生效 |
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
@@ -1352,3 +1353,22 @@ macOS 客户端此前有大量「实现了但服务端不认」的功能,断
- `remote_open` 仍拒绝 `MAC`(屏幕/注入链路的 macOS 实机验证还没做),本批不动。
- `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`)。
+230 -2
View File
@@ -18,7 +18,7 @@
],
"version": 2,
"protocolVersion": "2025-06-18",
"toolCount": 54,
"toolCount": 55,
"tools": [
{
"name": "list_hosts",
@@ -1207,7 +1207,7 @@
},
{
"name": "get_server_status",
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/文件写入/管理/主机管理/高风险操作/键盘记录/远程交谈/生成客户端)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
"gate": null,
"platforms": [
"win",
@@ -4995,6 +4995,234 @@
"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",
"description": "获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。仅在 McpMachine=0(主机管理工具关闭)时出现——那是本服务端唯一能列进程的路径;开启主机管理后改用 host_inspect 的 processes 项(字段更全、支持 arch 过滤)。",
+151 -13
View File
@@ -328,6 +328,18 @@ static BOOL IsAgentMode()
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 初始化
BOOL IsRunningAsAdmin()
@@ -373,6 +385,116 @@ BOOL LaunchAsAdmin(const char* szFilePath, const char* verb)
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()
{
// 检查是否已注册右键菜单
@@ -510,6 +632,35 @@ BOOL CMy2015RemoteApp::InitInstance()
// 代理模式由服务管理,不应再次请求管理员权限提升
// 否则会导致:1) 原进程正常退出(exitCode=0)不被视为崩溃 2) 被提升的进程脱离服务监控
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")) {
Mprintf("[InitInstance] 程序没有管理员权限,用户选择以管理员身份重新运行。\n");
return FALSE;
@@ -534,19 +685,6 @@ BOOL CMy2015RemoteApp::InitInstance()
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();
pSplash->Create(NULL);
+2
View File
@@ -2580,6 +2580,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
// 生成客户端(build_client):独立开关默认关;写客户端二进制,要求只读关。
McpServer().SetBuildEnabled(THIS_CFG.GetInt("settings", "McpBuild", 0) != 0);
// 平台门禁:默认开。调用前拦掉目标客户端根本没实现的工具(立刻 -32005),
// 否则会照常下发命令然后白等超时。关掉它只影响这道拦截,不改任何工具的执行路径。
McpServer().SetPlatformGuardEnabled(
@@ -330,6 +330,7 @@
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpTlsProxy.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpBuildClient.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
@@ -403,6 +404,7 @@
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpTlsProxy.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpBuildClient.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
@@ -92,6 +92,7 @@
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpBuildClient.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
@@ -210,6 +211,7 @@
<ClInclude Include="TriggerSettingsDlg.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpBuildClient.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
+94 -20
View File
@@ -47,6 +47,12 @@ enum Payload {
Payload_PDF,
};
// Linux / macOS / Android 是固定架构的预编译模板,没有 Windows 的安装/加壳/增肥语义。
static bool IsWindowsTarget(int index)
{
return !(index == IndexLinuxGhost || index == IndexMacGhost || index == IndexAndroidGhost);
}
// CBuildDlg 对话框
IMPLEMENT_DYNAMIC(CBuildDlg, CDialog)
@@ -223,9 +229,9 @@ CBuildDlg::CBuildDlg(CWnd* pParent)
, m_sInstallDir(_T(""))
, m_sInstallName(_T(""))
, m_sDownloadUrl(_T(""))
, m_nWindowsCompress(CLIENT_COMPRESS_SC_AES_OLD)
, m_nAnchorUserCheck(-1)
{
}
CBuildDlg::~CBuildDlg()
@@ -904,6 +910,7 @@ BOOL CBuildDlg::OnInitDialog()
m_ComboCompress.InsertStringL(CLIENT_SHELLCODE_BINARY, "ShellCode BIN");
m_ComboCompress.InsertStringL(CLIENT_COMP_SC_AES_OLD_UPX, "SC AES<Old> + UPX");
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_SC_AES_OLD);
m_nWindowsCompress = m_ComboCompress.GetCurSel(); // 与上面的默认值保持一致
m_ComboLocation.InsertStringL(0, "ProgramData");
m_ComboLocation.InsertStringL(1, "ProgramFiles - Admin");
@@ -995,10 +1002,12 @@ CString CBuildDlg::GetFilePath(CString type, CString filter, BOOL isOpen)
return "";
}
// 选 Linux / macOS 客户端时禁用对它们不适用的 Windows-only 选项:
// - 架构 (m_ComboBits):Linux/macOS binary 是固定架构的预编译资源
// 选 Linux / macOS / Android 客户端时禁用对它们不适用的 Windows-only 选项:
// - 架构 (m_ComboBits):这些 binary 是固定架构的预编译资源
// - 加壳 (m_ComboCompress):UPX / ShellCode AES 等都是 Windows PE 概念
// - 高级 group:安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,全是 Windows 安装/伪装相关
// - 运行模式 (m_ComboRunType):runningType 只有 Windows 客户端(ClientDll)消费
// - 高级 group:安装位置 / 安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,
// 全是 Windows 安装/伪装相关
void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
{
static const int ids[] = {
@@ -1006,8 +1015,11 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
IDC_COMBO_BITS, IDC_STATIC_BUILD_ARCH,
// 加壳
IDC_COMBO_COMPRESS, IDC_STATIC_BUILD_PACK,
// 高级 group + 内部所有控件
// 运行模式
IDC_COMBO_RUNTYPE, IDC_STATIC_BUILD_MODE,
// 高级 group + 内部所有控件(含「安装目录」下拉框与它的标签)
IDC_STATIC_BUILD_ADVANCED,
IDC_STATIC_LOCATION, IDC_COMBO_INSTALL_LOC,
IDC_STATIC_PAYLOAD, IDC_STATIC_PAYLOAD2, IDC_STATIC_PAYLOAD3,
IDC_STATIC_BUILD_PADDING, IDC_STATIC_DOWNLOAD,
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):
// 1. 生成目标里真的有客户端代码(ghost.exe / ServerDll.dll);
// 2. 协议会用到这份锚(TCP / HTTP;WS 走明文,WSS 的锚是反代那张证书);
@@ -1036,13 +1083,22 @@ void CBuildDlg::UpdateTlsAnchorState()
const bool testRun = (index == IndexTestRun_DLL || index == IndexTestRun_MemDLL ||
index == IndexTestRun_InjSC || index == IndexTestRunMsc ||
index == IndexTestRunSystem);
// Linux/macOS/Android 模板里没有锚块(只有 Windows 的 client/ 侧编译了
// common/tls_anchor.h),它们的信任锚由主控在线下发;文案要说清这一点,
// 不能笼统写成「不含客户端」。
const bool posixTarget = (index == IndexLinuxGhost || index == IndexMacGhost ||
index == IndexAndroidGhost);
CString label;
bool usable = false;
if (!embeddable) {
// TestRun 只是加载器,锚要生成进 ServerDll.dll —— 这条提示比「不含客户端」有用。
label = testRun ? _TR("内嵌TLS信任锚(锚在ServerDll.dll里)")
: _TR("内嵌TLS信任锚(该目标不含客户端)");
if (testRun)
label = _TR("内嵌TLS信任锚(锚在ServerDll.dll里)");
else if (posixTarget)
label = _TR("内嵌TLS信任锚(仅Windows客户端模板支持)");
else
label = _TR("内嵌TLS信任锚(该目标不含客户端)");
} else if (proto != PROTO_TCP && proto != PROTO_HTTP) {
label = _TR("内嵌TLS信任锚(该协议不走TLS)");
} else if (!ServerTlsIdentity::IsReady()) {
@@ -1078,9 +1134,31 @@ void CBuildDlg::OnCbnSelchangeComboProto()
void CBuildDlg::OnCbnSelchangeComboExe()
{
auto n = m_ComboExe.GetCurSel();
EnableWindowsOnlyControls(!(n == IndexLinuxGhost || n == IndexMacGhost || n == IndexAndroidGhost));
const int n = m_ComboExe.GetCurSel();
const BOOL windowsTarget = IsWindowsTarget(n);
EnableWindowsOnlyControls(windowsTarget);
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) {
CString name = GetFilePath(_T("dll"), _T("All Files (*.*)|*.*|DLL Files (*.dll)|*.dll|EXE Files (*.exe)|*.exe|"));
if (!name.IsEmpty()) {
@@ -1150,14 +1228,13 @@ void CBuildDlg::OnClientRunasAdmin()
void CBuildDlg::OnCbnSelchangeComboCompress()
{
m_ComboPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
m_StaticPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
m_ComboPayload.SetFocus();
m_BtnFileServer.ShowWindow(
m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && m_ComboPayload.GetCurSel() ? SW_SHOW : SW_HIDE);
// 记下用户在当前 Windows 目标下的加壳选择;切到 Linux/macOS/Android 时控件会置灰、
// 显示值切到「无」,切回来时恢复这个值。
if (IsWindowsTarget(m_ComboExe.GetCurSel()))
m_nWindowsCompress = m_ComboCompress.GetCurSel();
m_BtnFileServer.SetCheck(BST_UNCHECKED);
m_StaticDownload.ShowWindow(SW_HIDE);
m_EditDownloadUrl.ShowWindow(SW_HIDE);
UpdatePayloadControls();
m_ComboPayload.SetFocus();
static bool warned = false;
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && !warned) {
warned = true;
@@ -1313,9 +1390,6 @@ void CBuildDlg::OnBnClickedCheckFileserver()
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_StaticDownload.ShowWindow(SW_HIDE);
m_EditDownloadUrl.ShowWindow(SW_HIDE);
UpdatePayloadControls();
}
+10 -1
View File
@@ -17,7 +17,8 @@ namespace ResFileName {
extern const char* GHOST_X86;
extern const char* GHOST_X64;
extern const char* GHOST_LINUX;
extern const char* GHOST_MACOS; // 预留
extern const char* GHOST_MACOS;
extern const char* GHOST_ANDROID;
// TestRun 加载器
extern const char* TESTRUN_X86;
extern const char* TESTRUN_X64;
@@ -109,6 +110,14 @@ public:
void EnableWindowsOnlyControls(BOOL enable);
CComboBox m_ComboLocation;
// 载荷/下载服务几行的可见性(由「目标是否 Windows」+「加壳方式」+「载荷类型」共同决定)
void UpdatePayloadControls();
// 菜单项联动:随机名称 / 以管理员权限运行只对 Windows 目标有意义
void UpdateTargetMenuState(BOOL windowsTarget);
// 非 Windows 目标期间暂存的加壳选择:控件置灰后仍显示旧值会让人误以为会按它生成,
// 所以切到 Linux/macOS/Android 时先切到「无」,切回 Windows 时恢复。
int m_nWindowsCompress;
// 内嵌服务端 TLS 信任锚(动态创建:不改 .rc,避免 GBK 资源文件的字节级编辑)。
// 可用性三条件见 UpdateTlsAnchorState;生成时由 OnBnClickedOk 调用 EmbedTlsAnchorInto。
CButton m_ChkTlsAnchor;
File diff suppressed because it is too large. Load diff
+34
View File
@@ -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
+3
View File
@@ -599,6 +599,9 @@ const ToolHints kToolHints[] = {
{ "chat_send", false, false, false, true },
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
{ "chat_close", false, false, true, true },
// --- 生成客户端(McpBuild)---
// 写服务端本机文件(可覆盖),会留下可分发的客户端二进制;不触达任何外部主机。
{ "build_client", false, true, false, false },
};
} // namespace
+19 -3
View File
@@ -11,6 +11,7 @@
#include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用)
#include "McpMachine.h" // 主机管理 / 连接管理工具族
#include "McpChat.h" // 远程交谈工具族
#include "McpBuildClient.h" // 生成客户端工具族(build_client)
#include <sstream>
#include <fstream>
@@ -283,12 +284,12 @@ const char* kServerInstructions =
u8"2) 工具的可见性与开关\n"
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
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"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——"
u8"它们不在列表里但仍可调用。"
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"只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / "
@@ -350,6 +351,10 @@ const char* kServerInstructions =
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
u8"不跟随重定向,响应体上限 64KB),不要为此自己写 Invoke-WebRequest / curl;Windows 与 Linux 可用,"
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"5) 客户端平台差异\n"
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
@@ -2410,7 +2415,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
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);
inputSchema["type"] = "object";
@@ -2812,6 +2817,10 @@ std::string BuildToolsListResult(const Json::Value& id) {
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
McpChat::AppendTools(tools);
// 20b) 生成客户端(build_client):服务端本地工具,独立开关 McpBuild(默认关),
// 另要求 McpReadonly=0;关闭时不追加任何工具。
McpBuildClient::AppendTools(tools);
// 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。
// 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁,
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
@@ -4580,6 +4589,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
switches["keylog"] = srv.IsKeylogEnabled();
switches["chat"] = srv.IsChatEnabled();
switches["build"] = srv.IsBuildEnabled();
status["switches"] = switches;
int onlineCount = 0, offlineCount = 0;
@@ -11991,6 +12001,9 @@ const ToolPlatform kToolPlatforms[] = {
{ "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "host_set_remark", 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 文件传输
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac },
{ "list_files", kPlatWin|kPlatLnx|kPlatMac },
@@ -12397,6 +12410,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
// P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。
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 默认为「在线 + 离线」。
if (toolName == "list_hosts") return BuildListHosts(id, args, parent, false);
if (toolName == "list_online_hosts") return BuildListHosts(id, args, parent, false);
+8
View File
@@ -566,6 +566,13 @@ public:
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
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 键)=====
// 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 600000]。
// 改动需重启服务端生效(与其它 Mcp* 开关一致)。
@@ -999,6 +1006,7 @@ private:
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
bool m_buildEnabled = false; // 生成客户端开关(默认关;build_client)
// 平台门禁(默认开):调用前拦掉「该客户端根本没实现」的工具,立刻返回 -32005。
// 关闭后这类调用会照常下发命令,通常表现为白等超时。判据表见 McpServer.cpp 的
// kToolPlatforms,与 mcp/tools.json 的 platforms 字段对应。
+12
View File
@@ -181,6 +181,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
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_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
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_btnChat.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_editWhitelist.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 chat = THIS_CFG.GetInt("settings", "McpChat", 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", "");
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
@@ -265,6 +270,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
m_btnChat.SetCheck(chat ? 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()));
@@ -339,6 +345,7 @@ void CMcpSettingsDlg::OnOK()
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
bool build = (m_btnBuild.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", "McpChat", chat ? 1 : 0);
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
THIS_CFG.SetInt("settings", "McpBuild", build ? 1 : 0);
std::string whitelist = CT2A(sWhitelist);
whitelist = NormalizeWhitelist(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("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
_TR("提示"), MB_ICONINFORMATION);
@@ -494,6 +503,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnBuild.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
const int whitelistH = 90;
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
+2
View File
@@ -46,6 +46,7 @@ private:
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
IDC_MCP_BUILD = 1021, // 「启用客户端生成」复选框(build_client,要求只读关)
};
CButton m_btnEnable;
@@ -61,6 +62,7 @@ private:
CButton m_btnMachineDangerous;
CButton m_btnChat;
CButton m_btnKeylog;
CButton m_btnBuild;
CStatic m_lblWhitelist;
CEdit m_editWhitelist;
CButton m_btnHttps;
+8
View File
@@ -2058,6 +2058,8 @@ MCPԶ
远程交谈开关的改动需重启程序生效。=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam.
启用键盘记录(AI 采集击键)=Keylogger aktivieren (KI-Tastenaufzeichnung)
键盘记录开关的改动需重启程序生效。=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.
第 %d 个钱包地址不合法!=Wallet-Adresse #%d ist ungueltig!
%d 新连接\r\n=%d Neue Verbindung\r\n
@@ -2225,6 +2227,7 @@ HTTPS
内嵌TLS信任锚(首连即加密)=TLS-Vertrauensanker einbetten (TLS von Anfang an)
内嵌TLS信任锚(锚在ServerDll.dll里)=TLS-Vertrauensanker einbetten (in ServerDll.dll)
内嵌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 (Server-TLS aus)
内嵌 TLS 信任锚失败,已取消生成:=TLS-Vertrauensanker konnte nicht eingebettet werden, Generierung abgebrochen:
@@ -2252,3 +2255,8 @@ 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接下来的操作需要在设备上完成:\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
; === 完整性级别自检(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
+8
View File
@@ -2059,6 +2059,8 @@ MCPԶ
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
键盘记录开关的改动需重启程序生效。=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 开关与证书路径的改动需重启程序生效。=Changes to the HTTPS switch and certificate paths take effect after restart.
证书或私钥文件不存在,请检查路径。=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信任锚(锚在ServerDll.dll里)=Embed TLS trust anchor (use ServerDll.dll)
内嵌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 (server TLS is off)
内嵌 TLS 信任锚失败,已取消生成:=Failed to embed the TLS trust anchor, generation cancelled:
@@ -2264,3 +2267,8 @@ 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接下来的操作需要在设备上完成:\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
; === 完整性级别自检(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
+8
View File
@@ -2052,6 +2052,8 @@ MCPԶ
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
启用客户端生成(AI 生成客户端文件,要求只读关)=啟用客戶端生成(AI 生成客戶端檔案,要求唯讀關閉)
客户端生成开关的改动需重启程序生效;它还会写出带主控凭据的客户端文件,请谨慎开启。=客戶端生成開關的變更需重新啟動程式生效;它還會寫出帶主控憑證的客戶端檔案,請謹慎開啟。
启用 HTTPS(本端口同时接受 TLS 连接)=啟用 HTTPS(本連接埠同時接受 TLS 連線)
HTTPS 开关与证书路径的改动需重启程序生效。=HTTPS 開關與憑證路徑的改動需重啟程式生效。
证书或私钥文件不存在,请检查路径。=憑證或私鑰檔案不存在,請檢查路徑。
@@ -2230,6 +2232,7 @@ MCP:
内嵌TLS信任锚(首连即加密)=內嵌TLS信任錨(首連即加密)
内嵌TLS信任锚(锚在ServerDll.dll里)=內嵌TLS信任錨(錨在ServerDll.dll裡)
内嵌TLS信任锚(该目标不含客户端)=內嵌TLS信任錨(該目標不含客戶端)
内嵌TLS信任锚(仅Windows客户端模板支持)=內嵌TLS信任錨(僅Windows客戶端模板支援)
内嵌TLS信任锚(该协议不走TLS)=內嵌TLS信任錨(該協議不走TLS)
内嵌TLS信任锚(服务端未启用TLS)=內嵌TLS信任錨(服務端未啟用TLS)
内嵌 TLS 信任锚失败,已取消生成:=內嵌 TLS 信任錨失敗,已取消生成:
@@ -2257,3 +2260,8 @@ 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接下来的操作需要在设备上完成:\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 開啟「終端機(系統管理員)」,貼上執行後再重新啟動本程式。
已复制=已複製
+16 -10
View File
@@ -1,6 +1,6 @@
# MCP 工具清单维护
`mcp/tools.json` 是 MCP 全部 61 个工具的**单一来源候选**:工具名、描述、
`mcp/tools.json` 是 MCP 全部 55 个工具的**单一来源候选**:工具名、描述、
inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate` / `write` / `manage`)。
它的用途不限于给 Go 服务端复用。当前 26KB 的工具描述埋在 11k 行 C++ 里,
@@ -20,23 +20,28 @@ inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate`
## 更新流程
改动 C++ 里的工具定义(`McpServer.cpp` / `McpMachine.cpp` / `McpChat.cpp`)之后:
改动 C++ 里的工具定义(`McpServer.cpp` / `McpMachine.cpp` / `McpChat.cpp` /
`McpBuildClient.cpp`)之后:
```bash
# 0. 先重编并启动主控端,确保服务端跑的是新代码
cd C:/github/YAMA
# 1. 抓取(token 自动从注册表读;端口自动探测 6545/6544)
python tools/mcp_tools/dump_tools.py "" /tmp/tools_raw.json
# 清单是「McpMachine=1」与「McpMachine=0」两份抓取的并集,需在两次抓取之间
# 改配置并重启服务端(关闭态那份包含 5 个降级工具)。
python tools/mcp_tools/dump_tools.py "" /tmp/tools_raw_on.json
# ...把 McpMachine 改成 0、重启服务端...
python tools/mcp_tools/dump_tools.py "" /tmp/tools_raw_off.json
# 2. 生成
python tools/mcp_tools/make_tools_json.py /tmp/tools_raw.json mcp/tools.json
# 2. 生成(第三参数是关闭主机管理时的抓取)
python tools/mcp_tools/make_tools_json.py /tmp/tools_raw_on.json mcp/tools.json /tmp/tools_raw_off.json
# 3. 校验
python tools/mcp_tools/verify_tools.py --live mcp/tools.json
```
第 3 步输出 `PASS: 61 个工具完全一致` 才算成功。
第 3 步输出 `PASS: 55 个工具完全一致` 才算成功。
### 如果工具数量变了
@@ -53,6 +58,7 @@ python tools/mcp_tools/verify_tools.py --live mcp/tools.json
- `McpServer.cpp:BuildToolsListResult` —— 内联的 41 个
- `McpMachine.cpp:AppendTools` —— 16 个(总开关 `IsMachineEnabled` 用 early return)
- `McpChat.cpp:AppendTools` —— 4 个(总开关 `IsChatEnabled` 用 early return)
- `McpBuildClient.cpp:AppendTools` —— 1 个(开关 `McpBuild` 用 early return)
`PLATFORMS` 还要额外核对各平台客户端有没有实现对应命令,见下节。
@@ -60,8 +66,8 @@ python tools/mcp_tools/verify_tools.py --live mcp/tools.json
| 字段 | 含义 |
|---|---|
| `gate` | 该工具出现所需的开关(`null` = 无条件)。取值:`machine` / `chat` / `terminal` / `remote_control` / `file_transfer` / `file_write` / `keylog` / `manage` |
| `write` | 需要 `!McpReadonly` |
| `gate` | 该工具出现所需的开关(`null` = 无条件)。取值:`machine` / `chat` / `terminal` / `remote_control` / `file_transfer` / `file_write` / `keylog` / `manage` / `build` |
| `write` | 执行需要 `!McpReadonly`(只影响调用,不影响可见性;只改服务端本地数据的工具在只读下仍会列出) |
| `manage` | 额外需要 `McpManage`(仅 `kill_network_connection` 用到) |
| `platforms` | 该工具涉及的**任一主机**都必须落在此集合内:`win` / `lnx` / `mac` / `apk` |
| `roles` | 仅多主机工具才有。按参数名细分平台,表达 `platforms` 说不清的方向性能力 |
@@ -88,7 +94,7 @@ python tools/mcp_tools/verify_tools.py --live mcp/tools.json
| 命令分支 | `client/`、`linux/main.cpp`、`macos/main.mm`、`android/app/src/main/cpp/main.cpp` |
| 能力位 | `common/commands.h` 的 `LOGIN_INFOR::DefaultCaps()`;Linux 另在 `linux/main.cpp:RefreshLoginCaps` 追加 `SCREEN_PREVIEW` |
当前分布(54 个工具):
当前分布(55 个工具):
| platforms | 数量 | 典型工具 |
|---|---|---|
@@ -191,7 +197,7 @@ macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThre
```bash
python tools/mcp_tools/check_platform_table.py
# PASS: 61 个工具的 platforms 两边完全一致,且门禁都能拿到主机 id
# PASS: 55 个工具的 platforms 两边完全一致,且门禁都能拿到主机 id
```
## 与 Go 服务端的关系
+5
View File
@@ -114,6 +114,9 @@ GATE = {
"chat_send": ("chat", False, False),
"chat_wait": ("chat", False, False),
"chat_close": ("chat", False, False),
# ---- 生成客户端(McpBuild,写服务端本机文件;另需 readonly 关)----
"build_client": ("build", True, False),
}
# platforms: 该工具涉及的任一主机都必须落在此集合内。
@@ -160,6 +163,8 @@ PLATFORMS = {
"mcp_cancel_session": _APK,
"host_set_remark": _APK,
"host_set_watch_level": _APK,
# 生成客户端只写服务端本机文件,不触达任何主机;与客户端平台无关。
"build_client": _APK,
# SYSTEM / LIST_DRIVE / QUERY_LOG:三个桌面平台都实现了;APK 也实现了 QUERY_LOG
# (android/.../main.cpp ClientLogThread → TOKEN_REPORT_LOG)