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:
1 parent
13c02fe50b
commit
45e1dd9f6c
10 files changed
+676
-5218
No files matched your search
@@ -8480,10 +8480,6 @@ LRESULT CMy2015RemoteDlg::OnOpenKeyboardDialog(WPARAM wParam, LPARAM lParam)
|
||||
|
||||
LRESULT CMy2015RemoteDlg::OnOpenProxyDialog(WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
if (!ENABLE_HPSOCKET) {
|
||||
ShowMessage("Operation Failed", "This feature is unavailable due to HPSocket disabled");
|
||||
return S_OK;
|
||||
}
|
||||
return OpenDialog<CProxyMapDlg, IDD_PROXY>(wParam, lParam);
|
||||
}
|
||||
|
||||
|
||||
@@ -344,11 +344,8 @@
|
||||
<ClInclude Include="PluginSettingsDlg.h" />
|
||||
<ClInclude Include="PreviewTipWnd.h" />
|
||||
<ClInclude Include="TriggerSettingsDlg.h" />
|
||||
<ClInclude Include="proxy\HPSocket.h" />
|
||||
<ClInclude Include="proxy\HPTypeDef.h" />
|
||||
<ClInclude Include="proxy\ProxyConnectServer.h" />
|
||||
<ClInclude Include="proxy\ProxyMapDlg.h" />
|
||||
<ClInclude Include="proxy\SocketInterface.h" />
|
||||
<ClInclude Include="pwd_gen.h" />
|
||||
<ClInclude Include="RegisterDlg.h" />
|
||||
<ClInclude Include="Resource.h" />
|
||||
|
||||
@@ -125,11 +125,8 @@
|
||||
<ClInclude Include="ZstaPickerDlg.h" />
|
||||
<ClInclude Include="IOCPServer.h" />
|
||||
<ClInclude Include="KeyBoardDlg.h" />
|
||||
<ClInclude Include="proxy\HPSocket.h" />
|
||||
<ClInclude Include="proxy\HPTypeDef.h" />
|
||||
<ClInclude Include="proxy\ProxyConnectServer.h" />
|
||||
<ClInclude Include="proxy\ProxyMapDlg.h" />
|
||||
<ClInclude Include="proxy\SocketInterface.h" />
|
||||
<ClInclude Include="pwd_gen.h" />
|
||||
<ClInclude Include="RegisterDlg.h" />
|
||||
<ClInclude Include="Resource.h" />
|
||||
|
||||
@@ -1,821 +0,0 @@
|
||||
/*
|
||||
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
|
||||
*
|
||||
* Author : Bruce Liang
|
||||
* Website : https://github.com/ldcsaa
|
||||
* Project : https://github.com/ldcsaa/HP-Socket
|
||||
* Blog : http://www.cnblogs.com/ldcsaa
|
||||
* Wiki : http://www.oschina.net/p/hp-socket
|
||||
* QQ Group : 44636872, 75375912
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/******************************************************************************
|
||||
Module: HPSocket
|
||||
|
||||
Usage:
|
||||
方法一:
|
||||
--------------------------------------------------------------------------------------
|
||||
0. 应用程序包含 HPTypeDef.h / SocketInterface.h / HPSocket.h 头文件
|
||||
1. 调用 HP_Create_Xxx() 函数创建 HPSocket 对象
|
||||
2. 使用完毕后调用 HP_Destroy_Xxx() 函数销毁 HPSocket 对象
|
||||
|
||||
方法二:
|
||||
--------------------------------------------------------------------------------------
|
||||
0. 应用程序包含 SocketInterface.h 和 HPSocket.h 头文件
|
||||
1. 创建 CXxxPtr 智能指针,通过智能指针使用 HPSocket 对象
|
||||
|
||||
Release:
|
||||
<-- 动态链接库 -->
|
||||
1. x86/HPSocket.dll - (32位/MBCS/Release)
|
||||
2. x86/HPSocket_D.dll - (32位/MBCS/DeBug)
|
||||
3. x86/HPSocket_U.dll - (32位/UNICODE/Release)
|
||||
4. x86/HPSocket_UD.dll - (32位/UNICODE/DeBug)
|
||||
5. x64/HPSocket.dll - (64位/MBCS/Release)
|
||||
6. x64/HPSocket_D.dll - (64位/MBCS/DeBug)
|
||||
7. x64/HPSocket_U.dll - (64位/UNICODE/Release)
|
||||
8. x64/HPSocket_UD.dll - (64位/UNICODE/DeBug)
|
||||
|
||||
<-- 静态链接库 -->
|
||||
!!注意!!:使用 HPSocket 静态库时,需要在工程属性中定义预处理宏 -> HPSOCKET_STATIC_LIB
|
||||
1. x86/static/HPSocket.lib - (32位/MBCS/Release)
|
||||
2. x86/static/HPSocket_D.lib - (32位/MBCS/DeBug)
|
||||
3. x86/static/HPSocket_U.lib - (32位/UNICODE/Release)
|
||||
4. x86/static/HPSocket_UD.lib - (32位/UNICODE/DeBug)
|
||||
5. x64/static/HPSocket.lib - (64位/MBCS/Release)
|
||||
6. x64/static/HPSocket_D.lib - (64位/MBCS/DeBug)
|
||||
7. x64/static/HPSocket_U.lib - (64位/UNICODE/Release)
|
||||
8. x64/static/HPSocket_UD.lib - (64位/UNICODE/DeBug)
|
||||
|
||||
******************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "SocketInterface.h"
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/****************************************************************** TCP/UDP Exports ******************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/**************************************************/
|
||||
/************** HPSocket 对象智能指针 **************/
|
||||
|
||||
template<class T, class _Listener, class _Creator> class CHPObjectPtr
|
||||
{
|
||||
public:
|
||||
CHPObjectPtr& Reset(T* pObj = nullptr)
|
||||
{
|
||||
if(pObj != m_pObj) {
|
||||
if(m_pObj)
|
||||
_Creator::Destroy(m_pObj);
|
||||
|
||||
m_pObj = pObj;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
CHPObjectPtr& Attach(T* pObj)
|
||||
{
|
||||
return Reset(pObj);
|
||||
}
|
||||
|
||||
T* Detach()
|
||||
{
|
||||
T* pObj = m_pObj;
|
||||
m_pObj = nullptr;
|
||||
|
||||
return pObj;
|
||||
}
|
||||
|
||||
BOOL IsValid () const
|
||||
{
|
||||
return m_pObj != nullptr ;
|
||||
}
|
||||
T* Get () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
T* operator -> () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
operator T* () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
|
||||
CHPObjectPtr& operator = (T* pObj)
|
||||
{
|
||||
return Reset(pObj) ;
|
||||
}
|
||||
|
||||
public:
|
||||
CHPObjectPtr(_Listener* pListener = nullptr)
|
||||
{
|
||||
m_pObj = _Creator::Create(pListener);
|
||||
}
|
||||
|
||||
CHPObjectPtr(BOOL bCreate, _Listener* pListener = nullptr)
|
||||
{
|
||||
m_pObj = bCreate ? _Creator::Create(pListener) : nullptr;
|
||||
}
|
||||
|
||||
virtual ~CHPObjectPtr()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
private:
|
||||
CHPObjectPtr(const CHPObjectPtr&);
|
||||
CHPObjectPtr& operator = (const CHPObjectPtr&);
|
||||
|
||||
protected:
|
||||
T* m_pObj;
|
||||
};
|
||||
|
||||
/**************************************************/
|
||||
/**************** HPSocket 导出函数 ****************/
|
||||
|
||||
// 创建 ITcpServer 对象
|
||||
HPSOCKET_API ITcpServer* HP_Create_TcpServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpAgent 对象
|
||||
HPSOCKET_API ITcpAgent* HP_Create_TcpAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpClient 对象
|
||||
HPSOCKET_API ITcpClient* HP_Create_TcpClient(ITcpClientListener* pListener);
|
||||
// 创建 ITcpPullServer 对象
|
||||
HPSOCKET_API ITcpPullServer* HP_Create_TcpPullServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpPullAgent 对象
|
||||
HPSOCKET_API ITcpPullAgent* HP_Create_TcpPullAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpPullClient 对象
|
||||
HPSOCKET_API ITcpPullClient* HP_Create_TcpPullClient(ITcpClientListener* pListener);
|
||||
// 创建 ITcpPackServer 对象
|
||||
HPSOCKET_API ITcpPackServer* HP_Create_TcpPackServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpPackAgent 对象
|
||||
HPSOCKET_API ITcpPackAgent* HP_Create_TcpPackAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpPackClient 对象
|
||||
HPSOCKET_API ITcpPackClient* HP_Create_TcpPackClient(ITcpClientListener* pListener);
|
||||
|
||||
// 销毁 ITcpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpServer(ITcpServer* pServer);
|
||||
// 销毁 ITcpAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpAgent(ITcpAgent* pAgent);
|
||||
// 销毁 ITcpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpClient(ITcpClient* pClient);
|
||||
// 销毁 ITcpPullServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullServer(ITcpPullServer* pServer);
|
||||
// 销毁 ITcpPullAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullAgent(ITcpPullAgent* pAgent);
|
||||
// 销毁 ITcpPullClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullClient(ITcpPullClient* pClient);
|
||||
// 销毁 ITcpPackServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackServer(ITcpPackServer* pServer);
|
||||
// 销毁 ITcpPackAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackAgent(ITcpPackAgent* pAgent);
|
||||
// 销毁 ITcpPackClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackClient(ITcpPackClient* pClient);
|
||||
|
||||
#ifdef _UDP_SUPPORT
|
||||
|
||||
// 创建 IUdpServer 对象
|
||||
HPSOCKET_API IUdpServer* HP_Create_UdpServer(IUdpServerListener* pListener);
|
||||
// 创建 IUdpClient 对象
|
||||
HPSOCKET_API IUdpClient* HP_Create_UdpClient(IUdpClientListener* pListener);
|
||||
// 创建 IUdpCast 对象
|
||||
HPSOCKET_API IUdpCast* HP_Create_UdpCast(IUdpCastListener* pListener);
|
||||
// 创建 IUdpNode 对象
|
||||
HPSOCKET_API IUdpNode* HP_Create_UdpNode(IUdpNodeListener* pListener);
|
||||
// 创建 IUdpArqServer 对象
|
||||
HPSOCKET_API IUdpArqServer* HP_Create_UdpArqServer(IUdpServerListener* pListener);
|
||||
// 创建 IUdpArqClient 对象
|
||||
HPSOCKET_API IUdpArqClient* HP_Create_UdpArqClient(IUdpClientListener* pListener);
|
||||
|
||||
// 销毁 IUdpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpServer(IUdpServer* pServer);
|
||||
// 销毁 IUdpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpClient(IUdpClient* pClient);
|
||||
// 销毁 IUdpCast 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpCast(IUdpCast* pCast);
|
||||
// 销毁 IUdpNode 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpNode(IUdpNode* pNode);
|
||||
// 销毁 IUdpArqServer 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpArqServer(IUdpArqServer* pServer);
|
||||
// 销毁 IUdpArqClient 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpArqClient(IUdpArqClient* pClient);
|
||||
|
||||
#endif
|
||||
|
||||
// ITcpServer 对象创建器
|
||||
struct TcpServer_Creator {
|
||||
static ITcpServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpAgent 对象创建器
|
||||
struct TcpAgent_Creator {
|
||||
static ITcpAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpClient 对象创建器
|
||||
struct TcpClient_Creator {
|
||||
static ITcpClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullServer 对象创建器
|
||||
struct TcpPullServer_Creator {
|
||||
static ITcpPullServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpPullServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullAgent 对象创建器
|
||||
struct TcpPullAgent_Creator {
|
||||
static ITcpPullAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpPullAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullClient 对象创建器
|
||||
struct TcpPullClient_Creator {
|
||||
static ITcpPullClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpPullClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackServer 对象创建器
|
||||
struct TcpPackServer_Creator {
|
||||
static ITcpPackServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpPackServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackAgent 对象创建器
|
||||
struct TcpPackAgent_Creator {
|
||||
static ITcpPackAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpPackAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackClient 对象创建器
|
||||
struct TcpPackClient_Creator {
|
||||
static ITcpPackClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpPackClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpServer, ITcpServerListener, TcpServer_Creator> CTcpServerPtr;
|
||||
// ITcpAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpAgent, ITcpAgentListener, TcpAgent_Creator> CTcpAgentPtr;
|
||||
// ITcpClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpClient, ITcpClientListener, TcpClient_Creator> CTcpClientPtr;
|
||||
// ITcpPullServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullServer, ITcpServerListener, TcpPullServer_Creator> CTcpPullServerPtr;
|
||||
// ITcpPullAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullAgent, ITcpAgentListener, TcpPullAgent_Creator> CTcpPullAgentPtr;
|
||||
// ITcpPullClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullClient, ITcpClientListener, TcpPullClient_Creator> CTcpPullClientPtr;
|
||||
// ITcpPackServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackServer, ITcpServerListener, TcpPackServer_Creator> CTcpPackServerPtr;
|
||||
// ITcpPackAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackAgent, ITcpAgentListener, TcpPackAgent_Creator> CTcpPackAgentPtr;
|
||||
// ITcpPackClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackClient, ITcpClientListener, TcpPackClient_Creator> CTcpPackClientPtr;
|
||||
|
||||
#ifdef _UDP_SUPPORT
|
||||
|
||||
// IUdpServer 对象创建器
|
||||
struct UdpServer_Creator {
|
||||
static IUdpServer* Create(IUdpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpServer* pServer)
|
||||
{
|
||||
HP_Destroy_UdpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpClient 对象创建器
|
||||
struct UdpClient_Creator {
|
||||
static IUdpClient* Create(IUdpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpClient* pClient)
|
||||
{
|
||||
HP_Destroy_UdpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpCast 对象创建器
|
||||
struct UdpCast_Creator {
|
||||
static IUdpCast* Create(IUdpCastListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpCast(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpCast* pCast)
|
||||
{
|
||||
HP_Destroy_UdpCast(pCast);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpNode 对象创建器
|
||||
struct UdpNode_Creator {
|
||||
static IUdpNode* Create(IUdpNodeListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpNode(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpNode* pNode)
|
||||
{
|
||||
HP_Destroy_UdpNode(pNode);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpArqServer 对象创建器
|
||||
struct UdpArqServer_Creator {
|
||||
static IUdpArqServer* Create(IUdpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpArqServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpArqServer* pServer)
|
||||
{
|
||||
HP_Destroy_UdpArqServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpArqClient 对象创建器
|
||||
struct UdpArqClient_Creator {
|
||||
static IUdpArqClient* Create(IUdpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpArqClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpArqClient* pClient)
|
||||
{
|
||||
HP_Destroy_UdpArqClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpServer 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpServer, IUdpServerListener, UdpServer_Creator> CUdpServerPtr;
|
||||
// IUdpClient 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpClient, IUdpClientListener, UdpClient_Creator> CUdpClientPtr;
|
||||
// IUdpCast 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpCast, IUdpCastListener, UdpCast_Creator> CUdpCastPtr;
|
||||
// IUdpNode 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpNode, IUdpNodeListener, UdpNode_Creator> CUdpNodePtr;
|
||||
// IUdpArqServer 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpArqServer, IUdpServerListener, UdpArqServer_Creator> CUdpArqServerPtr;
|
||||
// IUdpArqClient 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpArqClient, IUdpClientListener, UdpArqClient_Creator> CUdpArqClientPtr;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/*************************************************************** Global Function Exports *************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
// 获取 HPSocket 版本号(4 个字节分别为:主版本号,子版本号,修正版本号,构建编号)
|
||||
HPSOCKET_API DWORD HP_GetHPSocketVersion();
|
||||
|
||||
// 获取错误描述文本
|
||||
HPSOCKET_API LPCTSTR HP_GetSocketErrorDesc(EnSocketError enCode);
|
||||
// 调用系统的 GetLastError() 方法获取系统错误代码
|
||||
HPSOCKET_API DWORD SYS_GetLastError ();
|
||||
// 调用系统的 WSAGetLastError() 方法获取系统错误代码
|
||||
HPSOCKET_API int SYS_WSAGetLastError();
|
||||
// 调用系统的 setsockopt()
|
||||
HPSOCKET_API int SYS_SetSocketOption(SOCKET sock, int level, int name, LPVOID val, int len);
|
||||
// 调用系统的 getsockopt()
|
||||
HPSOCKET_API int SYS_GetSocketOption(SOCKET sock, int level, int name, LPVOID val, int* len);
|
||||
// 调用系统的 ioctlsocket()
|
||||
HPSOCKET_API int SYS_IoctlSocket(SOCKET sock, long cmd, ULONG* arg);
|
||||
// 调用系统的 WSAIoctl()
|
||||
HPSOCKET_API int SYS_WSAIoctl(SOCKET sock, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned);
|
||||
|
||||
// 设置 socket 选项:IPPROTO_TCP -> TCP_NODELAY
|
||||
HPSOCKET_API int SYS_SSO_NoDelay(SOCKET sock, BOOL bNoDelay);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_DONTLINGER
|
||||
HPSOCKET_API int SYS_SSO_DontLinger(SOCKET sock, BOOL bDont);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_LINGER
|
||||
HPSOCKET_API int SYS_SSO_Linger(SOCKET sock, USHORT l_onoff, USHORT l_linger);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_RCVBUF
|
||||
HPSOCKET_API int SYS_SSO_RecvBuffSize(SOCKET sock, int size);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_SNDBUF
|
||||
HPSOCKET_API int SYS_SSO_SendBuffSize(SOCKET sock, int size);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_RCVTIMEO
|
||||
HPSOCKET_API int SYS_SSO_RecvTimeOut(SOCKET sock, int ms);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_SNDTIMEO
|
||||
HPSOCKET_API int SYS_SSO_SendTimeOut(SOCKET sock, int ms);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_EXCLUSIVEADDRUSE / SO_REUSEADDR
|
||||
HPSOCKET_API int SYS_SSO_ReuseAddress(SOCKET sock, EnReuseAddressPolicy opt);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_EXCLUSIVEADDRUSE
|
||||
HPSOCKET_API int SYS_SSO_ExclusiveAddressUse(SOCKET sock, BOOL bExclusive);
|
||||
|
||||
// 获取 SOCKET 本地地址信息
|
||||
HPSOCKET_API BOOL SYS_GetSocketLocalAddress(SOCKET socket, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
|
||||
// 获取 SOCKET 远程地址信息
|
||||
HPSOCKET_API BOOL SYS_GetSocketRemoteAddress(SOCKET socket, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
|
||||
|
||||
/* 枚举主机 IP 地址 */
|
||||
HPSOCKET_API BOOL SYS_EnumHostIPAddresses(LPCTSTR lpszHost, EnIPAddrType enType, LPTIPAddr** lpppIPAddr, int& iIPAddrCount);
|
||||
/* 释放 LPTIPAddr* */
|
||||
HPSOCKET_API BOOL SYS_FreeHostIPAddresses(LPTIPAddr* lppIPAddr);
|
||||
/* 检查字符串是否符合 IP 地址格式 */
|
||||
HPSOCKET_API BOOL SYS_IsIPAddress(LPCTSTR lpszAddress, EnIPAddrType* penType = nullptr);
|
||||
/* 通过主机名获取 IP 地址 */
|
||||
HPSOCKET_API BOOL SYS_GetIPAddress(LPCTSTR lpszHost, TCHAR lpszIP[], int& iIPLenth, EnIPAddrType& enType);
|
||||
|
||||
/* 64 位网络字节序转主机字节序 */
|
||||
HPSOCKET_API ULONGLONG SYS_NToH64(ULONGLONG value);
|
||||
/* 64 位主机字节序转网络字节序 */
|
||||
HPSOCKET_API ULONGLONG SYS_HToN64(ULONGLONG value);
|
||||
/* 短整型高低字节交换 */
|
||||
HPSOCKET_API USHORT SYS_SwapEndian16(USHORT value);
|
||||
/* 长整型高低字节交换 */
|
||||
HPSOCKET_API DWORD SYS_SwapEndian32(DWORD value);
|
||||
/* 检查是否小端字节序 */
|
||||
HPSOCKET_API BOOL SYS_IsLittleEndian();
|
||||
|
||||
/* 分配内存 */
|
||||
HPSOCKET_API LPBYTE SYS_Malloc(int size);
|
||||
/* 重新分配内存 */
|
||||
HPSOCKET_API LPBYTE SYS_Realloc(LPBYTE p, int size);
|
||||
/* 释放内存 */
|
||||
HPSOCKET_API VOID SYS_Free(LPBYTE p);
|
||||
/* 分配内存块 */
|
||||
HPSOCKET_API LPVOID SYS_Calloc(int number, int size);
|
||||
|
||||
// CP_XXX -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_CodePageToUnicodeEx(int iCodePage, const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> CP_XXX
|
||||
HPSOCKET_API BOOL SYS_UnicodeToCodePageEx(int iCodePage, const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// GBK -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_GbkToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> GBK
|
||||
HPSOCKET_API BOOL SYS_UnicodeToGbkEx(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// UTF8 -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_Utf8ToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> UTF8
|
||||
HPSOCKET_API BOOL SYS_UnicodeToUtf8Ex(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// GBK -> UTF8
|
||||
HPSOCKET_API BOOL SYS_GbkToUtf8Ex(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// UTF8 -> GBK
|
||||
HPSOCKET_API BOOL SYS_Utf8ToGbkEx(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
|
||||
// CP_XXX -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_CodePageToUnicode(int iCodePage, const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> CP_XXX
|
||||
HPSOCKET_API BOOL SYS_UnicodeToCodePage(int iCodePage, const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// GBK -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_GbkToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> GBK
|
||||
HPSOCKET_API BOOL SYS_UnicodeToGbk(const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// UTF8 -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_Utf8ToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> UTF8
|
||||
HPSOCKET_API BOOL SYS_UnicodeToUtf8(const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// GBK -> UTF8
|
||||
HPSOCKET_API BOOL SYS_GbkToUtf8(const char szSrc[], char szDest[], int& iDestLength);
|
||||
// UTF8 -> GBK
|
||||
HPSOCKET_API BOOL SYS_Utf8ToGbk(const char szSrc[], char szDest[], int& iDestLength);
|
||||
|
||||
// 计算 Base64 编码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessBase64EncodeBound(DWORD dwSrcLen);
|
||||
// 计算 Base64 解码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessBase64DecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// Base64 编码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_Base64Encode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Base64 解码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_Base64Decode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
|
||||
// 计算 URL 编码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessUrlEncodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// 计算 URL 解码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessUrlDecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// URL 编码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_UrlEncode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// URL 解码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_UrlDecode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
|
||||
#ifdef _ZLIB_SUPPORT
|
||||
|
||||
// 普通压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
// (默认参数:iLevel -> -1,iMethod -> 8,iWindowBits -> 15,iMemLevel -> 8,iStrategy -> 0)
|
||||
HPSOCKET_API int SYS_Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 高级压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iLevel -> -1,iMethod -> 8,iWindowBits -> 15,iMemLevel -> 8,iStrategy -> 0)
|
||||
HPSOCKET_API int SYS_CompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iLevel = -1, int iMethod = 8, int iWindowBits = 15, int iMemLevel = 8, int iStrategy = 0);
|
||||
// 普通解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iWindowBits -> 15)
|
||||
HPSOCKET_API int SYS_Uncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 高级解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iWindowBits -> 15)
|
||||
HPSOCKET_API int SYS_UncompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iWindowBits = 15);
|
||||
// 推测压缩结果长度
|
||||
HPSOCKET_API DWORD SYS_GuessCompressBound(DWORD dwSrcLen, BOOL bGZip = FALSE);
|
||||
|
||||
// Gzip 压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_GZipCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Gzip 解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_GZipUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 推测 Gzip 解压结果长度(如果返回 0 或不合理值则说明输入内容并非有效的 Gzip 格式)
|
||||
HPSOCKET_API DWORD SYS_GZipGuessUncompressBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef _BROTLI_SUPPORT
|
||||
|
||||
// Brotli 压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
// (默认参数:iQuality -> 11,iWindow -> 22,iMode -> 0)
|
||||
HPSOCKET_API int SYS_BrotliCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Brotli 高级压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iQuality -> 11,iWindow -> 22,iMode -> 0)
|
||||
HPSOCKET_API int SYS_BrotliCompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iQuality = 11, int iWindow = 22, int iMode = 0);
|
||||
// Brotli 解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_BrotliUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Brotli 推测压缩结果长度
|
||||
HPSOCKET_API DWORD SYS_BrotliGuessCompressBound(DWORD dwSrcLen);
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/******************************************************************** HTTP Exports *******************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _HTTP_SUPPORT
|
||||
|
||||
// 创建 IHttpServer 对象
|
||||
HPSOCKET_API IHttpServer* HP_Create_HttpServer(IHttpServerListener* pListener);
|
||||
// 创建 IHttpAgent 对象
|
||||
HPSOCKET_API IHttpAgent* HP_Create_HttpAgent(IHttpAgentListener* pListener);
|
||||
// 创建 IHttpClient 对象
|
||||
HPSOCKET_API IHttpClient* HP_Create_HttpClient(IHttpClientListener* pListener);
|
||||
// 创建 IHttpSyncClient 对象
|
||||
HPSOCKET_API IHttpSyncClient* HP_Create_HttpSyncClient(IHttpClientListener* pListener = nullptr);
|
||||
|
||||
// 销毁 IHttpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpServer(IHttpServer* pServer);
|
||||
// 销毁 IHttpAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpAgent(IHttpAgent* pAgent);
|
||||
// 销毁 IHttpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpClient(IHttpClient* pClient);
|
||||
// 销毁 IHttpSyncClient 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpSyncClient(IHttpSyncClient* pClient);
|
||||
|
||||
// IHttpServer 对象创建器
|
||||
struct HttpServer_Creator {
|
||||
static IHttpServer* Create(IHttpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpServer* pServer)
|
||||
{
|
||||
HP_Destroy_HttpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpAgent 对象创建器
|
||||
struct HttpAgent_Creator {
|
||||
static IHttpAgent* Create(IHttpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_HttpAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpClient 对象创建器
|
||||
struct HttpClient_Creator {
|
||||
static IHttpClient* Create(IHttpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpClient* pClient)
|
||||
{
|
||||
HP_Destroy_HttpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpSyncClient 对象创建器
|
||||
struct HttpSyncClient_Creator {
|
||||
static IHttpSyncClient* Create(IHttpClientListener* pListener = nullptr)
|
||||
{
|
||||
return HP_Create_HttpSyncClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpSyncClient* pClient)
|
||||
{
|
||||
HP_Destroy_HttpSyncClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpServer 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpServer, IHttpServerListener, HttpServer_Creator> CHttpServerPtr;
|
||||
// IHttpAgent 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpAgent, IHttpAgentListener, HttpAgent_Creator> CHttpAgentPtr;
|
||||
// IHttpClient 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpClient, IHttpClientListener, HttpClient_Creator> CHttpClientPtr;
|
||||
// IHttpSyncClient 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpSyncClient, IHttpClientListener, HttpSyncClient_Creator> CHttpSyncClientPtr;
|
||||
|
||||
/**************************************************************************/
|
||||
/*************************** HTTP Cookie 管理方法 **************************/
|
||||
|
||||
/* 从文件加载 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_LoadFromFile(LPCSTR lpszFile, BOOL bKeepExists = TRUE);
|
||||
/* 保存 Cookie 到文件 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_SaveToFile(LPCSTR lpszFile, BOOL bKeepExists = TRUE);
|
||||
/* 清理 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_ClearCookies(LPCSTR lpszDomain = nullptr, LPCSTR lpszPath = nullptr);
|
||||
/* 清理过期 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_RemoveExpiredCookies(LPCSTR lpszDomain = nullptr, LPCSTR lpszPath = nullptr);
|
||||
/* 设置 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_SetCookie(LPCSTR lpszName, LPCSTR lpszValue, LPCSTR lpszDomain, LPCSTR lpszPath, int iMaxAge = -1, BOOL bHttpOnly = FALSE, BOOL bSecure = FALSE, int enSameSite = 0, BOOL bOnlyUpdateValueIfExists = TRUE);
|
||||
/* 删除 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_DeleteCookie(LPCSTR lpszDomain, LPCSTR lpszPath, LPCSTR lpszName);
|
||||
/* 设置是否允许第三方 Cookie */
|
||||
HPSOCKET_API void HP_HttpCookie_MGR_SetEnableThirdPartyCookie(BOOL bEnableThirdPartyCookie = TRUE);
|
||||
/* 检查是否允许第三方 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_IsEnableThirdPartyCookie();
|
||||
|
||||
/* Cookie expires 字符串转换为整数 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_ParseExpires(LPCSTR lpszExpires, __time64_t& tmExpires);
|
||||
/* 整数转换为 Cookie expires 字符串 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_MakeExpiresStr(char lpszBuff[], int& iBuffLen, __time64_t tmExpires);
|
||||
/* 生成 Cookie 字符串 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_ToString(char lpszBuff[], int& iBuffLen, LPCSTR lpszName, LPCSTR lpszValue, LPCSTR lpszDomain, LPCSTR lpszPath, int iMaxAge /*= -1*/, BOOL bHttpOnly /*= FALSE*/, BOOL bSecure /*= FALSE*/, int enSameSite /*= 0*/);
|
||||
/* 获取当前 UTC 时间 */
|
||||
HPSOCKET_API __time64_t HP_HttpCookie_HLP_CurrentUTCTime();
|
||||
/* Max-Age -> expires */
|
||||
HPSOCKET_API __time64_t HP_HttpCookie_HLP_MaxAgeToExpires(int iMaxAge);
|
||||
/* expires -> Max-Age */
|
||||
HPSOCKET_API int HP_HttpCookie_HLP_ExpiresToMaxAge(__time64_t tmExpires);
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/************************************************************* HTTP Global Function Exports **********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** Thread Pool Exports ****************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
// 创建 IHPThreadPool 对象
|
||||
HPSOCKET_API IHPThreadPool* HP_Create_ThreadPool(IHPThreadPoolListener* pListener = nullptr);
|
||||
// 销毁 IHPThreadPool 对象
|
||||
HPSOCKET_API void HP_Destroy_ThreadPool(IHPThreadPool* pThreadPool);
|
||||
|
||||
/*
|
||||
* 名称:创建 TSocketTask 对象
|
||||
* 描述:创建任务对象,该对象最终需由 HP_Destroy_SocketTaskObj() 销毁
|
||||
*
|
||||
* 参数: fnTaskProc -- 任务处理函数
|
||||
* pSender -- 发起对象
|
||||
* dwConnID -- 连接 ID
|
||||
* pBuffer -- 数据缓冲区
|
||||
* iBuffLen -- 数据缓冲区长度
|
||||
* enBuffType -- 数据缓冲区类型(默认:TBT_COPY)
|
||||
* TBT_COPY :(深拷贝)pBuffer 复制到 TSocketTask 对象。此后 TSocketTask 对象与 pBuffer 不再有任何关联
|
||||
* -> 适用于 pBuffer 不大或 pBuffer 生命周期不受控的场景
|
||||
* TBT_REFER :(浅拷贝)pBuffer 不复制到 TSocketTask 对象,需确保 TSocketTask 对象生命周期内 pBuffer 必须有效
|
||||
* -> 适用于 pBuffer 较大或 pBuffer 可重用,并且 pBuffer 生命周期受控的场景
|
||||
* TBT_ATTACH :(附属)执行浅拷贝,但 TSocketTask 对象会获得 pBuffer 的所有权,并负责释放 pBuffer,避免多次缓冲区拷贝
|
||||
* -> 注意:pBuffer 必须由 SYS_Malloc()/SYS_Calloc() 函数分配才能使用本类型,否则可能会发生内存访问错误
|
||||
* wParam -- 自定义参数
|
||||
* lParam -- 自定义参数
|
||||
* 返回值: LPTSocketTask
|
||||
*/
|
||||
HPSOCKET_API LPTSocketTask HP_Create_SocketTaskObj(Fn_SocketTaskProc fnTaskProc, PVOID pSender, CONNID dwConnID, LPCBYTE pBuffer, INT iBuffLen, EnTaskBufferType enBuffType = TBT_COPY, WPARAM wParam = 0, LPARAM lParam = 0);
|
||||
|
||||
// 销毁 TSocketTask 对象
|
||||
HPSOCKET_API void HP_Destroy_SocketTaskObj(LPTSocketTask pTask);
|
||||
|
||||
// IHPThreadPool 对象创建器
|
||||
struct HPThreadPool_Creator {
|
||||
static IHPThreadPool* Create(IHPThreadPoolListener* pListener = nullptr)
|
||||
{
|
||||
return HP_Create_ThreadPool(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHPThreadPool* pThreadPool)
|
||||
{
|
||||
HP_Destroy_ThreadPool(pThreadPool);
|
||||
}
|
||||
};
|
||||
|
||||
// IHPThreadPool 对象智能指针
|
||||
typedef CHPObjectPtr<IHPThreadPool, IHPThreadPoolListener, HPThreadPool_Creator> CHPThreadPoolPtr;
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/********************************************************* Compressor / Decompressor Exports *********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/* 销毁压缩器对象 */
|
||||
HPSOCKET_API void HP_Destroy_Compressor(IHPCompressor* pCompressor);
|
||||
/* 销毁解压器对象 */
|
||||
HPSOCKET_API void HP_Destroy_Decompressor(IHPDecompressor* pDecompressor);
|
||||
|
||||
#ifdef _ZLIB_SUPPORT
|
||||
|
||||
/* 创建 ZLib 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_ZLibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits = 15, int iLevel = -1, int iMethod = 8, int iMemLevel = 8, int iStrategy = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 GZip 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_GZipCompressor(Fn_CompressDataCallback fnCallback, int iLevel = -1, int iMethod = 8, int iMemLevel = 8, int iStrategy = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 ZLib 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_ZLibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits = 15, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 GZip 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_GZipDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize = 16 * 1024);
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef _BROTLI_SUPPORT
|
||||
|
||||
/* 创建 Brotli 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_BrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality = 11, int iWindow = 22, int iMode = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 Brotli 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_BrotliDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize = 16 * 1024);
|
||||
|
||||
#endif
|
||||
@@ -1,571 +0,0 @@
|
||||
/*
|
||||
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
|
||||
*
|
||||
* Author : Bruce Liang
|
||||
* Website : https://github.com/ldcsaa
|
||||
* Project : https://github.com/ldcsaa/HP-Socket
|
||||
* Blog : http://www.cnblogs.com/ldcsaa
|
||||
* Wiki : http://www.oschina.net/p/hp-socket
|
||||
* QQ Group : 44636872, 75375912
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
/* HP-Socket 版本号 */
|
||||
#define HP_VERSION_MAJOR 6 // 主版本号
|
||||
#define HP_VERSION_MINOR 0 // 子版本号
|
||||
#define HP_VERSION_REVISE 3 // 修正版本号
|
||||
#define HP_VERSION_BUILD 1 // 构建编号
|
||||
|
||||
//#define _UDP_DISABLED // 禁用 UDP
|
||||
//#define _SSL_DISABLED // 禁用 SSL
|
||||
//#define _HTTP_DISABLED // 禁用 HTTP
|
||||
//#define _ZLIB_DISABLED // 禁用 ZLIB
|
||||
//#define _BROTLI_DISABLED // 禁用 BROTLI
|
||||
|
||||
/* 是否启用 UDP,如果定义了 _UDP_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_UDP_DISABLED)
|
||||
#ifndef _UDP_SUPPORT
|
||||
#define _UDP_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 SSL,如果定义了 _SSL_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_SSL_DISABLED)
|
||||
#ifndef _SSL_SUPPORT
|
||||
#define _SSL_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 HTTP,如果定义了 _HTTP_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_HTTP_DISABLED)
|
||||
#ifndef _HTTP_SUPPORT
|
||||
#define _HTTP_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 ZLIB,如果定义了 _ZLIB_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_ZLIB_DISABLED)
|
||||
#ifndef _ZLIB_SUPPORT
|
||||
#define _ZLIB_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 BROTLI,如果定义了 _BROTLI_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_BROTLI_DISABLED)
|
||||
#ifndef _BROTLI_SUPPORT
|
||||
#define _BROTLI_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/**************************************************/
|
||||
/********** imports / exports HPSocket4C **********/
|
||||
|
||||
#ifdef HPSOCKET_STATIC_LIB
|
||||
#define HPSOCKET_API EXTERN_C
|
||||
#else
|
||||
#ifdef HPSOCKET_EXPORTS
|
||||
#define HPSOCKET_API EXTERN_C __declspec(dllexport)
|
||||
#else
|
||||
#define HPSOCKET_API EXTERN_C __declspec(dllimport)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define __HP_CALL __stdcall
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** Base Type Definitions **************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
typedef const BYTE* LPCBYTE, PCBYTE;
|
||||
typedef ULONG_PTR TID, THR_ID, NTHR_ID, PID, PRO_ID;
|
||||
|
||||
/************************************************************************
|
||||
名称:连接 ID 数据类型
|
||||
描述:应用程序可以把 CONNID 定义为自身需要的类型(如:ULONG / ULONGLONG)
|
||||
************************************************************************/
|
||||
typedef ULONG_PTR CONNID, HP_CONNID;
|
||||
|
||||
/************************************************************************
|
||||
名称:通信组件服务状态
|
||||
描述:应用程序可以通过通信组件的 GetState() 方法获取组件当前服务状态
|
||||
************************************************************************/
|
||||
typedef enum EnServiceState {
|
||||
SS_STARTING = 0, // 正在启动
|
||||
SS_STARTED = 1, // 已经启动
|
||||
SS_STOPPING = 2, // 正在停止
|
||||
SS_STOPPED = 3, // 已经停止
|
||||
} En_HP_ServiceState;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 操作类型
|
||||
描述:应用程序的 OnClose() 事件中通过该参数标识是哪种操作导致的错误
|
||||
************************************************************************/
|
||||
typedef enum EnSocketOperation {
|
||||
SO_UNKNOWN = 0, // Unknown
|
||||
SO_ACCEPT = 1, // Acccept
|
||||
SO_CONNECT = 2, // Connect
|
||||
SO_SEND = 3, // Send
|
||||
SO_RECEIVE = 4, // Receive
|
||||
SO_CLOSE = 5, // Close
|
||||
} En_HP_SocketOperation;
|
||||
|
||||
/************************************************************************
|
||||
名称:事件处理结果
|
||||
描述:事件的返回值,不同的返回值会影响通信组件的后续行为
|
||||
************************************************************************/
|
||||
typedef enum EnHandleResult {
|
||||
HR_OK = 0, // 成功
|
||||
HR_IGNORE = 1, // 忽略
|
||||
HR_ERROR = 2, // 错误
|
||||
} En_HP_HandleResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:数据抓取结果
|
||||
描述:数据抓取操作的返回值
|
||||
************************************************************************/
|
||||
typedef enum EnFetchResult {
|
||||
FR_OK = 0, // 成功
|
||||
FR_LENGTH_TOO_LONG = 1, // 抓取长度过大
|
||||
FR_DATA_NOT_FOUND = 2, // 找不到 ConnID 对应的数据
|
||||
} En_HP_FetchResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:数据发送策略
|
||||
描述:Server 组件和 Agent 组件的数据发送策略
|
||||
|
||||
* 打包发送策略(默认) :尽量把多个发送操作的数据组合在一起发送,增加传输效率
|
||||
* 安全发送策略 :尽量把多个发送操作的数据组合在一起发送,并控制传输速度,避免缓冲区溢出
|
||||
* 直接发送策略 :对每一个发送操作都直接投递,适用于负载不高但要求实时性较高的场合
|
||||
************************************************************************/
|
||||
typedef enum EnSendPolicy {
|
||||
SP_PACK = 0, // 打包模式(默认)
|
||||
SP_SAFE = 1, // 安全模式
|
||||
SP_DIRECT = 2, // 直接模式
|
||||
} En_HP_SendPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:OnSend 事件同步策略
|
||||
描述:Server 组件和 Agent 组件的 OnSend 事件同步策略
|
||||
|
||||
* 不同步(默认) :不同步 OnSend 事件,可能同时触发 OnReceive 和 OnClose 事件
|
||||
* 同步 OnClose :只同步 OnClose 事件,可能同时触发 OnReceive 事件
|
||||
* 同步 OnReceive :(只用于 TCP 组件)同步 OnReceive 和 OnClose 事件,不可能同时触发 OnReceive 或 OnClose 事件
|
||||
************************************************************************/
|
||||
typedef enum EnOnSendSyncPolicy {
|
||||
OSSP_NONE = 0, // 不同步(默认)
|
||||
OSSP_CLOSE = 1, // 同步 OnClose
|
||||
OSSP_RECEIVE = 2, // 同步 OnReceive(只用于 TCP 组件)
|
||||
} En_HP_OnSendSyncPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:地址重用选项
|
||||
描述:通信组件底层 socket 的地址重用选项
|
||||
************************************************************************/
|
||||
typedef enum EnReuseAddressPolicy {
|
||||
RAP_NONE = 0, // 不重用
|
||||
RAP_ADDR_ONLY = 1, // 仅重用地址
|
||||
RAP_ADDR_AND_PORT = 2, // 重用地址和端口
|
||||
} En_HP_ReuseAddressPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:操作结果代码
|
||||
描述:组件 Start() / Stop() 方法执行失败时,可通过 GetLastError() 获取错误代码
|
||||
************************************************************************/
|
||||
typedef enum EnSocketError {
|
||||
SE_OK = NO_ERROR, // 成功
|
||||
SE_ILLEGAL_STATE = 1, // 当前状态不允许操作
|
||||
SE_INVALID_PARAM = 2, // 非法参数
|
||||
SE_SOCKET_CREATE = 3, // 创建 SOCKET 失败
|
||||
SE_SOCKET_BIND = 4, // 绑定 SOCKET 失败
|
||||
SE_SOCKET_PREPARE = 5, // 设置 SOCKET 失败
|
||||
SE_SOCKET_LISTEN = 6, // 监听 SOCKET 失败
|
||||
SE_CP_CREATE = 7, // 创建完成端口失败
|
||||
SE_WORKER_THREAD_CREATE = 8, // 创建工作线程失败
|
||||
SE_DETECT_THREAD_CREATE = 9, // 创建监测线程失败
|
||||
SE_SOCKE_ATTACH_TO_CP = 10, // 绑定完成端口失败
|
||||
SE_CONNECT_SERVER = 11, // 连接服务器失败
|
||||
SE_NETWORK = 12, // 网络错误
|
||||
SE_DATA_PROC = 13, // 数据处理错误
|
||||
SE_DATA_SEND = 14, // 数据发送失败
|
||||
SE_GC_START = 15, // 垃圾回收启动失败
|
||||
|
||||
/***** SSL Socket 扩展操作结果代码 *****/
|
||||
SE_SSL_ENV_NOT_READY = 101, // SSL 环境未就绪
|
||||
} En_HP_SocketError;
|
||||
|
||||
/************************************************************************
|
||||
名称:播送模式
|
||||
描述:UDP 组件的播送模式(组播或广播)
|
||||
************************************************************************/
|
||||
typedef enum EnCastMode {
|
||||
CM_UNICAST = -1, // 单播
|
||||
CM_MULTICAST = 0, // 组播
|
||||
CM_BROADCAST = 1, // 广播
|
||||
} En_HP_CastMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:IP 地址类型
|
||||
描述:IP 地址类型枚举值
|
||||
************************************************************************/
|
||||
typedef enum EnIPAddrType {
|
||||
IPT_ALL = 0, // 所有
|
||||
IPT_IPV4 = 1, // IPv4
|
||||
IPT_IPV6 = 2, // IPv6
|
||||
} En_HP_IPAddrType;
|
||||
|
||||
/************************************************************************
|
||||
名称:IP 地址条目结构体
|
||||
描述:IP 地址的地址簇/地址值结构体
|
||||
************************************************************************/
|
||||
typedef struct TIPAddr {
|
||||
En_HP_IPAddrType type;
|
||||
LPCTSTR address;
|
||||
} *LPTIPAddr, HP_TIPAddr, *HP_LPTIPAddr;
|
||||
|
||||
/************************************************************************
|
||||
名称:拒绝策略
|
||||
描述:调用被拒绝后的处理策略
|
||||
************************************************************************/
|
||||
typedef enum EnRejectedPolicy {
|
||||
TRP_CALL_FAIL = 0, // 立刻返回失败
|
||||
TRP_WAIT_FOR = 1, // 等待(直到成功、超时或线程池关闭等原因导致失败)
|
||||
TRP_CALLER_RUN = 2, // 调用者线程直接执行
|
||||
} En_HP_RejectedPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:任务缓冲区类型
|
||||
描述:TSockeTask 对象创建和销毁时,根据不同类型的缓冲区类型作不同的处理
|
||||
************************************************************************/
|
||||
typedef enum EnTaskBufferType {
|
||||
TBT_COPY = 0, // 深拷贝
|
||||
TBT_REFER = 1, // 浅拷贝
|
||||
TBT_ATTACH = 2, // 附属(不负责创建,但负责销毁)
|
||||
} En_HP_TaskBufferType;
|
||||
|
||||
/************************************************************************
|
||||
名称:任务处理函数
|
||||
描述:任务处理入口函数
|
||||
参数:pvArg -- 自定义参数
|
||||
返回值:(无)
|
||||
************************************************************************/
|
||||
typedef VOID (__HP_CALL *Fn_TaskProc)(PVOID pvArg);
|
||||
typedef Fn_TaskProc HP_Fn_TaskProc;
|
||||
|
||||
struct TSocketTask;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 任务处理函数
|
||||
描述:Socket 任务处理入口函数
|
||||
参数:pTask -- Socket 任务结构体指针
|
||||
返回值:(无)
|
||||
************************************************************************/
|
||||
typedef VOID (__HP_CALL *Fn_SocketTaskProc)(struct TSocketTask* pTask);
|
||||
typedef Fn_SocketTaskProc HP_Fn_SocketTaskProc;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 任务结构体
|
||||
描述:封装 Socket 任务相关数据结构
|
||||
************************************************************************/
|
||||
typedef struct TSocketTask {
|
||||
HP_Fn_SocketTaskProc fn; // 任务处理函数
|
||||
PVOID sender; // 发起对象
|
||||
CONNID connID; // 连接 ID
|
||||
LPCBYTE buf; // 数据缓冲区
|
||||
INT bufLen; // 数据缓冲区长度
|
||||
En_HP_TaskBufferType bufType; // 缓冲区类型
|
||||
WPARAM wparam; // 自定义参数
|
||||
LPARAM lparam; // 自定义参数
|
||||
} *LPTSocketTask, HP_TSocketTask, *HP_LPTSocketTask;
|
||||
|
||||
/************************************************************************
|
||||
名称:获取 HPSocket 版本号
|
||||
描述:版本号(4 个字节分别为:主版本号,子版本号,修正版本号,构建编号)
|
||||
************************************************************************/
|
||||
inline DWORD GetHPSocketVersion()
|
||||
{
|
||||
return (HP_VERSION_MAJOR << 24) | (HP_VERSION_MINOR << 16) | (HP_VERSION_REVISE << 8) | HP_VERSION_BUILD;
|
||||
}
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** SSL Type Definitions ***************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _SSL_SUPPORT
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL 工作模式
|
||||
描述:标识 SSL 的工作模式,客户端模式或服务端模式
|
||||
************************************************************************/
|
||||
typedef enum EnSSLSessionMode {
|
||||
SSL_SM_CLIENT = 0, // 客户端模式
|
||||
SSL_SM_SERVER = 1, // 服务端模式
|
||||
} En_HP_SSLSessionMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL 验证模式
|
||||
描述:SSL 验证模式选项,SSL_VM_PEER 可以和后面两个选项组合一起
|
||||
************************************************************************/
|
||||
typedef enum EnSSLVerifyMode {
|
||||
SSL_VM_NONE = 0x00, // SSL_VERIFY_NONE
|
||||
SSL_VM_PEER = 0x01, // SSL_VERIFY_PEER
|
||||
SSL_VM_FAIL_IF_NO_PEER_CERT = 0x02, // SSL_VERIFY_FAIL_IF_NO_PEER_CERT
|
||||
SSL_VM_CLIENT_ONCE = 0x04, // SSL_VERIFY_CLIENT_ONCE
|
||||
} En_HP_SSLVerifyMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL Session 信息类型
|
||||
描述:用于 GetSSLSessionInfo(),标识输出的 Session 信息类型
|
||||
************************************************************************/
|
||||
typedef enum EnSSLSessionInfo {
|
||||
SSL_SSI_MIN = 0, //
|
||||
SSL_SSI_CTX = 0, // SSL CTX (输出类型:SSL_CTX*)
|
||||
SSL_SSI_CTX_METHOD = 1, // SSL CTX Mehtod (输出类型:SSL_METHOD*)
|
||||
SSL_SSI_CTX_CIPHERS = 2, // SSL CTX Ciphers (输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_CTX_CERT_STORE = 3, // SSL CTX Cert Store (输出类型:X509_STORE*)
|
||||
SSL_SSI_SERVER_NAME_TYPE = 4, // Server Name Type (输出类型:int)
|
||||
SSL_SSI_SERVER_NAME = 5, // Server Name (输出类型:LPCSTR)
|
||||
SSL_SSI_VERSION = 6, // SSL Version (输出类型:LPCSTR)
|
||||
SSL_SSI_METHOD = 7, // SSL Method (输出类型:SSL_METHOD*)
|
||||
SSL_SSI_CERT = 8, // SSL Cert (输出类型:X509*)
|
||||
SSL_SSI_PKEY = 9, // SSL Private Key (输出类型:EVP_PKEY*)
|
||||
SSL_SSI_CURRENT_CIPHER = 10, // SSL Current Cipher (输出类型:SSL_CIPHER*)
|
||||
SSL_SSI_CIPHERS = 11, // SSL Available Ciphers(输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_CLIENT_CIPHERS = 12, // SSL Client Ciphers (输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_PEER_CERT = 13, // SSL Peer Cert (输出类型:X509*)
|
||||
SSL_SSI_PEER_CERT_CHAIN = 14, // SSL Peer Cert Chain (输出类型:STACK_OF(X509)*)
|
||||
SSL_SSI_VERIFIED_CHAIN = 15, // SSL Verified Chain (输出类型:STACK_OF(X509)*)
|
||||
SSL_SSI_MAX = 15, //
|
||||
} En_HP_SSLSessionInfo;
|
||||
|
||||
/************************************************************************
|
||||
名称:SNI 服务名称回调函数
|
||||
描述:根据服务器名称选择 SSL 证书
|
||||
参数:
|
||||
lpszServerName -- 服务器名称(域名)
|
||||
|
||||
返回值:
|
||||
0 -- 成功,使用默认 SSL 证书索引
|
||||
正数 -- 成功,使用返回值对应的 SNI 主机证书索引
|
||||
负数 -- 失败,中断 SSL 握手
|
||||
|
||||
************************************************************************/
|
||||
typedef int (__HP_CALL *Fn_SNI_ServerNameCallback)(LPCTSTR lpszServerName, PVOID pContext);
|
||||
typedef Fn_SNI_ServerNameCallback HP_Fn_SNI_ServerNameCallback;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** HTTP Type Definitions **************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _HTTP_SUPPORT
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 版本
|
||||
描述:低字节:主版本号,高字节:次版本号
|
||||
************************************************************************/
|
||||
|
||||
typedef enum EnHttpVersion {
|
||||
HV_1_0 = MAKEWORD(1, 0), // HTTP/1.0
|
||||
HV_1_1 = MAKEWORD(1, 1) // HTTP/1.1
|
||||
} En_HP_HttpVersion;
|
||||
|
||||
/************************************************************************
|
||||
名称:URL 域
|
||||
描述:HTTP 请求行中 URL 段位的域定义
|
||||
************************************************************************/
|
||||
typedef enum EnHttpUrlField {
|
||||
HUF_SCHEMA = 0, // Schema
|
||||
HUF_HOST = 1, // Host
|
||||
HUF_PORT = 2, // Port
|
||||
HUF_PATH = 3, // Path
|
||||
HUF_QUERY = 4, // Query String
|
||||
HUF_FRAGMENT = 5, // Fragment
|
||||
HUF_USERINFO = 6, // User Info
|
||||
HUF_MAX = 7, // (Field Count)
|
||||
} En_HP_HttpUrlField;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 解析结果标识
|
||||
描述:指示 HTTP 解析器是否继续执行解析操作
|
||||
************************************************************************/
|
||||
typedef enum EnHttpParseResult {
|
||||
HPR_OK = 0, // 解析成功
|
||||
HPR_SKIP_BODY = 1, // 跳过当前请求 BODY(仅用于 OnHeadersComplete 事件)
|
||||
HPR_UPGRADE = 2, // 升级协议(仅用于 OnHeadersComplete 事件)
|
||||
HPR_ERROR = -1, // 解析错误,终止解析,断开连接
|
||||
} En_HP_HttpParseResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 协议升级类型
|
||||
描述:标识 HTTP 升级为哪种协议
|
||||
************************************************************************/
|
||||
typedef enum EnHttpUpgradeType {
|
||||
HUT_NONE = 0, // 没有升级
|
||||
HUT_WEB_SOCKET = 1, // WebSocket
|
||||
HUT_HTTP_TUNNEL = 2, // HTTP 隧道
|
||||
HUT_UNKNOWN = -1, // 未知类型
|
||||
} En_HP_HttpUpgradeType;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 状态码
|
||||
描述:HTTP 标准状态码
|
||||
************************************************************************/
|
||||
typedef enum EnHttpStatusCode {
|
||||
HSC_CONTINUE = 100,
|
||||
HSC_SWITCHING_PROTOCOLS = 101,
|
||||
HSC_PROCESSING = 102,
|
||||
HSC_EARLY_HINTS = 103,
|
||||
HSC_RESPONSE_IS_STALE = 110,
|
||||
HSC_REVALIDATION_FAILED = 111,
|
||||
HSC_DISCONNECTED_OPERATION = 112,
|
||||
HSC_HEURISTIC_EXPIRATION = 113,
|
||||
HSC_MISCELLANEOUS_WARNING = 199,
|
||||
|
||||
HSC_OK = 200,
|
||||
HSC_CREATED = 201,
|
||||
HSC_ACCEPTED = 202,
|
||||
HSC_NON_AUTHORITATIVE_INFORMATION = 203,
|
||||
HSC_NO_CONTENT = 204,
|
||||
HSC_RESET_CONTENT = 205,
|
||||
HSC_PARTIAL_CONTENT = 206,
|
||||
HSC_MULTI_STATUS = 207,
|
||||
HSC_ALREADY_REPORTED = 208,
|
||||
HSC_TRANSFORMATION_APPLIED = 214,
|
||||
HSC_IM_USED = 226,
|
||||
HSC_MISCELLANEOUS_PERSISTENT_WARNING = 299,
|
||||
|
||||
HSC_MULTIPLE_CHOICES = 300,
|
||||
HSC_MOVED_PERMANENTLY = 301,
|
||||
HSC_MOVED_TEMPORARILY = 302,
|
||||
HSC_SEE_OTHER = 303,
|
||||
HSC_NOT_MODIFIED = 304,
|
||||
HSC_USE_PROXY = 305,
|
||||
HSC_SWITCH_PROXY = 306,
|
||||
HSC_TEMPORARY_REDIRECT = 307,
|
||||
HSC_PERMANENT_REDIRECT = 308,
|
||||
|
||||
HSC_BAD_REQUEST = 400,
|
||||
HSC_UNAUTHORIZED = 401,
|
||||
HSC_PAYMENT_REQUIRED = 402,
|
||||
HSC_FORBIDDEN = 403,
|
||||
HSC_NOT_FOUND = 404,
|
||||
HSC_METHOD_NOT_ALLOWED = 405,
|
||||
HSC_NOT_ACCEPTABLE = 406,
|
||||
HSC_PROXY_AUTHENTICATION_REQUIRED = 407,
|
||||
HSC_REQUEST_TIMEOUT = 408,
|
||||
HSC_CONFLICT = 409,
|
||||
HSC_GONE = 410,
|
||||
HSC_LENGTH_REQUIRED = 411,
|
||||
HSC_PRECONDITION_FAILED = 412,
|
||||
HSC_REQUEST_ENTITY_TOO_LARGE = 413,
|
||||
HSC_REQUEST_URI_TOO_LONG = 414,
|
||||
HSC_UNSUPPORTED_MEDIA_TYPE = 415,
|
||||
HSC_REQUESTED_RANGE_NOT_SATISFIABLE = 416,
|
||||
HSC_EXPECTATION_FAILED = 417,
|
||||
HSC_IM_A_TEAPOT = 418,
|
||||
HSC_PAGE_EXPIRED = 419,
|
||||
HSC_ENHANCE_YOUR_CALM = 420,
|
||||
HSC_MISDIRECTED_REQUEST = 421,
|
||||
HSC_UNPROCESSABLE_ENTITY = 422,
|
||||
HSC_LOCKED = 423,
|
||||
HSC_FAILED_DEPENDENCY = 424,
|
||||
HSC_UNORDERED_COLLECTION = 425,
|
||||
HSC_UPGRADE_REQUIRED = 426,
|
||||
HSC_PRECONDITION_REQUIRED = 428,
|
||||
HSC_TOO_MANY_REQUESTS = 429,
|
||||
HSC_REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL = 430,
|
||||
HSC_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
|
||||
HSC_LOGIN_TIMEOUT = 440,
|
||||
HSC_NO_RESPONSE = 444,
|
||||
HSC_RETRY_WITH = 449,
|
||||
HSC_BLOCKED_BY_PARENTAL_CONTROL = 450,
|
||||
HSC_UNAVAILABLE_FOR_LEGAL_REASONS = 451,
|
||||
HSC_CLIENT_CLOSED_LOAD_BALANCED_REQUEST = 460,
|
||||
HSC_INVALID_X_FORWARDED_FOR = 463,
|
||||
HSC_REQUEST_HEADER_TOO_LARGE = 494,
|
||||
HSC_SSL_CERTIFICATE_ERROR = 495,
|
||||
HSC_SSL_CERTIFICATE_REQUIRED = 496,
|
||||
HSC_HTTP_REQUEST_SENT_TO_HTTPS_PORT = 497,
|
||||
HSC_INVALID_TOKEN = 498,
|
||||
HSC_CLIENT_CLOSED_REQUEST = 499,
|
||||
|
||||
HSC_INTERNAL_SERVER_ERROR = 500,
|
||||
HSC_NOT_IMPLEMENTED = 501,
|
||||
HSC_BAD_GATEWAY = 502,
|
||||
HSC_SERVICE_UNAVAILABLE = 503,
|
||||
HSC_GATEWAY_TIMEOUT = 504,
|
||||
HSC_HTTP_VERSION_NOT_SUPPORTED = 505,
|
||||
HSC_VARIANT_ALSO_NEGOTIATES = 506,
|
||||
HSC_INSUFFICIENT_STORAGE = 507,
|
||||
HSC_LOOP_DETECTED = 508,
|
||||
HSC_BANDWIDTH_LIMIT_EXCEEDED = 509,
|
||||
HSC_NOT_EXTENDED = 510,
|
||||
HSC_NETWORK_AUTHENTICATION_REQUIRED = 511,
|
||||
HSC_WEB_SERVER_UNKNOWN_ERROR = 520,
|
||||
HSC_WEB_SERVER_IS_DOWN = 521,
|
||||
HSC_CONNECTION_TIMEOUT = 522,
|
||||
HSC_ORIGIN_IS_UNREACHABLE = 523,
|
||||
HSC_TIMEOUT_OCCURED = 524,
|
||||
HSC_SSL_HANDSHAKE_FAILED = 525,
|
||||
HSC_INVALID_SSL_CERTIFICATE = 526,
|
||||
HSC_RAILGUN_ERROR = 527,
|
||||
HSC_SITE_IS_OVERLOADED = 529,
|
||||
HSC_SITE_IS_FROZEN = 530,
|
||||
HSC_IDENTITY_PROVIDER_AUTHENTICATION_ERROR = 561,
|
||||
HSC_NETWORK_READ_TIMEOUT = 598,
|
||||
HSC_NETWORK_CONNECT_TIMEOUT = 599,
|
||||
|
||||
HSC_UNPARSEABLE_RESPONSE_HEADERS = 600
|
||||
} En_HP_HttpStatusCode;
|
||||
|
||||
/************************************************************************
|
||||
名称:Name/Value 结构体
|
||||
描述:字符串名值对结构体
|
||||
************************************************************************/
|
||||
typedef struct TNVPair {
|
||||
LPCSTR name;
|
||||
LPCSTR value;
|
||||
} HP_TNVPair,
|
||||
TParam, HP_TParam, *LPPARAM, *HP_LPPARAM,
|
||||
THeader, HP_THeader, *LPHEADER, *HP_LPHEADER,
|
||||
TCookie, HP_TCookie, *LPCOOKIE, *HP_LPCOOKIE;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/********************************************************** Compress / Decompress Definitions ********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/************************************************************************
|
||||
名称:数据回调函数
|
||||
描述:回调处理过程中产生的数据输出
|
||||
参数:
|
||||
pData -- 数据缓冲区
|
||||
iLength -- 数据长度
|
||||
pContext -- 回调上下文
|
||||
|
||||
返回值:
|
||||
TRUE -- 成功
|
||||
FALSE -- 失败
|
||||
|
||||
************************************************************************/
|
||||
typedef BOOL (__HP_CALL *Fn_DataCallback)(const BYTE* pData, int iLength, PVOID pContext);
|
||||
typedef Fn_DataCallback Fn_CompressDataCallback;
|
||||
typedef Fn_DataCallback Fn_DecompressDataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_DataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_CompressDataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_DecompressDataCallback;
|
||||
@@ -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());
|
||||
}
|
||||
@@ -1,51 +1,100 @@
|
||||
#pragma once
|
||||
#include "HPSocket.h"
|
||||
#include "SocketInterface.h"
|
||||
#include "Buffer.h"
|
||||
#include <IOCPServer.h>
|
||||
|
||||
#define NC_CLIENT_CONNECT 0x0001
|
||||
#define NC_CLIENT_DISCONNECT 0x0002
|
||||
#define NC_TRANSMIT 0x0003
|
||||
#define NC_RECEIVE 0x0004
|
||||
// 本机 SOCKS5 监听器(代理映射的「本地侧」)。
|
||||
//
|
||||
// 原实现建立在 HP-Socket(https://github.com/ldcsaa/HP-Socket)之上,为这一个功能
|
||||
// 引入整套 SDK(库 + DLL)并不划算,且 HP-Socket 版一直以 ENABLE_HPSOCKET=0 关闭,
|
||||
// 从未真正跑过。这里用阻塞 socket + select 自实现,接口面按原对话框的实际用法裁剪:
|
||||
// 端口监听、每连接收发、按连接 id 断开、连接计数。
|
||||
//
|
||||
// 线程模型(对齐 server/2015Remote/SimpleWebSocket.h 与客户端 ProxyManager 的既有做法):
|
||||
// * 1 个 accept 线程,select 200ms 轮询,便于在 Shutdown 时自然退出;
|
||||
// * 每连接 1 个中继线程,select 200ms 轮询 socket 可读后 recv,只做字节转发;
|
||||
// * 回调(PROXYNOTIFYPROC)在 accept 线程 / 中继线程内同步调用,回调里可以调
|
||||
// Send/Disconnect,但不要等待本对象 Shutdown(会自锁)。
|
||||
// socket 的关闭权归中继线程独有:Disconnect 只置停止位并 shutdown(),由中继线程在
|
||||
// 退出前 closesocket,避免多线程同时关闭同一个句柄。
|
||||
|
||||
typedef void (CALLBACK* NOTIFYPROC)(void* user, ClientContext* ctx, UINT nCode);
|
||||
#include "stdafx.h"
|
||||
#include <WinSock2.h>
|
||||
#include <WS2tcpip.h>
|
||||
|
||||
typedef CList<ClientContext*, ClientContext* > ContextList;
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
class CProxyConnectServer :public CTcpPullServerListener
|
||||
// 连接 id。42 亿个够用,且与代理报文里那 4 字节 id 字段同宽(磁盘/线缆格式不变)。
|
||||
typedef uint32_t CONNID;
|
||||
|
||||
#define NC_CLIENT_CONNECT 0x0001
|
||||
#define NC_CLIENT_DISCONNECT 0x0002
|
||||
#define NC_TRANSMIT 0x0003
|
||||
#define NC_RECEIVE 0x0004
|
||||
|
||||
// nCode == NC_RECEIVE 时 pData/nLen 是本机连接上刚收到的字节(TCP 流的一片段,
|
||||
// 不保证对齐 SOCKS5 消息边界);其余 nCode 下 pData == nullptr、nLen == 0。
|
||||
typedef void (CALLBACK* PROXYNOTIFYPROC)(void* pUser, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
|
||||
class CProxyConnectServer
|
||||
{
|
||||
public:
|
||||
CProxyConnectServer(void);
|
||||
~CProxyConnectServer(void);
|
||||
CProxyConnectServer();
|
||||
~CProxyConnectServer();
|
||||
|
||||
BOOL Initialize(NOTIFYPROC pNotifyProc, void* user, int nMaxConnections, int nPort);
|
||||
BOOL Send(ClientContext* pContext, LPBYTE lpData, UINT nSize);
|
||||
BOOL SendWithSplit(CONNID dwConnID, LPBYTE lpData, UINT nSize, UINT nSplitSize);
|
||||
// 绑定 0.0.0.0:nPort 并开始 accept。nMaxConnections <= 0 表示不限制。
|
||||
BOOL Initialize(PROXYNOTIFYPROC pNotifyProc, void* pUser, int nMaxConnections, int nPort);
|
||||
|
||||
// 停止监听、断开全部连接、等待所有线程退出。可重复调用。
|
||||
void Shutdown();
|
||||
void ClearClient();
|
||||
BOOL Disconnect(CONNID dwConnID);
|
||||
BOOL IsConnected(CONNID dwConnID);
|
||||
int IsOverMaxConnectionCount();
|
||||
|
||||
virtual EnHandleResult OnPrepareListen(ITcpServer* pSender, SOCKET soListen);
|
||||
virtual EnHandleResult OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient);
|
||||
virtual EnHandleResult OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
|
||||
virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength);
|
||||
virtual EnHandleResult OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
|
||||
virtual EnHandleResult OnShutdown(ITcpServer* pSender);
|
||||
// 向本机连接发数据。全部字节发出返回 TRUE;连接不存在或出错返回 FALSE。
|
||||
BOOL Send(CONNID id, const BYTE* pData, UINT nSize);
|
||||
|
||||
CTcpPullServerPtr m_TcpServer;
|
||||
// 主动断开某个本机连接(中继线程会在 200ms 内退出并回调 NC_CLIENT_DISCONNECT)。
|
||||
BOOL Disconnect(CONNID id);
|
||||
|
||||
BOOL HasStarted() const
|
||||
{
|
||||
return m_bRunning.load(std::memory_order_acquire);
|
||||
}
|
||||
int GetConnectionCount();
|
||||
USHORT GetPort() const
|
||||
{
|
||||
return m_nPort;
|
||||
}
|
||||
|
||||
private:
|
||||
NOTIFYPROC m_pNotifyProc;
|
||||
void* m_pUser;
|
||||
ContextList m_listFreePool;
|
||||
CLock m_Locker;
|
||||
int m_nPort; // 插件端口
|
||||
CONNID m_IDs[65535]; // 所有连接ID
|
||||
LONG m_bStop; // 端口停止上线控制
|
||||
int m_nMaxConnection; // 最大连接数
|
||||
BOOL m_bIsRun; // 运行状态
|
||||
DWORD m_dwIndex; // 连接编号
|
||||
struct Conn {
|
||||
CONNID id = 0;
|
||||
SOCKET sock = INVALID_SOCKET;
|
||||
std::atomic<bool> stop{ false };
|
||||
std::atomic<bool> finished{ false }; // 中继线程已走完(可以 join)
|
||||
std::mutex sendLock; // 串行化 Send 与中继线程的 closesocket
|
||||
std::thread thread;
|
||||
};
|
||||
|
||||
void AcceptLoop();
|
||||
void RelayLoop(std::shared_ptr<Conn> pConn);
|
||||
void ReapFinished();
|
||||
BOOL SetSocketOptions(SOCKET s) const;
|
||||
|
||||
USHORT m_nPort = 0;
|
||||
int m_nMaxConnection = 0;
|
||||
SOCKET m_listenSocket = INVALID_SOCKET;
|
||||
std::thread m_acceptThread;
|
||||
std::atomic<bool> m_bRunning{ false };
|
||||
PROXYNOTIFYPROC m_pNotifyProc = nullptr;
|
||||
void* m_pUser = nullptr;
|
||||
|
||||
std::mutex m_connLock;
|
||||
std::map<CONNID, std::shared_ptr<Conn>> m_conns;
|
||||
CONNID m_nextId = 1;
|
||||
|
||||
// 已退出、等待 join 的连接。由 accept 线程与 Shutdown 收割,避免线程句柄越积越多。
|
||||
std::vector<std::shared_ptr<Conn>> m_graveyard;
|
||||
std::mutex m_graveLock;
|
||||
};
|
||||
@@ -9,24 +9,39 @@
|
||||
#define new DEBUG_NEW
|
||||
#endif
|
||||
|
||||
#if !ENABLE_HPSOCKET
|
||||
HPSOCKET_API{
|
||||
ITcpPullServer * HP_Create_TcpPullServer(ITcpServerListener * pListener) { return 0; }
|
||||
void HP_Destroy_TcpPullServer(ITcpPullServer * pServer) {}
|
||||
int SYS_SSO_RecvBuffSize(SOCKET sock, int size) { return 0; }
|
||||
int SYS_SSO_SendBuffSize(SOCKET sock, int size) { return 0; }
|
||||
}
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// CProxyMapDlg dialog
|
||||
|
||||
#define IDM_PROXY_CHROME 8000
|
||||
#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)
|
||||
@@ -39,6 +54,7 @@ void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
|
||||
BEGIN_MESSAGE_MAP(CProxyMapDlg, CDialog)
|
||||
ON_WM_SYSCOMMAND()
|
||||
ON_WM_SIZE()
|
||||
ON_MESSAGE(WM_PROXY_APPEND_LOG, &CProxyMapDlg::OnProxyLog)
|
||||
END_MESSAGE_MAP()
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
@@ -49,56 +65,46 @@ BOOL CProxyMapDlg::OnInitDialog()
|
||||
|
||||
SetIcon(m_hIcon, TRUE); // Set big icon
|
||||
SetIcon(m_hIcon, FALSE); // Set small icon
|
||||
// TODO: Add extra initialization here
|
||||
m_iocpLocal = new CProxyConnectServer;
|
||||
|
||||
m_iocpLocal = new CProxyConnectServer;
|
||||
if (m_iocpLocal == NULL) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
m_Edit.SetLimitText(MAXDWORD);
|
||||
m_EditOther.SetLimitText(MAXDWORD);
|
||||
CString str;
|
||||
|
||||
// 开启IPCP服务器
|
||||
srand((unsigned int)time(NULL));
|
||||
|
||||
m_nPort = 5543; // 初始尝试端口
|
||||
// 监听端口:先试 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;
|
||||
}
|
||||
|
||||
// 端口冲突,生成 10000-65535 之间的随机端口
|
||||
// 提示:10000 + (0 到 55535)
|
||||
int nextPort = 10000 + (rand() % 55536);
|
||||
|
||||
// 避免随机到和刚才一样的端口
|
||||
while (nextPort == m_nPort) {
|
||||
nextPort = 10000 + (rand() % 55536);
|
||||
}
|
||||
m_nPort = nextPort;
|
||||
m_nPort = (USHORT)nextPort;
|
||||
}
|
||||
|
||||
if (!bSuccess) {
|
||||
MessageBoxL("初始化代理服务器失败!", "提示", MB_ICONINFORMATION);
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
TCHAR ip[256] = {};
|
||||
int len = sizeof(ip);
|
||||
m_iocpLocal->m_TcpServer->GetListenAddress(ip, len, m_nPort);
|
||||
|
||||
CString strString;
|
||||
strString.FormatL("%s - 代理服务", m_IPAddress);
|
||||
SetWindowText(strString);
|
||||
|
||||
CString str;
|
||||
str.FormatL(_T("SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n"), m_nPort);
|
||||
AddLog(str.GetBuffer(0));
|
||||
LogLine(false, str.GetString());
|
||||
|
||||
CMenu* pSysMenu = GetSystemMenu(FALSE);
|
||||
if (pSysMenu != NULL) {
|
||||
@@ -117,95 +123,241 @@ void CProxyMapDlg::OnCancel()
|
||||
ShowWindow(SW_HIDE);
|
||||
return;
|
||||
}
|
||||
m_iocpLocal->Shutdown();
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
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 CALLBACK CProxyMapDlg::NotifyProc(void *user, ClientContext* pContext, UINT nCode)
|
||||
int CProxyMapDlg::GetSessionState(CONNID id)
|
||||
{
|
||||
CProxyMapDlg* g_pProxyMap = (CProxyMapDlg*)user;
|
||||
if (g_pProxyMap->m_bIsClosed) return;
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
auto it = m_sessions.find(id);
|
||||
return it == m_sessions.end() ? -1 : it->second.state;
|
||||
}
|
||||
|
||||
DWORD index = pContext->ID;
|
||||
TCHAR szMsg[200] = { 0 };
|
||||
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:
|
||||
wsprintf(szMsg, _TRF("%d 新连接\r\n"), index);
|
||||
break;
|
||||
case NC_CLIENT_DISCONNECT:
|
||||
if (pContext->m_bProxyConnected) {
|
||||
BYTE lpData[5] = "";
|
||||
lpData[0] = COMMAND_PROXY_CLOSE;
|
||||
memcpy(lpData + 1, &index, sizeof(DWORD));
|
||||
g_pProxyMap->m_ContextObject->Send2Client(lpData, 5);
|
||||
}
|
||||
wsprintf(szMsg, _TRF("%d 本地连接断开\r\n"), index);
|
||||
break;
|
||||
case NC_TRANSMIT:
|
||||
dlg->OnLocalConnect(id);
|
||||
break;
|
||||
case NC_RECEIVE:
|
||||
if (pContext->m_bProxyConnected == 2) {
|
||||
g_pProxyMap->m_ContextObject->Send2Client(pContext->InDeCompressedBuffer.GetBuffer(0),
|
||||
pContext->InDeCompressedBuffer.GetBufferLength());
|
||||
wsprintf(szMsg, _TRF("%d <==发 %d bytes\r\n"), index, pContext->InDeCompressedBuffer.GetBufferLength() - 5);
|
||||
} else if (pContext->m_bProxyConnected == 0) {
|
||||
char msg_auth_ok[] = { 0X05, 0X00 }; // VERSION SOCKS, AUTH MODE, OK
|
||||
LPBYTE lpData = pContext->InDeCompressedBuffer.GetBuffer(5);
|
||||
pContext->m_bProxyConnected = 1;
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, (LPBYTE)msg_auth_ok, sizeof(msg_auth_ok));
|
||||
wsprintf(szMsg, _TRF("%d 返回标示 %d %d %d\r\n"), index, lpData[0], lpData[1], lpData[2]);
|
||||
} else if (pContext->m_bProxyConnected == 1) {
|
||||
LPBYTE lpData = pContext->InDeCompressedBuffer.GetBuffer(5);
|
||||
BYTE buf[11] = {};
|
||||
if (lpData[0] == 5 && lpData[1] == 1 && (pContext->InDeCompressedBuffer.GetBufferLength() > 10)) {
|
||||
if (lpData[3] == 1) { // ipv4
|
||||
buf[0] = COMMAND_PROXY_CONNECT; // 1个字节 ip v4 连接
|
||||
memcpy(buf + 1, &index, 4); // 四个字节 套接字的编号
|
||||
memcpy(buf + 5, lpData + 4, 6); // 4字节ip 2字节端口
|
||||
g_pProxyMap->m_ContextObject->Send2Client(buf, sizeof(buf));
|
||||
in_addr inaddr = {};
|
||||
inaddr.s_addr = *(DWORD*)(buf + 5);
|
||||
char szmsg1[MAX_PATH];
|
||||
wsprintfA(szmsg1, "%d IPV4 连接 %s:%d...\r\n", index, inet_ntoa(inaddr), ntohs(*(USHORT*)(buf + 9)));
|
||||
} else if (lpData[3] == 3) { // 域名
|
||||
Socks5Info* Socks5Request = (Socks5Info*)lpData;
|
||||
BYTE* HostName = new BYTE[Socks5Request->IP_LEN + 8];
|
||||
ZeroMemory(HostName, Socks5Request->IP_LEN + 8);
|
||||
HostName[0] = COMMAND_PROXY_CONNECT_HOSTNAME;
|
||||
memcpy(HostName + 7, &Socks5Request->szIP, Socks5Request->IP_LEN);
|
||||
memcpy(HostName + 1, &index, 4);
|
||||
memcpy(HostName + 5, &Socks5Request->szIP + Socks5Request->IP_LEN, 2);
|
||||
g_pProxyMap->m_ContextObject->Send2Client(HostName, Socks5Request->IP_LEN + 8);
|
||||
SAFE_DELETE_ARRAY(HostName);
|
||||
wsprintf(szMsg, _TRF("域名 连接 %d \r\n"), index);
|
||||
} else if (lpData[3] == 4) { //ipv6
|
||||
char msg_ipv6_nok[] = { 0X05, 0X08, 0X00, 0X01, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00 }; // IPv6 not support
|
||||
wsprintf(szMsg, _TRF("%d IPV6连接 不支持..."), index);
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, (LPBYTE)msg_ipv6_nok, sizeof(msg_ipv6_nok));
|
||||
g_pProxyMap->m_iocpLocal->Disconnect(pContext->m_Socket);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
buf[0] = 5;
|
||||
buf[1] = 7;
|
||||
buf[2] = 0;
|
||||
buf[3] = lpData[3];
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, buf, sizeof(buf));
|
||||
g_pProxyMap->m_iocpLocal->Disconnect(pContext->m_Socket);
|
||||
wsprintf(szMsg, _TRF("%d 不符要求, 断开 %d %d %d\r\n"), index, lpData[0], lpData[1], lpData[3]);
|
||||
}
|
||||
}
|
||||
dlg->OnLocalReceive(id, pData, nLen);
|
||||
break;
|
||||
case NC_CLIENT_DISCONNECT:
|
||||
dlg->OnLocalDisconnect(id);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (...) {}
|
||||
if (szMsg[0])
|
||||
g_pProxyMap->AddLog_other(szMsg);
|
||||
return;
|
||||
} 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()
|
||||
@@ -214,81 +366,58 @@ void CProxyMapDlg::OnReceive()
|
||||
|
||||
void CProxyMapDlg::OnReceiveComplete()
|
||||
{
|
||||
if (m_iocpLocal == NULL)
|
||||
return;
|
||||
|
||||
if (m_iocpLocal->m_TcpServer->HasStarted() == FALSE || m_bIsClosed)
|
||||
if (m_iocpLocal == NULL || !m_iocpLocal->HasStarted() || m_bIsClosed)
|
||||
return;
|
||||
|
||||
LPBYTE buf = m_ContextObject->m_DeCompressionBuffer.GetBuffer(0);
|
||||
DWORD index = *(DWORD*)&buf[1];
|
||||
TCHAR szMsg[200];
|
||||
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: {
|
||||
char msg_request_co_ok[] = { 0X05, 0X00, 0X00, 0X01, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00 }; // Request connect OK
|
||||
|
||||
BYTE sendbuf[10] = "";
|
||||
sendbuf[0] = 5;
|
||||
sendbuf[1] = (buf[9] || buf[10]) ? 0 : 5;
|
||||
sendbuf[2] = 0;
|
||||
sendbuf[3] = 1;
|
||||
memcpy(&sendbuf[4], &buf[5], 6);
|
||||
|
||||
ClientContext* pContext_proxy = NULL;
|
||||
if (m_iocpLocal->m_TcpServer->GetConnectionExtra((CONNID)index, (PVOID*)&pContext_proxy) && pContext_proxy != nullptr) {
|
||||
if (sendbuf[1] == 0) {
|
||||
pContext_proxy->m_bProxyConnected = 2;
|
||||
wsprintf(szMsg, _TRF("%d 连接成功\r\n"), index);
|
||||
} else
|
||||
wsprintf(szMsg, _TRF("%d 连接失败\r\n"), index);
|
||||
m_iocpLocal->Send(pContext_proxy, sendbuf, sizeof(sendbuf));
|
||||
AddLog(szMsg);
|
||||
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;
|
||||
}
|
||||
break;
|
||||
case TOKEN_PROXY_BIND_RESULT:
|
||||
break;
|
||||
case TOKEN_PROXY_CLOSE: {
|
||||
wsprintf(szMsg, _T("%d TOKEN_PROXY_CLOSE\r\n"), index);
|
||||
|
||||
m_iocpLocal->Disconnect(index);
|
||||
AddLog(szMsg);
|
||||
}
|
||||
break;
|
||||
case TOKEN_PROXY_DATA: {
|
||||
ClientContext* pContext_proxy = NULL;
|
||||
BOOL ok = FALSE;
|
||||
if (m_iocpLocal->m_TcpServer->GetConnectionExtra((CONNID)index, (PVOID*)&pContext_proxy) && pContext_proxy != nullptr) {
|
||||
ok = m_iocpLocal->Send(pContext_proxy, &buf[5], m_ContextObject->m_DeCompressionBuffer.GetBufferLength() - 5);
|
||||
if (ok == FALSE) {
|
||||
wsprintf(szMsg, _T("%d TOKEN_PROXY_CLOSE\r\n"), index);
|
||||
m_iocpLocal->Disconnect(index);
|
||||
AddLog(szMsg);
|
||||
return;
|
||||
}
|
||||
wsprintf(szMsg, _TRF("%d ==>收 %d bytes\r\n"), index, m_ContextObject->m_DeCompressionBuffer.GetBufferLength() - 5);
|
||||
AddLog(szMsg);
|
||||
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;
|
||||
}
|
||||
}
|
||||
break;
|
||||
str.FormatL(_TRF("%u ==>收 %u bytes\r\n"), id, len - 5);
|
||||
break;
|
||||
default:
|
||||
// 传输发生异常数据
|
||||
break;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void CProxyMapDlg::AddLog(TCHAR* lpText)
|
||||
{
|
||||
if (m_bIsClosed == TRUE) return;
|
||||
m_Edit.SetSel(-1, -1);
|
||||
m_Edit.ReplaceSel(lpText);
|
||||
}
|
||||
|
||||
void CProxyMapDlg::AddLog_other(TCHAR* lpText)
|
||||
{
|
||||
if (m_bIsClosed == TRUE) return;
|
||||
m_EditOther.SetSel(-1, -1);
|
||||
m_EditOther.ReplaceSel(lpText);
|
||||
if (!str.IsEmpty())
|
||||
LogLine(false, str.GetString());
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnSize(UINT nType, int cx, int cy)
|
||||
|
||||
@@ -3,65 +3,70 @@
|
||||
#include "ProxyConnectServer.h"
|
||||
#include "Resource.h"
|
||||
|
||||
// 这个库比较大,且只在需要代理映射时使用
|
||||
// 如有需要,需手动开启并链接这个库
|
||||
// https://github.com/ldcsaa/HP-Socket
|
||||
// 惠普 socket - High Performance socket
|
||||
#define ENABLE_HPSOCKET 0
|
||||
|
||||
#if ENABLE_HPSOCKET
|
||||
#ifdef _WIN64
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "HPSocket_x64D.lib")
|
||||
#else
|
||||
#pragma comment(lib, "HPSocket_x64.lib")
|
||||
#endif
|
||||
|
||||
#else
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "HPSocket_D.lib")
|
||||
#else
|
||||
#pragma comment(lib, "HPSocket.lib")
|
||||
#endif
|
||||
|
||||
#endif
|
||||
#endif
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// CProxyMapDlg dialog
|
||||
typedef struct {
|
||||
BYTE Ver; // Version Number
|
||||
BYTE CMD; // 0x01==TCP CONNECT,0x02==TCP BIND,0x03==UDP ASSOCIATE
|
||||
BYTE RSV;
|
||||
BYTE ATYP;
|
||||
BYTE IP_LEN;
|
||||
BYTE szIP;
|
||||
} Socks5Info;
|
||||
|
||||
//
|
||||
// 代理映射的「本地侧」:在本机监听一个 SOCKS5 端口,把浏览器/curl 的连接
|
||||
// 转发到目标主机的客户端,再由客户端连真正的目标。本文件只处理 SOCKS5 与
|
||||
// 代理报文,socket 层在 ProxyConnectServer(自实现,不再依赖 HP-Socket)。
|
||||
//
|
||||
// 代理测试: curl --socks5 127.0.0.1:5543 https://www.example.com
|
||||
class CProxyMapDlg : public DialogBase
|
||||
{
|
||||
public:
|
||||
CProxyMapDlg(CWnd* pParent = NULL, Server* pIOCPServer = NULL, ClientContext* pContext = NULL);
|
||||
virtual ~CProxyMapDlg();
|
||||
|
||||
enum { IDD = IDD_PROXY };
|
||||
|
||||
static void CALLBACK NotifyProc(void* user, ClientContext* pContext, UINT nCode);
|
||||
// 监听器回调(运行在 accept 线程 / 每连接中继线程内)
|
||||
static void CALLBACK NotifyProc(void* user, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
|
||||
void OnReceiveComplete();
|
||||
void OnReceive();
|
||||
void AddLog(TCHAR* lpText);
|
||||
void AddLog_other(TCHAR* lpText);
|
||||
virtual void DoDataExchange(CDataExchange* pDX);
|
||||
virtual void OnCancel();
|
||||
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
|
||||
virtual BOOL OnInitDialog();
|
||||
afx_msg void OnSize(UINT nType, int cx, int cy);
|
||||
afx_msg LRESULT OnProxyLog(WPARAM wParam, LPARAM lParam);
|
||||
DECLARE_MESSAGE_MAP()
|
||||
|
||||
private:
|
||||
CProxyConnectServer* m_iocpLocal;
|
||||
// 每条本机连接在「本地侧」的状态。SOCKS5 握手在这里推进:
|
||||
// 0 待认证(等客户端的 VER/NMETHODS)
|
||||
// 1 已回「无需认证」,等 CONNECT 请求
|
||||
// 2 隧道(CONNECT 已下发且客户端回连成功),之后全是裸数据
|
||||
struct LocalSession {
|
||||
int state = 0;
|
||||
bool connectSent = false; // 是否已向客户端下发过 CONNECT(决定断开时要不要回 CLOSE)
|
||||
};
|
||||
|
||||
void OnLocalConnect(CONNID id);
|
||||
void OnLocalReceive(CONNID id, const BYTE* pData, UINT nLen);
|
||||
void OnLocalDisconnect(CONNID id);
|
||||
|
||||
// 组 [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);
|
||||
|
||||
CProxyConnectServer* m_iocpLocal;
|
||||
CEdit m_Edit;
|
||||
USHORT m_nPort;
|
||||
CEdit m_EditOther;
|
||||
USHORT m_nPort;
|
||||
|
||||
std::mutex m_sessLock;
|
||||
std::map<CONNID, LocalSession> m_sessions;
|
||||
|
||||
// 两个日志框的全文(只在 UI 线程读写)。
|
||||
CString m_strLog;
|
||||
CString m_strLogOther;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user