Improve: Harden the self-implemented SOCKS5 proxy listener
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
This commit is contained in:
1 parent
45e1dd9f6c
commit
5bff9df3fc
7 files changed
+409
-134
No files matched your search
@@ -978,6 +978,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS-Proxy-Server: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u Neue Verbindung\r\n
|
||||
%u 返回标示 %u %u\r\n=%u Begruessung Antwort %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPv4 Verbindung %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u Hostname Verbindung %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPv6 nicht unterstuetzt...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u Ungueltige Anfrage, Trennung %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u Verbunden\r\n
|
||||
%u 连接失败\r\n=%u Verbindung fehlgeschlagen\r\n
|
||||
%u 握手超时, 断开\r\n=%u Handshake-Timeout, Trennung\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u Zu viele Handshake-Daten, Trennung\r\n
|
||||
%u 本地连接断开\r\n=%u Lokale Verbindung getrennt\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u Lokale Verbindung getrennt (gesendet %s, empfangen %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << gesendet %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> empfangen %s\r\n
|
||||
%u 客户端请求断开\r\n=%u Client fordert Trennung\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u Senden an Client fehlgeschlagen, Trennung\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
|
||||
@@ -982,6 +982,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS proxy server: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u New connection\r\n
|
||||
%u 返回标示 %u %u\r\n=%u Greeting reply %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPv4 connect %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u Hostname connect %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPv6 unsupported...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u Bad request, disconnecting %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u Connected\r\n
|
||||
%u 连接失败\r\n=%u Connection failed\r\n
|
||||
%u 握手超时, 断开\r\n=%u Handshake timeout, disconnecting\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u Too much handshake data, disconnecting\r\n
|
||||
%u 本地连接断开\r\n=%u Local connection closed\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u Local connection closed (sent %s, received %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << sent %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> received %s\r\n
|
||||
%u 客户端请求断开\r\n=%u Client requested disconnect\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u Downlink send failed, disconnecting\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
|
||||
@@ -980,6 +980,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS 代理軟體請設定伺服器為: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u 新連線\r\n
|
||||
%u 返回标示 %u %u\r\n=%u 回覆標示 %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPV4 連線 %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u 網域 連線 %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPV6連線 不支援...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u 不符要求, 中斷 %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u 連線成功\r\n
|
||||
%u 连接失败\r\n=%u 連線失敗\r\n
|
||||
%u 握手超时, 断开\r\n=%u 握手逾時, 中斷\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u 握手資料過多, 中斷\r\n
|
||||
%u 本地连接断开\r\n=%u 本端連線中斷\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u 本端連線中斷 (上行 %s, 下行 %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << 上行 %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> 下行 %s\r\n
|
||||
%u 客户端请求断开\r\n=%u 用戶端請求中斷\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u 下行傳送失敗, 中斷\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "stdafx.h"
|
||||
#include "ProxyConnectServer.h"
|
||||
|
||||
#include <chrono>
|
||||
|
||||
#define PROXY_RECV_CHUNK (16 * 1024) // 单次 recv 的上限
|
||||
#define PROXY_POLL_MS 200 // select 轮询周期,决定 Shutdown/Disconnect 的响应时延
|
||||
#define PROXY_SEND_TIMEOUT_MS 5000 // 向本机连接发送的超时,避免卡住调用方线程
|
||||
@@ -26,7 +28,8 @@ BOOL CProxyConnectServer::SetSocketOptions(SOCKET s) const
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, int nMaxConnections, int nPort)
|
||||
BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, PROXYCANRECVPROC pCanRecvProc,
|
||||
void* pUser, int nMaxConnections, int nPort)
|
||||
{
|
||||
if (m_bRunning.load(std::memory_order_acquire))
|
||||
return FALSE;
|
||||
@@ -47,7 +50,9 @@ BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, i
|
||||
|
||||
sockaddr_in addr = {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = INADDR_ANY; // 与原 HP-Socket 版一致:0.0.0.0
|
||||
// 只监听回环。本代理没有认证,绑 0.0.0.0 会把本机变成一个对局域网/公网开放的
|
||||
// SOCKS5 出口;而对话框的提示、Chrome 启动参数用的都是 127.0.0.1,没有远程使用场景。
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
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());
|
||||
@@ -65,6 +70,7 @@ BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, i
|
||||
SetSocketOptions(s);
|
||||
|
||||
m_pNotifyProc = pNotifyProc;
|
||||
m_pCanRecvProc = pCanRecvProc;
|
||||
m_pUser = pUser;
|
||||
m_nMaxConnection = nMaxConnections;
|
||||
m_nPort = (USHORT)nPort;
|
||||
@@ -72,7 +78,7 @@ BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, i
|
||||
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);
|
||||
Mprintf("CProxyConnectServer: listening on 127.0.0.1:%d\n", nPort);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -145,6 +151,13 @@ void CProxyConnectServer::RelayLoop(std::shared_ptr<Conn> pConn)
|
||||
std::vector<BYTE> buf(PROXY_RECV_CHUNK);
|
||||
|
||||
while (!pConn->stop.load(std::memory_order_acquire)) {
|
||||
// 流控:下游(主连接发往客户端的队列)堆积时不收数据,让本机连接的对端按
|
||||
// TCP 窗口自己减速。这里只是暂停 recv,socket 不关,Disconnect/Shutdown 仍有效。
|
||||
if (m_pCanRecvProc != nullptr && !m_pCanRecvProc(m_pUser, pConn->id)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(PROXY_POLL_MS));
|
||||
continue;
|
||||
}
|
||||
|
||||
fd_set readSet;
|
||||
FD_ZERO(&readSet);
|
||||
FD_SET(pConn->sock, &readSet);
|
||||
|
||||
@@ -39,14 +39,22 @@ typedef uint32_t CONNID;
|
||||
// 不保证对齐 SOCKS5 消息边界);其余 nCode 下 pData == nullptr、nLen == 0。
|
||||
typedef void (CALLBACK* PROXYNOTIFYPROC)(void* pUser, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
|
||||
// 流控回调:中继线程每轮 recv 之前问一次「现在还能不能收」。返回 FALSE 时暂停
|
||||
// 读取(不 recv),让本机连接的对端按 TCP 窗口自行减速;返回 TRUE 后恢复。
|
||||
// 在本机连接的中继线程上调用,要求实现足够轻量、线程安全。
|
||||
typedef BOOL (CALLBACK* PROXYCANRECVPROC)(void* pUser, CONNID id);
|
||||
|
||||
class CProxyConnectServer
|
||||
{
|
||||
public:
|
||||
CProxyConnectServer();
|
||||
~CProxyConnectServer();
|
||||
|
||||
// 绑定 0.0.0.0:nPort 并开始 accept。nMaxConnections <= 0 表示不限制。
|
||||
BOOL Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, int nMaxConnections, int nPort);
|
||||
// 绑定 127.0.0.1:nPort 并开始 accept。nMaxConnections <= 0 表示不限制。
|
||||
// 只监听回环:这是个无认证的 SOCKS5 入口,绑 0.0.0.0 等于对局域网/公网开放代理;
|
||||
// 对话框里给用户的提示也是「代理服务器填 127.0.0.1」。
|
||||
BOOL Initialize(PROXYNOTIFYPROC pNotifyProc, PROXYCANRECVPROC pCanRecvProc,
|
||||
void* pUser, int nMaxConnections, int nPort);
|
||||
|
||||
// 停止监听、断开全部连接、等待所有线程退出。可重复调用。
|
||||
void Shutdown();
|
||||
@@ -88,6 +96,7 @@ private:
|
||||
std::thread m_acceptThread;
|
||||
std::atomic<bool> m_bRunning{ false };
|
||||
PROXYNOTIFYPROC m_pNotifyProc = nullptr;
|
||||
PROXYCANRECVPROC m_pCanRecvProc = nullptr; // 可为空,表示不限流
|
||||
void* m_pUser = nullptr;
|
||||
|
||||
std::mutex m_connLock;
|
||||
|
||||
@@ -17,6 +17,28 @@
|
||||
|
||||
#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
|
||||
@@ -54,6 +76,7 @@ void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
|
||||
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()
|
||||
|
||||
@@ -81,7 +104,7 @@ BOOL CProxyMapDlg::OnInitDialog()
|
||||
BOOL bSuccess = FALSE;
|
||||
const int nMaxRetries = 10;
|
||||
for (int i = 0; i < nMaxRetries; ++i) {
|
||||
if (m_iocpLocal->Initialize(NotifyProc, this, 100000, m_nPort)) {
|
||||
if (m_iocpLocal->Initialize(NotifyProc, CanRecvProc, this, 100000, m_nPort)) {
|
||||
bSuccess = TRUE;
|
||||
break;
|
||||
}
|
||||
@@ -112,6 +135,10 @@ BOOL CProxyMapDlg::OnInitDialog()
|
||||
pSysMenu->AppendMenuL(MF_STRING, IDM_PROXY_CHROME, _T("代理打开Chrome(请关闭所有Chrome进程)(&P)"));
|
||||
}
|
||||
|
||||
// 卡在握手阶段的连接不会自己退出(客户端不回结果、本地对端连上却不发数据),
|
||||
// 用定时器统一扫一遍。
|
||||
SetTimer(IDT_PROXY_HANDSHAKE, PROXY_TIMEOUT_TICK_MS, NULL);
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -123,6 +150,7 @@ void CProxyMapDlg::OnCancel()
|
||||
ShowWindow(SW_HIDE);
|
||||
return;
|
||||
}
|
||||
KillTimer(IDT_PROXY_HANDSHAKE);
|
||||
if (m_iocpLocal) {
|
||||
// Shutdown 会等所有本地连接的中继线程退出,之后不会再有回调进来。
|
||||
m_iocpLocal->Shutdown();
|
||||
@@ -138,29 +166,15 @@ void CProxyMapDlg::OnCancel()
|
||||
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));
|
||||
// 队列满(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)
|
||||
@@ -169,19 +183,26 @@ LRESULT CProxyMapDlg::OnProxyLog(WPARAM wParam, LPARAM 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)
|
||||
AppendLog(m_Edit, m_strLog, *pText);
|
||||
m_bLogDirtyMain = true;
|
||||
else
|
||||
AppendLog(m_EditOther, m_strLogOther, *pText);
|
||||
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(CEdit& edit, CString& buffer, LPCTSTR text)
|
||||
void CProxyMapDlg::AppendLog(CString& buffer, LPCTSTR text)
|
||||
{
|
||||
// 模板里两个日志框都是 ES_READONLY(只能选择/复制),EM_REPLACESEL 会被系统忽略,
|
||||
// 所以自己维护一份文本再整段 SetWindowText。
|
||||
// 所以自己维护一份文本再整段 SetWindowText(见 FlushLog)。
|
||||
buffer += text;
|
||||
if (buffer.GetLength() > MAX_LOG_CHARS) {
|
||||
buffer = buffer.Right(MAX_LOG_CHARS);
|
||||
@@ -189,9 +210,23 @@ void CProxyMapDlg::AppendLog(CEdit& edit, CString& buffer, LPCTSTR text)
|
||||
if (nl > 0)
|
||||
buffer = buffer.Mid(nl + 1); // 从下一行的行首开始,避免半行
|
||||
}
|
||||
edit.SetWindowText(buffer);
|
||||
edit.SetSel(buffer.GetLength(), buffer.GetLength());
|
||||
edit.SendMessage(EM_SCROLLCARET);
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -231,11 +266,24 @@ void CALLBACK CProxyMapDlg::NotifyProc(void* user, CONNID id, const BYTE* pData,
|
||||
}
|
||||
}
|
||||
|
||||
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] = LocalSession();
|
||||
m_sessions[id] = s;
|
||||
}
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 新连接\r\n"), id);
|
||||
@@ -247,107 +295,171 @@ 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; // 会话已结束(例如刚被断开)
|
||||
std::vector<BYTE> toLocal; // 要回给本机 SOCKS 客户端的应答
|
||||
std::vector<BYTE> toClient; // 要下发给客户端的 CONNECT 报文
|
||||
std::vector<BYTE> forward; // 隧道阶段要转发的数据
|
||||
CString progress; // 隧道进度日志(限流后才有内容)
|
||||
bool bClose = false;
|
||||
|
||||
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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
if (!m_ContextObject->Send2Client(packet.data(), (ULONG)packet.size())) {
|
||||
|
||||
// 以下都在锁外: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);
|
||||
return;
|
||||
}
|
||||
|
||||
// 按 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;
|
||||
}
|
||||
LogLine(true, str.GetString());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -356,7 +468,12 @@ void CProxyMapDlg::OnLocalDisconnect(CONNID id)
|
||||
SendProxyPacket(COMMAND_PROXY_CLOSE, id, NULL, 0);
|
||||
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 本地连接断开\r\n"), id);
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -387,18 +504,37 @@ void CProxyMapDlg::OnReceiveComplete()
|
||||
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);
|
||||
|
||||
// 进入隧道阶段,取走握手期间粘在 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 TOKEN_PROXY_CLOSE\r\n"), id);
|
||||
str.FormatL(_TRF("%u 客户端请求断开\r\n"), id);
|
||||
m_iocpLocal->Disconnect(id);
|
||||
break;
|
||||
case TOKEN_PROXY_DATA:
|
||||
@@ -406,11 +542,23 @@ void CProxyMapDlg::OnReceiveComplete()
|
||||
if (len <= 5)
|
||||
break;
|
||||
if (!m_iocpLocal->Send(id, &buf[5], len - 5)) {
|
||||
str.FormatL(_TRF("%u TOKEN_PROXY_CLOSE\r\n"), id);
|
||||
str.FormatL(_TRF("%u 下行发送失败, 断开\r\n"), id);
|
||||
m_iocpLocal->Disconnect(id);
|
||||
break;
|
||||
}
|
||||
str.FormatL(_TRF("%u ==>收 %u bytes\r\n"), id, len - 5);
|
||||
{
|
||||
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:
|
||||
// 传输发生异常数据
|
||||
@@ -420,6 +568,36 @@ void CProxyMapDlg::OnReceiveComplete()
|
||||
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);
|
||||
|
||||
@@ -25,6 +25,8 @@ public:
|
||||
|
||||
// 监听器回调(运行在 accept 线程 / 每连接中继线程内)
|
||||
static void CALLBACK NotifyProc(void* user, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
// 流控回调(运行在该连接的中继线程内):主连接发送队列堆积时暂停读取本地连接
|
||||
static BOOL CALLBACK CanRecvProc(void* user, CONNID id);
|
||||
|
||||
void OnReceiveComplete();
|
||||
void OnReceive();
|
||||
@@ -33,30 +35,49 @@ public:
|
||||
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
|
||||
virtual BOOL OnInitDialog();
|
||||
afx_msg void OnSize(UINT nType, int cx, int cy);
|
||||
afx_msg void OnTimer(UINT_PTR nIDEvent);
|
||||
afx_msg LRESULT OnProxyLog(WPARAM wParam, LPARAM lParam);
|
||||
DECLARE_MESSAGE_MAP()
|
||||
|
||||
private:
|
||||
// 每条本机连接在「本地侧」的状态。SOCKS5 握手在这里推进:
|
||||
// 0 待认证(等客户端的 VER/NMETHODS)
|
||||
// 1 已回「无需认证」,等 CONNECT 请求
|
||||
// 2 隧道(CONNECT 已下发且客户端回连成功),之后全是裸数据
|
||||
// SOCKS5 握手的阶段。只有 ST_TUNNEL 之后流里才是裸数据。
|
||||
enum {
|
||||
ST_GREETING = 0, // 等客户端的 VER/NMETHODS
|
||||
ST_REQUEST = 1, // 已回「无需认证」,等 CONNECT 请求
|
||||
ST_CONNECTING = 2, // CONNECT 已交给客户端,等它回结果
|
||||
ST_TUNNEL = 3 // 隧道已建立,字节原样转发
|
||||
};
|
||||
|
||||
// 每条本机连接的「本地侧」状态。
|
||||
struct LocalSession {
|
||||
int state = 0;
|
||||
bool connectSent = false; // 是否已向客户端下发过 CONNECT(决定断开时要不要回 CLOSE)
|
||||
int state = ST_GREETING;
|
||||
bool connectSent = false; // 是否已向客户端下发过 CONNECT(决定断开时要不要回 CLOSE)
|
||||
ULONGLONG lastTick = 0; // 最近一次收到数据 / 状态推进的时刻(GetTickCount64)
|
||||
// 隧道字节数(连接结束时打一行汇总)。分片级日志会淹没界面、拖慢 UI 线程,
|
||||
// 300MB 的下载能产生上万条消息。
|
||||
ULONGLONG bytesToTarget = 0; // 本机 -> 客户端
|
||||
ULONGLONG bytesFromTarget = 0; // 客户端 -> 本机
|
||||
ULONGLONG lastLogTick = 0; // 上次打印进度日志的时刻
|
||||
// 握手阶段攒下的字节。TCP 是流:一次 recv 可能是半条消息,也可能连隧道数据一起
|
||||
// 带过来,所以先攒着,按状态机逐条切分。
|
||||
std::vector<BYTE> pending;
|
||||
};
|
||||
|
||||
void OnLocalConnect(CONNID id);
|
||||
void OnLocalReceive(CONNID id, const BYTE* pData, UINT nLen);
|
||||
void OnLocalDisconnect(CONNID id);
|
||||
// 按 SOCKS5 字节流推进握手。需要下发的报文放进 toLocal(回本机客户端)/
|
||||
// toClient(发给客户端的 CONNECT),由调用方在锁外发送。
|
||||
// 返回 false 表示协议不符,调用方应断开这条连接。
|
||||
bool ParseSocks5(CONNID id, LocalSession& s, std::vector<BYTE>& toLocal, std::vector<BYTE>& toClient);
|
||||
|
||||
// 组 [token][id:4][payload] 发给客户端(与客户端 CProxyManager 的协议一致)。
|
||||
BOOL SendProxyPacket(BYTE token, CONNID id, const BYTE* pData, UINT nLen);
|
||||
int GetSessionState(CONNID id);
|
||||
bool SetSessionState(CONNID id, int state);
|
||||
void LogLine(bool other, LPCTSTR text);
|
||||
// 日志框是只读的(EM_REPLACESEL 无效),文本先在 buffer 里累积再整段写入。
|
||||
void AppendLog(CEdit& edit, CString& buffer, LPCTSTR text);
|
||||
// 日志框是只读的(EM_REPLACESEL 无效),文本先在 buffer 里累积,再由 FlushLog
|
||||
// 合并刷进控件(每行都 SetWindowText 会拖死 UI 线程)。
|
||||
void AppendLog(CString& buffer, LPCTSTR text);
|
||||
void FlushLog();
|
||||
|
||||
CProxyConnectServer* m_iocpLocal;
|
||||
CEdit m_Edit;
|
||||
@@ -69,4 +90,7 @@ private:
|
||||
// 两个日志框的全文(只在 UI 线程读写)。
|
||||
CString m_strLog;
|
||||
CString m_strLogOther;
|
||||
bool m_bLogDirtyMain = false;
|
||||
bool m_bLogDirtyOther = false;
|
||||
bool m_bLogFlushPending = false;
|
||||
};
|
||||
Reference in new issue
Block a user