Feature: Implement the proxy mapping listener without HP-Socket

The proxy mapping dialog ("代理映射") depended on HP-Socket: three vendored
SDK headers (4787 lines) plus #pragma comment(lib) lines pulling in four
prebuilt lib/DLL variants, all guarded by ENABLE_HPSOCKET, which has been 0
since the initial commit -- so the feature was dead code that only answered
"This feature is unavailable due to HPSocket disabled" and no build of this
repository ever ran it.

Replace that dependency with a small listener built on blocking sockets and
select, which is the same approach the client's CProxyManager and the
server's own SimpleWebSocket already take. The accept loop polls every
200 ms so Shutdown can return without closing a socket another thread is
selecting on, and each accepted connection gets a relay thread that only
has to recv and hand bytes to the dialog. Connection sockets are closed by
their relay thread alone; Disconnect only raises a stop flag and calls
shutdown() under the same lock the relay thread takes before closesocket,
so a recycled handle is never shut down by mistake. Finished threads are
parked in a graveyard and joined by the accept thread, which keeps the
thread handle count flat across open/close cycles.

ProxyMapDlg keeps the SOCKS5 state machine it had, but now stores its
per-connection state in a map keyed by the connection id instead of
relying on HP-Socket's GetConnectionExtra, and it logs through a posted
window message rather than touching CEdit from worker threads. The two log
panes in IDD_PROXY are ES_READONLY, so EM_REPLACESEL was silently ignored
(the original code had the same latent bug); the dialog now keeps the pane
text itself and writes it with SetWindowText, bounded to 256 KB per pane.

The vcxproj and filters lose the three SDK headers, and the dialog gate in
OnOpenProxyDialog loses its ENABLE_HPSOCKET check.

Tested against a Debug server with a Debug Windows client on the same
host: curl through the listener succeeds over both the IPv4 and the
hostname ATYP paths, a 4 MB transfer arrives byte-identical, a refused
target maps to SOCKS5 reply 5, killing the client mid-transfer closes the
dialog and releases the port, and five open/close cycles leave the server's
handle and thread counts unchanged.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-29 15:37:16 +01:00
1 parent 13c02fe50b
commit 45e1dd9f6c
10 files changed
+676 -5218

No files matched your search

+256 -184
View File
@@ -1,221 +1,293 @@
#include "stdafx.h"
#include "ProxyConnectServer.h"
#define MAX_SEND_BUFFER 65535 // 最大发送数据长度 1024*64
#define MAX_RECV_BUFFER 65535 // 最大接收数据长度
#define PROXY_RECV_CHUNK (16 * 1024) // 单次 recv 的上限
#define PROXY_POLL_MS 200 // select 轮询周期,决定 Shutdown/Disconnect 的响应时延
#define PROXY_SEND_TIMEOUT_MS 5000 // 向本机连接发送的超时,避免卡住调用方线程
CProxyConnectServer::CProxyConnectServer(void) :m_TcpServer(this)
CProxyConnectServer::CProxyConnectServer()
{
Mprintf("CProxyConnectServer\r\n");
m_bIsRun = TRUE;
m_dwIndex = 0;
memset(m_IDs, 0, sizeof(m_IDs));
}
CProxyConnectServer::~CProxyConnectServer(void)
CProxyConnectServer::~CProxyConnectServer()
{
if (m_TcpServer->GetState() != SS_STOPPED)
m_TcpServer->Stop();
while (m_TcpServer->GetState() != SS_STOPPED) {
Sleep(300);
}
Shutdown();
Mprintf("~CProxyConnectServer\r\n");
}
BOOL CProxyConnectServer::Initialize(NOTIFYPROC pNotifyProc, void*user, int nMaxConnections, int nPort)
BOOL CProxyConnectServer::SetSocketOptions(SOCKET s) const
{
m_nMaxConnection = nMaxConnections;
m_TcpServer->SetMaxConnectionCount(nMaxConnections);
m_TcpServer->SetSendPolicy(SP_DIRECT);
m_TcpServer->SetNoDelay(TRUE);
m_pNotifyProc = pNotifyProc;
m_pUser = user;
m_nPort = nPort;
m_bStop = FALSE;
return m_TcpServer->Start(_T("0.0.0.0"), nPort);
BOOL bNoDelay = TRUE;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char*)&bNoDelay, sizeof(bNoDelay));
DWORD dwSendTimeout = PROXY_SEND_TIMEOUT_MS;
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char*)&dwSendTimeout, sizeof(dwSendTimeout));
return TRUE;
}
EnHandleResult CProxyConnectServer::OnPrepareListen(ITcpServer* pSender, SOCKET soListen)
BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, int nMaxConnections, int nPort)
{
SYS_SSO_SendBuffSize(soListen, MAX_SEND_BUFFER);
SYS_SSO_RecvBuffSize(soListen, MAX_RECV_BUFFER);
return HR_OK;
}
EnHandleResult CProxyConnectServer::OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient)
{
if (!m_bIsRun)return HR_ERROR;
ClientContext* pContext = NULL;
{
m_Locker.lock();
if (!m_listFreePool.IsEmpty()) {
pContext = m_listFreePool.RemoveHead();
} else {
pContext = new(std::nothrow) ClientContext;
}
m_Locker.unlock();
}
if (pContext == NULL)
return HR_ERROR;
pContext->InitMember(dwConnID, nullptr);
pContext->m_Socket = dwConnID;
char szAddress[64] = {};
int iAddressLen = sizeof(szAddress);
USHORT usPort = 0;
pSender->GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort);
Mprintf("CProxyConnectServer: new connection %s:%d\n", szAddress, usPort);
pContext->ID = dwConnID;
m_TcpServer->SetConnectionExtra(dwConnID, pContext);
m_pNotifyProc(m_pUser, pContext, NC_CLIENT_CONNECT);
return HR_OK;
}
EnHandleResult CProxyConnectServer::OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
return HR_OK;
}
EnHandleResult CProxyConnectServer::OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength)
{
ClientContext* pContext = NULL;
if ((!m_TcpServer->GetConnectionExtra(dwConnID, (PVOID*)&pContext)) && (pContext != nullptr) && (iLength <= 0))
return HR_ERROR;
PBYTE pData = new BYTE[iLength];
m_TcpServer->Fetch(dwConnID, pData, iLength);
pContext->InDeCompressedBuffer.ClearBuffer();
BYTE bToken = COMMAND_PROXY_DATA;
pContext->InDeCompressedBuffer.Write(&bToken, sizeof(bToken));
pContext->InDeCompressedBuffer.Write((LPBYTE)&pContext->ID, sizeof(DWORD));
pContext->InDeCompressedBuffer.Write((PBYTE)pData, iLength);
SAFE_DELETE_ARRAY(pData);
m_pNotifyProc(m_pUser, pContext, NC_RECEIVE);
return HR_OK;
}
EnHandleResult CProxyConnectServer::OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
ClientContext* pContext = NULL;
if (m_TcpServer->GetConnectionExtra(dwConnID, (PVOID*)&pContext) && pContext != nullptr)
m_TcpServer->SetConnectionExtra(dwConnID, NULL);
if (!pContext)
return HR_OK;
m_pNotifyProc(m_pUser, pContext, NC_CLIENT_DISCONNECT);
pContext->InCompressedBuffer.ClearBuffer();
pContext->InDeCompressedBuffer.ClearBuffer();
pContext->OutCompressedBuffer.ClearBuffer();
m_Locker.lock();
m_listFreePool.AddTail(pContext);
m_Locker.unlock();
return HR_OK;
}
EnHandleResult CProxyConnectServer::OnShutdown(ITcpServer* pSender)
{
return HR_OK;
}
BOOL CProxyConnectServer::Send(ClientContext* pContext, LPBYTE lpData, UINT nSize)
{
if (pContext == NULL)
if (m_bRunning.load(std::memory_order_acquire))
return FALSE;
if (pNotifyProc == nullptr || nPort <= 0 || nPort > 65535)
return FALSE;
BOOL rt = FALSE;;
if (nSize > 0 && m_bIsRun) {
pContext->OutCompressedBuffer.Write(lpData, nSize);
rt = SendWithSplit(pContext->m_Socket, pContext->OutCompressedBuffer.GetBuffer(0),
pContext->OutCompressedBuffer.GetBufferLength(), MAX_SEND_BUFFER);
pContext->OutCompressedBuffer.ClearBuffer();
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
Mprintf("CProxyConnectServer: socket() failed: %d\n", WSAGetLastError());
return FALSE;
}
return rt;
// 用 SO_EXCLUSIVEADDRUSE 而不是 SO_REUSEADDR:Windows 上 SO_REUSEADDR 允许绑定一个
// 已被别人监听的端口(甚至会抢走对方的连接),对话框「端口被占用就换随机端口」的重试
// 逻辑会失效。EXCLUSIVE 让 bind 如实失败。
BOOL bExclusive = TRUE;
setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&bExclusive, sizeof(bExclusive));
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY; // 与原 HP-Socket 版一致:0.0.0.0
addr.sin_port = htons((u_short)nPort);
if (bind(s, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Mprintf("CProxyConnectServer: bind(%d) failed: %d\n", nPort, WSAGetLastError());
closesocket(s);
return FALSE;
}
if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Mprintf("CProxyConnectServer: listen(%d) failed: %d\n", nPort, WSAGetLastError());
closesocket(s);
return FALSE;
}
// 非阻塞:select 报可读后仍可能有竞争(对端在 accept 前 RST),避免 accept 卡住。
u_long ulNonBlock = 1;
ioctlsocket(s, FIONBIO, &ulNonBlock);
SetSocketOptions(s);
m_pNotifyProc = pNotifyProc;
m_pUser = pUser;
m_nMaxConnection = nMaxConnections;
m_nPort = (USHORT)nPort;
m_listenSocket = s;
m_bRunning.store(true, std::memory_order_release);
m_acceptThread = std::thread(&CProxyConnectServer::AcceptLoop, this);
Mprintf("CProxyConnectServer: listening on 0.0.0.0:%d\n", nPort);
return TRUE;
}
BOOL CProxyConnectServer::SendWithSplit(CONNID dwConnID, LPBYTE lpData, UINT nSize, UINT nSplitSize)
void CProxyConnectServer::AcceptLoop()
{
int nSend = 0;
UINT nSendRetry = 0;
BOOL rt = TRUE;
if (nSize >= nSplitSize) {
UINT i = 0;
nSendRetry = nSize / nSplitSize;
for (i = 0; i < nSendRetry; i++) {
rt = m_TcpServer->Send(dwConnID, lpData, nSplitSize);
if (!rt)
return rt;
lpData += nSplitSize;
nSend += nSplitSize;
while (m_bRunning.load(std::memory_order_acquire)) {
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(m_listenSocket, &readSet);
timeval tv = {};
tv.tv_sec = 0;
tv.tv_usec = PROXY_POLL_MS * 1000;
int sel = select(0, &readSet, nullptr, nullptr, &tv);
if (!m_bRunning.load(std::memory_order_acquire))
break;
if (sel == SOCKET_ERROR) {
Mprintf("CProxyConnectServer: select() failed: %d\n", WSAGetLastError());
break;
}
if (nSize - nSend < nSplitSize) {
if (nSize - nSend > 0) {
rt = m_TcpServer->Send(dwConnID, lpData, nSize - nSend);
if (!rt)
return rt;
ReapFinished();
if (sel == 0)
continue;
sockaddr_in peer = {};
int peerLen = sizeof(peer);
SOCKET s = accept(m_listenSocket, (sockaddr*)&peer, &peerLen);
if (s == INVALID_SOCKET) {
// 非阻塞 accept 的竞争(对端已断开)属正常,继续。
if (WSAGetLastError() != WSAEWOULDBLOCK)
Mprintf("CProxyConnectServer: accept() failed: %d\n", WSAGetLastError());
continue;
}
if (m_nMaxConnection > 0 && GetConnectionCount() >= m_nMaxConnection) {
Mprintf("CProxyConnectServer: reject, max connections (%d) reached\n", m_nMaxConnection);
closesocket(s);
continue;
}
SetSocketOptions(s);
auto pConn = std::make_shared<Conn>();
pConn->sock = s;
{
std::lock_guard<std::mutex> lock(m_connLock);
CONNID id = m_nextId++;
if (m_nextId == 0)
m_nextId = 1; // 回绕后仍跳过 0
while (m_conns.find(id) != m_conns.end()) {
id = m_nextId++;
if (m_nextId == 0)
m_nextId = 1;
}
pConn->id = id;
m_conns[id] = pConn;
}
} else {
rt = m_TcpServer->Send(dwConnID, lpData, nSize);
if (!rt)
return rt;
char szPeer[64] = {};
inet_ntop(AF_INET, &peer.sin_addr, szPeer, sizeof(szPeer));
Mprintf("CProxyConnectServer: new connection #%u from %s:%u\n",
pConn->id, szPeer, (UINT)ntohs(peer.sin_port));
// 先通知「新连接」(对话框据此建立会话状态),再开始收数据。
m_pNotifyProc(m_pUser, pConn->id, nullptr, 0, NC_CLIENT_CONNECT);
pConn->thread = std::thread(&CProxyConnectServer::RelayLoop, this, pConn);
}
return TRUE;
}
void CProxyConnectServer::RelayLoop(std::shared_ptr<Conn> pConn)
{
std::vector<BYTE> buf(PROXY_RECV_CHUNK);
while (!pConn->stop.load(std::memory_order_acquire)) {
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(pConn->sock, &readSet);
timeval tv = {};
tv.tv_sec = 0;
tv.tv_usec = PROXY_POLL_MS * 1000;
int sel = select(0, &readSet, nullptr, nullptr, &tv);
if (sel == SOCKET_ERROR)
break;
if (sel == 0)
continue;
int nRecv = recv(pConn->sock, (char*)buf.data(), (int)buf.size(), 0);
if (nRecv <= 0)
break; // 0 = 对端关闭;<0 = 出错/已 shutdown
m_pNotifyProc(m_pUser, pConn->id, buf.data(), (UINT)nRecv, NC_RECEIVE);
}
{
std::lock_guard<std::mutex> lock(pConn->sendLock);
if (pConn->sock != INVALID_SOCKET) {
closesocket(pConn->sock);
pConn->sock = INVALID_SOCKET;
}
}
Mprintf("CProxyConnectServer: connection #%u closed\n", pConn->id);
m_pNotifyProc(m_pUser, pConn->id, nullptr, 0, NC_CLIENT_DISCONNECT);
{
std::lock_guard<std::mutex> lock(m_connLock);
m_conns.erase(pConn->id);
std::lock_guard<std::mutex> grave(m_graveLock);
m_graveyard.push_back(pConn); // 由 accept 线程或 Shutdown 负责 join
}
pConn->finished.store(true, std::memory_order_release);
}
void CProxyConnectServer::ReapFinished()
{
std::vector<std::shared_ptr<Conn>> done;
{
std::lock_guard<std::mutex> lock(m_graveLock);
done.swap(m_graveyard);
}
for (auto& pConn : done) {
if (pConn->thread.joinable())
pConn->thread.join();
}
}
BOOL CProxyConnectServer::Send(CONNID id, const BYTE* pData, UINT nSize)
{
if (pData == nullptr || nSize == 0)
return FALSE;
std::shared_ptr<Conn> pConn;
{
std::lock_guard<std::mutex> lock(m_connLock);
auto it = m_conns.find(id);
if (it == m_conns.end())
return FALSE;
pConn = it->second;
}
std::lock_guard<std::mutex> lock(pConn->sendLock);
if (pConn->sock == INVALID_SOCKET)
return FALSE;
UINT sent = 0;
while (sent < nSize) {
int n = send(pConn->sock, (const char*)pData + sent, (int)(nSize - sent), 0);
if (n <= 0) {
Mprintf("CProxyConnectServer: send #%u failed: %d\n", id, WSAGetLastError());
return FALSE;
}
sent += (UINT)n;
}
return TRUE;
}
BOOL CProxyConnectServer::Disconnect(CONNID id)
{
std::shared_ptr<Conn> pConn;
{
std::lock_guard<std::mutex> lock(m_connLock);
auto it = m_conns.find(id);
if (it == m_conns.end())
return FALSE;
pConn = it->second;
}
pConn->stop.store(true, std::memory_order_release);
// 只 shutdown 不 close:关闭权归中继线程。这里与中继线程的 close 共用 sendLock,
// 免得句柄已被关闭、又被系统复用给别的 socket 之后 shutdown 到别人身上。
std::lock_guard<std::mutex> lock(pConn->sendLock);
if (pConn->sock != INVALID_SOCKET)
shutdown(pConn->sock, SD_BOTH);
return TRUE;
}
int CProxyConnectServer::GetConnectionCount()
{
std::lock_guard<std::mutex> lock(m_connLock);
return (int)m_conns.size();
}
void CProxyConnectServer::Shutdown()
{
DWORD dwCount = 65535;
CONNID *pIDs = new CONNID[dwCount]();
BOOL status = m_TcpServer->GetAllConnectionIDs(pIDs, dwCount);
if (status && (dwCount > 0)) {
for (DWORD i = 0; i < dwCount; i++) {
Disconnect(pIDs[i]);
}
}
m_TcpServer->Stop();
m_bIsRun = FALSE;
while (m_TcpServer->GetState() != SS_STOPPED)
Sleep(10);
if (!m_bRunning.exchange(false, std::memory_order_acq_rel))
return;
m_Locker.lock();
while (!m_listFreePool.IsEmpty())
delete m_listFreePool.RemoveTail();
m_Locker.unlock();
SAFE_DELETE_ARRAY(pIDs);
}
void CProxyConnectServer::ClearClient()
{
DWORD dwCount = 65535;
CONNID* pIDs = new CONNID[dwCount]();
BOOL status = m_TcpServer->GetAllConnectionIDs(pIDs, dwCount);
if (status && (dwCount > 0)) {
for (DWORD i = 0; i < dwCount; i++) {
m_TcpServer->Disconnect(pIDs[i]);
}
// 1) 停 accept:accept 线程的 select 有 200ms 超时,靠 m_bRunning 自然退出,
// 避免在其他线程里 close 一个正被 select 的监听句柄。
if (m_acceptThread.joinable())
m_acceptThread.join();
if (m_listenSocket != INVALID_SOCKET) {
closesocket(m_listenSocket);
m_listenSocket = INVALID_SOCKET;
}
SAFE_DELETE_ARRAY(pIDs);
}
// 2) 断开并等待所有中继线程。
std::vector<std::shared_ptr<Conn>> conns;
{
std::lock_guard<std::mutex> lock(m_connLock);
for (auto& kv : m_conns)
conns.push_back(kv.second);
m_conns.clear();
}
for (auto& pConn : conns) {
pConn->stop.store(true, std::memory_order_release);
// 与 Disconnect 同理:shutdown 必须和中继线程的 closesocket 互斥,
// 否则可能对一个已被回收复用的句柄动手。
std::lock_guard<std::mutex> lock(pConn->sendLock);
if (pConn->sock != INVALID_SOCKET)
shutdown(pConn->sock, SD_BOTH);
}
for (auto& pConn : conns) {
if (pConn->thread.joinable())
pConn->thread.join();
}
BOOL CProxyConnectServer::Disconnect(CONNID dwConnID)
{
m_TcpServer->Disconnect(dwConnID);
return 0;
}
// 3) 收割自然退出但还没 join 的连接。
ReapFinished();
BOOL CProxyConnectServer::IsConnected(CONNID dwConnID)
{
return m_TcpServer->IsConnected(dwConnID);
}
BOOL CProxyConnectServer::IsOverMaxConnectionCount()
{
return (m_TcpServer->GetConnectionCount() > (DWORD)m_nMaxConnection);
Mprintf("CProxyConnectServer: shutdown, %d connection(s) closed\n", (int)conns.size());
}