Follow-up to the HP-Socket replacement: the four items the first pass deliberately left out, plus two defects that the new tests turned up. The listener now binds 127.0.0.1 instead of INADDR_ANY. The dialog only ever points the user (and the Chrome shortcut) at 127.0.0.1, and an unauthenticated SOCKS5 port open on every interface is an open proxy. The SOCKS5 handshake is parsed as a byte stream. The previous code assumed one callback carried exactly one message, which happens to hold for curl and Chrome but not in general: a greeting split across segments was answered twice, and a CONNECT request followed by tunnel data in the same read dropped the trailing bytes. Each connection now keeps a pending buffer and a four-state machine (greeting, request, connecting, tunnel), and bytes that arrive before CONNECT_RESULT are replayed to the client once the tunnel opens, after the SOCKS5 reply. Flow control: the listener takes a PROXYCANRECVPROC callback that is consulted before each recv. The dialog answers it from the main connection's send queue, so a download that outruns the client link pauses the local read instead of growing the server's buffer. A 300MB transfer through the tunnel peaks 150KB above the idle working set. Handshake watchdog: sessions that stall in greeting/request/connecting are dropped after 30 seconds; established tunnels are left alone. Two defects in the log path, both surfaced by the watchdog test. Logging every 32KB chunk produced roughly 9000 posted messages for a 300MB transfer, which starved the UI thread's timers (the first watchdog run never fired) and could overflow the message queue; and every line re-set the whole 256KB text into the read-only edit. Transfers now log cumulative progress once per second and a per-connection total at teardown, panes are refreshed at most every 100ms from a dirty flag, and a failed PostMessage no longer leaks its CString. Localization: the new session-log strings were also added to en_US.ini, zh_TW.ini and de_DE.ini (16 keys each, GBK, kept in the existing FormatL section). Two of the lines were reworded instead of translated as-is: the close notice now says what happened (the client asked to close, or the downlink send failed) rather than printing the protocol token name, and the throughput arrows are now << and >> because CIniParser splits an entry at the first '=', so the old <== and ==> could never have served as keys. Testing: curl IPv4 and hostname tunnels, 4MB and 300MB transfers byte-identical, byte-at-a-time and pipelined handshakes, refused target (REP=5), SOCKS client killed mid-transfer, client process killed mid-transfer (dialog closes, port released), 20 parallel connections, five open/close cycles with no handle or thread growth, and the 30s handshake timeout. The dialog log was checked at runtime with Language=en_US and renders in English only. Co-Authored-By: deepseek-flash
632 lines
23 KiB
C++
632 lines
23 KiB
C++
// 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 IDT_PROXY_HANDSHAKE 1
|
|
#define IDT_PROXY_LOG_FLUSH 2
|
|
#define PROXY_HANDSHAKE_TIMEOUT_MS 30000 // 握手/等客户端回结果的时间上限
|
|
#define PROXY_TIMEOUT_TICK_MS 5000 // 超时扫描周期
|
|
#define PROXY_LOG_FLUSH_MS 100 // 日志框合并刷新的窗口
|
|
#define PROXY_MAX_PENDING ((size_t)64 * 1024) // 握手阶段最多缓存的字节数
|
|
#define PROXY_OUTBUF_HIGH_WATER (2 * 1024 * 1024) // 主连接发送队列的高水位
|
|
#define PROXY_LOG_INTERVAL_MS 1000 // 隧道数据进度的打印间隔(每连接)
|
|
|
|
// 人类的字节数。隧道里按 32KB 分片记账,直接打字节数既吵又不好读。
|
|
static CString FormatBytes(ULONGLONG n)
|
|
{
|
|
CString str;
|
|
if (n >= 1024ULL * 1024)
|
|
str.FormatL(_T("%.2f MB"), n / (1024.0 * 1024.0));
|
|
else if (n >= 1024ULL)
|
|
str.FormatL(_T("%.1f KB"), n / 1024.0);
|
|
else
|
|
str.FormatL(_T("%I64u B"), n);
|
|
return str;
|
|
}
|
|
|
|
#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_WM_TIMER()
|
|
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, CanRecvProc, 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)"));
|
|
}
|
|
|
|
// 卡在握手阶段的连接不会自己退出(客户端不回结果、本地对端连上却不发数据),
|
|
// 用定时器统一扫一遍。
|
|
SetTimer(IDT_PROXY_HANDSHAKE, PROXY_TIMEOUT_TICK_MS, NULL);
|
|
|
|
return TRUE;
|
|
}
|
|
|
|
void CProxyMapDlg::OnCancel()
|
|
{
|
|
m_bIsClosed = true;
|
|
// 等待数据处理完毕
|
|
if (IsProcessing()) {
|
|
ShowWindow(SW_HIDE);
|
|
return;
|
|
}
|
|
KillTimer(IDT_PROXY_HANDSHAKE);
|
|
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();
|
|
}
|
|
|
|
void CProxyMapDlg::LogLine(bool other, LPCTSTR text)
|
|
{
|
|
if (m_bIsClosed || GetSafeHwnd() == NULL || text == NULL)
|
|
return;
|
|
// 回调可能来自监听/中继线程,控件只能在 UI 线程上碰:转成消息投递。
|
|
// 队列满(PostMessage 失败)时必须自己释放,否则每丢一条就漏一个 CString。
|
|
CString* pText = new CString(text);
|
|
if (!PostMessage(WM_PROXY_APPEND_LOG, (WPARAM)(other ? 1 : 0), (LPARAM)pText))
|
|
delete pText;
|
|
}
|
|
|
|
LRESULT CProxyMapDlg::OnProxyLog(WPARAM wParam, LPARAM lParam)
|
|
{
|
|
CString* pText = (CString*)lParam;
|
|
if (pText == NULL)
|
|
return 0;
|
|
if (!m_bIsClosed) {
|
|
CString& buffer = (wParam == 0) ? m_strLog : m_strLogOther;
|
|
AppendLog(buffer, *pText);
|
|
// 只累积、不刷控件:日志密集时每行都 SetWindowText 整段文本会把 UI 线程拖死,
|
|
// 攒一小段时间合并刷新一次。
|
|
if (wParam == 0)
|
|
m_bLogDirtyMain = true;
|
|
else
|
|
m_bLogDirtyOther = true;
|
|
if (!m_bLogFlushPending) {
|
|
m_bLogFlushPending = (SetTimer(IDT_PROXY_LOG_FLUSH, PROXY_LOG_FLUSH_MS, NULL) != 0);
|
|
}
|
|
}
|
|
delete pText;
|
|
return 0;
|
|
}
|
|
|
|
void CProxyMapDlg::AppendLog(CString& buffer, LPCTSTR text)
|
|
{
|
|
// 模板里两个日志框都是 ES_READONLY(只能选择/复制),EM_REPLACESEL 会被系统忽略,
|
|
// 所以自己维护一份文本再整段 SetWindowText(见 FlushLog)。
|
|
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); // 从下一行的行首开始,避免半行
|
|
}
|
|
}
|
|
|
|
void CProxyMapDlg::FlushLog()
|
|
{
|
|
m_bLogFlushPending = false;
|
|
if (m_bLogDirtyMain) {
|
|
m_bLogDirtyMain = false;
|
|
m_Edit.SetWindowText(m_strLog);
|
|
m_Edit.SetSel(m_strLog.GetLength(), m_strLog.GetLength());
|
|
m_Edit.SendMessage(EM_SCROLLCARET);
|
|
}
|
|
if (m_bLogDirtyOther) {
|
|
m_bLogDirtyOther = false;
|
|
m_EditOther.SetWindowText(m_strLogOther);
|
|
m_EditOther.SetSel(m_strLogOther.GetLength(), m_strLogOther.GetLength());
|
|
m_EditOther.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);
|
|
}
|
|
}
|
|
|
|
BOOL CALLBACK CProxyMapDlg::CanRecvProc(void* user, CONNID /*id*/)
|
|
{
|
|
CProxyMapDlg* dlg = (CProxyMapDlg*)user;
|
|
if (dlg == NULL || dlg->m_bIsClosed || dlg->m_ContextObject == NULL)
|
|
return FALSE;
|
|
// 主连接的发送队列是异步 WSASend 的源:本机读得比客户端链路快时它会一直涨。
|
|
// 到这里反过来把压力交还给 SOCKS 客户端 —— 暂停 recv,靠 TCP 窗口让浏览器/curl
|
|
// 自己慢下来,避免服务端内存被一个下载任务吃光。
|
|
return dlg->m_ContextObject->OutCompressedBuffer.GetBufferLength() < PROXY_OUTBUF_HIGH_WATER;
|
|
}
|
|
|
|
void CProxyMapDlg::OnLocalConnect(CONNID id)
|
|
{
|
|
LocalSession s;
|
|
s.lastTick = GetTickCount64();
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
m_sessions[id] = s;
|
|
}
|
|
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;
|
|
|
|
std::vector<BYTE> toLocal; // 要回给本机 SOCKS 客户端的应答
|
|
std::vector<BYTE> toClient; // 要下发给客户端的 CONNECT 报文
|
|
std::vector<BYTE> forward; // 隧道阶段要转发的数据
|
|
CString progress; // 隧道进度日志(限流后才有内容)
|
|
bool bClose = false;
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
auto it = m_sessions.find(id);
|
|
if (it == m_sessions.end())
|
|
return; // 会话已结束(例如刚被断开)
|
|
LocalSession& s = it->second;
|
|
s.lastTick = GetTickCount64();
|
|
|
|
if (s.state == ST_TUNNEL) {
|
|
s.bytesToTarget += nLen;
|
|
if (s.lastTick - s.lastLogTick >= PROXY_LOG_INTERVAL_MS) {
|
|
s.lastLogTick = s.lastTick;
|
|
progress.FormatL(_TRF("%u << 上行 %s\r\n"), id, FormatBytes(s.bytesToTarget).GetString());
|
|
}
|
|
forward.assign(pData, pData + nLen);
|
|
} else if (s.pending.size() + nLen > PROXY_MAX_PENDING) {
|
|
// 握手阶段塞进 64KB 还没成帧,不可能是正常的 SOCKS5 客户端。
|
|
bClose = true;
|
|
CString str;
|
|
str.FormatL(_TRF("%u 握手数据过多, 断开\r\n"), id);
|
|
LogLine(true, str.GetString());
|
|
} else {
|
|
s.pending.insert(s.pending.end(), pData, pData + nLen);
|
|
bClose = !ParseSocks5(id, s, toLocal, toClient);
|
|
}
|
|
}
|
|
|
|
// 以下都在锁外:Send/Disconnect 可能触发中继线程的关闭路径,没必要持锁。
|
|
if (!toLocal.empty() && !m_iocpLocal->Send(id, toLocal.data(), (UINT)toLocal.size()))
|
|
bClose = true;
|
|
if (!toClient.empty() && !m_ContextObject->Send2Client(toClient.data(), (ULONG)toClient.size()))
|
|
bClose = true;
|
|
if (!forward.empty()) {
|
|
if (!SendProxyPacket(COMMAND_PROXY_DATA, id, forward.data(), (UINT)forward.size()))
|
|
bClose = true;
|
|
}
|
|
if (!progress.IsEmpty())
|
|
LogLine(true, progress.GetString());
|
|
if (bClose)
|
|
m_iocpLocal->Disconnect(id);
|
|
}
|
|
|
|
// 按 TCP 字节流解析 SOCKS5 握手:一次 recv 可能只到半条消息,也可能把整条消息连着
|
|
// 后续隧道数据一起带出来,所以用状态机 + 待处理缓冲逐条切分,不能假设「一次回调 = 一条消息」。
|
|
// 需要下发的报文放进 toLocal / toClient,由调用方在锁外发送(本函数在 m_sessLock 内调用)。
|
|
bool CProxyMapDlg::ParseSocks5(CONNID id, LocalSession& s,
|
|
std::vector<BYTE>& toLocal, std::vector<BYTE>& toClient)
|
|
{
|
|
for (;;) {
|
|
if (s.state == ST_GREETING) {
|
|
// VER NMETHODS METHODS[NMETHODS]
|
|
if (s.pending.size() < 2)
|
|
return true;
|
|
if (s.pending[0] != SOCKS5_VER)
|
|
return false;
|
|
const size_t need = 2 + (size_t)s.pending[1];
|
|
if (s.pending.size() < need)
|
|
return true;
|
|
const BYTE ver = s.pending[0];
|
|
const BYTE nmethods = s.pending[1];
|
|
s.pending.erase(s.pending.begin(), s.pending.begin() + need);
|
|
|
|
// 本代理不需要认证:直接回「无认证」,不检查客户端提供了哪些方法。
|
|
toLocal.push_back(SOCKS5_VER);
|
|
toLocal.push_back(0x00);
|
|
s.state = ST_REQUEST;
|
|
|
|
CString str;
|
|
str.FormatL(_TRF("%u 返回标示 %u %u\r\n"), id, ver, nmethods);
|
|
LogLine(true, str.GetString());
|
|
continue; // 同一次 recv 里可能已经带着 CONNECT 请求
|
|
}
|
|
|
|
if (s.state != ST_REQUEST)
|
|
return true; // ST_CONNECTING 等结果、ST_TUNNEL 走转发,都不在这里推进
|
|
|
|
// VER CMD RSV ATYP DST.ADDR DST.PORT
|
|
if (s.pending.size() < 4)
|
|
return true;
|
|
const BYTE ver = s.pending[0];
|
|
const BYTE cmd = s.pending[1];
|
|
const BYTE atyp = s.pending[3];
|
|
if (ver != SOCKS5_VER || cmd != SOCKS5_CMD_CONNECT) {
|
|
const BYTE reply[10] = { SOCKS5_VER, SOCKS5_REP_CMD_UNSUPPORTED, 0, atyp, 0, 0, 0, 0, 0, 0 };
|
|
toLocal.assign(reply, reply + sizeof(reply));
|
|
CString str;
|
|
str.FormatL(_TRF("%u 不符要求, 断开 %u %u %u\r\n"), id, ver, cmd, atyp);
|
|
LogLine(true, str.GetString());
|
|
return false;
|
|
}
|
|
|
|
std::vector<BYTE> packet;
|
|
CString str;
|
|
if (atyp == SOCKS5_ATYP_IPV4) {
|
|
if (s.pending.size() < 10)
|
|
return true;
|
|
packet.assign(11, 0);
|
|
packet[0] = COMMAND_PROXY_CONNECT;
|
|
memcpy(&packet[1], &id, sizeof(CONNID));
|
|
memcpy(&packet[5], &s.pending[4], 6); // 4 字节 IPv4 + 2 字节端口
|
|
s.pending.erase(s.pending.begin(), s.pending.begin() + 10);
|
|
|
|
in_addr inaddr = {};
|
|
memcpy(&inaddr.s_addr, &packet[5], 4);
|
|
char szDest[INET_ADDRSTRLEN] = {};
|
|
inet_ntop(AF_INET, &inaddr, szDest, sizeof(szDest));
|
|
u_short port = 0;
|
|
memcpy(&port, &packet[9], 2);
|
|
str.FormatL(_TRF("%u IPV4 连接 %s:%u...\r\n"), id, szDest, (UINT)ntohs(port));
|
|
} else if (atyp == SOCKS5_ATYP_HOST) {
|
|
const size_t hostLen = s.pending.size() > 4 ? s.pending[4] : 0;
|
|
if (hostLen == 0)
|
|
return false;
|
|
const size_t need = 5 + hostLen + 2;
|
|
if (s.pending.size() < need)
|
|
return true;
|
|
|
|
packet.assign(7 + hostLen + 1, 0); // 末尾补的 1 字节是域名的 '\0'
|
|
packet[0] = COMMAND_PROXY_CONNECT_HOSTNAME;
|
|
memcpy(&packet[1], &id, sizeof(CONNID));
|
|
memcpy(&packet[5], &s.pending[5 + hostLen], 2); // 端口
|
|
memcpy(&packet[7], &s.pending[5], hostLen); // 域名(客户端按 gethostbyname 解析)
|
|
s.pending.erase(s.pending.begin(), s.pending.begin() + need);
|
|
|
|
u_short port = 0;
|
|
memcpy(&port, &packet[5], 2);
|
|
str.FormatL(_TRF("%u 域名 连接 %s:%u\r\n"), id, (LPCSTR)&packet[7], (UINT)ntohs(port));
|
|
} 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 };
|
|
toLocal.assign(reply, reply + sizeof(reply));
|
|
str.FormatL(_TRF("%u IPV6连接 不支持...\r\n"), id);
|
|
LogLine(true, str.GetString());
|
|
return false;
|
|
} else {
|
|
return false;
|
|
}
|
|
|
|
// 先置 connectSent 再由调用方下发:CONNECT 一旦发出,本地连接断开时就必须回 CLOSE,
|
|
// 否则客户端的子连接和目标 socket 会一直挂着。
|
|
s.connectSent = true;
|
|
s.state = ST_CONNECTING;
|
|
// pending 里可能已经粘着隧道数据,等客户端回 CONNECT_RESULT 后再转发(见 OnReceiveComplete)。
|
|
toClient.swap(packet);
|
|
LogLine(true, str.GetString());
|
|
return true;
|
|
}
|
|
}
|
|
|
|
void CProxyMapDlg::OnLocalDisconnect(CONNID id)
|
|
{
|
|
bool connectSent = false;
|
|
ULONGLONG up = 0, down = 0;
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
auto it = m_sessions.find(id);
|
|
if (it != m_sessions.end()) {
|
|
connectSent = it->second.connectSent;
|
|
up = it->second.bytesToTarget;
|
|
down = it->second.bytesFromTarget;
|
|
m_sessions.erase(it);
|
|
}
|
|
}
|
|
// 已经向客户端下发过 CONNECT 的,要通知它关掉目标 socket,否则那条连接会挂在客户端。
|
|
if (connectSent)
|
|
SendProxyPacket(COMMAND_PROXY_CLOSE, id, NULL, 0);
|
|
|
|
CString str;
|
|
if (up != 0 || down != 0) {
|
|
str.FormatL(_TRF("%u 本地连接断开 (上行 %s, 下行 %s)\r\n"), id,
|
|
FormatBytes(up).GetString(), FormatBytes(down).GetString());
|
|
} else {
|
|
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));
|
|
|
|
// 进入隧道阶段,取走握手期间粘在 CONNECT 请求后面的字节。
|
|
std::vector<BYTE> buffered;
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
auto it = m_sessions.find(id);
|
|
if (it != m_sessions.end()) {
|
|
it->second.lastTick = GetTickCount64();
|
|
if (ok) {
|
|
it->second.state = ST_TUNNEL;
|
|
buffered.swap(it->second.pending);
|
|
it->second.bytesToTarget += buffered.size(); // 记账要和转发一致
|
|
} else {
|
|
it->second.pending.clear();
|
|
}
|
|
}
|
|
}
|
|
// 应答先于数据:SOCKS5 客户端要等到应答才认为隧道可用(curl 甚至会先等这条
|
|
// 10 字节回复再发请求),顺序反了它会把数据当垃圾丢掉。
|
|
if (ok && !buffered.empty())
|
|
SendProxyPacket(COMMAND_PROXY_DATA, id, buffered.data(), (UINT)buffered.size());
|
|
if (ok)
|
|
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 客户端请求断开\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 下行发送失败, 断开\r\n"), id);
|
|
m_iocpLocal->Disconnect(id);
|
|
break;
|
|
}
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
auto it = m_sessions.find(id);
|
|
if (it != m_sessions.end()) {
|
|
LocalSession& s = it->second;
|
|
s.bytesFromTarget += len - 5;
|
|
const ULONGLONG now = GetTickCount64();
|
|
if (now - s.lastLogTick >= PROXY_LOG_INTERVAL_MS) {
|
|
s.lastLogTick = now;
|
|
str.FormatL(_TRF("%u >> 下行 %s\r\n"), id, FormatBytes(s.bytesFromTarget).GetString());
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
default:
|
|
// 传输发生异常数据
|
|
return;
|
|
}
|
|
if (!str.IsEmpty())
|
|
LogLine(false, str.GetString());
|
|
}
|
|
|
|
void CProxyMapDlg::OnTimer(UINT_PTR nIDEvent)
|
|
{
|
|
if (nIDEvent == IDT_PROXY_LOG_FLUSH) {
|
|
// 一次性定时器:攒够一批日志就刷新控件。
|
|
KillTimer(IDT_PROXY_LOG_FLUSH);
|
|
FlushLog();
|
|
} else if (nIDEvent == IDT_PROXY_HANDSHAKE && m_iocpLocal != NULL && !m_bIsClosed) {
|
|
// 握手(含 CONNECTING 等客户端回结果)卡住就清掉,免得每点一次页面就在
|
|
// 服务端留一条永远不动的本地连接。隧道阶段是长连接,不参与超时。
|
|
const ULONGLONG now = GetTickCount64();
|
|
std::vector<CONNID> stale;
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_sessLock);
|
|
for (auto& kv : m_sessions) {
|
|
if (kv.second.state != ST_TUNNEL &&
|
|
now - kv.second.lastTick > PROXY_HANDSHAKE_TIMEOUT_MS) {
|
|
stale.push_back(kv.first);
|
|
}
|
|
}
|
|
}
|
|
for (CONNID id : stale) {
|
|
CString str;
|
|
str.FormatL(_TRF("%u 握手超时, 断开\r\n"), id);
|
|
LogLine(true, str.GetString());
|
|
m_iocpLocal->Disconnect(id);
|
|
}
|
|
}
|
|
__super::OnTimer(nIDEvent);
|
|
}
|
|
|
|
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);
|
|
}
|