Fix: Close the gaps the WebSocket transport review found
Three of the findings only bite in deployment. First, the client's TLS and WebSocket handshakes run synchronously on the reconnect thread with no socket timeout, so a peer that accepts TCP and then goes quiet (black-holed proxy upstream, middlebox that only receives) blocks recv() forever and stalls the reconnect loop until the process is restarted. Set a 15 s SO_RCVTIMEO and SO_SNDTIMEO for the handshake window - the same value both server handshake threads use - and clear them once the connection is up so the worker thread's select plus blocking recv keeps working as before. Second, per-IP rate limiting counted the getpeername address before the real device was known. Behind a same-host reverse proxy that address is loopback, which IPWhitelist always trusts, so WS traffic was neither counted nor banned; behind a remote proxy every device shares one bucket, and tripping the threshold disconnected all of them. Count and ban by the forwarded device IP once the upgrade resolves it, mirroring the Go server's limitDirectPeer and handleConnection split. Direct connections keep their accept-time count and are not counted twice. Third, the protocol switch disarmed its five-minute auto-revert as soon as the new entry connected, which only proves TCP/TLS/WS handshaking finished. If login is never accepted there (wrong backend, reverse proxy pointing at some other WS service), the revert could never fire and the client would keep retrying a dead entry. Disarm on the first CMD_MASTERSETTING instead, which the server only sends after adding the host to its online list, and re-check it on every heartbeat so a late one still counts. The smaller items came along: free the handshake parameter when CreateThread fails in both handshake starters, move the WS_Handshaking fail-closed guard ahead of the TLS branch so it also covers WSS (where tlsState is already TLS_Ready), generate the frame mask from a per-channel PRNG inside the send lock instead of an unseeded global rand(), make the transport flags and the WS session's ready flag atomic, drop rather than send unframed application bytes when a WS session has closed, and abort a protocol switch whose PEM fails to load instead of moving to an entry that cannot connect. The Go server now bounds the upgrade sniff even when ReadTimeout is zero, and the design doc records the two-stage limiter, the login-based disarm and the review items that stay as known limits. The protocol switch's input prompt is cut down to "reverse-proxy entry (host:port)" - the label static is only 81 dialog units wide, and the old sentence ran to roughly three times that. The three language files follow: en_US and zh_TW gain the shortened prompt and drop the long key it replaced, the German file gains the protocol-switch block it never had, and its WebSocket tip key is corrected - it had picked up a Go-server clause the source string never carried, so the tip was never translated at all. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
99db28e2e2
commit
50a489e316
12 files changed
+264
-40
No files matched your search
@@ -816,13 +816,18 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
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);
|
||||
// 协议切换:新入口已经打通(登录包发出且连接仍在),撤销自动回退计时
|
||||
if (ClientObject->IsConnected())
|
||||
ConfirmProtoSwitch(cfg);
|
||||
|
||||
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);
|
||||
if (assigned && time(0) > valid_to) {
|
||||
app.SetProcessState(S_CLIENT_UPDATE);
|
||||
settings.SetServer(ip.c_str(), port);
|
||||
|
||||
@@ -391,6 +391,9 @@ BOOL ConnectWithTimeout(SOCKET sock, SOCKADDR *addr, int timeout_sec=5)
|
||||
|
||||
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
|
||||
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
|
||||
m_loginAcked.store(false, std::memory_order_release);
|
||||
if (szServerIP != NULL && uPort != 0) {
|
||||
SetServerAddress(szServerIP, uPort);
|
||||
}
|
||||
@@ -467,6 +470,29 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
SetKeepAliveOptions(m_sClientSocket);
|
||||
#endif
|
||||
}
|
||||
// 握手超时:TLS / WebSocket 握手都是同步阻塞的(WsChannel::Handshake 逐字节 recv 等
|
||||
// 101 响应),而 socket 默认没有收超时——对端接受 TCP 却迟迟不回数据时(反代上游黑洞、
|
||||
// 中间设备只收不发),recv 会永久阻塞,StartClient 的重连循环整个停摆,只能重启进程。
|
||||
// 这里给握手窗口设 15s 超时(与服务端两个握手线程同一个值),握手结束后立刻清零,
|
||||
// 避免影响 WorkThread 之后依赖 select + 阻塞 recv 的常规收包。
|
||||
bool hsTmoSet = false;
|
||||
#ifdef _WIN32
|
||||
{
|
||||
DWORD hsTmo = 15000;
|
||||
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO,
|
||||
(const char*)&hsTmo, sizeof(hsTmo)) == 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&hsTmo, sizeof(hsTmo));
|
||||
}
|
||||
#else
|
||||
{
|
||||
struct timeval hsTmo;
|
||||
hsTmo.tv_sec = 15;
|
||||
hsTmo.tv_usec = 0;
|
||||
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &hsTmo, sizeof(hsTmo)) == 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &hsTmo, sizeof(hsTmo));
|
||||
}
|
||||
#endif
|
||||
|
||||
// WebSocket 传输(PROTO_WS / PROTO_WSS):出站被限制在 80/443/8080 等端口时,经反代
|
||||
// 分流进来。与应用协议无关,位置和 TLS 相同(TLS 之下、应用协议之上);须在
|
||||
// m_bConnected 置位前完成,确保工作线程不会在 Upgrade 尚未完成时就开始 recv。
|
||||
@@ -550,6 +576,20 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
WS_UPGRADE_PATH, wsDegraded ? " (明文,等待信任锚)"
|
||||
: (wsTls ? " (TLS)" : ""));
|
||||
}
|
||||
// 握手阶段结束(成功路径):清零握手超时,恢复普通阻塞收包。
|
||||
if (hsTmoSet) {
|
||||
#ifdef _WIN32
|
||||
DWORD noTmo = 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&noTmo, sizeof(noTmo));
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&noTmo, sizeof(noTmo));
|
||||
#else
|
||||
struct timeval noTmo;
|
||||
noTmo.tv_sec = 0;
|
||||
noTmo.tv_usec = 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &noTmo, sizeof(noTmo));
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &noTmo, sizeof(noTmo));
|
||||
#endif
|
||||
}
|
||||
m_bConnected = TRUE;
|
||||
Mprintf("连接服务端成功: %s:%d.\n", m_sCurIP.c_str(), (int)port);
|
||||
|
||||
|
||||
+14
-2
@@ -39,6 +39,7 @@
|
||||
#endif
|
||||
#include "IOCPBase.h"
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <chrono>
|
||||
|
||||
@@ -289,6 +290,14 @@ public:
|
||||
// 仅在我们正在等待 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
|
||||
@@ -342,14 +351,17 @@ protected:
|
||||
// WebSocket 传输(PROTO_WS / PROTO_WSS):ConnectServer 里握手成功时置位,
|
||||
// Disconnect 时清除。与 m_useTls 一样按连接锁定,Send/Recv 不再现查 protoType。
|
||||
WsChannel m_ws;
|
||||
bool m_useWs = false;
|
||||
// 收发分处两个线程:连接线程写、接收/发送线程读。形式上必须是原子量(x86 上实践
|
||||
// 无害,但换成别的架构就不能再依赖这个巧合)。
|
||||
std::atomic<bool> m_useWs{false};
|
||||
std::atomic<bool> m_loginAcked{false};
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
|
||||
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
|
||||
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
|
||||
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
|
||||
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
|
||||
bool m_useTls = false;
|
||||
std::atomic<bool> m_useTls{false};
|
||||
#endif
|
||||
BOOL m_bWorkThread;
|
||||
HANDLE m_hWorkThread;
|
||||
|
||||
@@ -944,10 +944,21 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
uint32_t certLen = p.certLen < maxCert ? p.certLen : maxCert;
|
||||
if (certLen > 0) {
|
||||
std::string certPem((const char*)szBuffer + 1 + sizeof(ProtoSwitchPacket), certLen);
|
||||
const std::string prevCert = m_cfg->GetStr("settings", "tls_cert");
|
||||
m_cfg->SetStr("settings", "tls_cert", certPem);
|
||||
std::string err;
|
||||
if (!TlsReload(err))
|
||||
Mprintf("[proto-switch] trust anchor reload failed: %s\n", err.c_str());
|
||||
if (!TlsReload(err)) {
|
||||
// 放弃本次切换(不写 proto_override/entry_*,不断连):PEM 加载不了时客户端
|
||||
// 会进入 TlsLoadError() 的 fail-closed 状态,切过去只会「新入口连不上,等
|
||||
// 5 分钟自动回退」——而且自动回退本身也可能被误撤销。回滚证书并回报操作端。
|
||||
m_cfg->SetStr("settings", "tls_cert", prevCert);
|
||||
const std::string loadErr = err;
|
||||
TlsReload(err); // 让 TLS 上下文回到旧锚(失败也不影响:旧锚此前是好的)
|
||||
Mprintf("[proto-switch] trust anchor reload failed: %s, switch aborted\n", loadErr.c_str());
|
||||
ClientMsg msg("协议切换", ("证书加载失败,已取消切换: " + loadErr).c_str());
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (restore) {
|
||||
@@ -1231,6 +1242,11 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
OnHeatbeatResponse(szBuffer, ulLength);
|
||||
break;
|
||||
case CMD_MASTERSETTING:
|
||||
// 登录已被服务端接受:服务端把本机加入在线列表后才下发 MasterSettings
|
||||
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径)。协议切换的
|
||||
// 自动回退靠这个信号撤销,而不是只看连接是否建立——连接建立只说明握手完成。
|
||||
if (m_ClientObject)
|
||||
m_ClientObject->SetLoginAcked(true);
|
||||
if (ulLength > MasterSettingsOldSize) {
|
||||
memcpy(&m_settings, szBuffer + 1, ulLength > sizeof(MasterSettings) ? sizeof(MasterSettings) : MasterSettingsOldSize);
|
||||
if (m_settings.Signature[0] && m_LoginSignature.empty()) {
|
||||
|
||||
+33
-3
@@ -18,6 +18,9 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -320,13 +323,18 @@ private:
|
||||
hn = 10;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(m_sendMtx);
|
||||
// 掩码在锁内、用本实例私有的 PRNG 生成:发送线程与接收线程(pong / close)都会
|
||||
// 写帧,锁外取掩码会让两个线程并发推进共享状态;而全局 rand() 更不能用了——
|
||||
// HttpMask 的构造函数里有 srand(time(nullptr)),会在同进程内重置全局序列。
|
||||
// xorshift64 对本场景足够(RFC 6455 §5.3 只要求掩码来自概率性熵源,不承担安全职责)。
|
||||
unsigned long long r = NextMask64();
|
||||
unsigned char mask[4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
mask[i] = (unsigned char)(rand() & 0xFF);
|
||||
mask[i] = (unsigned char)((r >> (8 * i)) & 0xFF);
|
||||
memcpy(hdr + hn, mask, 4);
|
||||
hn += 4;
|
||||
|
||||
std::lock_guard<std::mutex> lock(m_sendMtx);
|
||||
// 复用同一个缓冲区:发送热路径上每帧不再分配一个新 vector。
|
||||
m_frame.resize((size_t)hn + (size_t)len);
|
||||
char* frame = m_frame.data();
|
||||
@@ -341,7 +349,29 @@ private:
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
TlsChannel* m_tls = NULL; // WSS 时指向 IOCPClient 的 TLS 会话
|
||||
#endif
|
||||
bool m_ready = false;
|
||||
// 会话是否就绪。收、发分处两个线程,且 Disconnect 可能从接收线程侧走 Reset(),
|
||||
// 故用原子量:x86 上裸 bool 实践无害,但换架构就不能再依赖这个巧合。
|
||||
std::atomic<bool> m_ready{false};
|
||||
|
||||
// 写帧掩码用的私有 PRNG(只在 m_sendMtx 内推进)。种子取地址 + 时间,够用即可:
|
||||
// 掩码只用于让帧在链路上不再是固定形态,安全性由 TLS 与隧道内登录承担。
|
||||
unsigned long long NextMask64()
|
||||
{
|
||||
unsigned long long x = m_maskState;
|
||||
if (x == 0) {
|
||||
x = (unsigned long long)(uintptr_t)this;
|
||||
x = x * 0x9E3779B97F4A7C15ULL ^ (unsigned long long)time(nullptr);
|
||||
if (x == 0)
|
||||
x = 0x2545F4914F6CDD1DULL;
|
||||
}
|
||||
// xorshift64*
|
||||
x ^= x >> 12;
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
m_maskState = x;
|
||||
return x * 0x2545F4914F6CDD1DULL;
|
||||
}
|
||||
unsigned long long m_maskState = 0;
|
||||
|
||||
// 写方向串行化(发送线程与接收线程的 pong/close 都会写帧),以及复用的整帧缓冲。
|
||||
std::mutex m_sendMtx;
|
||||
|
||||
Reference in new issue
Block a user