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
This commit was merged in pull request #5.
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-30 19:15:14 +01:00
1 parent 50a489e316
commit 46f4bf2dfb
12 files changed
+149 -38

No files matched your search

+25 -10
View File
@@ -542,7 +542,14 @@ void CBuildDlg::OnBnClickedOk()
g_ConnectAddress.SetAdminId(GetMasterHash().c_str());
g_ConnectAddress.SetServer(m_strIP, atoi(m_strPort));
g_ConnectAddress.runningType = m_ComboRunType.GetCurSel();
g_ConnectAddress.protoType = m_ComboProto.GetCurSel();
// 协议值取自 item data(见 OnInitDialog 里的 addProto)。取不到时退回序号,保持旧行为。
int protoSel = m_ComboProto.GetCurSel();
if (protoSel >= 0) {
DWORD_PTR protoData = m_ComboProto.GetItemData(protoSel);
if (protoData != (DWORD_PTR)CB_ERR)
protoSel = (int)protoData;
}
g_ConnectAddress.protoType = protoSel;
g_ConnectAddress.iHeaderEnc = m_ComboEncrypt.GetCurSel();
memcpy(g_ConnectAddress.pwdHash, GetPwdHash().c_str(), sizeof(g_ConnectAddress.pwdHash));
memcpy(g_ConnectAddress.szGroupName, m_sGroupName, m_sGroupName.GetLength());
@@ -837,15 +844,23 @@ BOOL CBuildDlg::OnInitDialog()
m_ComboRunType.InsertStringL(RUNNING_PARALLEL, "并发上线");
m_ComboRunType.SetCurSel(RUNNING_RANDOM);
m_ComboProto.InsertStringL(PROTO_TCP, "TCP");
m_ComboProto.InsertStringL(PROTO_UDP, "UDP");
m_ComboProto.InsertStringL(PROTO_HTTP, "HTTP");
m_ComboProto.InsertStringL(PROTO_RANDOM, "随机");
m_ComboProto.InsertStringL(PROTO_KCP, "KCP");
// 序号即 protoType,中间不能有空洞(下方 GetCurSel 直接当协议值用)
m_ComboProto.InsertStringL(PROTO_WS, "WebSocket");
m_ComboProto.InsertStringL(PROTO_WSS, "WS+TLS");
m_ComboProto.SetCurSel(PROTO_TCP);
// 协议值挂在 item data 上,不再依赖「下拉框序号 == protoType」。两者目前确实相等,
// 但只要以后有 PROTO_* 常量没进这个下拉框(PROTO_HTTPS 就已经是这种情况),
// 后加项序号与协议值就会错位,而错误的值只会在客户端连不上时才暴露。
auto addProto = [this](int proto, LPCSTR text) {
// AddString 追加到末尾并返回新条目下标;用它定位,不依赖任何「下标 == 枚举值」约定。
int idx = m_ComboProto.AddStringL(text);
if (idx >= 0)
m_ComboProto.SetItemData(idx, (DWORD_PTR)proto);
};
addProto(PROTO_TCP, "TCP");
addProto(PROTO_UDP, "UDP");
addProto(PROTO_HTTP, "HTTP");
addProto(PROTO_RANDOM, "随机");
addProto(PROTO_KCP, "KCP");
addProto(PROTO_WS, "WebSocket");
addProto(PROTO_WSS, "WS+TLS");
m_ComboProto.SetCurSel(0);
m_ComboEncrypt.InsertStringL(PROTOCOL_SHINE, "Shine");
m_ComboEncrypt.InsertStringL(PROTOCOL_HELL, "HELL");
+24 -5
View File
@@ -1258,6 +1258,16 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
}
// TLS_Plain:明文直通(原路径)。WS 连接在这里先解帧。
// dwTrans == 0 是对端干净关闭(FIN)。WS 改造前这条分支直接调 ParseReceivedData,
// 它对 dataLen == 0 返回 FALSE 从而拆连接;换成 DispatchPlain 后该语义丢了——0 字节
// 一路返回 1 → PostRecv,而 FIN 已经消费掉,这条连接就停在 CLOSE_WAIT 里,直到
// keepalive(3 分钟)才回收(实测:对端 FIN 后连接一直留在 CLOSE_WAIT,进程不空转)。
// 期间它占着 IOCP 上下文、挂着一枚 WSARecv 和限流槽。这里补回与另外两条分支一致的收尾。
if (dwTrans == 0) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
{
int r = DispatchPlain(ContextObject, (const BYTE*)ContextObject->szBuffer, dwTrans, ctx, z);
if (r < 0) {
@@ -1290,13 +1300,14 @@ int IOCPServer::DispatchPlain(CONTEXT_OBJECT* ContextObject, const BYTE* data, D
}
if (ws == WS_Undecided) {
ContextObject->tlsPreClassify.insert(ContextObject->tlsPreClassify.end(), data, data + len);
if (ContextObject->tlsPreClassify.size() < 6) {
// WS 有自己的缓冲(该状态机在 HTTPS 升级 / 反代路径上也会用到),不再借 tlsPreClassify。
ContextObject->wsPreClassify.insert(ContextObject->wsPreClassify.end(), data, data + len);
if (ContextObject->wsPreClassify.size() < 6) {
return 1; // 头还没攒够,继续收
}
std::vector<BYTE> first;
first.swap(ContextObject->tlsPreClassify);
ContextObject->tlsPreClassify.clear();
first.swap(ContextObject->wsPreClassify);
ContextObject->wsPreClassify.clear();
if (first.size() >= 4 && memcmp(first.data(), "GET ", 4) == 0) {
if (!StartWsHandshake(ContextObject, first)) {
Mprintf("[WS] StartWsHandshake failed for %s (fail-closed)\n",
@@ -1440,8 +1451,16 @@ BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
const bool wsStateReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready);
if (wsStateReady && (ContextObject->ws == NULL || !ContextObject->ws->IsOpen())) {
// 升级过 WS 但会话已关(Feed 报错 / 收到 close)而状态还没降级:绝不能把应用字节
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,由接收路径的 RemoveStaleContext 收尾。
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,并主动 shutdown 让挂起的 recv
// 立刻返回 0 字节——否则接收路径要等对端 FIN 才醒,期间这条连接既发不出也收不到,
// 只能靠心跳超时兜底(最坏要几分钟)。
//
// 这里不能直接调 RemoveStaleContext:它会等待 IoRefCount 归零,而本函数的调用方
// 常常就处在一个 IoRef 里(发送失败→兜底发送),等于自己等自己,5 秒后超时放行,
// 反而可能把已回收复用的 CONTEXT_OBJECT 交回给调用者。shutdown 是异步且无阻塞的,
// 真正的收尾仍由接收路径的 -2 返回值触发。
Mprintf("[WS] session closed for %s, dropping send\n", ContextObject->GetPeerName().c_str());
shutdown(ContextObject->sClientSocket, SD_BOTH);
return FALSE;
}
bool wsReady = wsStateReady;
+6 -1
View File
@@ -429,6 +429,10 @@ public:
// ---- WebSocket 传输层状态(分层在 TLS 之上:WSS = TLS 里的 WS)----
std::atomic<int> wsState{ WS_Undecided }; // ServerWsState
ServerWsSession* ws = nullptr; // 每连接 WS 会话(升级线程独占→就绪后共用)
// WS 升级前的首包缓冲(判定 "GET " 用)。与 tlsPreClassify 刻意分开:两者服务于不同的
// 状态机,此前串行复用同一个 vector(TLS 判定完 move 走再 clear,WS 又塞回来),字段名
// 与用途对不上,排查时容易误读。两条路径仍按先后串行,互不重叠。
std::vector<BYTE> wsPreClassify;
// 子连接身份校验:客户端发 TOKEN_CONN_AUTH 通过验证后置位。
// 主连接(走 TOKEN_LOGIN 流程)不参与此机制。当前阶段宽容(未通过也接受),
@@ -591,9 +595,10 @@ public:
FreeTls();
tlsState.store(TLS_Unclassified, std::memory_order_release);
tlsPreClassify.clear();
// 复用对象池时重置 WebSocket 状态:释放旧会话、回到未判定。
// 复用对象池时重置 WebSocket 状态:释放旧会话、回到未判定、清空首包缓冲。
FreeWs();
wsState.store(WS_Undecided, std::memory_order_release);
wsPreClassify.clear();
// 复用对象池时清空发送进行中标志,避免上次连接残留的 bSendPending 抑制新连接的发送。
bSendPending = false;
}