Fix: Bound the Linux TLS handshake with a deadline

The handshake loop retried SSL_do_handshake on SSL_ERROR_WANT_READ and
nothing else. IOCPClient arms the socket with SO_RCVTIMEO for the
handshake, and a read timeout surfaces as EAGAIN, which OpenSSL reports
as WANT_READ rather than a syscall error. A peer that accepted TCP and
then went silent therefore put the loop into an endless retry: the
handshake never finished, never failed, and logged nothing, while the
main loop sat inside the read. Even SIGTERM could not stop the process,
because the exit flag is only observed between heartbeats.

Observed on a Linux client moving back to 443 when a transfer expired:
frps had the connection ESTABLISHED, the server had sent a partial
flight, the client's Recv-Q was empty and its log stopped dead at the
reconnect line. Reproduced locally against a TCP server that accepts and
never replies: one connection in 75 seconds and no output at all.

Give the whole handshake a 30 second budget, longer than the 15 second
read timeout so a single wake-up still fits, and treat expiry as a
failure the caller can retry. The stalled peer now logs
"[TLS] handshake timed out after Ns (peer silent), aborting" and the
reconnect loop keeps running.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-07 23:04:09 +01:00
1 parent 4309865570
commit 7240879792
1 file changed
+18 -2
+18 -2
View File
@@ -23,6 +23,7 @@
#include <openssl/x509_vfy.h>
#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
@@ -445,15 +446,30 @@ bool TlsChannel::Handshake(int sock, const char* sni, const std::string& /*host*
SSL_set_tlsext_host_name(ssl, sni);
SSL_set_connect_state(ssl);
// 阻塞 socket:WANT_READ / WANT_WRITE 只在记录分片等极端情形出现,重试即可。
// 阻塞 socket:正常路径不会出现 WANT_READ/WANT_WRITE,但这两种情况必须重试。
// 关键坑:调用方给 socket 设了 SO_RCVTIMEO(IOCPClient 的握手超时,15s)。读超时后
// recv 返回 EAGAIN,OpenSSL 报的是 WANT_READ 而不是 SYSCALL——无脑 continue 会把
// 「对端只收不发」变成永久重试:握手既不结束、也不失败、更不打一行日志,主循环就
// 停摆在这里(2026-11-07 实机复现:frps 侧连接 ESTAB、Recv-Q 空、客户端零日志)。
// 所以这里给整个握手一个总时限,超时按失败处理,交回外层重连。
const auto hsStart = std::chrono::steady_clock::now();
const auto hsDeadline = std::chrono::seconds(30); // > 内核读超时(15s),留一次重试余量
for (;;) {
ERR_clear_error();
int r = SSL_do_handshake(ssl);
if (r == 1)
break;
int e = SSL_get_error(ssl, r);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) {
if (std::chrono::steady_clock::now() - hsStart > hsDeadline) {
Mprintf("[TLS] handshake timed out after %llds (peer silent), aborting\n",
(long long)std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - hsStart).count());
SSL_free(ssl);
return false;
}
continue;
}
if (e == SSL_ERROR_SSL) {
unsigned long err = ERR_peek_last_error();