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:
yuanyuanxianganddeepseek-flash committed 2026-10-30 18:11:34 +01:00
1 parent 99db28e2e2
commit 50a489e316
12 files changed
+264 -40

No files matched your search

+63 -19
View File
@@ -1009,6 +1009,7 @@ BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
ContextObject->IoRefCount.fetch_sub(1);
delete ContextObject->tls;
ContextObject->tls = NULL;
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
return FALSE;
}
CloseHandle(h);
@@ -1066,23 +1067,46 @@ DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam)
Mprintf("[WS] %s upgraded via reverse proxy, real client %s\n",
ctx->GetPeerName().c_str(), fwd.c_str());
ctx->SetPeerName(fwd);
}
ctx->wsState.store(WS_Ready, std::memory_order_release);
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
if (!pending.empty()) {
ZSTD_DCtx* dctx = ZSTD_createDCtx();
z_stream z = {};
inflateInit2(&z, 15);
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
inflateEnd(&z);
ZSTD_freeDCtx(dctx);
if (r < 0) {
ok = false;
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
// 两段式限流(与 Go 端 limitDirectPeer / handleConnection 同构)。accept 阶段按
// getpeername 计的那一次对经反代的连接没有意义:反代同机时对端是回环地址,
// IPWhitelist 对回环恒为 true,黑名单 / 封禁 / 计数全部不生效。真实设备 IP 到
// 这里才知道,所以在这里按真实 IP 重做一次。直连连接(fwd 为空)在 accept 阶段
// 已经计过数,不重复计数。
bool blocked = This->IsIPBlacklisted(fwd);
if (!blocked) {
blocked = This->IsIPBanned(fwd);
if (!blocked) {
This->RecordConnection(fwd); // 超阈值时内部会 BanIP
blocked = This->IsIPBanned(fwd); // 本次连接把计数顶过阈值
}
}
if (blocked) {
Mprintf("[WS] real client %s rejected by IP ban/rate limit (fail-closed)\n", fwd.c_str());
ok = false;
}
}
if (ok) {
ctx->wsState.store(WS_Ready, std::memory_order_release);
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
if (!pending.empty()) {
ZSTD_DCtx* dctx = ZSTD_createDCtx();
z_stream z = {};
inflateInit2(&z, 15);
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
inflateEnd(&z);
ZSTD_freeDCtx(dctx);
if (r < 0) {
ok = false;
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
}
}
} else {
ctx->wsState.store(WS_None, std::memory_order_release);
}
} else {
ctx->wsState.store(WS_None, std::memory_order_release);
@@ -1124,6 +1148,7 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
ContextObject->IoRefCount.fetch_sub(1);
ContextObject->FreeWs();
ContextObject->wsState.store(WS_None, std::memory_order_release);
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
return FALSE;
}
CloseHandle(h);
@@ -1132,6 +1157,18 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
{
// 握手线程独占 socket(TLS 或 WS 升级期间):正常不应出现 IORead,出现即属异常,fail-closed。
// 必须放在函数最开头——WSS 升级时 tlsState 已经是 TLS_Ready,若把判断放在 TLS 分支之后,
// 这段字节会先走解密分支再进 DispatchPlain,被当成业务协议解析,同时与握手线程并发读
// 同一个 socket。放在最前面才能同时覆盖明文与 TLS 两条路径。
if (ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
Mprintf("[WS] unexpected IORead during handshake for %s (closing)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
int st = ContextObject->tlsState.load(std::memory_order_acquire);
// ---- 未分类:按 ClientHello 头嗅探明文 / TLS(见设计文档 §5.2)----
@@ -1210,8 +1247,9 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
return TRUE;
}
// TLS_Handshaking / WS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
if (st == TLS_Handshaking || ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
// TLS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
// (WS_Handshaking 在函数开头已判定,不在这里。)
if (st == TLS_Handshaking) {
Mprintf("[TLS] unexpected IORead during handshake for %s (closing)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
@@ -1399,8 +1437,14 @@ BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
// 客户端解密后得到的是「旧 TLS 记录」→ Unknown header 17 03 03。故只加密本次新追加的尾部。
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
// WS(含 WSS):同样只处理本次新追加的尾部——前缀可能还有在途未发完的帧/密文。
bool wsReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready) &&
ContextObject->ws != NULL && ContextObject->ws->IsOpen();
const bool wsStateReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready);
if (wsStateReady && (ContextObject->ws == NULL || !ContextObject->ws->IsOpen())) {
// 升级过 WS 但会话已关(Feed 报错 / 收到 close)而状态还没降级:绝不能把应用字节
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,由接收路径的 RemoveStaleContext 收尾。
Mprintf("[WS] session closed for %s, dropping send\n", ContextObject->GetPeerName().c_str());
return FALSE;
}
bool wsReady = wsStateReady;
ULONG oldLen = (tlsReady || wsReady) ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
if (WriteContextData(ContextObject, szBuffer, ulOriginalLength, ContextObject->Zcctx)) {