Files
SimpleRemoter/client/IOCPClient.h
T
yuanyuanxianganddeepseek-flash 46f4bf2dfb Fix: Make the WebSocket transport reachable and bounded on every platform
The POSIX clients were built without a connection config - Linux, macOS and
Android all construct IOCPClient without the injected CONNECT_ADDRESS - so
ConnectServer saw protoType -1 and quietly dialled the master port in plain
TCP. Setting protoType to WS in their settings did nothing and logged nothing,
and since CLIENT_CAP_PROTO_SWITCH is Windows-only the server could not move
them either. Give the client a SetDefaultProto() for that construction path
and call it from all three mains before the reconnect loop, with a one-shot
log when neither a conn nor a default protocol is available so the silent
fallback becomes visible next time.

Bound what a peer can make the client read. ReadHeader accepted the 8-byte
extended length and rejected only the sign bit, so a frame length of nearly
2^63 kept the connection streaming into a frame that would never end - alive
but never delivering another packet. Cap single frames at 256 MB, the same
value ServerWsSession already applies to client frames, and drop the
connection past it; real traffic is far below that.

Stop Reset() from writing the receive thread's frame state. Disconnect() can
run from the heartbeat or command thread, not just the receive thread, so
Reset() now only flips the atomic ready flag and a new ResetFrames() clears
m_remaining, m_masked and m_maskPos from Handshake() alone, before the
receive thread starts reading the socket. Those fields keep a single owner
without adding a lock to the receive hot path.

Finish a dead WS session instead of leaving it to the keepalive timer. When
the session had closed but wsState was still WS_Ready, sends were dropped and
nothing woke the pending recv, so a peer that closed and then went quiet held
the context for the 3-minute keepalive. shutdown() the socket there so the
recv returns zero bytes and the normal -2 teardown runs; RemoveStaleContext
would deadlock against the caller's own IoRefCount and can hand back a reused
context.

That shutdown only finishes the connection if a zero-byte read still tears it
down, and on the plain path it no longer did. DispatchPlain answers an empty
buffer with "handled", so a peer's FIN left the connection in CLOSE_WAIT
until keepalive - holding an IOCP context, a pending WSARecv and a rate-limit
slot - where the pre-WS code called ParseReceivedData and tore down at once.
Restore that teardown on the TLS_Plain branch, matching the other two. Checked
against a Debug server: a plain socket that half-closes used to sit in
CLOSE_WAIT with the peer's recv timing out, and now disappears immediately
with recv returning zero.

Two smaller cleanups from the same review. Give the WS upgrade its own prefix
buffer (wsPreClassify) instead of borrowing the TLS sniffer's, which was
serially reused for two state machines and read as if it were one. And stop
deriving the build dialog's protoType from the combo box index: items now
carry the protocol value as item data, keyed off the index AddString returns,
so inserting an option in the middle can no longer write the wrong number into
the generated client without any error. ApplyProtoSwitch loses its bool
return, which contradicted its own side effects and was ignored by every
caller.

Co-Authored-By: deepseek-flash
2026-10-30 19:15:14 +01:00

415 lines
14 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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); }
// 主动断开当前连接,关闭 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; // 登录消息签名
};