Files
SimpleRemoter/server/2015Remote/proxy/ProxyMapDlg.cpp
T
yuanyuanxianganddeepseek-flash 45e1dd9f6c 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
2026-10-29 15:37:16 +01:00

454 lines
14 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ProxyMapDlg.cpp : implementation file
//
#include "stdafx.h"
#include "2015Remote.h"
#include "ProxyMapDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// CProxyMapDlg dialog
#define IDM_PROXY_CHROME 8000
#define WM_PROXY_APPEND_LOG (WM_APP + 101) // wParam: 0 = 主窗格,1 = 副窗格;lParam: CString*
#define MAX_LOG_CHARS (256 * 1024) // 单个日志框保留的最大字符数(超出丢头部)
#define SOCKS5_VER 5
#define SOCKS5_CMD_CONNECT 1
#define SOCKS5_ATYP_IPV4 1
#define SOCKS5_ATYP_HOST 3
#define SOCKS5_ATYP_IPV6 4
#define SOCKS5_REP_SUCCEEDED 0
#define SOCKS5_REP_REFUSED 5
#define SOCKS5_REP_CMD_UNSUPPORTED 7
#define SOCKS5_REP_ATYP_UNSUPPORTED 8
CProxyMapDlg::CProxyMapDlg(CWnd* pParent, Server* pIOCPServer, ClientContext* pContext)
: CDialogBase(CProxyMapDlg::IDD, pParent, pIOCPServer, pContext, IDI_Proxifier)
{
m_iocpLocal = NULL;
m_nPort = 0;
}
CProxyMapDlg::~CProxyMapDlg()
{
// 兜底:正常关闭走 OnCancel,已经把监听器停掉并置空;这里只处理没走到 OnCancel 的销毁
// 路径,避免监听线程继续回调一个正在析构的对象。
if (m_iocpLocal) {
m_iocpLocal->Shutdown();
SAFE_DELETE(m_iocpLocal);
}
}
void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
{
__super::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT, m_Edit);
DDX_Control(pDX, IDC_EDIT_OTHER, m_EditOther);
}
BEGIN_MESSAGE_MAP(CProxyMapDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_SIZE()
ON_MESSAGE(WM_PROXY_APPEND_LOG, &CProxyMapDlg::OnProxyLog)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
BOOL CProxyMapDlg::OnInitDialog()
{
__super::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
m_iocpLocal = new CProxyConnectServer;
if (m_iocpLocal == NULL) {
return FALSE;
}
m_Edit.SetLimitText(MAXDWORD);
m_EditOther.SetLimitText(MAXDWORD);
srand((unsigned int)time(NULL));
// 监听端口:先试 5543,被占用就换 10000-65535 的随机端口。
m_nPort = 5543;
BOOL bSuccess = FALSE;
const int nMaxRetries = 10;
for (int i = 0; i < nMaxRetries; ++i) {
if (m_iocpLocal->Initialize(NotifyProc, this, 100000, m_nPort)) {
bSuccess = TRUE;
break;
}
int nextPort = 10000 + (rand() % 55536);
while (nextPort == m_nPort) {
nextPort = 10000 + (rand() % 55536);
}
m_nPort = (USHORT)nextPort;
}
if (!bSuccess) {
MessageBoxL("初始化代理服务器失败!", "提示", MB_ICONINFORMATION);
SAFE_DELETE(m_iocpLocal);
return FALSE;
}
CString strString;
strString.FormatL("%s - 代理服务", m_IPAddress);
SetWindowText(strString);
CString str;
str.FormatL(_T("SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n"), m_nPort);
LogLine(false, str.GetString());
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL) {
pSysMenu->AppendMenuSeparator(MF_SEPARATOR);
pSysMenu->AppendMenuL(MF_STRING, IDM_PROXY_CHROME, _T("代理打开Chrome(请关闭所有Chrome进程)(&P)"));
}
return TRUE;
}
void CProxyMapDlg::OnCancel()
{
m_bIsClosed = true;
// 等待数据处理完毕
if (IsProcessing()) {
ShowWindow(SW_HIDE);
return;
}
if (m_iocpLocal) {
// Shutdown 会等所有本地连接的中继线程退出,之后不会再有回调进来。
m_iocpLocal->Shutdown();
SAFE_DELETE(m_iocpLocal);
}
{
std::lock_guard<std::mutex> lock(m_sessLock);
m_sessions.clear();
}
CancelIO();
DialogBase::OnClose();
}
int CProxyMapDlg::GetSessionState(CONNID id)
{
std::lock_guard<std::mutex> lock(m_sessLock);
auto it = m_sessions.find(id);
return it == m_sessions.end() ? -1 : it->second.state;
}
bool CProxyMapDlg::SetSessionState(CONNID id, int state)
{
std::lock_guard<std::mutex> lock(m_sessLock);
auto it = m_sessions.find(id);
if (it == m_sessions.end())
return false;
it->second.state = state;
return true;
}
void CProxyMapDlg::LogLine(bool other, LPCTSTR text)
{
if (m_bIsClosed || GetSafeHwnd() == NULL || text == NULL)
return;
// 回调可能来自监听/中继线程,控件只能在 UI 线程上碰:转成消息投递。
PostMessage(WM_PROXY_APPEND_LOG, (WPARAM)(other ? 1 : 0), (LPARAM)new CString(text));
}
LRESULT CProxyMapDlg::OnProxyLog(WPARAM wParam, LPARAM lParam)
{
CString* pText = (CString*)lParam;
if (pText == NULL)
return 0;
if (!m_bIsClosed) {
if (wParam == 0)
AppendLog(m_Edit, m_strLog, *pText);
else
AppendLog(m_EditOther, m_strLogOther, *pText);
}
delete pText;
return 0;
}
void CProxyMapDlg::AppendLog(CEdit& edit, CString& buffer, LPCTSTR text)
{
// 模板里两个日志框都是 ES_READONLY(只能选择/复制),EM_REPLACESEL 会被系统忽略,
// 所以自己维护一份文本再整段 SetWindowText。
buffer += text;
if (buffer.GetLength() > MAX_LOG_CHARS) {
buffer = buffer.Right(MAX_LOG_CHARS);
int nl = buffer.Find('\n');
if (nl > 0)
buffer = buffer.Mid(nl + 1); // 从下一行的行首开始,避免半行
}
edit.SetWindowText(buffer);
edit.SetSel(buffer.GetLength(), buffer.GetLength());
edit.SendMessage(EM_SCROLLCARET);
}
BOOL CProxyMapDlg::SendProxyPacket(BYTE token, CONNID id, const BYTE* pData, UINT nLen)
{
if (m_ContextObject == NULL || m_bIsClosed)
return FALSE;
std::vector<BYTE> buf(5 + nLen);
buf[0] = token;
memcpy(&buf[1], &id, sizeof(CONNID));
if (nLen > 0 && pData != NULL)
memcpy(&buf[5], pData, nLen);
return m_ContextObject->Send2Client(buf.data(), (ULONG)buf.size());
}
void CALLBACK CProxyMapDlg::NotifyProc(void* user, CONNID id, const BYTE* pData, UINT nLen, UINT nCode)
{
CProxyMapDlg* dlg = (CProxyMapDlg*)user;
if (dlg == NULL || dlg->m_bIsClosed || dlg->m_iocpLocal == NULL)
return;
try {
switch (nCode) {
case NC_CLIENT_CONNECT:
dlg->OnLocalConnect(id);
break;
case NC_RECEIVE:
dlg->OnLocalReceive(id, pData, nLen);
break;
case NC_CLIENT_DISCONNECT:
dlg->OnLocalDisconnect(id);
break;
default:
break;
}
} catch (...) {
Mprintf("CProxyMapDlg: notify #%u (code %u) raised an exception\n", id, nCode);
}
}
void CProxyMapDlg::OnLocalConnect(CONNID id)
{
{
std::lock_guard<std::mutex> lock(m_sessLock);
m_sessions[id] = LocalSession();
}
CString str;
str.FormatL(_TRF("%u 新连接\r\n"), id);
LogLine(true, str.GetString());
}
void CProxyMapDlg::OnLocalReceive(CONNID id, const BYTE* pData, UINT nLen)
{
if (pData == NULL || nLen == 0)
return;
const int state = GetSessionState(id);
if (state < 0)
return; // 会话已结束(例如刚被断开)
if (state == 2) {
SendProxyPacket(COMMAND_PROXY_DATA, id, pData, nLen);
CString str;
str.FormatL(_TRF("%u <==发 %u bytes\r\n"), id, nLen);
LogLine(true, str.GetString());
return;
}
if (state == 0) {
// 认证阶段:本代理不接受认证,直接回「无认证」。不解析客户端提供了哪些方法。
const BYTE authOk[2] = { SOCKS5_VER, 0x00 };
if (m_iocpLocal->Send(id, authOk, sizeof(authOk)))
SetSessionState(id, 1);
CString str;
str.FormatL(_TRF("%u 返回标示 %u %u\r\n"), id,
nLen > 0 ? pData[0] : 0, nLen > 1 ? pData[1] : 0);
LogLine(true, str.GetString());
return;
}
// state == 1:SOCKS5 CONNECT 请求。VER CMD RSV ATYP DST.ADDR DST.PORT
const BYTE atyp = (nLen > 3) ? pData[3] : 0;
if (nLen < 10 || pData[0] != SOCKS5_VER || pData[1] != SOCKS5_CMD_CONNECT) {
BYTE reply[11] = { SOCKS5_VER, SOCKS5_REP_CMD_UNSUPPORTED, 0, atyp, 0, 0, 0, 0, 0, 0, 0 };
m_iocpLocal->Send(id, reply, sizeof(reply));
m_iocpLocal->Disconnect(id);
CString str;
str.FormatL(_TRF("%u 不符要求, 断开 %u %u %u\r\n"), id,
nLen > 0 ? pData[0] : 0, nLen > 1 ? pData[1] : 0, atyp);
LogLine(true, str.GetString());
return;
}
// 组下发给客户端的 CONNECT 报文:
// IPv4 / 域名: [token][id:4][ip:4][port:2] 与 [token][id:4][port:2][hostname\0]
std::vector<BYTE> packet;
CString str;
if (atyp == SOCKS5_ATYP_IPV4) {
packet.assign(11, 0);
packet[0] = COMMAND_PROXY_CONNECT;
memcpy(&packet[1], &id, sizeof(CONNID));
memcpy(&packet[5], pData + 4, 6); // 4 字节 IPv4 + 2 字节端口
in_addr inaddr = {};
memcpy(&inaddr.s_addr, pData + 4, 4);
char szDest[64] = {};
inet_ntop(AF_INET, &inaddr, szDest, sizeof(szDest));
str.FormatL(_TRF("%u IPV4 连接 %s:%u...\r\n"), id, szDest,
(UINT)ntohs(*(u_short*)(pData + 8)));
} else if (atyp == SOCKS5_ATYP_HOST) {
const int hostLen = pData[4];
if (nLen < (UINT)(5 + hostLen + 2)) {
m_iocpLocal->Disconnect(id);
return;
}
packet.assign(7 + hostLen + 1, 0);
packet[0] = COMMAND_PROXY_CONNECT_HOSTNAME;
memcpy(&packet[1], &id, sizeof(CONNID));
memcpy(&packet[5], pData + 5 + hostLen, 2); // 端口
memcpy(&packet[7], pData + 5, hostLen); // 域名(按 gethostbyname 解析)
str.FormatL(_TRF("%u 域名 连接 %s:%u\r\n"), id, (LPCSTR)&packet[7],
(UINT)ntohs(*(u_short*)(pData + 5 + hostLen)));
} else if (atyp == SOCKS5_ATYP_IPV6) {
const BYTE reply[10] = { SOCKS5_VER, SOCKS5_REP_ATYP_UNSUPPORTED, 0, SOCKS5_ATYP_IPV4, 0, 0, 0, 0, 0, 0 };
m_iocpLocal->Send(id, reply, sizeof(reply));
m_iocpLocal->Disconnect(id);
str.FormatL(_TRF("%u IPV6连接 不支持...\r\n"), id);
LogLine(true, str.GetString());
return;
} else {
m_iocpLocal->Disconnect(id);
return;
}
// 先标记再下发:CONNECT 一旦交给客户端,本地连接断开时就必须回 CLOSE,
// 否则客户端的子连接和目标 socket 会一直挂着。
{
std::lock_guard<std::mutex> lock(m_sessLock);
auto it = m_sessions.find(id);
if (it == m_sessions.end())
return;
it->second.connectSent = true;
}
if (!m_ContextObject->Send2Client(packet.data(), (ULONG)packet.size())) {
m_iocpLocal->Disconnect(id);
return;
}
LogLine(true, str.GetString());
}
void CProxyMapDlg::OnLocalDisconnect(CONNID id)
{
bool connectSent = false;
{
std::lock_guard<std::mutex> lock(m_sessLock);
auto it = m_sessions.find(id);
if (it != m_sessions.end()) {
connectSent = it->second.connectSent;
m_sessions.erase(it);
}
}
// 已经向客户端下发过 CONNECT 的,要通知它关掉目标 socket,否则那条连接会挂在客户端。
if (connectSent)
SendProxyPacket(COMMAND_PROXY_CLOSE, id, NULL, 0);
CString str;
str.FormatL(_TRF("%u 本地连接断开\r\n"), id);
LogLine(true, str.GetString());
}
void CProxyMapDlg::OnReceive()
{
}
void CProxyMapDlg::OnReceiveComplete()
{
if (m_iocpLocal == NULL || !m_iocpLocal->HasStarted() || m_bIsClosed)
return;
LPBYTE buf = m_ContextObject->m_DeCompressionBuffer.GetBuffer(0);
ULONG len = m_ContextObject->m_DeCompressionBuffer.GetBufferLength();
if (len < 5)
return;
CONNID id = 0;
memcpy(&id, &buf[1], sizeof(CONNID));
CString str;
switch (buf[0]) {
case TOKEN_PROXY_CONNECT_RESULT: {
if (len < 11)
break;
// [token][id:4][ip:4][port:2];端口为 0 表示客户端连不上目标。
const bool ok = !(buf[9] == 0 && buf[10] == 0);
BYTE reply[10] = { SOCKS5_VER, (BYTE)(ok ? SOCKS5_REP_SUCCEEDED : SOCKS5_REP_REFUSED), 0, SOCKS5_ATYP_IPV4, 0, 0, 0, 0, 0, 0 };
memcpy(&reply[4], &buf[5], 6);
m_iocpLocal->Send(id, reply, sizeof(reply));
if (ok) {
SetSessionState(id, 2);
str.FormatL(_TRF("%u 连接成功\r\n"), id);
} else {
str.FormatL(_TRF("%u 连接失败\r\n"), id);
}
break;
}
case TOKEN_PROXY_BIND_RESULT:
break;
case TOKEN_PROXY_CLOSE:
str.FormatL(_TRF("%u TOKEN_PROXY_CLOSE\r\n"), id);
m_iocpLocal->Disconnect(id);
break;
case TOKEN_PROXY_DATA:
// 空数据包不转发(Send 对 nSize == 0 直接返回 FALSE,不能当成连接出错)。
if (len <= 5)
break;
if (!m_iocpLocal->Send(id, &buf[5], len - 5)) {
str.FormatL(_TRF("%u TOKEN_PROXY_CLOSE\r\n"), id);
m_iocpLocal->Disconnect(id);
break;
}
str.FormatL(_TRF("%u ==>收 %u bytes\r\n"), id, len - 5);
break;
default:
// 传输发生异常数据
return;
}
if (!str.IsEmpty())
LogLine(false, str.GetString());
}
void CProxyMapDlg::OnSize(UINT nType, int cx, int cy)
{
__super::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if (!IsWindowVisible())
return;
RECT rectClient;
RECT rectEdit = {};
GetClientRect(&rectClient);
rectEdit.left = 0;
rectEdit.top = 0;
rectEdit.right = rectClient.right;
rectEdit.bottom = rectClient.bottom;
m_Edit.MoveWindow(&rectEdit);
}
void CProxyMapDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
CMenu* pSysMenu = GetSystemMenu(FALSE);
switch (nID) {
case IDM_PROXY_CHROME: {
CString strCommand;
strCommand.FormatL(_T(" /c start chrome.exe --show-app-list --proxy-server=\"SOCKS5://127.0.0.1:%d\""), m_nPort);
ShellExecute(NULL, _T("open"), _T("cmd.exe"), strCommand, NULL, SW_SHOW);
}
break;
}
__super::OnSysCommand(nID, lParam);
}