Fix(client): rotate HELL header encoding across reconnects

A Release client drew one of the twelve HELL header encodings in the
constructor and kept it for life. The Go fallback server latches a type
from the first packet and only decodes None..V6, so every client that
drew V7..V10 could never log in to it — a third of them, at random, for
good.

The main connection now advances to the next type when it reconnects
after a connection that was never login-acked (CMD_MASTERSETTING), and
republishes the accepted type into CONNECT_ADDRESS::szFuture. A type that
did log in is kept, so a healthy client no longer churns through values
the fallback would reject. Sub-connections, including one-shot ones
(file/process/screen), inherit the published value at construction and
on every reconnect instead of rolling their own dice. Debug keeps its
None..V6-only range; the initial Release type now comes from
random_device rather than time() % N, which handed a whole batch started
in the same second the same value.

The slot sits at szFuture+16, after LOCAL_TEST_CLIENT_MAGIC, guarded by
static_asserts; it is memory-only and never persisted or sent. Swapping
the encoder is a single atomic function-pointer store, so the send and
receive threads see either the old or the new encoder and never a
dropped object.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-13 16:47:53 +01:00
1 parent a818ace83c
commit 9fadb58c76
5 files changed
+178 -10

No files matched your search

+101 -6
View File
@@ -27,6 +27,7 @@ inline int WSAGetLastError()
#include "IOCPClient.h"
#include <assert.h>
#include <string>
#include <random>
#if USING_ZLIB
#include "zlib/zlib.h"
#define Z_FAILED(p) (Z_OK != (p))
@@ -197,6 +198,35 @@ bool IOCPClient::TryHandleAuthResponse(PBYTE buf, ULONG len)
}
// HELL 头加密可选类型数:Debug 版与服务端(含 Go fallback)对齐,只到 HeaderEncV6;
// Release 版保留全部类型,靠主连接重连轮转去命中后端支持的那几种。
static int HeaderEncCount()
{
#ifdef _DEBUG
return HeaderEncV6 + 1;
#else
return HeaderEncNum;
#endif
}
// 构造时的初始类型。原来直接 time(nullptr) % N:同一秒内启动的一批客户端会拿到
// 同一个类型,快速重连也反复取到同一个值。
// 不持有静态发生器:本函数会被多个并存实例(并发上线/分享)的构造线程调用,无共享
// 状态就无需加锁;random_device 个别平台在 /dev/urandom 不可用时会抛异常,退回时钟。
static int RandomHeaderEncIndex(int count)
{
unsigned v = 0;
try {
std::random_device rd;
v = rd();
} catch (...) {
// 极少数平台取不到 /dev/urandom 会抛异常:退回时钟(纳秒级,够打散同秒启动)。
v = (unsigned)std::chrono::steady_clock::now().time_since_epoch().count()
^ (unsigned)time(nullptr);
}
return (int)(v % (unsigned)count);
}
IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, CONNECT_ADDRESS* conn,
const std::string& pubIP, void* main) : g_bExit(bExit)
{
@@ -230,13 +260,24 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_DataProcess = NULL;
m_ReconnectFunc = NULL;
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
#ifdef _DEBUG
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
#else
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
#endif
m_EncoderType = encoder;
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
if (encoder) {
const int count = HeaderEncCount();
int idx = -1;
if (conn) {
// 子连接优先继承主连接「已被当前后端接受」的类型(PublishHeaderEncoder)。
// 0 表示尚未发布,回退随机,保持原有的打散效果。
int published = GetHeaderEncSelect(conn);
if (published >= 1 && published <= count)
idx = published - 1;
}
if (idx < 0)
idx = RandomHeaderEncIndex(count);
m_headerEncIdx.store(idx);
m_Encoder = new HellEncoder(GetHeaderEncoder((HeaderEncType)idx), new XOREncoder16());
} else {
m_Encoder = new ProtocolEncoder();
}
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
@@ -266,6 +307,52 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
#endif
}
void IOCPClient::PrepareHeaderEncoderForConnect()
{
if (!m_EncoderType) {
return; // Shine:没有头加密函数可换
}
const int count = HeaderEncCount();
if (!m_bMainLink) {
// 子连接:跟随主连接最新发布的、已被当前后端接受的类型。一次性子连接(文件/
// 进程等只连一次)因此不会自己掷骰子撞上 Go fallback 不认识的 V7~V10。
// 取舍:后端切换(C++ 主控挂掉、Go fallback 接管)到主连接重连并重发布之间的
// 窗口里,子连接会拿旧值反复碰壁;主连接一发布新值就自愈。这里不自己轮转,是为
// 了让「一次性子连接只连一次」这种最常见的情形始终用主连接验证过的值。
int published = m_conn ? GetHeaderEncSelect(m_conn) : 0;
if (published >= 1 && published <= count) {
int idx = published - 1;
if (idx != m_headerEncIdx.load(std::memory_order_relaxed)) {
m_headerEncIdx.store(idx, std::memory_order_relaxed);
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
}
return;
}
// 主连接尚未发布(例如键盘子连接在主连接登录前就建好了):退化为轮转,见下。
}
// 第一次建连沿用构造时确定的类型(继承值或随机初值)。之后只在「上一条连接没有
// 被登录接受」时才换下一种:已被接受说明当前后端解析得了这个类型,重连沿用即可;
// 无故轮转只会在 Go fallback 上白丢几轮(V7~V10 会被它拒掉)。
// m_loginAcked 由 ConnectServer 在本函数**之后**才清零,所以这里读到的是上一条连接
// 的结论(见调用处注释)。
if (m_headerEncAttempts.fetch_add(1, std::memory_order_relaxed) > 0
&& !m_loginAcked.load(std::memory_order_acquire)) {
int idx = (m_headerEncIdx.load(std::memory_order_relaxed) + 1) % count;
m_headerEncIdx.store(idx, std::memory_order_relaxed);
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
}
}
void IOCPClient::PublishHeaderEncoder()
{
// 只有主连接、且确实在用 HELL 头加密时才有意义。
if (m_bMainLink && m_EncoderType && m_conn) {
SetHeaderEncSelect(m_conn, m_headerEncIdx.load(std::memory_order_relaxed));
}
}
void IOCPClient::SetMultiThreadCompress(int threadNum)
{
#if USING_CTX
@@ -443,6 +530,14 @@ BOOL ConnectWithTimeout(SOCKET sock, const struct sockaddr* addr, int timeout_se
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
{
// 每次建连(含重连)先定下这次要用的 HELL 头加密函数。必须在建 socket / 启动收发
// 线程之前完成:后端只在每条连接的**第一个**包上识别并锁定头加密方式(Go 的
// parser.go 首包锁存,认不出就 ErrUnsupported 直接断开),换类型只对「下一条连接的
// 首包」有意义;此刻旧连接已断开,也就避开了与收发线程争用编码器对象。
// 注意顺序:PrepareHeaderEncoderForConnect 要读上一条连接的 m_loginAcked,故它必须是
// 本条连接清零登录标志**之前**的第一条语句。
PrepareHeaderEncoderForConnect();
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
m_loginAcked.store(false, std::memory_order_release);