Compare commits

..

29 Commits

Author SHA1 Message Date
ttttupup
c58293edc5 'feat:syncmsg' 2024-05-22 18:36:38 +08:00
ttttupup
a39dad9e31 feat:群功能 2024-05-07 20:40:29 +08:00
ttttupup
c4a9efa322 feat:更新偏移 2024-04-29 22:44:24 +08:00
ttttupup
227a296624 feat:3.9.10.19 2024-04-27 22:46:18 +08:00
ttttupup
efb5dba007 feat:update 2024-04-10 21:26:40 +08:00
ttttupup
f2183bb735 feat:空接口 2024-04-08 16:07:58 +08:00
ttttupup
493d8aa0c8 feat:增加3.9.9.43空实现 2024-04-08 16:06:59 +08:00
ttttupup
9836771ef7 feat: doAddMsg hook 2024-04-07 10:00:53 +08:00
ttttupup
74ac1c944e feat: controller 2024-04-06 23:37:50 +08:00
ttttupup
b6e07cc3d7 feat: fix 2024-04-06 23:37:07 +08:00
ttttupup
ff21d07e40 feat: json util 2024-04-06 15:56:42 +08:00
ttttupup
c2367968ec 'feat:base' 2024-04-06 11:45:10 +08:00
ttttupup
a90d667799 'feat:基础功能' 2024-04-06 11:38:16 +08:00
ttttupup
2eb798458c feat:补充好友标签,增加打开url 2024-01-06 13:56:51 +08:00
ttttupup
28db38b45e feat: 语音转换 2023-12-26 18:00:05 +08:00
ttttupup
1207eb6fc8 feat:内存扫描 2023-12-22 23:23:50 +08:00
ttttupup
84611a8b33 feat:基础发送接口 2023-12-22 23:23:05 +08:00
ttttupup
012008f243 doc: 文档 2023-12-20 22:11:23 +08:00
ttttupup
f95c36c5d5 feat: 3.9.8.25 2023-12-20 17:56:37 +08:00
ttttupup
514fd1dff4 Merge branch 'dev-3.9.7.29' of https://github.com/ttttupup/wxhelper into dev-3.9.7.29 2023-11-08 21:16:29 +08:00
ttttupup
6fb7653269 doc: 3.9.7.29 doc 2023-11-08 21:07:16 +08:00
hugy
4dcd18db6c doc: 3.9.7.29 doc 2023-11-08 20:32:06 +08:00
hugy
06bfc6b7c0 feat: db 2023-11-08 20:21:51 +08:00
hugy
5ccfbc40a4 feat: db 2023-11-08 20:21:15 +08:00
hugy
bede8f7150 feat: check login and self info 2023-11-01 21:57:03 +08:00
hugy
1ff56fc055 feat: 好友列表 2023-10-26 22:16:31 +08:00
hugy
8ab646be96 feat: 消息同步 2023-10-26 20:25:10 +08:00
hugy
2767576351 feat : 3.9.7.29 2023-10-17 20:54:52 +08:00
hugy
9f2b0f9925 feat: 3.9.7.29 first commit 2023-10-17 20:53:57 +08:00
182 changed files with 19299 additions and 21906 deletions

1
.gitignore vendored
View File

@ -33,3 +33,4 @@
CMakePresets.json
.vscode
out
.vs

13
.gitmodules vendored
View File

@ -1,3 +1,10 @@
[submodule "spdlog"]
path = spdlog
url = https://github.com/gabime/spdlog
[submodule "spdlog"]
path = app/3rdparty/spdlog
url = https://github.com/gabime/spdlog.git
branch = v1.x
[submodule "app/3rdparty/json"]
path = app/3rdparty/json
url = https://github.com/nlohmann/json
[submodule "app/3rdparty/Detours"]
path = app/3rdparty/Detours
url = https://github.com/microsoft/Detours

View File

@ -1,53 +1,6 @@
cmake_minimum_required(VERSION 3.0.0)
# include(ExternalProject)
project(wxhelper VERSION 1.0.0)
enable_language(ASM_MASM)
cmake_minimum_required(VERSION 3.10...3.27)
project(app VERSION 1.0.0)
# SET(CMAKE_ASM_NASM_FLAGS "-w0")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D '_UNICODE' /D 'UNICODE' ")
file(GLOB CPP_FILES ${PROJECT_SOURCE_DIR}/src/*.cc ${PROJECT_SOURCE_DIR}/src/*.cpp ${PROJECT_SOURCE_DIR}/src/*.c )
file(GLOB ASM_FILES ${PROJECT_SOURCE_DIR}/src/*.asm )
include_directories(${VCPKG_INSTALLED_DIR}/x64-windows/include ${PROJECT_SOURCE_DIR}/spdlog/include ${DETOURS_INCLUDE_DIRS})
# include_directories(${VCPKG_INSTALLED_DIR}/x64-windows/include ${PROJECT_SOURCE_DIR}/spdlog/include )
add_subdirectory(spdlog)
add_subdirectory(source)
# find_package(spdlog CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
find_path(DETOURS_INCLUDE_DIRS "detours/detours.h")
find_library(DETOURS_LIBRARY detours REQUIRED)
add_library(wxhelper SHARED ${CPP_FILES} ${ASM_FILES} )
target_link_libraries(wxhelper PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(wxhelper PRIVATE spdlog::spdlog spdlog::spdlog_header_only)
target_link_libraries(wxhelper PRIVATE ${DETOURS_LIBRARY})
SET_TARGET_PROPERTIES(wxhelper PROPERTIES LINKER_LANGUAGE C
ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
OUTPUT_NAME "wxhelper"
PREFIX "")
add_subdirectory(app)

225
README.md
View File

@ -1,10 +1,10 @@
# wxhelper
wechat hook 。PC端微信逆向学习。支持3.8.0.413.8.1.26, 3.9.0.28, 3.9.2.23,3.9.2.26版本。
wechat hook 。PC端微信逆向学习。
#### 免责声明:
本仓库发布的内容,仅用于学习研究,请勿用于非法用途和商业用途!如因此产生任何法律纠纷,均与作者无关!
#### 项目说明:
<font color= "#dd0000">本项目是逆向习项目,可能会造成封号等后果。请自行承担风险。仅用于学习研究,请勿于非法用途。</font>
<font color= "#dd0000">本项目是逆向习项目,可能会造成封号等后果。请自行承担风险。仅用于学习研究,请勿于非法用途。</font>
#### 实现原理:
逆向分析PC端微信客户端定位相关功能关键Call编写dll调用关键Call。然后将该dll文件注入到微信进程。
@ -18,30 +18,27 @@ dll在注入成功时创建了一个默认端口为19088的http服务端
|-------------------------- |----------------- -------------- --------
```
#### 使用说明:
支持的版本3.8.0.41、3.8.1.26、3.9.0.28、3.9.2.23、3.9.2.26 、3.9.5.81。
源码和主要实现在相应的分支内。
src:主要的dll代码
tool简单的注入工具一个是控制台一个是图形界面。
python: tcpserver.py: 简单的服务器用以接收消息内容。decrpty.py: 微信数据库解密工具。 http_server.pyhttp server端。
source: 简单的命令行远程注入源码。
其他目录:热心作者提供的一些客户端。
#### 快速开始:
#### 0.首先安装对应的版本的微信分支名称即代表的是微信对应的版本。dll的前缀都会带有微信版本。
#### 1.使用注入工具注入wxhelper.dll,注入成功后即可通过postman直接调用对应的接口。
#### 2.可以使用python/clent.py进行简单测试。
1.使用注入工具将wxhelper.dll注入到WeChat中。
2.执行
```
curl --location --request POST '127.0.0.1:19088/api/checkLogin'
```
即可检查登录状态。
如果已经登录则执行获取登录用户信息
```
curl --location --request POST '127.0.0.1:19088/api/userInfo'
```
3.其他更多接口参考相关文档。
##### 特别注意:
##### 1.hook相关的接口都需要先调用对应的hook接口server端才会收到相应消息。
##### 2.注意个别接口在一些版本没有实现,功能预览里没有的功能就是没有实现。
##### 3.如果注入不成功,请先检查注入工具,或者使用其他注入工具。
##### 4.相关功能只在win11环境下进行简单测试其他环境无法保证。
#### 参与项目
个人精力和水平有限,项目还有许多不足,欢迎提出 issues 或 pr。期待你的贡献。
个人精力和水平有限,项目还有许多不足,欢迎提出 issues 或 pr。
@ -49,12 +46,12 @@ source: 简单的命令行远程注入源码。
个人常用的方法请参考https://github.com/ttttupup/wxhelper/wiki
使用上的问题可查询https://github.com/ttttupup/wxhelper/discussions
数据库解密请参考https://github.com/ttttupup/wxhelper/wiki
个人精力有限,只维护最新版本旧版本的bug会在新版本中修复不维护旧版本。
个人精力有限,该项目随缘更新。
#### 编译环境
Visual Studio 2022(x86)
Visual Studio 2022
Visual Studio code
@ -62,183 +59,35 @@ cmake
vcpkg
#### 编译构建
先准备好编译环境。
#### <font color= "#dd0000"> 以下是x86环境构建3.9.5.81是x64环境具体参考对应分支。</font>
```
cd wxhelper/app/3rdparty
git clone https://github.com/microsoft/Detours.git
git clone https://github.com/gabime/spdlog.git
git clone https://github.com/nlohmann/json.git
或者使用vcpkg 安装相应库
vcpkg install detours:x64-windows
vcpkg install nlohmann-json:x64-windows
vcpkg install spdlog:x64-windows
cd wxhelper/cmake
copy detours.cmake wxhelper/app/3rdparty/Detours/CMakeLists.txt
cd wxhelper
mkdir build
cd build
cmake -DCMAKE_C_COMPILER=cl.exe \
-DCMAKE_CXX_COMPILER=cl.exe \
-DCMAKE_ASM_MASM_COMPILER=ml64.exe \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_INSTALL_PREFIX=C:/other/codeSource/windows/wxhelper/out/install/x86-debug \
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=C:/vcpkg/scripts/buildsystems/vcpkg.cmake \
-SC:/wxhelper \
-BC:/wxhelper/build/x86-debug\
-DCMAKE_INSTALL_PREFIX=${SOURCE_DIR}/wxhelper/install/x64-debug \
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${VCPKG_INSTALL_DIR}/scripts/buildsystems/vcpkg.cmake \
-SC:${SOURCE_DIR}/wxhelper \
-BC:${SOURCE_DIR}/wxhelper/build/x64-debug\
-G Ninja
cmake --build ..
```
如果有错误按错误提示修正即可。
以下是在vscode中操作vs中的操作类似。
1.安装vcpkgcmakevscode
2.安装相应的库如果安装的版本不同则根据vcpkg安装成功后提示的find_package修改CMakeLists.txt内容即可。或者自己编译。
```
vcpkg install mongoose
vcpkg install nlohmann-json
```
3.vscode 配置CMakePresets.json,主要设置CMAKE_C_COMPILER 和CMAKE_CXX_COMPILER 为cl.exe.参考如下
```
{
"name": "x86-release",
"displayName": "x86-release",
"description": "Sets Ninja generator, build and install directory",
"generator": "Ninja",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"architecture":{
"value": "x86",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe",
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}",
"CMAKE_TOOLCHAIN_FILE": {
"value": "C:/soft/vcpkg/scripts/buildsystems/vcpkg.cmake",
"type": "FILEPATH"
}
},
"environment": {
}
}
```
4.执行cmake build vscode中右键configure all projects,在Terminal中点击Run Task如没有先配置build任务然后运行即可
5.命令行注入工具,注入命令
``` javascript
//-i 注入程序名 -p 注入dll路径
// -u 卸载程序名 -d 卸载dll名称
// -m pid 关闭微信互斥体,多开微信
// -P port 指定http端口需要使用 specify-port 分支的生成的dll
// -I 注入程序的pid
//注入
ConsoleInject.exe -i demo.exe -p E:\testInject.dll
//卸载
ConsoleInject.exe -u demo.exe -d testInject.dll
//多开
ConsoleInject.exe -m 1222
// 注入并指定http端口
ConsoleInject.exe -i demo.exe -p E:\testInject.dll -P 18888
// 注入指定pid并关闭多开限制
ConsoleInject.exe -I 15048 -p E:\testInject.dll -m 15048
```
6.如果想改变端口可以在微信目录下创建config.ini配置文件,修改端口即可。不创建则默认端口19088。
``` shell
[config]
port=19099
```
#### 更新说明
2022-12-26 增加3.8.1.26版本支持。
2022-12-29 新增提取文字功能。
2023-01-02 退出微信登录。
2023-01-31 新增修改群昵称仅支持3.8.1.26)。
2023-02-01 新增拍一拍仅支持3.8.1.26)。
2023-02-04 新增群消息置顶和取消置顶。
2023-02-06 新增确认收款。
2023-02-08 新增朋友圈消息。
2023-02-09 新增3.9.0.28版本基础功能。
2023-02-13 新增群昵称和微信名称。
2023-02-17 : 新增通过wxid添加好友,搜索查找微信。
2023-03-02 新增发送@消息
2023-03-04 新增消息附件下载
2023-03-21 新增hook语音
2023-03-30 新增获取语音文件(推荐使用这个非hook接口)
2023-04-08 : 3.9.2.23版本功能更新
2023-06-05 3.9.2.26版本更新
2023-07-07 3.9.5.81版本更新
#### 功能预览:
0.检查是否登录
1.获取登录微信信息
2.发送文本
3.发送@文本
5.发送图片
6.发送文件
9.hook消息
10.取消hook消息
11.hook图片
12.取消hook图片
13.hook语音
14.取消hook语音
17.删除好友
19.通过手机或qq查找微信
20.通过wxid添加好友
23.通过好友申请
25.获取群成员
26.获取群成员昵称
27.删除群成员
28.增加群成员
31.修改群昵称
32.获取数据库句柄
34.查询数据库
35.hook日志
36.取消hook日志
40.转发消息
44.退出登录
45.确认收款
46.联系人列表
47.获取群详情
48.获取解密图片
49.图片提取文字ocr
50.拍一拍
51.群消息置顶消息
52.群消息取消置顶
53.朋友圈首页
54.朋友圈下一页
55.获取联系人或者群名称
56.获取消息附件(图片,视频,文件)
57.获取语音文件(silk3格式)
58.登录二维码
59.邀请入群
60.获取群/群成员详情
61.撤回消息
62.发送公众号消息
63.转发公众号消息
64.发送小程序
65.退款
66.下载头像(勿用,没什么用)
#### 感谢
https://github.com/ljc545w/ComWeChatRobot
https://github.com/NationalSecurityAgency/ghidra
https://github.com/x64dbg/x64dbg
#### 讨论组
https://t.me/+LmvAauweyUpjYzJl

23
app/3rdparty/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.10...3.27)
add_subdirectory(base64)
add_subdirectory(lz4)
add_subdirectory(mongoose)
add_subdirectory(spdlog)
add_subdirectory(tinyxml2)
if(USE_EXTERNAL_DETOURS)
find_path(DETOURS_INCLUDE_DIRS "detours/detours.h")
find_library(DETOURS_LIBRARY detours REQUIRED)
else()
add_subdirectory(Detours)
endif()
if(USE_EXTERNAL_JSON)
find_package(nlohmann_json 3.2.0 REQUIRED)
else()
set(JSON_BuildTests OFF CACHE INTERNAL "")
add_subdirectory(json)
endif()

1
app/3rdparty/Detours vendored Submodule

@ -0,0 +1 @@
Subproject commit 4b8c659f549b0ab21cf649377c7a84eb708f5e68

6
app/3rdparty/base64/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.10...3.27)
aux_source_directory(. BASE64_SOURCE)
add_library(base64 ${BASE64_SOURCE})
target_include_directories(base64 INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

View File

@ -1,14 +1,13 @@
#include "pch.h"
/*
/*
base64.cpp and base64.h
base64 encoding and decoding with C++.
More information at
https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
Version: 2.rc.08 (release candidate)
Version: 2.rc.09 (release candidate)
Copyright (C) 2004-2017, 2020, 2021 Ren<EFBFBD><EFBFBD> Nyffenegger
Copyright (C) 2004-2017, 2020-2022 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
@ -28,7 +27,7 @@
3. This notice may not be removed or altered from any source distribution.
Ren<EFBFBD><EFBFBD> Nyffenegger rene.nyffenegger@adp-gmbh.ch
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
@ -53,22 +52,16 @@ static const char *base64_chars[2] = {
"0123456789"
"-_" };
static unsigned int pos_of_char(const unsigned char chr)
{
static unsigned int pos_of_char(const unsigned char chr) {
//
// Return the position of chr within base64_encode()
//
if (chr >= 'A' && chr <= 'Z')
return chr - 'A';
else if (chr >= 'a' && chr <= 'z')
return chr - 'a' + ('Z' - 'A') + 1;
else if (chr >= '0' && chr <= '9')
return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;
else if (chr == '+' || chr == '-')
return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
else if (chr == '/' || chr == '_')
return 63; // Ditto for '/' and '_'
if (chr >= 'A' && chr <= 'Z') return chr - 'A';
else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1;
else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;
else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_'
else
//
// 2020-10-23: Throw std::exception rather than const char*
@ -77,20 +70,17 @@ static unsigned int pos_of_char(const unsigned char chr)
throw std::runtime_error("Input is not valid base64-encoded data.");
}
static std::string insert_linebreaks(std::string str, size_t distance)
{
static std::string insert_linebreaks(std::string str, size_t distance) {
//
// Provided by https://github.com/JomaCorpFX, adapted by me.
//
if (!str.length())
{
if (!str.length()) {
return "";
}
size_t pos = distance;
while (pos < str.size())
{
while (pos < str.size()) {
str.insert(pos, "\n");
pos += distance + 1;
}
@ -99,31 +89,26 @@ static std::string insert_linebreaks(std::string str, size_t distance)
}
template <typename String, unsigned int line_length>
static std::string encode_with_line_breaks(String s)
{
static std::string encode_with_line_breaks(String s) {
return insert_linebreaks(base64_encode(s, false), line_length);
}
template <typename String>
static std::string encode_pem(String s)
{
static std::string encode_pem(String s) {
return encode_with_line_breaks<String, 64>(s);
}
template <typename String>
static std::string encode_mime(String s)
{
static std::string encode_mime(String s) {
return encode_with_line_breaks<String, 76>(s);
}
template <typename String>
static std::string encode(String s, bool url)
{
static std::string encode(String s, bool url) {
return base64_encode(reinterpret_cast<const unsigned char*>(s.data()), s.length(), url);
}
std::string base64_encode(unsigned char const *bytes_to_encode, size_t in_len, bool url)
{
std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) {
size_t len_encoded = (in_len + 2) / 3 * 4;
@ -145,27 +130,22 @@ std::string base64_encode(unsigned char const *bytes_to_encode, size_t in_len, b
unsigned int pos = 0;
while (pos < in_len)
{
while (pos < in_len) {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);
if (pos + 1 < in_len)
{
if (pos + 1 < in_len) {
ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]);
if (pos + 2 < in_len)
{
if (pos + 2 < in_len) {
ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]);
ret.push_back(base64_chars_[bytes_to_encode[pos + 2] & 0x3f]);
}
else
{
else {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]);
ret.push_back(trailing_char);
}
}
else
{
else {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]);
ret.push_back(trailing_char);
@ -175,22 +155,20 @@ std::string base64_encode(unsigned char const *bytes_to_encode, size_t in_len, b
pos += 3;
}
return ret;
}
template <typename String>
static std::string decode(String encoded_string, bool remove_linebreaks)
{
static std::string decode(String const& encoded_string, bool remove_linebreaks) {
//
// decode(<EFBFBD><EFBFBD>) is templated so that it can be used with String = const std::string&
// decode() is templated so that it can be used with String = const std::string&
// or std::string_view (requires at least C++17)
//
if (encoded_string.empty())
return std::string();
if (encoded_string.empty()) return std::string();
if (remove_linebreaks)
{
if (remove_linebreaks) {
std::string copy(encoded_string);
@ -212,8 +190,7 @@ static std::string decode(String encoded_string, bool remove_linebreaks)
std::string ret;
ret.reserve(approx_length_of_decoded_string);
while (pos < length_of_string)
{
while (pos < length_of_string) {
//
// Iterate over encoded input string in chunks. The size of all
// chunks except the last one is 4 bytes.
@ -227,32 +204,33 @@ static std::string decode(String encoded_string, bool remove_linebreaks)
// The last chunk produces at least one and up to three bytes.
//
size_t pos_of_char_1 = pos_of_char(encoded_string[pos + 1]);
size_t pos_of_char_1 = pos_of_char(encoded_string.at(pos + 1));
//
// Emit the first output byte that is produced in each chunk:
//
ret.push_back(static_cast<std::string::value_type>(((pos_of_char(encoded_string[pos + 0])) << 2) + ((pos_of_char_1 & 0x30) >> 4)));
ret.push_back(static_cast<std::string::value_type>(((pos_of_char(encoded_string.at(pos + 0))) << 2) + ((pos_of_char_1 & 0x30) >> 4)));
if ((pos + 2 < length_of_string) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045)
encoded_string[pos + 2] != '=' &&
encoded_string[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also.
encoded_string.at(pos + 2) != '=' &&
encoded_string.at(pos + 2) != '.' // accept URL-safe base 64 strings, too, so check for '.' also.
)
{
//
// Emit a chunk's second byte (which might not be produced in the last chunk).
//
unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos + 2]);
unsigned int pos_of_char_2 = pos_of_char(encoded_string.at(pos + 2));
ret.push_back(static_cast<std::string::value_type>(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2)));
if ((pos + 3 < length_of_string) &&
encoded_string[pos + 3] != '=' &&
encoded_string[pos + 3] != '.')
encoded_string.at(pos + 3) != '=' &&
encoded_string.at(pos + 3) != '.'
)
{
//
// Emit a chunk's third byte (which might not be produced in the last chunk).
//
ret.push_back(static_cast<std::string::value_type>(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string[pos + 3])));
ret.push_back(static_cast<std::string::value_type>(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string.at(pos + 3))));
}
}
@ -262,23 +240,19 @@ static std::string decode(String encoded_string, bool remove_linebreaks)
return ret;
}
std::string base64_decode(std::string const &s, bool remove_linebreaks)
{
std::string base64_decode(std::string const& s, bool remove_linebreaks) {
return decode(s, remove_linebreaks);
}
std::string base64_encode(std::string const &s, bool url)
{
std::string base64_encode(std::string const& s, bool url) {
return encode(s, url);
}
std::string base64_encode_pem(std::string const &s)
{
std::string base64_encode_pem(std::string const& s) {
return encode_pem(s);
}
std::string base64_encode_mime(std::string const &s)
{
std::string base64_encode_mime(std::string const& s) {
return encode_mime(s);
}
@ -289,23 +263,19 @@ std::string base64_encode_mime(std::string const &s)
// Provided by Yannic Bonenberger (https://github.com/Yannic)
//
std::string base64_encode(std::string_view s, bool url)
{
std::string base64_encode(std::string_view s, bool url) {
return encode(s, url);
}
std::string base64_encode_pem(std::string_view s)
{
std::string base64_encode_pem(std::string_view s) {
return encode_pem(s);
}
std::string base64_encode_mime(std::string_view s)
{
std::string base64_encode_mime(std::string_view s) {
return encode_mime(s);
}
std::string base64_decode(std::string_view s, bool remove_linebreaks)
{
std::string base64_decode(std::string_view s, bool remove_linebreaks) {
return decode(s, remove_linebreaks);
}

View File

@ -1,8 +1,8 @@
//
// base64 encoding and decoding with C++.
// Version: 2.rc.08 (release candidate)
//
#pragma once
// base64 encoding and decoding with C++.
// Version: 2.rc.09 (release candidate)
//
#ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A
#define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A

1
app/3rdparty/json vendored Submodule

@ -0,0 +1 @@
Subproject commit 199dea11b17c533721b26249e2dcaee6ca1d51d3

6
app/3rdparty/lz4/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.10...3.27)
aux_source_directory(. LZ4_SOURCE)
add_library(lz4 ${LZ4_SOURCE})
target_include_directories(lz4 INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

View File

@ -1,4 +1,4 @@
/*
/*
LZ4 - Fast LZ compression algorithm
Copyright (C) 2011-2020, Yann Collet.
@ -425,7 +425,8 @@ static U16 LZ4_readLE16(const void* memPtr)
{
if (LZ4_isLittleEndian()) {
return LZ4_read16(memPtr);
} else {
}
else {
const BYTE* p = (const BYTE*)memPtr;
return (U16)((U16)p[0] + (p[1] << 8));
}
@ -435,7 +436,8 @@ static void LZ4_writeLE16(void* memPtr, U16 value)
{
if (LZ4_isLittleEndian()) {
LZ4_write16(memPtr, value);
} else {
}
else {
BYTE* p = (BYTE*)memPtr;
p[0] = (BYTE)value;
p[1] = (BYTE)(value >> 8);
@ -488,7 +490,8 @@ LZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, con
LZ4_memcpy(dstPtr + 4, srcPtr, 4);
srcPtr -= dec64table[offset];
dstPtr += 8;
} else {
}
else {
LZ4_memcpy(dstPtr, srcPtr, 8);
dstPtr += 8;
srcPtr += 8;
@ -590,7 +593,8 @@ static unsigned LZ4_NbCommonBytes (reg_t val)
val ^= val - 1;
return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56);
# endif
} else /* 32 bits */ {
}
else /* 32 bits */ {
# if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r;
_BitScanForward(&r, (U32)val);
@ -604,7 +608,8 @@ static unsigned LZ4_NbCommonBytes (reg_t val)
return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
# endif
}
} else /* Big Endian CPU */ {
}
else /* Big Endian CPU */ {
if (sizeof(val) == 8) {
# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
@ -635,13 +640,16 @@ static unsigned LZ4_NbCommonBytes (reg_t val)
Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
Note that this code path is never triggered in 32-bits mode. */
unsigned r;
if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
if (!(val >> by32)) { r = 4; }
else { r = 0; val >>= by32; }
if (!(val >> 16)) { r += 2; val >>= 8; }
else { val >>= 24; }
r += (!val);
return r;
#endif
# endif
} else /* 32 bits */ {
}
else /* 32 bits */ {
# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
!defined(LZ4_FORCE_SW_BITCOUNT)
@ -667,9 +675,11 @@ unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
if (!diff) {
pIn += STEPSIZE; pMatch += STEPSIZE;
} else {
}
else {
return LZ4_NbCommonBytes(diff);
} }
}
}
while (likely(pIn < pInLimit - (STEPSIZE - 1))) {
reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
@ -770,7 +780,8 @@ LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
if (LZ4_isLittleEndian()) {
const U64 prime5bytes = 889523592379ULL;
return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
} else {
}
else {
const U64 prime8bytes = 11400714785074694791ULL;
return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
}
@ -877,7 +888,8 @@ LZ4_prepareTable(LZ4_stream_t_internal* const cctx,
MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
cctx->currentOffset = 0;
cctx->tableType = (U32)clearedTable;
} else {
}
else {
DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
}
}
@ -970,7 +982,8 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
/* Instead, they use the block we just compressed. */
cctx->dictCtx = NULL;
cctx->dictSize = (U32)inputSize;
} else {
}
else {
cctx->dictSize += (U32)inputSize;
}
cctx->currentOffset += (U32)inputSize;
@ -982,7 +995,8 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
{ U32 const h = LZ4_hashPosition(ip, tableType);
if (tableType == byPtr) {
LZ4_putPositionOnHash(ip, h, cctx->hashTable, byPtr);
} else {
}
else {
LZ4_putIndexOnHash(startIndex, h, cctx->hashTable, tableType);
} }
ip++; forwardH = LZ4_hashPosition(ip, tableType);
@ -1014,7 +1028,8 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
} while ((match + LZ4_DISTANCE_MAX < ip)
|| (LZ4_read32(match) != LZ4_read32(ip)));
} else { /* byU32, byU16 */
}
else { /* byU32, byU16 */
const BYTE* forwardIp = ip;
int step = 1;
@ -1040,22 +1055,26 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
match = dictBase + matchIndex;
matchIndex += dictDelta; /* make dictCtx index comparable with current context */
lowLimit = dictionary;
} else {
}
else {
match = base + matchIndex;
lowLimit = (const BYTE*)source;
}
} else if (dictDirective == usingExtDict) {
}
else if (dictDirective == usingExtDict) {
if (matchIndex < startIndex) {
DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex);
assert(startIndex - matchIndex >= MINMATCH);
assert(dictBase);
match = dictBase + matchIndex;
lowLimit = dictionary;
} else {
}
else {
match = base + matchIndex;
lowLimit = (const BYTE*)source;
}
} else { /* single continuous memory segment */
}
else { /* single continuous memory segment */
match = base + matchIndex;
}
forwardH = LZ4_hashPosition(forwardIp, tableType);
@ -1130,7 +1149,8 @@ _next_match:
DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source));
assert(offset <= LZ4_DISTANCE_MAX && offset > 0);
LZ4_writeLE16(op, (U16)offset); op += 2;
} else {
}
else {
DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match));
assert(ip - match <= LZ4_DISTANCE_MAX);
LZ4_writeLE16(op, (U16)(ip - match)); op += 2;
@ -1152,7 +1172,8 @@ _next_match:
ip += more;
}
DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode + MINMATCH);
} else {
}
else {
matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, matchlimit);
ip += (size_t)matchCode + MINMATCH;
DEBUGLOG(6, " with matchLength=%u", matchCode + MINMATCH);
@ -1179,7 +1200,8 @@ _next_match:
LZ4_clearHash(h, cctx->hashTable, tableType);
}
}
} else {
}
else {
assert(outputDirective == limitedOutput);
return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
}
@ -1195,7 +1217,8 @@ _next_match:
}
op += matchCode / 255;
*op++ = (BYTE)(matchCode % 255);
} else
}
else
*token += (BYTE)(matchCode);
}
/* Ensure we have enough space for the last literals. */
@ -1210,7 +1233,8 @@ _next_match:
{ U32 const h = LZ4_hashPosition(ip - 2, tableType);
if (tableType == byPtr) {
LZ4_putPositionOnHash(ip - 2, h, cctx->hashTable, byPtr);
} else {
}
else {
U32 const idx = (U32)((ip - 2) - base);
LZ4_putIndexOnHash(idx, h, cctx->hashTable, tableType);
} }
@ -1222,9 +1246,12 @@ _next_match:
LZ4_putPosition(ip, cctx->hashTable, tableType);
if ((match + LZ4_DISTANCE_MAX >= ip)
&& (LZ4_read32(match) == LZ4_read32(ip)))
{ token=op++; *token=0; goto _next_match; }
{
token = op++; *token = 0; goto _next_match;
}
} else { /* byU32, byU16 */
}
else { /* byU32, byU16 */
U32 const h = LZ4_hashPosition(ip, tableType);
U32 const current = (U32)(ip - base);
@ -1238,20 +1265,24 @@ _next_match:
match = dictBase + matchIndex;
lowLimit = dictionary; /* required for match length counter */
matchIndex += dictDelta;
} else {
}
else {
match = base + matchIndex;
lowLimit = (const BYTE*)source; /* required for match length counter */
}
} else if (dictDirective==usingExtDict) {
}
else if (dictDirective == usingExtDict) {
if (matchIndex < startIndex) {
assert(dictBase);
match = dictBase + matchIndex;
lowLimit = dictionary; /* required for match length counter */
} else {
}
else {
match = base + matchIndex;
lowLimit = (const BYTE*)source; /* required for match length counter */
}
} else { /* single memory segment */
}
else { /* single memory segment */
match = base + matchIndex;
}
LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
@ -1283,7 +1314,8 @@ _last_literals:
assert(olimit >= op);
lastRun = (size_t)(olimit - op) - 1/*token*/;
lastRun -= (lastRun + 256 - RUN_MASK) / 256; /*additional length tokens*/
} else {
}
else {
assert(outputDirective == limitedOutput);
return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
}
@ -1294,7 +1326,8 @@ _last_literals:
*op++ = RUN_MASK << ML_BITS;
for (; accumulator >= 255; accumulator -= 255) *op++ = 255;
*op++ = (BYTE)accumulator;
} else {
}
else {
*op++ = (BYTE)(lastRun << ML_BITS);
}
LZ4_memcpy(op, anchor, lastRun);
@ -1362,14 +1395,17 @@ int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int
if (maxOutputSize >= LZ4_compressBound(inputSize)) {
if (inputSize < LZ4_64Klimit) {
return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
} else {
}
else {
const tableType_t tableType = ((sizeof(void*) == 4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
}
} else {
}
else {
if (inputSize < LZ4_64Klimit) {
return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
} else {
}
else {
const tableType_t tableType = ((sizeof(void*) == 4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
}
@ -1398,24 +1434,29 @@ int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst
LZ4_prepareTable(ctx, srcSize, tableType);
if (ctx->currentOffset) {
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
} else {
}
else {
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
}
} else {
}
else {
const tableType_t tableType = ((sizeof(void*) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
LZ4_prepareTable(ctx, srcSize, tableType);
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
}
} else {
}
else {
if (srcSize < LZ4_64Klimit) {
const tableType_t tableType = byU16;
LZ4_prepareTable(ctx, srcSize, tableType);
if (ctx->currentOffset) {
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
} else {
}
else {
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
}
} else {
}
else {
const tableType_t tableType = ((sizeof(void*) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
LZ4_prepareTable(ctx, srcSize, tableType);
return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
@ -1459,13 +1500,16 @@ static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src,
if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */
return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
} else {
}
else {
if (*srcSizePtr < LZ4_64Klimit) {
return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
} else {
}
else {
tableType_t const addrMode = ((sizeof(void*) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
} }
}
}
}
@ -1703,13 +1747,16 @@ int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream,
*/
LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr));
result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
} else {
}
else {
result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
}
} else { /* small data <= 4 KB */
}
else { /* small data <= 4 KB */
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
} else {
}
else {
result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
}
}
@ -1730,7 +1777,8 @@ int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char*
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
} else {
}
else {
result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
}
@ -1876,7 +1924,8 @@ LZ4_decompress_unsafe_generic(
LZ4_memmove(op, extMatch, ml);
op += ml;
ml = 0;
} else {
}
else {
/* match split between extDict & prefix */
LZ4_memmove(op, extMatch, extml);
op += extml;
@ -2030,7 +2079,8 @@ LZ4_decompress_generic(
if ((cpy > oend - 32) || (ip + length > iend - 32)) { goto safe_literal_copy; }
LZ4_wildCopy32(op, ip, cpy);
ip += length; op = cpy;
} else {
}
else {
cpy = op + length;
DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
/* We don't need to check oend, since we check it once for each loop below */
@ -2065,7 +2115,8 @@ LZ4_decompress_generic(
if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
goto safe_match_copy;
}
} else {
}
else {
length += MINMATCH;
if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
goto safe_match_copy;
@ -2083,7 +2134,9 @@ LZ4_decompress_generic(
LZ4_memcpy(op + 16, match + 16, 2);
op += length;
continue;
} } }
}
}
}
if (checkOffset && (unlikely(match + dictSize < lowPrefix))) {
DEBUGLOG(6, "Error : pos=%zi, offset=%zi => outside buffers", op - lowPrefix, op - match);
@ -2096,16 +2149,19 @@ LZ4_decompress_generic(
if (partialDecoding) {
DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
length = MIN(length, (size_t)(oend - op));
} else {
}
else {
DEBUGLOG(6, "end-of-block condition violated")
goto _output_error;
} }
}
}
if (length <= (size_t)(lowPrefix - match)) {
/* match fits entirely within external dictionary : just copy */
LZ4_memmove(op, dictEnd - (lowPrefix - match), length);
op += length;
} else {
}
else {
/* match stretches into both external dictionary and current block */
size_t const copySize = (size_t)(lowPrefix - match);
size_t const restSize = length - copySize;
@ -2115,10 +2171,12 @@ LZ4_decompress_generic(
BYTE* const endOfMatch = op + restSize;
const BYTE* copyFrom = lowPrefix;
while (op < endOfMatch) { *op++ = *copyFrom++; }
} else {
}
else {
LZ4_memcpy(op, lowPrefix, restSize);
op += restSize;
} }
}
}
continue;
}
@ -2128,7 +2186,8 @@ LZ4_decompress_generic(
assert((op <= oend) && (oend - op >= 32));
if (unlikely(offset < 16)) {
LZ4_memcpy_using_offset(op, match, cpy, offset);
} else {
}
else {
LZ4_wildCopy32(op, match, cpy);
}
@ -2229,7 +2288,8 @@ LZ4_decompress_generic(
assert(op <= oend);
length = (size_t)(oend - op);
}
} else {
}
else {
/* We must be on the last sequence (or invalid) because of the parsing limitations
* so check that we exactly consume the input and don't overrun the output buffer.
*/
@ -2251,7 +2311,8 @@ LZ4_decompress_generic(
if (!partialDecoding || (cpy == oend) || (ip >= (iend - 2))) {
break;
}
} else {
}
else {
LZ4_wildCopy8(op, ip, cpy); /* can overwrite up to 8 bytes beyond cpy */
ip += length; op = cpy;
}
@ -2288,7 +2349,8 @@ LZ4_decompress_generic(
/* match fits entirely within external dictionary : just copy */
LZ4_memmove(op, dictEnd - (lowPrefix - match), length);
op += length;
} else {
}
else {
/* match stretches into both external dictionary and current block */
size_t const copySize = (size_t)(lowPrefix - match);
size_t const restSize = length - copySize;
@ -2298,10 +2360,12 @@ LZ4_decompress_generic(
BYTE* const endOfMatch = op + restSize;
const BYTE* copyFrom = lowPrefix;
while (op < endOfMatch) *op++ = *copyFrom++;
} else {
}
else {
LZ4_memcpy(op, lowPrefix, restSize);
op += restSize;
} }
}
}
continue;
}
assert(match >= lowPrefix);
@ -2317,7 +2381,8 @@ LZ4_decompress_generic(
BYTE* const copyEnd = op + mlen;
if (matchEnd > op) { /* overlap copy */
while (op < copyEnd) { *op++ = *match++; }
} else {
}
else {
LZ4_memcpy(op, match, mlen);
}
op = copyEnd;
@ -2334,7 +2399,8 @@ LZ4_decompress_generic(
match += inc32table[offset];
LZ4_memcpy(op + 4, match, 4);
match -= dec64table[offset];
} else {
}
else {
LZ4_memcpy(op, match, 8);
match += 8;
}
@ -2349,7 +2415,8 @@ LZ4_decompress_generic(
op = oCopyLimit;
}
while (op < cpy) { *op++ = *match++; }
} else {
}
else {
LZ4_memcpy(op, match, 8);
if (length > 16) { LZ4_wildCopy8(op + 8, match + 8, cpy); }
}
@ -2515,7 +2582,8 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti
if (dictSize) {
assert(dictionary != NULL);
lz4sd->prefixEnd = (const BYTE*)dictionary + dictSize;
} else {
}
else {
lz4sd->prefixEnd = (const BYTE*)dictionary;
}
lz4sd->externalDict = NULL;
@ -2562,7 +2630,8 @@ int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const ch
if (result <= 0) return result;
lz4sd->prefixSize = (size_t)result;
lz4sd->prefixEnd = (BYTE*)dest + result;
} else if (lz4sd->prefixEnd == (BYTE*)dest) {
}
else if (lz4sd->prefixEnd == (BYTE*)dest) {
/* They're rolling the current segment. */
if (lz4sd->prefixSize >= 64 KB - 1)
result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
@ -2575,7 +2644,8 @@ int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const ch
if (result <= 0) return result;
lz4sd->prefixSize += (size_t)result;
lz4sd->prefixEnd += result;
} else {
}
else {
/* The buffer wraps around, or they're switching to another buffer. */
lz4sd->extDictSize = lz4sd->prefixSize;
lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
@ -2607,7 +2677,8 @@ LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode,
if (result <= 0) return result;
lz4sd->prefixSize = (size_t)originalSize;
lz4sd->prefixEnd = (BYTE*)dest + originalSize;
} else if (lz4sd->prefixEnd == (BYTE*)dest) {
}
else if (lz4sd->prefixEnd == (BYTE*)dest) {
DEBUGLOG(5, "continue using existing prefix");
result = LZ4_decompress_unsafe_generic(
(const BYTE*)source, (BYTE*)dest, originalSize,
@ -2616,7 +2687,8 @@ LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode,
if (result <= 0) return result;
lz4sd->prefixSize += (size_t)originalSize;
lz4sd->prefixEnd += originalSize;
} else {
}
else {
DEBUGLOG(5, "prefix becomes extDict");
lz4sd->extDictSize = lz4sd->prefixSize;
lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;

862
app/3rdparty/lz4/lz4.h vendored Normal file
View File

@ -0,0 +1,862 @@
/*
* LZ4 - Fast LZ compression algorithm
* Header File
* Copyright (C) 2011-2020, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://www.lz4.org
- LZ4 source repository : https://github.com/lz4/lz4
*/
#if defined (__cplusplus)
extern "C" {
#endif
#ifndef LZ4_H_2983827168210
#define LZ4_H_2983827168210
/* --- Dependency --- */
#include <stddef.h> /* size_t */
/**
Introduction
LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core,
scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
The LZ4 compression library provides in-memory compression and decompression functions.
It gives full buffer control to user.
Compression can be done in:
- a single step (described as Simple Functions)
- a single step, reusing a context (described in Advanced Functions)
- unbounded multiple steps (described as Streaming compression)
lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md).
Decompressing such a compressed block requires additional metadata.
Exact metadata depends on exact decompression function.
For the typical case of LZ4_decompress_safe(),
metadata includes block's compressed size, and maximum bound of decompressed size.
Each application is free to encode and pass such metadata in whichever way it wants.
lz4.h only handle blocks, it can not generate Frames.
Blocks are different from Frames (doc/lz4_Frame_format.md).
Frames bundle both blocks and metadata in a specified manner.
Embedding metadata is required for compressed data to be self-contained and portable.
Frame format is delivered through a companion API, declared in lz4frame.h.
The `lz4` CLI can only manage frames.
*/
/*^***************************************************************
* Export parameters
*****************************************************************/
/*
* LZ4_DLL_EXPORT :
* Enable exporting of functions when building a Windows DLL
* LZ4LIB_VISIBILITY :
* Control library symbols visibility.
*/
#ifndef LZ4LIB_VISIBILITY
# if defined(__GNUC__) && (__GNUC__ >= 4)
# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default")))
# else
# define LZ4LIB_VISIBILITY
# endif
#endif
#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY
#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
#else
# define LZ4LIB_API LZ4LIB_VISIBILITY
#endif
/*! LZ4_FREESTANDING :
* When this macro is set to 1, it enables "freestanding mode" that is
* suitable for typical freestanding environment which doesn't support
* standard C library.
*
* - LZ4_FREESTANDING is a compile-time switch.
* - It requires the following macros to be defined:
* LZ4_memcpy, LZ4_memmove, LZ4_memset.
* - It only enables LZ4/HC functions which don't use heap.
* All LZ4F_* functions are not supported.
* - See tests/freestanding.c to check its basic setup.
*/
#if defined(LZ4_FREESTANDING) && (LZ4_FREESTANDING == 1)
# define LZ4_HEAPMODE 0
# define LZ4HC_HEAPMODE 0
# define LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION 1
# if !defined(LZ4_memcpy)
# error "LZ4_FREESTANDING requires macro 'LZ4_memcpy'."
# endif
# if !defined(LZ4_memset)
# error "LZ4_FREESTANDING requires macro 'LZ4_memset'."
# endif
# if !defined(LZ4_memmove)
# error "LZ4_FREESTANDING requires macro 'LZ4_memmove'."
# endif
#elif ! defined(LZ4_FREESTANDING)
# define LZ4_FREESTANDING 0
#endif
/*------ Version ------*/
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
#define LZ4_VERSION_MINOR 9 /* for new (non-breaking) interface capabilities */
#define LZ4_VERSION_RELEASE 4 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
#define LZ4_QUOTE(str) #str
#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) /* requires v1.7.3+ */
LZ4LIB_API int LZ4_versionNumber(void); /**< library version number; useful to check dll version; requires v1.3.0+ */
LZ4LIB_API const char* LZ4_versionString(void); /**< library version string; useful to check dll version; requires v1.7.5+ */
/*-************************************
* Tuning parameter
**************************************/
#define LZ4_MEMORY_USAGE_MIN 10
#define LZ4_MEMORY_USAGE_DEFAULT 14
#define LZ4_MEMORY_USAGE_MAX 20
/*!
* LZ4_MEMORY_USAGE :
* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; )
* Increasing memory usage improves compression ratio, at the cost of speed.
* Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality.
* Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
*/
#ifndef LZ4_MEMORY_USAGE
# define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
#endif
#if (LZ4_MEMORY_USAGE < LZ4_MEMORY_USAGE_MIN)
# error "LZ4_MEMORY_USAGE is too small !"
#endif
#if (LZ4_MEMORY_USAGE > LZ4_MEMORY_USAGE_MAX)
# error "LZ4_MEMORY_USAGE is too large !"
#endif
/*-************************************
* Simple Functions
**************************************/
/*! LZ4_compress_default() :
* Compresses 'srcSize' bytes from buffer 'src'
* into already allocated 'dst' buffer of size 'dstCapacity'.
* Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize).
* It also runs faster, so it's a recommended setting.
* If the function cannot compress 'src' into a more limited 'dst' budget,
* compression stops *immediately*, and the function result is zero.
* In which case, 'dst' content is undefined (invalid).
* srcSize : max supported value is LZ4_MAX_INPUT_SIZE.
* dstCapacity : size of buffer 'dst' (which must be already allocated)
* @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity)
* or 0 if compression fails
* Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer).
*/
LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);
/*! LZ4_decompress_safe() :
* @compressedSize : is the exact complete size of the compressed block.
* @dstCapacity : is the size of destination buffer (which must be already allocated),
* is an upper bound of decompressed size.
* @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
* If destination buffer is not large enough, decoding will stop and output an error code (negative value).
* If the source stream is detected malformed, the function will stop decoding and return a negative result.
* Note 1 : This function is protected against malicious data packets :
* it will never writes outside 'dst' buffer, nor read outside 'source' buffer,
* even if the compressed block is maliciously modified to order the decoder to do these actions.
* In such case, the decoder stops immediately, and considers the compressed block malformed.
* Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them.
* The implementation is free to send / store / derive this information in whichever way is most beneficial.
* If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead.
*/
LZ4LIB_API int LZ4_decompress_safe(const char* src, char* dst, int compressedSize, int dstCapacity);
/*-************************************
* Advanced Functions
**************************************/
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
/*! LZ4_compressBound() :
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
This function is primarily useful for memory allocation purposes (destination buffer size).
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize)
inputSize : max supported value is LZ4_MAX_INPUT_SIZE
return : maximum output size in a "worst case" scenario
or 0, if input size is incorrect (too large or negative)
*/
LZ4LIB_API int LZ4_compressBound(int inputSize);
/*! LZ4_compress_fast() :
Same as LZ4_compress_default(), but allows selection of "acceleration" factor.
The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
An acceleration value of "1" is the same as regular LZ4_compress_default()
Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c).
Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c).
*/
LZ4LIB_API int LZ4_compress_fast(const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_compress_fast_extState() :
* Same as LZ4_compress_fast(), using an externally allocated memory space for its state.
* Use LZ4_sizeofState() to know how much memory must be allocated,
* and allocate it on 8-bytes boundaries (using `malloc()` typically).
* Then, provide this buffer as `void* state` to compression function.
*/
LZ4LIB_API int LZ4_sizeofState(void);
LZ4LIB_API int LZ4_compress_fast_extState(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_compress_destSize() :
* Reverse the logic : compresses as much data as possible from 'src' buffer
* into already allocated buffer 'dst', of size >= 'targetDestSize'.
* This function either compresses the entire 'src' content into 'dst' if it's large enough,
* or fill 'dst' buffer completely with as much data as possible from 'src'.
* note: acceleration parameter is fixed to "default".
*
* *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
* New value is necessarily <= input value.
* @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
* or 0 if compression fails.
*
* Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):
* the produced compressed content could, in specific circumstances,
* require to be decompressed into a destination buffer larger
* by at least 1 byte than the content to decompress.
* If an application uses `LZ4_compress_destSize()`,
* it's highly recommended to update liblz4 to v1.9.2 or better.
* If this can't be done or ensured,
* the receiving decompression function should provide
* a dstCapacity which is > decompressedSize, by at least 1 byte.
* See https://github.com/lz4/lz4/issues/859 for details
*/
LZ4LIB_API int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize);
/*! LZ4_decompress_safe_partial() :
* Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',
* into destination buffer 'dst' of size 'dstCapacity'.
* Up to 'targetOutputSize' bytes will be decoded.
* The function stops decoding on reaching this objective.
* This can be useful to boost performance
* whenever only the beginning of a block is required.
*
* @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize)
* If source stream is detected malformed, function returns a negative result.
*
* Note 1 : @return can be < targetOutputSize, if compressed block contains less data.
*
* Note 2 : targetOutputSize must be <= dstCapacity
*
* Note 3 : this function effectively stops decoding on reaching targetOutputSize,
* so dstCapacity is kind of redundant.
* This is because in older versions of this function,
* decoding operation would still write complete sequences.
* Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize,
* it could write more bytes, though only up to dstCapacity.
* Some "margin" used to be required for this operation to work properly.
* Thankfully, this is no longer necessary.
* The function nonetheless keeps the same signature, in an effort to preserve API compatibility.
*
* Note 4 : If srcSize is the exact size of the block,
* then targetOutputSize can be any value,
* including larger than the block's decompressed size.
* The function will, at most, generate block's decompressed size.
*
* Note 5 : If srcSize is _larger_ than block's compressed size,
* then targetOutputSize **MUST** be <= block's decompressed size.
* Otherwise, *silent corruption will occur*.
*/
LZ4LIB_API int LZ4_decompress_safe_partial(const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity);
/*-*********************************************
* Streaming Compression Functions
***********************************************/
typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
/**
Note about RC_INVOKED
- RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio).
https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros
- Since rc.exe is a legacy compiler, it truncates long symbol (> 30 chars)
and reports warning "RC4011: identifier truncated".
- To eliminate the warning, we surround long preprocessor symbol with
"#if !defined(RC_INVOKED) ... #endif" block that means
"skip this block when rc.exe is trying to read it".
*/
#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
LZ4LIB_API LZ4_stream_t* LZ4_createStream(void);
LZ4LIB_API int LZ4_freeStream(LZ4_stream_t* streamPtr);
#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
#endif
/*! LZ4_resetStream_fast() : v1.9.0+
* Use this to prepare an LZ4_stream_t for a new chain of dependent blocks
* (e.g., LZ4_compress_fast_continue()).
*
* An LZ4_stream_t must be initialized once before usage.
* This is automatically done when created by LZ4_createStream().
* However, should the LZ4_stream_t be simply declared on stack (for example),
* it's necessary to initialize it first, using LZ4_initStream().
*
* After init, start any new stream with LZ4_resetStream_fast().
* A same LZ4_stream_t can be re-used multiple times consecutively
* and compress multiple streams,
* provided that it starts each new stream with LZ4_resetStream_fast().
*
* LZ4_resetStream_fast() is much faster than LZ4_initStream(),
* but is not compatible with memory regions containing garbage data.
*
* Note: it's only useful to call LZ4_resetStream_fast()
* in the context of streaming compression.
* The *extState* functions perform their own resets.
* Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive.
*/
LZ4LIB_API void LZ4_resetStream_fast(LZ4_stream_t* streamPtr);
/*! LZ4_loadDict() :
* Use this function to reference a static dictionary into LZ4_stream_t.
* The dictionary must remain available during compression.
* LZ4_loadDict() triggers a reset, so any previous data will be forgotten.
* The same dictionary will have to be loaded on decompression side for successful decoding.
* Dictionary are useful for better compression of small data (KB range).
* While LZ4 accept any input as dictionary,
* results are generally better when using Zstandard's Dictionary Builder.
* Loading a size of 0 is allowed, and is the same as reset.
* @return : loaded dictionary size, in bytes (necessarily <= 64 KB)
*/
LZ4LIB_API int LZ4_loadDict(LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
/*! LZ4_compress_fast_continue() :
* Compress 'src' content using data from previously compressed blocks, for better compression ratio.
* 'dst' buffer must be already allocated.
* If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
*
* @return : size of compressed block
* or 0 if there is an error (typically, cannot fit into 'dst').
*
* Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block.
* Each block has precise boundaries.
* Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata.
* It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together.
*
* Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory !
*
* Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB.
* Make sure that buffers are separated, by at least one byte.
* This construction ensures that each block only depends on previous block.
*
* Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB.
*
* Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed.
*/
LZ4LIB_API int LZ4_compress_fast_continue(LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_saveDict() :
* If last 64KB data cannot be guaranteed to remain available at its current memory location,
* save it into a safer place (char* safeBuffer).
* This is schematically equivalent to a memcpy() followed by LZ4_loadDict(),
* but is much faster, because LZ4_saveDict() doesn't need to rebuild tables.
* @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error.
*/
LZ4LIB_API int LZ4_saveDict(LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize);
/*-**********************************************
* Streaming Decompression Functions
* Bufferless synchronous API
************************************************/
typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */
/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() :
* creation / destruction of streaming decompression tracking context.
* A tracking context can be re-used multiple times.
*/
#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);
LZ4LIB_API int LZ4_freeStreamDecode(LZ4_streamDecode_t* LZ4_stream);
#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
#endif
/*! LZ4_setStreamDecode() :
* An LZ4_streamDecode_t context can be allocated once and re-used multiple times.
* Use this function to start decompression of a new stream of blocks.
* A dictionary can optionally be set. Use NULL or size 0 for a reset order.
* Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.
* @return : 1 if OK, 0 if error
*/
LZ4LIB_API int LZ4_setStreamDecode(LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
/*! LZ4_decoderRingBufferSize() : v1.8.2+
* Note : in a ring buffer scenario (optional),
* blocks are presumed decompressed next to each other
* up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize),
* at which stage it resumes from beginning of ring buffer.
* When setting such a ring buffer for streaming decompression,
* provides the minimum size of this ring buffer
* to be compatible with any source respecting maxBlockSize condition.
* @return : minimum ring buffer size,
* or 0 if there is an error (invalid maxBlockSize).
*/
LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */
/*! LZ4_decompress_safe_continue() :
* This decoding function allows decompression of consecutive blocks in "streaming" mode.
* The difference with the usual independent blocks is that
* new blocks are allowed to find references into former blocks.
* A block is an unsplittable entity, and must be presented entirely to the decompression function.
* LZ4_decompress_safe_continue() only accepts one block at a time.
* It's modeled after `LZ4_decompress_safe()` and behaves similarly.
*
* @LZ4_streamDecode : decompression state, tracking the position in memory of past data
* @compressedSize : exact complete size of one compressed block.
* @dstCapacity : size of destination buffer (which must be already allocated),
* must be an upper bound of decompressed size.
* @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
* If destination buffer is not large enough, decoding will stop and output an error code (negative value).
* If the source stream is detected malformed, the function will stop decoding and return a negative result.
*
* The last 64KB of previously decoded data *must* remain available and unmodified
* at the memory position where they were previously decoded.
* If less than 64KB of data has been decoded, all the data must be present.
*
* Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
* - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize).
* maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes.
* In which case, encoding and decoding buffers do not need to be synchronized.
* Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize.
* - Synchronized mode :
* Decompression buffer size is _exactly_ the same as compression buffer size,
* and follows exactly same update rule (block boundaries at same positions),
* and decoding function is provided with exact decompressed size of each block (exception for last block of the stream),
* _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB).
* - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes.
* In which case, encoding and decoding buffers do not need to be synchronized,
* and encoding ring buffer can have any size, including small ones ( < 64 KB).
*
* Whenever these conditions are not possible,
* save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression,
* then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block.
*/
LZ4LIB_API int
LZ4_decompress_safe_continue(LZ4_streamDecode_t* LZ4_streamDecode,
const char* src, char* dst,
int srcSize, int dstCapacity);
/*! LZ4_decompress_safe_usingDict() :
* Works the same as
* a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue()
* However, it's stateless: it doesn't need any LZ4_streamDecode_t state.
* Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
* Performance tip : Decompression speed can be substantially increased
* when dst == dictStart + dictSize.
*/
LZ4LIB_API int
LZ4_decompress_safe_usingDict(const char* src, char* dst,
int srcSize, int dstCapacity,
const char* dictStart, int dictSize);
/*! LZ4_decompress_safe_partial_usingDict() :
* Behaves the same as LZ4_decompress_safe_partial()
* with the added ability to specify a memory segment for past data.
* Performance tip : Decompression speed can be substantially increased
* when dst == dictStart + dictSize.
*/
LZ4LIB_API int
LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
int compressedSize,
int targetOutputSize, int maxOutputSize,
const char* dictStart, int dictSize);
#endif /* LZ4_H_2983827168210 */
/*^*************************************
* !!!!!! STATIC LINKING ONLY !!!!!!
***************************************/
/*-****************************************************************************
* Experimental section
*
* Symbols declared in this section must be considered unstable. Their
* signatures or semantics may change, or they may be removed altogether in the
* future. They are therefore only safe to depend on when the caller is
* statically linked against the library.
*
* To protect against unsafe usage, not only are the declarations guarded,
* the definitions are hidden by default
* when building LZ4 as a shared/dynamic library.
*
* In order to access these declarations,
* define LZ4_STATIC_LINKING_ONLY in your application
* before including LZ4's headers.
*
* In order to make their implementations accessible dynamically, you must
* define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library.
******************************************************************************/
#ifdef LZ4_STATIC_LINKING_ONLY
#ifndef LZ4_STATIC_3504398509
#define LZ4_STATIC_3504398509
#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS
#define LZ4LIB_STATIC_API LZ4LIB_API
#else
#define LZ4LIB_STATIC_API
#endif
/*! LZ4_compress_fast_extState_fastReset() :
* A variant of LZ4_compress_fast_extState().
*
* Using this variant avoids an expensive initialization step.
* It is only safe to call if the state buffer is known to be correctly initialized already
* (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized").
* From a high level, the difference is that
* this function initializes the provided state with a call to something like LZ4_resetStream_fast()
* while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream().
*/
LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_attach_dictionary() :
* This is an experimental API that allows
* efficient use of a static dictionary many times.
*
* Rather than re-loading the dictionary buffer into a working context before
* each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
* working LZ4_stream_t, this function introduces a no-copy setup mechanism,
* in which the working stream references the dictionary stream in-place.
*
* Several assumptions are made about the state of the dictionary stream.
* Currently, only streams which have been prepared by LZ4_loadDict() should
* be expected to work.
*
* Alternatively, the provided dictionaryStream may be NULL,
* in which case any existing dictionary stream is unset.
*
* If a dictionary is provided, it replaces any pre-existing stream history.
* The dictionary contents are the only history that can be referenced and
* logically immediately precede the data compressed in the first subsequent
* compression call.
*
* The dictionary will only remain attached to the working stream through the
* first compression call, at the end of which it is cleared. The dictionary
* stream (and source buffer) must remain in-place / accessible / unchanged
* through the completion of the first compression call on the stream.
*/
LZ4LIB_STATIC_API void
LZ4_attach_dictionary(LZ4_stream_t* workingStream,
const LZ4_stream_t* dictionaryStream);
/*! In-place compression and decompression
*
* It's possible to have input and output sharing the same buffer,
* for highly constrained memory environments.
* In both cases, it requires input to lay at the end of the buffer,
* and decompression to start at beginning of the buffer.
* Buffer size must feature some margin, hence be larger than final size.
*
* |<------------------------buffer--------------------------------->|
* |<-----------compressed data--------->|
* |<-----------decompressed size------------------>|
* |<----margin---->|
*
* This technique is more useful for decompression,
* since decompressed size is typically larger,
* and margin is short.
*
* In-place decompression will work inside any buffer
* which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize).
* This presumes that decompressedSize > compressedSize.
* Otherwise, it means compression actually expanded data,
* and it would be more efficient to store such data with a flag indicating it's not compressed.
* This can happen when data is not compressible (already compressed, or encrypted).
*
* For in-place compression, margin is larger, as it must be able to cope with both
* history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX,
* and data expansion, which can happen when input is not compressible.
* As a consequence, buffer size requirements are much higher,
* and memory savings offered by in-place compression are more limited.
*
* There are ways to limit this cost for compression :
* - Reduce history size, by modifying LZ4_DISTANCE_MAX.
* Note that it is a compile-time constant, so all compressions will apply this limit.
* Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX,
* so it's a reasonable trick when inputs are known to be small.
* - Require the compressor to deliver a "maximum compressed size".
* This is the `dstCapacity` parameter in `LZ4_compress*()`.
* When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail,
* in which case, the return code will be 0 (zero).
* The caller must be ready for these cases to happen,
* and typically design a backup scheme to send data uncompressed.
* The combination of both techniques can significantly reduce
* the amount of margin required for in-place compression.
*
* In-place compression can work in any buffer
* which size is >= (maxCompressedSize)
* with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success.
* LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX,
* so it's possible to reduce memory requirements by playing with them.
*/
#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize) (((compressedSize) >> 8) + 32)
#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize) ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize)) /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */
#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */
# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */
#endif
#define LZ4_COMPRESS_INPLACE_MARGIN (LZ4_DISTANCE_MAX + 32) /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */
#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize) ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN) /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */
#endif /* LZ4_STATIC_3504398509 */
#endif /* LZ4_STATIC_LINKING_ONLY */
#ifndef LZ4_H_98237428734687
#define LZ4_H_98237428734687
/*-************************************************************
* Private Definitions
**************************************************************
* Do not use these definitions directly.
* They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
* Accessing members will expose user code to API and/or ABI break in future versions of the library.
**************************************************************/
#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
# include <stdint.h>
typedef int8_t LZ4_i8;
typedef uint8_t LZ4_byte;
typedef uint16_t LZ4_u16;
typedef uint32_t LZ4_u32;
#else
typedef signed char LZ4_i8;
typedef unsigned char LZ4_byte;
typedef unsigned short LZ4_u16;
typedef unsigned int LZ4_u32;
#endif
/*! LZ4_stream_t :
* Never ever use below internal definitions directly !
* These definitions are not API/ABI safe, and may change in future versions.
* If you need static allocation, declare or allocate an LZ4_stream_t object.
**/
typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
struct LZ4_stream_t_internal {
LZ4_u32 hashTable[LZ4_HASH_SIZE_U32];
const LZ4_byte* dictionary;
const LZ4_stream_t_internal* dictCtx;
LZ4_u32 currentOffset;
LZ4_u32 tableType;
LZ4_u32 dictSize;
/* Implicit padding to ensure structure is aligned */
};
#define LZ4_STREAM_MINSIZE ((1UL << LZ4_MEMORY_USAGE) + 32) /* static size, for inter-version compatibility */
union LZ4_stream_u {
char minStateSize[LZ4_STREAM_MINSIZE];
LZ4_stream_t_internal internal_donotuse;
}; /* previously typedef'd to LZ4_stream_t */
/*! LZ4_initStream() : v1.9.0+
* An LZ4_stream_t structure must be initialized at least once.
* This is automatically done when invoking LZ4_createStream(),
* but it's not when the structure is simply declared on stack (for example).
*
* Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t.
* It can also initialize any arbitrary buffer of sufficient size,
* and will @return a pointer of proper type upon initialization.
*
* Note : initialization fails if size and alignment conditions are not respected.
* In which case, the function will @return NULL.
* Note2: An LZ4_stream_t structure guarantees correct alignment and size.
* Note3: Before v1.9.0, use LZ4_resetStream() instead
**/
LZ4LIB_API LZ4_stream_t* LZ4_initStream(void* buffer, size_t size);
/*! LZ4_streamDecode_t :
* Never ever use below internal definitions directly !
* These definitions are not API/ABI safe, and may change in future versions.
* If you need static allocation, declare or allocate an LZ4_streamDecode_t object.
**/
typedef struct {
const LZ4_byte* externalDict;
const LZ4_byte* prefixEnd;
size_t extDictSize;
size_t prefixSize;
} LZ4_streamDecode_t_internal;
#define LZ4_STREAMDECODE_MINSIZE 32
union LZ4_streamDecode_u {
char minStateSize[LZ4_STREAMDECODE_MINSIZE];
LZ4_streamDecode_t_internal internal_donotuse;
}; /* previously typedef'd to LZ4_streamDecode_t */
/*-************************************
* Obsolete Functions
**************************************/
/*! Deprecation warnings
*
* Deprecated functions make the compiler generate a warning when invoked.
* This is meant to invite users to update their source code.
* Should deprecation warnings be a problem, it is generally possible to disable them,
* typically with -Wno-deprecated-declarations for gcc
* or _CRT_SECURE_NO_WARNINGS in Visual.
*
* Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS
* before including the header file.
*/
#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS
# define LZ4_DEPRECATED(message) /* disable deprecation warnings */
#else
# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
# define LZ4_DEPRECATED(message) [[deprecated(message)]]
# elif defined(_MSC_VER)
# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45))
# define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
# elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31)
# define LZ4_DEPRECATED(message) __attribute__((deprecated))
# else
# pragma message("WARNING: LZ4_DEPRECATED needs custom implementation for this compiler")
# define LZ4_DEPRECATED(message) /* disabled */
# endif
#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */
/*! Obsolete compression functions (since v1.7.3) */
LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress(const char* src, char* dest, int srcSize);
LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput(const char* src, char* dest, int srcSize, int maxOutputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState(void* state, const char* source, char* dest, int inputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue(LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue(LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
/*! Obsolete decompression functions (since v1.8.0) */
LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress(const char* source, char* dest, int outputSize);
LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize(const char* source, char* dest, int isize, int maxOutputSize);
/* Obsolete streaming functions (since v1.7.0)
* degraded functionality; do not use!
*
* In order to perform streaming compression, these functions depended on data
* that is no longer tracked in the state. They have been preserved as well as
* possible: using them will still produce a correct output. However, they don't
* actually retain any history between compression calls. The compression ratio
* achieved will therefore be no better than compressing each chunk
* independently.
*/
LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create(char* inputBuffer);
LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void);
LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer);
LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer(void* state);
/*! Obsolete streaming decoding functions (since v1.7.0) */
LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k(const char* src, char* dst, int compressedSize, int maxDstSize);
LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k(const char* src, char* dst, int originalSize);
/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) :
* These functions used to be faster than LZ4_decompress_safe(),
* but this is no longer the case. They are now slower.
* This is because LZ4_decompress_fast() doesn't know the input size,
* and therefore must progress more cautiously into the input buffer to not read beyond the end of block.
* On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability.
* As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated.
*
* The last remaining LZ4_decompress_fast() specificity is that
* it can decompress a block without knowing its compressed size.
* Such functionality can be achieved in a more secure manner
* by employing LZ4_decompress_safe_partial().
*
* Parameters:
* originalSize : is the uncompressed size to regenerate.
* `dst` must be already allocated, its size must be >= 'originalSize' bytes.
* @return : number of bytes read from source buffer (== compressed size).
* The function expects to finish at block's end exactly.
* If the source stream is detected malformed, the function stops decoding and returns a negative result.
* note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer.
* However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds.
* Also, since match offsets are not validated, match reads from 'src' may underflow too.
* These issues never happen if input (compressed) data is correct.
* But they may happen if input data is invalid (error or intentional tampering).
* As a consequence, use these functions in trusted environments with trusted data **only**.
*/
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
LZ4LIB_API int LZ4_decompress_fast(const char* src, char* dst, int originalSize);
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
LZ4LIB_API int LZ4_decompress_fast_continue(LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
LZ4LIB_API int LZ4_decompress_fast_usingDict(const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
/*! LZ4_resetStream() :
* An LZ4_stream_t structure must be initialized at least once.
* This is done with LZ4_initStream(), or LZ4_resetStream().
* Consider switching to LZ4_initStream(),
* invoking LZ4_resetStream() will trigger deprecation warnings in the future.
*/
LZ4LIB_API void LZ4_resetStream(LZ4_stream_t* streamPtr);
#endif /* LZ4_H_98237428734687 */
#if defined (__cplusplus)
}
#endif

6
app/3rdparty/mongoose/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.10...3.27)
aux_source_directory(. MONGOOSE_SOURCE)
add_library(mongoose ${MONGOOSE_SOURCE})
target_include_directories(mongoose INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

8847
app/3rdparty/mongoose/mongoose.c vendored Normal file

File diff suppressed because it is too large Load Diff

1760
app/3rdparty/mongoose/mongoose.h vendored Normal file

File diff suppressed because it is too large Load Diff

1
app/3rdparty/spdlog vendored Submodule

@ -0,0 +1 @@
Subproject commit 91807c2e718890ca2c0c88620326c6919ce041f4

15
app/3rdparty/tinyxml2/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,15 @@
cmake_minimum_required(VERSION 3.10...3.27)
aux_source_directory(. TINYXML2_SOURCE)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN YES)
#add_library(tinyxml2 tinyxml2.cpp tinyxml2.h)
add_library(tinyxml2 ${TINYXML2_SOURCE})
add_library(tinyxml2::tinyxml2 ALIAS tinyxml2)
target_include_directories(tinyxml2 INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

View File

@ -1,4 +1,4 @@
/*
/*
Original code by Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied

View File

@ -1,4 +1,4 @@
/*
/*
Original code by Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied

7
app/CMakeLists.txt Normal file
View File

@ -0,0 +1,7 @@
cmake_minimum_required(VERSION 3.10...3.27)
add_subdirectory(injector)
add_subdirectory(wxhelper)

10
app/base/CMakeLists.txt Normal file
View File

@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 3.10...3.27)
aux_source_directory(./src BASE_SOURCE)
aux_source_directory(./src/include BASE_HEADER_SOURCE)
add_library(base ${BASE_SOURCE} ${BASE_HEADER_SOURCE})
target_include_directories(base PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/include)

View File

@ -0,0 +1,30 @@
#ifndef BASE_BASE_CONFIG_H_
#define BASE_BASE_CONFIG_H_
// Lib/Dll switch
#if !defined(BASE_EXPORTS) && !defined(BASE_IMPORTS) && !defined(BASE_STATIC)
#define BASE_STATIC
#endif
#if defined(_MSC_VER)
#ifndef COMPILER_MSVC
#define COMPILER_MSVC 1
#endif
#if defined(BASE_IMPORTS)
#define BASE_API __declspec(dllimport)
#elif defined(BASE_EXPORTS)
#define BASE_API __declspec(dllexport)
#else
#define BASE_API
#endif
#elif defined(__GNUC__)
#define COMPILER_GCC
#define BASE_API
#else
#error "Unknown or unsupported compiler"
#endif
#endif

View File

@ -0,0 +1,11 @@
#ifndef BASE_MEMORY_H_
#define BASE_MEMORY_H_
#include <windows.h>
#include <vector>
namespace base {
namespace memory {
std::vector<INT64> ScanAndMatchValue(INT64 value, INT64 start,int align);
int Sunday(const byte* total, int tlen, const byte* part, int plen);
}
} // namespace base
#endif

View File

@ -0,0 +1,11 @@
#ifndef BASE_NONCOPYABLE_H_
#define BASE_NONCOPYABLE_H_
class NonCopyable {
protected:
NonCopyable() {}
~NonCopyable() {}
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
#endif

View File

@ -1,5 +1,6 @@
#ifndef WXHELPER_SINGLETON_H_
#define WXHELPER_SINGLETON_H_
#ifndef BASE_SINGLETON_H_
#define BASE_SINGLETON_H_
namespace base {
template <typename T>
class Singleton {
protected:
@ -18,4 +19,5 @@ class Singleton {
return instance;
}
};
} // namespace base
#endif

View File

@ -1,8 +1,9 @@
#ifndef WXHELPER_THREAD_POOL_H_
#define WXHELPER_THREAD_POOL_H_
#include "Windows.h"
#ifndef BASE_THREAD_POOL_H_
#define BASE_THREAD_POOL_H_
#include "singleton.h"
namespace wxhelper {
#include <windows.h>
namespace base {
class ThreadPool :public Singleton<ThreadPool>{
public:

View File

@ -0,0 +1,73 @@
#ifndef BASE_UTILS_H_
#define BASE_UTILS_H_
#include <windows.h>
#include <string>
#include <vector>
namespace base {
namespace utils {
std::wstring Utf8ToWstring(const std::string &str);
std::string WstringToUtf8(const std::wstring &str);
std::wstring AnsiToWstring(const std::string &input, INT64 locale = CP_ACP);
std::string WstringToAnsi(const std::wstring &input, INT64 locale = CP_ACP);
std::string WcharToUtf8(wchar_t *wstr);
std::string StringToHex(const std::string &str);
std::string HexToString(const std::string &hex_str);
std::string BytesToHex(const BYTE *bytes, const int length);
void HexToBytes(const std::string &hex, BYTE *bytes);
template <typename T1, typename T2>
std::vector<T1> split(T1 str, T2 letter) {
std::vector<T1> arr;
size_t pos;
while ((pos = str.find_first_of(letter)) != T1::npos) {
T1 str1 = str.substr(0, pos);
arr.push_back(str1);
str = str.substr(pos + 1, str.length() - pos - 1);
}
arr.push_back(str);
return arr;
}
template <typename T1, typename T2>
T1 replace(T1 source, T2 replaced, T1 replaceto) {
std::vector<T1> v_arr = split(source, replaced);
if (v_arr.size() < 2) return source;
T1 temp;
for (unsigned int i = 0; i < v_arr.size() - 1; i++) {
temp += v_arr[i];
temp += replaceto;
}
temp += v_arr[v_arr.size() - 1];
return temp;
}
bool CreateConsole();
void CloseConsole();
void HideModule(HMODULE module);
bool IsDigit(const std::string &str);
std::string Bytes2Hex(const BYTE *bytes, const int length);
bool IsTextUtf8(const char *str, INT64 length);
template <typename T>
static T *WxHeapAlloc(size_t n) {
return (T *)HeapAlloc(GetProcessHeap(), 0, n);
}
} // namespace utils
} // namespace base
#endif

View File

@ -0,0 +1,5 @@
#ifndef BASE_WIN_HEADER_H_
#define BASE_WIN_HEADER_H_
#include <windows.h>
#endif

64
app/base/src/memory.cc Normal file
View File

@ -0,0 +1,64 @@
#include "include/memory.h"
namespace base {
namespace memory {
std::vector<INT64> ScanAndMatchValue(INT64 value, INT64 start, int align) {
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
std::vector<INT64> result;
INT64 min_addr =
reinterpret_cast<INT64>(sys_info.lpMinimumApplicationAddress);
INT64 max_addr =
reinterpret_cast<INT64>(sys_info.lpMaximumApplicationAddress);
const INT64 page_size = sys_info.dwPageSize;
min_addr = min_addr > start ? min_addr : start;
auto current_addr = min_addr;
MEMORY_BASIC_INFORMATION mem_info = {};
HANDLE handle = GetCurrentProcess();
while (current_addr < max_addr) {
VirtualQueryEx(handle, reinterpret_cast<LPVOID>(current_addr), &mem_info,
sizeof(MEMORY_BASIC_INFORMATION));
if ((INT64)mem_info.RegionSize <= 0) {
break;
}
INT64 region_size = mem_info.RegionSize;
if ((mem_info.State & MEM_COMMIT) == MEM_COMMIT &&
(mem_info.Protect & PAGE_GUARD) != PAGE_GUARD &&
(mem_info.Protect & PAGE_NOACCESS) != PAGE_NOACCESS) {
for (INT64 i = 0; i < region_size; i += align) {
if (value == *(INT64 *)current_addr) {
result.push_back(current_addr);
}
current_addr += align;
}
} else {
current_addr += region_size;
}
}
return result;
}
int Sunday(const byte* total, int tlen, const byte* part, int plen) {
byte move[128] = {0};
for (int i = 0; i < plen; i++) {
move[part[i]] = plen - i;
}
int s = 0;
int j;
while (s <= tlen - plen) {
j = 0;
while (total[s + j] == part[j]) {
j++;
if (j == plen) {
return s;
}
}
s += move[total[s + plen]];
}
return -1;
}
} // namespace memory
} // namespace base

View File

@ -1,10 +1,6 @@

#include "pch.h"
#include "thread_pool.h"
#include "include/thread_pool.h"
#include "Windows.h"
namespace wxhelper {
namespace base {
ThreadPool::~ThreadPool() {
if (cleanup_group_) {
CloseThreadpoolCleanupGroupMembers(cleanup_group_, true, NULL);
@ -45,4 +41,4 @@ bool ThreadPool::AddWork(PTP_WORK_CALLBACK callback,PVOID opt) {
return true;
}
} // namespace wxhelper
} // namespace base

225
app/base/src/utils.cc Normal file
View File

@ -0,0 +1,225 @@
#include "include/utils.h"
#include <winternl.h>
#include <fstream>
#include "utils.h"
namespace base {
namespace utils {
const std::string hex_table = "0123456789abcdef";
std::wstring Utf8ToWstring(const std::string &str) {
return AnsiToWstring(str, CP_UTF8);
}
std::string WstringToUtf8(const std::wstring &str) {
return WstringToAnsi(str, CP_UTF8);
}
std::wstring AnsiToWstring(const std::string &input, INT64 locale) {
int wchar_len = MultiByteToWideChar(locale, 0, input.c_str(), -1, NULL, 0);
if (wchar_len > 0) {
std::vector<wchar_t> temp(wchar_len);
MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, &temp[0], wchar_len);
return std::wstring(&temp[0]);
}
return std::wstring();
}
std::string WstringToAnsi(const std::wstring &input, INT64 locale) {
int char_len = WideCharToMultiByte(locale, 0, input.c_str(), -1, 0, 0, 0, 0);
if (char_len > 0) {
std::vector<char> temp(char_len);
WideCharToMultiByte(locale, 0, input.c_str(), -1, &temp[0], char_len, 0, 0);
return std::string(&temp[0]);
}
return std::string();
}
std::string WcharToUtf8(wchar_t *wstr) {
int c_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, FALSE);
if (c_size > 0) {
char *buffer = new char[c_size];
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, buffer, c_size, NULL, FALSE);
std::string str(buffer);
delete[] buffer;
buffer = NULL;
return str;
}
return std::string();
}
std::string StringToHex(const std::string &str) {
std::string sb;
for (int i = 0; i < str.length(); i++) {
sb += hex_table.at((str[i] & 0xf0) >> 4);
sb += hex_table.at((str[i] & 0x0f) >> 0);
}
return sb;
}
std::string HexToString(const std::string &hex_str) {
std::string ret;
for (int i = 0; i < hex_str.length(); i += 2) {
ret += BYTE(hex_table.find(hex_str.at(i)) << 4 |
hex_table.find(hex_str.at(i + 1)));
}
return ret;
}
std::string BytesToHex(const BYTE *bytes, const int length) {
if (bytes == NULL) {
return "";
}
std::string buff;
const int len = length;
for (int j = 0; j < len; j++) {
int high = bytes[j] / 16, low = bytes[j] % 16;
buff += (high < 10) ? ('0' + high) : ('a' + high - 10);
buff += (low < 10) ? ('0' + low) : ('a' + low - 10);
}
return buff;
}
void HexToBytes(const std::string &hex, BYTE *bytes) {
int byte_len = hex.length() / 2;
std::string str;
unsigned int n;
for (int i = 0; i < byte_len; i++) {
str = hex.substr(i * 2, 2);
sscanf_s(str.c_str(), "%x", &n);
bytes[i] = n;
}
}
bool CreateConsole() {
if (AllocConsole()) {
AttachConsole(GetCurrentProcessId());
FILE *retStream;
freopen_s(&retStream, "CONOUT$", "w", stdout);
if (!retStream) throw std::runtime_error("Stdout redirection failed.");
freopen_s(&retStream, "CONOUT$", "w", stderr);
if (!retStream) throw std::runtime_error("Stderr redirection failed.");
return false;
}
return true;
}
void CloseConsole() {
fclose(stdin);
fclose(stdout);
fclose(stderr);
FreeConsole();
}
void HideModule(HMODULE module) {
#ifdef _WIN64
PPEB peb = (PPEB)__readgsqword(0x60);
PPEB_LDR_DATA ldr = peb->Ldr;
void *cur_ptr = *((void **)((unsigned char *)ldr + 0x18));
void *next_ptr = cur_ptr;
do {
void *next = *((void **)((unsigned char *)next_ptr));
void *last = *((void **)((unsigned char *)next_ptr + 0x8));
void *base_addr = *((void **)((unsigned char *)next_ptr + 0x30));
if (base_addr == module) {
*((void **)((unsigned char *)last)) = next;
*((void **)((unsigned char *)next + 0x8)) = last;
cur_ptr = next;
}
next_ptr = *((void **)next_ptr);
} while (cur_ptr != next_ptr);
#else
void *peb_ptr = nullptr;
_asm {
PUSH EAX
MOV EAX, FS:[0x30]
MOV peb_ptr, EAX
POP EAX
}
void *ldr_ptr = *((void **)((unsigned char *)peb_ptr + 0xc));
void *cur_ptr = *((void **)((unsigned char *)ldr_ptr + 0x0c));
void *next_ptr = cur_ptr;
do {
void *next = *((void **)((unsigned char *)next_ptr));
void *last = *((void **)((unsigned char *)next_ptr + 0x4));
void *base_addr = *((void **)((unsigned char *)next_ptr + 0x18));
if (base_addr == module) {
*((void **)((unsigned char *)last)) = next;
*((void **)((unsigned char *)next + 0x4)) = last;
cur_ptr = next;
}
next_ptr = *((void **)next_ptr);
} while (cur_ptr != next_ptr);
}
#endif
}
bool IsDigit(const std::string &str) {
if (str.length() == 0) {
return false;
}
for (auto it : str) {
if (it < '0' || it > '9') {
return false;
}
}
return true;
}
std::string Bytes2Hex(const BYTE *bytes, const int length) {
if (bytes == NULL) {
return "";
}
std::string buff;
const int len = length;
for (int j = 0; j < len; j++) {
int high = bytes[j] / 16, low = bytes[j] % 16;
buff += (high < 10) ? ('0' + high) : ('a' + high - 10);
buff += (low < 10) ? ('0' + low) : ('a' + low - 10);
}
return buff;
}
bool IsTextUtf8(const char *str, INT64 length) {
char endian = 1;
bool littlen_endian = (*(char *)&endian == 1);
size_t i;
int bytes_num;
unsigned char chr;
i = 0;
bytes_num = 0;
while (i < length) {
if (littlen_endian) {
chr = *(str + i);
} else { // Big Endian
chr = (*(str + i) << 8) | *(str + i + 1);
i++;
}
if (bytes_num == 0) {
if ((chr & 0x80) != 0) {
while ((chr & 0x80) != 0) {
chr <<= 1;
bytes_num++;
}
if ((bytes_num < 2) || (bytes_num > 6)) {
return false;
}
bytes_num--;
}
} else {
if ((chr & 0xC0) != 0x80) {
return false;
}
bytes_num--;
}
i++;
}
return (bytes_num == 0);
}
} // namespace utils
} // namespace base

View File

@ -7,7 +7,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D '_UNICODE' /D 'UNICODE'")
file(GLOB INJECT_CPP_FILES ${PROJECT_SOURCE_DIR}/*.cc ${PROJECT_SOURCE_DIR}/*.cpp)
file(GLOB INJECT_CPP_FILES ${PROJECT_SOURCE_DIR}/src/*.cc ${PROJECT_SOURCE_DIR}/src/*.cpp)
add_executable (injector ${INJECT_CPP_FILES})

View File

@ -526,7 +526,7 @@ DWORD GetPIDForProcess(wchar_t* process)
if (!hSnapshot) {
return 0;
}
pe32.dwSize = sizeof(PROCESSENTRY32W);
pe32.dwSize = sizeof(PROCESSENTRY32);
for (working = Process32FirstW(hSnapshot, &pe32); working; working = Process32NextW(hSnapshot, &pe32))
{
if (!wcscmp(pe32.szExeFile, process))

View File

@ -0,0 +1,62 @@
cmake_minimum_required(VERSION 3.10...3.27)
project(wxhelper VERSION 1.0.0)
# enable_language(ASM_MASM)
# add_compile_options("/experimental:module")
message(${CMAKE_VERSION})
option(USE_EXTERNAL_JSON "Use an external JSON library" OFF)
option(USE_EXTERNAL_DETOURS "Use an external detours library" OFF)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17 /MD /EHsc /FAcs")
file(GLOB CPP_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c )
file(GLOB ASM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/*.asm )
if(USE_EXTERNAL_DETOURS)
include_directories(${VCPKG_INSTALLED_DIR}/x64-windows/include ${DETOURS_INCLUDE_DIRS})
else()
include_directories(${VCPKG_INSTALLED_DIR}/x64-windows/include )
endif()
add_subdirectory(../3rdparty 3rdparty)
add_subdirectory(../base base)
add_library(wxhelper SHARED ${CPP_FILES} ${ASM_FILES})
target_compile_definitions(wxhelper PRIVATE WECHAT_VERSION=391019)
# target_include_directories(wxhelper
# PRIVATE ../base/src/include
# PRIVATE ../3rdparty/spdlog/include
# PRIVATE ../3rdparty/base64
# PRIVATE ../3rdparty/lz4
# PRIVATE ../3rdparty/mongoose
# PRIVATE ../3rdparty/tinyxml2
# PRIVATE ../3rdparty/Detours/src
# )
target_link_libraries(wxhelper
PRIVATE base
PRIVATE spdlog::spdlog
PRIVATE lz4
PRIVATE base64
PRIVATE mongoose
PRIVATE nlohmann_json::nlohmann_json
PRIVATE tinyxml2
PRIVATE detours
)
SET_TARGET_PROPERTIES(wxhelper PROPERTIES LINKER_LANGUAGE C
ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib
OUTPUT_NAME "wxhelper"
PREFIX "")

View File

@ -0,0 +1,129 @@
#include "chat_controller.h"
#include "json_utils.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
#include "wechat_interface.h"
#include "wechat_service.h"
namespace jsonutils = wxhelper::jsonutils;
namespace wxhelper {
std::string ChatController::SendTextMsg(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
SPDLOG_INFO("sendTextMsg wxid={},msg={}", jp["wxid"], jp["msg"]);
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
std::wstring msg = jsonutils::GetWStringParam(jp, "msg");
int64_t success = wechat::WeChatService::GetInstance().SendTextMsg(wxid, msg);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
return ret_data.dump();
}
std::string ChatController::SendImageMsg(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
std::wstring image_path = jsonutils::GetWStringParam(jp, "imagePath");
int64_t success =
wechat::WeChatService::GetInstance().SendImageMsg(wxid, image_path);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string ChatController::SendFileMsg(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
std::wstring file_path = jsonutils::GetWStringParam(jp, "filePath");
int64_t success =
wechat::WeChatService::GetInstance().SendFileMsg(wxid, file_path);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string ChatController::SendAtText(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring chat_room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
std::vector<std::wstring> wxids = jsonutils::GetArrayParam(jp, "wxids");
std::wstring msg = jsonutils::GetWStringParam(jp, "msg");
int64_t success =
wechat::WeChatService::GetInstance().SendAtText(chat_room_id, wxids, msg);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string ChatController::SendMultiAtText(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
nlohmann::json array = jp["at"];
std::vector<std::pair<std::wstring, std::wstring>> at;
if (array.is_array()) {
for (const auto& item : array) {
at.push_back(std::make_pair(jsonutils::GetWStringParam(item, "wxid"),
jsonutils::GetWStringParam(item, "msg")));
}
}
std::wstring chat_room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
int64_t success =
wechat::WeChatService::GetInstance().SendMultiAtText(chat_room_id, at);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string ChatController::SendCustomEmotion(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatController::SendApplet(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatController::SendPatMsg(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring room_id = jsonutils::GetWStringParam(jp, "receiver");
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
int64_t success =
wechat::WeChatService::GetInstance().SendPatMsg(room_id, wxid);
nlohmann::json ret_data = {
{"code", success}, {"msg", "success"}, {"data", {}}};
return ret_data.dump();
}
std::string ChatController::ForwardMsg(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
int64_t msg_id = jsonutils::GetInt64Param(jp, "msgId");
int64_t success =
wechat::WeChatService::GetInstance().ForwardMsg(msg_id, wxid);
nlohmann::json ret = {
{"code", success}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatController::ForwardPublicMsgByMsgId(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatController::ForwardPublicMsg(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatController::GetContactOrChatRoomNickname(std::string params) {
int64_t success = -1;
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring wxid = jsonutils::GetWStringParam(jp, "wxid");
std::wstring nickname =
wechat::WeChatService::GetInstance().GetContactOrChatRoomNickname(wxid);
nlohmann::json ret = {{"code", success},
{"data", {"nickname", nickname}},
{"msg", "Not Implemented"}};
return ret.dump();
}
} // namespace wxhelper

View File

@ -0,0 +1,81 @@
#ifndef WXHELPER_CHAT_CONTROLLER_H_
#define WXHELPER_CHAT_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class ChatController : public http::HttpController<ChatController> {
public:
PATHS_BEGIN
ADD_PATH("/api/sendTextMsg", SendTextMsg);
ADD_PATH("/api/sendImagesMsg", SendImageMsg);
ADD_PATH("/api/sendFileMsg", SendFileMsg);
ADD_PATH("/api/sendAtText", SendAtText);
ADD_PATH("/api/sendMultiAtText", SendMultiAtText);
ADD_PATH("/api/sendCustomEmotion", SendCustomEmotion);
ADD_PATH("/api/sendApplet", SendApplet);
ADD_PATH("/api/sendPatMsg", SendPatMsg);
ADD_PATH("/api/forwardMsg", ForwardMsg);
ADD_PATH("/api/forwardPublicMsgByMsgId", ForwardPublicMsgByMsgId);
ADD_PATH("/api/forwardPublicMsg", ForwardPublicMsg);
PATHS_END
public:
/// @brief 发送文本
/// @param params json
/// @return json
static std::string SendTextMsg(std::string params);
/// @brief 发送图片
/// @param params json
/// @return json
static std::string SendImageMsg(std::string params);
/// @brief 发送文件
/// @param params json
/// @return json
static std::string SendFileMsg(std::string params);
/// @brief 发送@文本
/// @param params json
/// @return json
static std::string SendAtText(std::string params);
/// @brief 发送多个@文本
/// @param params json
/// @return json
static std::string SendMultiAtText(std::string params);
/// @brief 发送自定义表情
/// @param params json
/// @return json
static std::string SendCustomEmotion(std::string params);
/// @brief 发送小程序
/// @param params json
/// @return json
static std::string SendApplet(std::string params);
/// @brief 拍一拍
/// @param params json
/// @return json
static std::string SendPatMsg(std::string params);
/// @brief 转发消息
/// @param params json
/// @return json
static std::string ForwardMsg(std::string params);
/// @brief 转发公众号消息
/// @param params json
/// @return json
static std::string ForwardPublicMsgByMsgId(std::string params);
/// @brief 发送公众号消息
/// @param params json
/// @return json
static std::string ForwardPublicMsg(std::string params);
/// @brief 获取联系人昵称
/// @param params json
/// @return json
static std::string GetContactOrChatRoomNickname(std::string params);
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,113 @@
#include "chat_room_controller.h"
#include "json_utils.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
#include "wechat_interface.h"
#include "wechat_service.h"
namespace wxhelper {
std::string ChatRoomController::GetChatRoomDetailInfo(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
SPDLOG_INFO("GetChatRoomDetailInfo chatRoomId={}", jp["chatRoomId"]);
std::wstring room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
wechat::ChatRoomInfoInner chat_room_detail;
int64_t success = wechat::WeChatService::GetInstance().GetChatRoomDetailInfo(
room_id, chat_room_detail);
nlohmann::json ret_data = {
{"code", success}, {"msg", "success"}, {"data", {}}};
nlohmann::json detail = {
{"chatRoomId", chat_room_detail.chat_room_id},
{"notice", chat_room_detail.notice},
{"admin", chat_room_detail.admin},
{"xml", chat_room_detail.xml},
};
ret_data["data"] = detail;
return ret_data.dump();
}
std::string ChatRoomController::GetMemberFromChatRoom(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
SPDLOG_INFO("GetMemberFromChatRoom chatRoomId={}", jp["chatRoomId"]);
std::wstring room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
wechat::ChatRoomMemberInner member;
int64_t success = wechat::WeChatService::GetInstance().GetMemberFromChatRoom(
room_id, member);
nlohmann::json ret_data = {{"code", success}, {"data", {}}, {"msg", "success"}};
if (success > 0) {
nlohmann::json member_info = {
{"admin", member.admin},
{"chatRoomId", member.chat_room_id},
{"members", member.member},
{"adminNickname", member.admin_nickname},
{"memberNickname", member.member_nickname},
};
ret_data["data"] = member_info;
}
return ret_data.dump();
}
std::string ChatRoomController::AddMemberToChatRoom(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
SPDLOG_INFO("AddMemberToChatRoom chatRoomId={},memberIds={}",
jp["chatRoomId"], jp["memberIds"]);
std::wstring room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
std::vector<std::wstring> wxids = jsonutils::GetArrayParam(jp, "memberIds");
std::vector<std::wstring> wxid_list;
for (unsigned int i = 0; i < wxids.size(); i++) {
wxid_list.push_back(wxids[i]);
}
int64_t success = wechat::WeChatService::GetInstance().AddMemberToChatRoom(
room_id, wxid_list);
nlohmann::json ret = {
{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string ChatRoomController::DelMemberFromChatRoom(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
SPDLOG_INFO("DelMemberFromChatRoom chatRoomId={},memberIds={}",
jp["chatRoomId"], jp["memberIds"]);
std::wstring room_id = jsonutils::GetWStringParam(jp, "chatRoomId");
std::vector<std::wstring> wxids = jsonutils::GetArrayParam(jp, "memberIds");
std::vector<std::wstring> wxid_list;
for (unsigned int i = 0; i < wxids.size(); i++) {
wxid_list.push_back(wxids[i]);
}
INT64 success = wechat::WeChatService::GetInstance().DelMemberFromChatRoom(
room_id, wxid_list);
nlohmann::json ret_data = {
{"code", success}, {"msg", "success"}, {"data", {}}};
return ret_data.dump();
}
std::string ChatRoomController::CreateChatRoom(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatRoomController::QuitChatRoom(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatRoomController::InviteMemberToChatRoom(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatRoomController::TopMsg(std::string params) {
return std::string();
}
std::string ChatRoomController::RemoveTopMsg(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatRoomController::GetChatRoomMemberNickname(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string ChatRoomController::ModifyChatRoomMemberNickName(
std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
} // namespace wxhelper

View File

@ -0,0 +1,78 @@
#ifndef WXHELPER_CHAT_ROOM_CONTROLLER_H_
#define WXHELPER_CHAT_ROOM_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class ChatRoomController : public http::HttpController<ChatRoomController> {
public:
PATHS_BEGIN
ADD_PATH("/api/getChatRoomDetailInfo", GetChatRoomDetailInfo);
ADD_PATH("/api/getMemberFromChatRoom", GetMemberFromChatRoom);
ADD_PATH("/api/addMemberToChatRoom", AddMemberToChatRoom);
ADD_PATH("/api/delMemberFromChatRoom", DelMemberFromChatRoom);
ADD_PATH("/api/createChatRoom", CreateChatRoom);
ADD_PATH("/api/quitChatRoom", QuitChatRoom);
ADD_PATH("/api/inviteMemberToChatRoom", InviteMemberToChatRoom);
ADD_PATH("/api/topMsg", TopMsg);
ADD_PATH("/api/removeTopMsg", RemoveTopMsg);
ADD_PATH("/api/getChatRoomMemberNickname", GetChatRoomMemberNickname);
ADD_PATH("/api/modifyChatRoomMemberNickName", ModifyChatRoomMemberNickName);
PATHS_END
public:
/// @brief 获取群聊详情
/// @param params json
/// @return json
static std::string GetChatRoomDetailInfo(std::string params);
/// @brief 获取群成员
/// @param params json
/// @return json
static std::string GetMemberFromChatRoom(std::string params);
/// @brief 添加群成员
/// @param params json
/// @return json
static std::string AddMemberToChatRoom(std::string params);
/// @brief 删除群成员
/// @param params json
/// @return json
static std::string DelMemberFromChatRoom(std::string params);
/// @brief 创建群聊
/// @param params json
/// @return json
static std::string CreateChatRoom(std::string params);
/// @brief 退出群聊
/// @param params json
/// @return json
static std::string QuitChatRoom(std::string params);
/// @brief 邀请成员入群
/// @param params json
/// @return json
static std::string InviteMemberToChatRoom(std::string params);
/// @brief 群聊消息置顶
/// @param params json
/// @return json
static std::string TopMsg(std::string params);
/// @brief 取消群聊消息置顶
/// @param params json
/// @return json
static std::string RemoveTopMsg(std::string params);
/// @brief 获取群聊成员昵称
/// @param params json
/// @return json
static std::string GetChatRoomMemberNickname(std::string params);
/// @brief 修改群聊成员昵称
/// @param params json
/// @return json
static std::string ModifyChatRoomMemberNickName(std::string params);
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,70 @@
#include "client_socket.h"
#include <WS2tcpip.h>
#include <Winsock2.h>
#include "spdlog/spdlog.h"
namespace wxhelper {
SocketInit::SocketInit() {
WSADATA was_data = {0};
if (WSAStartup(MAKEWORD(2, 2), &was_data)) {
valid_ = true;
}
}
SocketInit::~SocketInit() {
if (valid_) {
WSACleanup();
}
}
TcpClient::TcpClient(std::string ip, int port) : ip_(ip), port_(port) {}
void TcpClient::SendAndCloseSocket(std::string& content) {
SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket < 0) {
SPDLOG_ERROR("socket init fail");
return;
}
BOOL status = false;
sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons((u_short)port_);
InetPtonA(AF_INET, ip_.c_str(), &client_addr.sin_addr.s_addr);
if (connect(client_socket, reinterpret_cast<sockaddr*>(&client_addr),
sizeof(sockaddr)) < 0) {
SPDLOG_ERROR("socket connect fail. host:{} , port:{},", ip_, port_);
closesocket(client_socket);
return;
}
char recv_buf[1024] = {0};
int ret =
send(client_socket, content.c_str(), static_cast<int>(content.size()), 0);
if (ret < 0) {
SPDLOG_ERROR("socket send fail ,ret:{}", ret);
closesocket(client_socket);
return;
}
ret = shutdown(client_socket, SD_SEND);
if (ret == SOCKET_ERROR) {
SPDLOG_ERROR("shutdown failed with erro:{}", ret);
closesocket(client_socket);
return;
}
do {
ret = recv(client_socket, recv_buf, sizeof(recv_buf), 0);
if (ret > 0) {
} else if (ret == 0) {
SPDLOG_INFO("Connection closed");
closesocket(client_socket);
return;
} else {
SPDLOG_ERROR("recv failed with error:{}", WSAGetLastError());
closesocket(client_socket);
return;
}
} while (ret > 0);
}
} // namespace wxhelper

View File

@ -0,0 +1,30 @@
#ifndef WXHELPER_CLIENT_SOCKET_H_
#define WXHELPER_CLIENT_SOCKET_H_
#include <string>
#include "noncopyable.h"
namespace wxhelper {
class SocketInit : public NonCopyable {
public:
SocketInit();
~SocketInit();
bool valid_{false};
};
static SocketInit kSocketInit;
class TcpClient : public NonCopyable {
public:
TcpClient()=default;
TcpClient(std::string ip, int port);
void SendAndCloseSocket(std::string& content);
private:
std::string ip_;
int port_;
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,64 @@
#include "config.h"
#include <Windows.h>
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
namespace wxhelper {
void Config::init() {
auto logger =
spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 23, 59);
logger->flush_on(spdlog::level::err);
spdlog::set_default_logger(logger);
spdlog::flush_every(std::chrono::seconds(3));
spdlog::set_level(spdlog::level::info);
spdlog::set_pattern("%Y-%m-%d %H:%M:%S [%l] [%t] - <%s>|<%#>|<%!>,%v");
http_server_port_ =
GetPrivateProfileInt("config", "HttpServerPort", 19088, "./config.ini");
hidden_dll_ = GetPrivateProfileInt("config", "HiddenDll", 0, "./config.ini");
TCHAR host[MAX_PATH];
GetPrivateProfileStringA("config", "HttpServerHost", "http://0.0.0.0", host,
sizeof(host), "./config.ini");
http_server_host_ = host;
TCHAR mode[MAX_PATH];
GetPrivateProfileString("config", "RecvMessageMode", "tcp", mode,
sizeof(mode), "./config.ini");
recv_message_mode_ = mode;
TCHAR tcp_ip[MAX_PATH];
GetPrivateProfileString("config", "RecvTcpIp", "127.0.0.1", tcp_ip,
sizeof(tcp_ip), "./config.ini");
recv_tcp_ip_ = tcp_ip;
recv_tcp_port_ =
GetPrivateProfileInt("config", "RecvTcpPort", 19099, "./config.ini");
TCHAR url[MAX_PATH];
GetPrivateProfileString("config", "RecvHttpUrl", "127.0.0.1", url,
sizeof(url), "./config.ini");
recv_http_url_ = url;
recv_http_timeout_ =
GetPrivateProfileInt("config", "RecvHttpTimeout", 3000, "./config.ini");
SPDLOG_INFO(
"wxhelper config:"
"HttpServerPort={},HttpServerHost={},RecvMessageMode={},RecvTcpIp="
"{},RecvTcpPort={},RecvHttpUrl={},RecvHttpTimeout={}",
http_server_port_, http_server_host_, recv_message_mode_, recv_tcp_ip_,
recv_tcp_port_, recv_http_url_, recv_http_timeout_);
}
int Config::GetHideDll() { return hidden_dll_; }
std::string Config::GetHttpServerHost() { return http_server_host_; }
int Config::GetHttpServerPort() { return http_server_port_; }
std::string Config::GetRecvMessageMode() { return recv_message_mode_; }
std::string Config::GetRecvTcpIp() { return recv_tcp_ip_; }
int Config::GetRecvTcpPort() { return recv_tcp_port_; }
std::string Config::GetRecvHttpUrl() { return recv_http_url_; }
int Config::GetRecvHttpTimeout() { return recv_http_timeout_; }
} // namespace wxhelper

34
app/wxhelper/src/config.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef WXHELPER_CONFIG_H_
#define WXHELPER_CONFIG_H_
#include <string>
#include "singleton.h"
namespace wxhelper {
class Config : public base::Singleton<Config> {
public:
void init();
int GetHideDll();
std::string GetHttpServerHost();
int GetHttpServerPort();
std::string GetRecvMessageMode();
std::string GetRecvTcpIp();
int GetRecvTcpPort();
std::string GetRecvHttpUrl();
int GetRecvHttpTimeout();
private:
int hidden_dll_;
std::string http_server_host_;
int http_server_port_;
std::string recv_message_mode_;
std::string recv_tcp_ip_;
int recv_tcp_port_;
std::string recv_http_url_;
int recv_http_timeout_;
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,66 @@
#include "contacts_controller.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
#include "wechat_interface.h"
#include "json_utils.h"
#include "wechat_service.h"
namespace jsonutils = wxhelper::jsonutils;
std::string wxhelper::ContactsController::GetContactList(std::string params) {
std::vector<wechat::ContactInner> vec;
int64_t success = wechat::WeChatService::GetInstance().GetContacts(vec);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
for (unsigned int i = 0; i < vec.size(); i++) {
nlohmann::json item = {
{"customAccount", vec[i].custom_account},
{"encryptName", vec[i].encrypt_name},
{"type", vec[i].type},
{"verifyFlag", vec[i].verify_flag},
{"wxid", vec[i].wxid},
{"nickname", vec[i].nickname},
{"pinyin", vec[i].pinyin},
{"pinyinAll", vec[i].pinyin_all},
{"reserved1", vec[i].reserved1},
{"reserved2", vec[i].reserved2},
{"remark", vec[i].remark},
{"remarkPinyin", vec[i].remark_pinyin},
{"remarkPinyinAll", vec[i].remark_pinyin_all},
{"labelIds", vec[i].label_ids},
};
ret_data["data"].push_back(item);
}
return ret_data.dump();
}
std::string wxhelper::ContactsController::GetContactProfile(
std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string wxhelper::ContactsController::DelContact(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string wxhelper::ContactsController::SearchContact(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string wxhelper::ContactsController::AddContact(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string wxhelper::ContactsController::VerifyApply(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}

View File

@ -0,0 +1,46 @@
#ifndef WXHELPER_CONTACTS_CONTROLLER_H_
#define WXHELPER_CONTACTS_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class ContactsController : public http::HttpController<ContactsController> {
public:
PATHS_BEGIN
ADD_PATH("/api/getContactList", GetContactList);
ADD_PATH("/api/getContactProfile", GetContactProfile);
ADD_PATH("/api/delContact", DelContact);
ADD_PATH("/api/searchContact", SearchContact);
ADD_PATH("/api/addContact", AddContact);
ADD_PATH("/api/verifyApply", VerifyApply);
PATHS_END
public:
/// @brief 好友通讯录
/// @param params json
/// @return json
static std::string GetContactList(std::string params);
/// @brief 联系人信息
/// @param params json
/// @return json
static std::string GetContactProfile(std::string params);
/// @brief 删除好友
/// @param params json
/// @return json
static std::string DelContact(std::string params);
/// @brief 搜索联系人
/// @param params json
/// @return json
static std::string SearchContact(std::string params);
/// @brief 加好友
/// @param params json
/// @return json
static std::string AddContact(std::string params);
/// @brief 通过好友验证
/// @param params json
/// @return json
static std::string VerifyApply(std::string params);
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,56 @@
#include "db_controller.h"
#include "nlohmann/json.hpp"
#include "utils.h"
#include "wechat_db.h"
#include "json_utils.h"
namespace wxhelper {
std::string DbController::GetDBInfo(std::string params) {
std::vector<void*> v = wechat::WeChatDb::GetInstance().GetWeChatDbHandles();
nlohmann::json ret_data = {{"data", nlohmann::json::array()}};
for (unsigned int i = 0; i < v.size(); ++i) {
nlohmann::json db_info;
db_info["tables"] = nlohmann::json::array();
wechat::DatabaseInfo* db = reinterpret_cast<wechat::DatabaseInfo*>(v[i]);
db_info["handle"] = db->handle;
std::wstring dbname(db->db_name);
db_info["databaseName"] = base::utils::WstringToUtf8(dbname);
for (auto table : db->tables) {
nlohmann::json table_info = {{"name", table.name},
{"tableName", table.table_name},
{"sql", table.sql},
{"rootpage", table.rootpage}};
db_info["tables"].push_back(table_info);
}
ret_data["data"].push_back(db_info);
}
ret_data["code"] = 1;
ret_data["msg"] = "success";
return ret_data.dump();
}
std::string DbController::ExecSql(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
int64_t db_handle = jsonutils::GetInt64Param(jp, "dbHandle");
std::string sql = jsonutils::GetStringParam(jp, "sql");
std::vector<std::vector<std::string>> items;
int success = wechat::WeChatDb::GetInstance().Select(db_handle, sql.c_str(), items);
nlohmann::json ret_data = {
{"data", nlohmann::json::array()}, {"code", success}, {"msg", "success"}};
if (success == 0) {
ret_data["msg"] = "no data";
return ret_data.dump();
}
for (auto it : items) {
nlohmann::json temp_arr = nlohmann::json::array();
for (size_t i = 0; i < it.size(); i++) {
temp_arr.push_back(it[i]);
}
ret_data["data"].push_back(temp_arr);
}
return ret_data.dump();
}
} // namespace wxhelper

View File

@ -0,0 +1,20 @@
#ifndef WXHELPER_DB_CONTROLLER_H_
#define WXHELPER_DB_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class DbController : public http::HttpController<DbController> {
public:
PATHS_BEGIN
ADD_PATH("/api/getDBInfo", GetDBInfo);
ADD_PATH("/api/execSql", ExecSql);
PATHS_END
public:
static std::string GetDBInfo(std::string params);
static std::string ExecSql(std::string params);
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,26 @@

#include "wxhelper.h"
BOOL APIENTRY DllMain(HMODULE module, DWORD ul_reason_for_call,
LPVOID reserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH: {
OutputDebugString("start\n");
DisableThreadLibraryCalls(module);
wxhelper::WxHelper::GetInstance().init(module);
break;
}
case DLL_THREAD_ATTACH: {
break;
}
case DLL_THREAD_DETACH: {
break;
}
case DLL_PROCESS_DETACH: {
OutputDebugString("end\n");
wxhelper::WxHelper::GetInstance().finally();
break;
}
}
return TRUE;
}

92
app/wxhelper/src/hook.cc Normal file
View File

@ -0,0 +1,92 @@
#include <WinSock2.h>
#include "hook.h"
#include "client_socket.h"
#include "config.h"
#include "detours.h"
#include "http_client.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
// #include "thread_pool.h"
#include "utils.h"
#include "wxutils.h"
namespace hook {
void SendHttpMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work) {
InnerMessageStruct *msg = (InnerMessageStruct *)context;
if (msg == NULL) {
SPDLOG_INFO("http msg is null");
return;
}
std::unique_ptr<InnerMessageStruct> sms(msg);
nlohmann::json j_msg = nlohmann::json::parse(
msg->buffer, msg->buffer + msg->length, nullptr, false);
if (j_msg.is_discarded()) {
return;
}
std::string jstr = j_msg.dump() + "\n";
std::string url = wxhelper::Config::GetInstance().GetRecvHttpUrl();
int timeout = wxhelper::Config::GetInstance().GetRecvHttpTimeout();
http::HttpClient client{url, timeout};
client.SendRequest(jstr);
}
void SendTcpMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work) {
InnerMessageStruct *msg = (InnerMessageStruct *)context;
if (msg == NULL) {
SPDLOG_INFO("add work:msg is null");
return;
}
std::unique_ptr<InnerMessageStruct> sms(msg);
nlohmann::json j_msg = nlohmann::json::parse(
msg->buffer, msg->buffer + msg->length, nullptr, false);
if (j_msg.is_discarded()) {
return;
}
std::string jstr = j_msg.dump() + "\n";
std::string ip = wxhelper::Config::GetInstance().GetRecvTcpIp();
int port = wxhelper::Config::GetInstance().GetRecvTcpPort();
wxhelper::TcpClient client{ip, port};
client.SendAndCloseSocket(jstr);
}
BaseHook::BaseHook(void *origin, void *detour)
: origin_(origin), detour_(detour) {}
int BaseHook::Hook() {
if (hook_flag_) {
SPDLOG_INFO("hook already called");
return 2;
}
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach((PVOID *)origin_, detour_);
LONG ret = DetourTransactionCommit();
if (ret == NO_ERROR) {
hook_flag_ = true;
}
return ret;
}
int BaseHook::Unhook() {
if (!hook_flag_) {
SPDLOG_INFO("hook already called");
return NO_ERROR;
}
UINT64 base = wxhelper::wxutils::GetWeChatWinBase();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach((PVOID *)origin_, detour_);
LONG ret = DetourTransactionCommit();
if (ret == NO_ERROR) {
hook_flag_ = false;
}
return ret;
}
} // namespace hook

38
app/wxhelper/src/hook.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef WXHELPER_HOOK_H_
#define WXHELPER_HOOK_H_
#include <Windows.h>
#include <stdint.h>
namespace hook {
struct InnerMessageStruct {
char* buffer;
int64_t length;
~InnerMessageStruct() {
if (this->buffer != NULL) {
delete[] this->buffer;
this->buffer = NULL;
}
}
};
void SendHttpMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work);
void SendTcpMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work);
class BaseHook {
public:
BaseHook():hook_flag_(false),origin_(nullptr),detour_(nullptr){}
BaseHook(void* origin, void* detour);
int Hook();
int Unhook();
virtual ~BaseHook() {}
protected:
bool hook_flag_;
void* origin_;
void* detour_;
};
} // namespace hook
#endif

View File

@ -0,0 +1,31 @@
#include "hook_controller.h"
#include "json_utils.h"
#include "nlohmann/json.hpp"
#include "sync_msg_hook.h"
namespace jsonutils = wxhelper::jsonutils;
namespace wxhelper {
std::string HookController::HookSyncMsg(std::string params) {
int success = SyncMsgHook::GetInstance().Hook();
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
return ret_data.dump();
}
std::string HookController::UnHookSyncMsg(std::string params) {
int success = SyncMsgHook::GetInstance().Unhook();
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
return ret_data.dump();
}
std::string HookController::HookLog(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string HookController::UnHookLog(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
} // namespace wxhelper

View File

@ -0,0 +1,36 @@
#ifndef WXHELPER_HOOK_CONTROLLER_H_
#define WXHELPER_HOOK_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class HookController : public http::HttpController<HookController> {
public:
PATHS_BEGIN
ADD_PATH("/api/hookSyncMsg", HookSyncMsg);
ADD_PATH("/api/unhookSyncMsg", UnHookSyncMsg);
ADD_PATH("/api/hookLog", HookLog);
ADD_PATH("/api/unhookLog", UnHookLog);
PATHS_END
public:
/// @brief hook消息
/// @param params json
/// @return json
static std::string HookSyncMsg(std::string params);
/// @brief 取消hook消息
/// @param params json
/// @return json
static std::string UnHookSyncMsg(std::string params);
/// @brief hook日志消息
/// @param params json
/// @return json
static std::string HookLog(std::string params);
/// @brief 取消hook日志消息
/// @param params json
/// @return json
static std::string UnHookLog(std::string params);
};
} // namespace wxhelper
#endif

View File

@ -0,0 +1,75 @@
#include "http_client.h"
namespace http {
HttpClient::HttpClient(std::string url, int timeout)
: url_(url), timeout_(timeout) {}
void HttpClient::SendRequest(const std::string &content) {
struct mg_mgr mgr;
Data data;
data.done = false;
data.post_data = content;
data.url = url_;
data.timeout = timeout_;
mg_mgr_init(&mgr);
mg_http_connect(&mgr, url_.c_str(), &HttpClient::OnHttpEvent, &data);
while (!data.done) {
mg_mgr_poll(&mgr, 500);
}
mg_mgr_free(&mgr);
data.done = false;
}
void HttpClient::OnHttpEvent(struct mg_connection *c, int ev, void *ev_data,
void *fn_data) {
Data *data = (Data *)fn_data;
const char *s_url = data->url.c_str();
int timeout = data->timeout;
if (ev == MG_EV_OPEN) {
// Connection created. Store connect expiration time in c->data
*(uint64_t *)c->data = mg_millis() + timeout;
} else if (ev == MG_EV_POLL) {
if (mg_millis() > *(uint64_t *)c->data &&
(c->is_connecting || c->is_resolving)) {
mg_error(c, "Connect timeout");
}
} else if (ev == MG_EV_CONNECT) {
struct mg_str host = mg_url_host(s_url);
if (mg_url_is_ssl(s_url)) {
// no implement
}
// Send request
size_t content_length = data->post_data.size();
mg_printf(c,
"POST %s HTTP/1.0\r\n"
"Host: %.*s\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %d\r\n"
"\r\n",
mg_url_uri(s_url), (int)host.len, host.ptr, content_length);
mg_send(c, data->post_data.c_str(), content_length);
} else if (ev == MG_EV_HTTP_MSG) {
// Response is received. Print it
#ifdef _DEBUG
struct mg_http_message *hm = (struct mg_http_message *)ev_data;
printf("%.*s", (int)hm->message.len, hm->message.ptr);
#endif
// c->is_closing = 1; // Tell mongoose to close this connection
c->is_draining = 1;
data->done = true; // Tell event loop to stops
} else if (ev == MG_EV_ERROR) {
data->done = true; // Error, tell event loop to stop
} else if (ev == MG_EV_CLOSE) {
if (!data->done) {
data->done = true;
}
} else if (ev == MG_EV_HTTP_CHUNK) {
mg_error(c, "http chunk no implement");
c->is_closing = 1;
data->done = true;
}
}
} // namespace http

View File

@ -0,0 +1,32 @@
#ifndef WXHELPER_HTTP_CLIENT_H_
#define WXHELPER_HTTP_CLIENT_H_
#include <string>
#include "mongoose.h"
#include "noncopyable.h"
#include "singleton.h"
namespace http {
struct Data {
bool done;
int timeout;
std::string url;
std::string post_data;
};
class HttpClient : public NonCopyable {
public:
explicit HttpClient(std::string url, int timeout);
void SendRequest(const std::string &content);
private:
static void OnHttpEvent(struct mg_connection *c, int ev, void *ev_data,
void *fn_data);
private:
std::string url_;
int timeout_;
};
} // namespace http
#endif

View File

@ -0,0 +1,42 @@

#ifndef WXHELPER_HTTP_CONTROLLER_H_
#define WXHELPER_HTTP_CONTROLLER_H_
#include "http_router.h"
#include "singleton.h"
namespace http {
#define PATHS_BEGIN static void AddPath() {
#define ADD_PATH(path, method) RegisterPath(path, &method)
#define PATHS_END }
class BaseHttpController {
public:
virtual ~BaseHttpController() {}
};
template <typename T>
class HttpController : public base::Singleton<T>{
public:
virtual ~HttpController() {}
protected:
HttpController() {}
static void RegisterPath(const std::string &path, HttpHandler function) {
HttpRouter::GetInstance().AddPathRouting(path, function);
}
private:
struct Registrator {
public:
Registrator() { T::AddPath(); }
};
static Registrator registrator_;
virtual void *GetRegistrator() { return &registrator_; }
};
template <typename T>
typename HttpController<T>::Registrator HttpController<T>::registrator_;
} // namespace http
#endif

View File

@ -0,0 +1,24 @@
#include "http_router.h"
#include <iostream>
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
namespace http {
void HttpRouter::AddPathRouting(const std::string &path, HttpHandler handler) {
route_table_[path] = handler;
SPDLOG_INFO("route table size={}", route_table_.size());
}
std::string HttpRouter::HandleHttpRequest(const std::string &path,
const std::string &param) {
SPDLOG_INFO("route table size={}", route_table_.size());
auto it = route_table_.find(path);
if (it != route_table_.end()) {
return it->second(param);
} else {
nlohmann::json ret_data = {
{"code", 200}, {"data", {}}, {"msg", "the url is not supported"}};
return ret_data.dump();
}
}
} // namespace http

View File

@ -0,0 +1,23 @@
#ifndef WXHELPER_HTTP_ROUTER_H_
#define WXHELPER_HTTP_ROUTER_H_
#include <functional>
#include <map>
#include <string>
#include "singleton.h"
namespace http {
typedef std::function<std::string(std::string)> HttpHandler;
class HttpRouter : public base::Singleton<HttpRouter> {
public:
void HttpRouter::AddPathRouting(const std::string &path, HttpHandler handler);
std::string HandleHttpRequest(const std::string &path,
const std::string &param);
private:
std::unordered_map<std::string, HttpHandler> route_table_{};
};
} // namespace http
#endif

View File

@ -0,0 +1,141 @@
#include "http_server.h"
#include "http_router.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
#include "utils.h"
namespace http {
HttpServer::~HttpServer() {
if (thread_ != nullptr) {
CloseHandle(thread_);
}
mg_mgr_free(&mgr_);
}
void HttpServer::init(std::string &&host, int port) {
if (port < 1 || port > 65535) {
throw std::invalid_argument("Port number is out of range.");
}
mg_mgr_init(&mgr_);
host_ = std::move(host);
port_ = port;
SPDLOG_INFO("http init :host={},port={}",host_,port_);
}
bool HttpServer::Start() {
if (running_) {
SPDLOG_INFO("http server is already running");
return true;
}
#ifdef _DEBUG
base::utils::CreateConsole();
#endif
running_.store(true);
thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)LaunchServer, this,
NULL, 0);
SPDLOG_INFO("CreateThread for http server ,the result is {}",thread_ != NULL);
return thread_ != NULL;
}
bool HttpServer::Stop() {
if (!running_) {
return true;
}
#ifdef _DEBUG
base::utils::CloseConsole();
#endif
running_ = false;
if (thread_) {
WaitForSingleObject(thread_, -1);
CloseHandle(thread_);
thread_ = NULL;
}
return true;
}
void HttpServer::LaunchServer(HttpServer *server) {
int port = server->GetPort();
std::string host = server->GetHost();
const mg_mgr * mgr = server->GetMgr();
std::string listen_addr = host +":"+ std::to_string(port);
if (mg_http_listen(const_cast<mg_mgr *>(mgr), listen_addr.c_str(),
EventHandler, NULL) == NULL) {
SPDLOG_ERROR("http server listen fail.port:{}", port);
return;
}
for (;;) {
mg_mgr_poll(const_cast<mg_mgr *>(mgr), 100);
}
}
void HttpServer::EventHandler(struct mg_connection *c, int ev, void *ev_data,
void *fn_data) {
if (ev == MG_EV_OPEN) {
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *)ev_data;
if (mg_http_match_uri(hm, "/websocket/*")) {
mg_ws_upgrade(c, hm, NULL);
} else if (mg_http_match_uri(hm, "/api/*")) {
HandleHttpRequest(c, hm, fn_data);
} else {
nlohmann::json res = {{"code", 400},
{"msg", "invalid url, please check url"},
{"data", NULL}};
std::string ret = res.dump();
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s\n",
ret.c_str());
}
} else if (ev == MG_EV_WS_MSG) {
HandleWebsocketRequest(c, ev_data, fn_data);
}
}
void HttpServer::HandleHttpRequest(struct mg_connection *c, void *ev_data,
void *fn_data) {
struct mg_http_message *hm = (struct mg_http_message *)ev_data;
std::string ret = R"({"code":200,"msg":"success"})";
try {
if (mg_vcasecmp(&hm->method, "GET") == 0) {
nlohmann::json ret_data = {
{"code", 200},
{"data", {}},
{"msg", "the get method is not supported.please use post method."}};
ret = ret_data.dump();
} else if (mg_vcasecmp(&hm->method, "POST") == 0) {
std::string url(hm->uri.ptr, hm->uri.len);
std::string p = "{}";
if (hm->body.len > 0){
nlohmann::json params =
nlohmann::json::parse(hm->body.ptr, hm->body.ptr + hm->body.len);
p = params.dump();
}
ret = HttpRouter::GetInstance().HandleHttpRequest(url, p);
}
} catch (nlohmann::json::exception &e) {
nlohmann::json res = {{"code", "500"}, {"msg", e.what()}, {"data", NULL}};
ret = res.dump();
}
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s\n",
ret.c_str());
}
void HttpServer::HandleWebsocketRequest(struct mg_connection *c, void *ev_data,
void *fn_data) {
struct mg_ws_message *wm = (struct mg_ws_message *)ev_data;
std::string ret = R"({"code":200,"msg":"success"})";
try {
nlohmann::json params =
nlohmann::json::parse(wm->data.ptr, wm->data.ptr + wm->data.len);
std::string cmd = params["cmd"];
std::string p = params.dump();
ret = HttpRouter::GetInstance().HandleHttpRequest(cmd, p);
} catch (nlohmann::json::exception &e) {
nlohmann::json res = {{"code", "500"}, {"msg", e.what()}, {"data", NULL}};
ret = res.dump();
}
mg_ws_send(c, ret.c_str(), ret.size(), WEBSOCKET_OP_TEXT);
}
} // namespace http

View File

@ -0,0 +1,41 @@
#ifndef WXHELPER_HTTP_SERVER_H_
#define WXHELPER_HTTP_SERVER_H_
#include <atomic>
#include <functional>
#include <map>
#include <string>
#include "mongoose.h"
#include "singleton.h"
namespace http {
class HttpServer : public base::Singleton<HttpServer> {
public:
~HttpServer();
void init(std::string &&host, int port);
bool Start();
bool Stop();
const mg_mgr *GetMgr() { return &mgr_; }
int GetPort() { return port_; }
bool GetRunning() { return running_; }
std::string GetHost() { return host_; }
private:
static void LaunchServer(HttpServer *server);
static void EventHandler(struct mg_connection *c, int ev, void *ev_data,
void *fn_data);
static void HandleHttpRequest(struct mg_connection *c, void *ev_data,
void *fn_data);
static void HandleWebsocketRequest(struct mg_connection *c, void *ev_data,
void *fn_data);
private:
struct mg_mgr mgr_;
std::string host_;
int port_;
std::atomic<bool> running_{false};
HANDLE thread_;
};
} // namespace http
#endif

View File

@ -0,0 +1,47 @@
#include "json_utils.h"
#include "utils.h"
#define STR2ULL(str) (base::utils::IsDigit(str) ? stoull(str) : 0)
#define STR2LL(str) (base::utils::IsDigit(str) ? stoll(str) : 0)
#define STR2I(str) (base::utils::IsDigit(str) ? stoi(str) : 0)
namespace wxhelper {
namespace jsonutils {
std::wstring GetWStringParam(nlohmann::json data, std::string key) {
return base::utils::Utf8ToWstring(data[key].get<std::string>());
}
std::vector<std::wstring> GetArrayParam(nlohmann::json data, std::string key) {
std::vector<std::wstring> result;
std::wstring param = GetWStringParam(data, key);
result = base::utils::split(param, L',');
return result;
}
int GetIntParam(nlohmann::json data, std::string key) {
int result;
try {
result = data[key].get<int>();
} catch (nlohmann::json::exception) {
result = STR2I(data[key].get<std::string>());
}
return result;
}
bool GetBoolParam(nlohmann::json data, std::string key) {
return data[key].get<bool>();
}
std::string GetStringParam(nlohmann::json data, std::string key) {
return data[key].get<std::string>();
}
int64_t GetInt64Param(nlohmann::json data, std::string key) {
int64_t result;
try {
result = data[key].get<int64_t>();
} catch (nlohmann::json::exception) {
result = STR2LL(data[key].get<std::string>());
}
return result;
}
} // namespace jsonutils
} // namespace wxhelper

View File

@ -0,0 +1,14 @@
#ifndef WXHELPER_JSON_UTILS_H_
#define WXHELPER_JSON_UTILS_H_
#include "nlohmann/json.hpp"
namespace wxhelper {
namespace jsonutils {
std::wstring GetWStringParam(nlohmann::json data, std::string key);
std::vector<std::wstring> GetArrayParam(nlohmann::json data, std::string key) ;
int GetIntParam(nlohmann::json data, std::string key);
bool GetBoolParam(nlohmann::json data, std::string key);
std::string GetStringParam(nlohmann::json data, std::string key);
int64_t GetInt64Param(nlohmann::json data, std::string key);
}
}
#endif

View File

@ -0,0 +1,132 @@
#include "misc_controller.h"
#include "json_utils.h"
#include "nlohmann/json.hpp"
#include "spdlog/spdlog.h"
#include "wechat_interface.h"
#include "wechat_service.h"
namespace jsonutils = wxhelper::jsonutils;
namespace wxhelper {
std::string MiscController::CheckLogin(std::string params) {
int64_t success = wechat::WeChatService::GetInstance().CheckLogin();
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::GetUserInfo(std::string params) {
wechat::SelfInfoInner out;
int64_t success = wechat::WeChatService::GetInstance().GetSelfInfo(out);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
nlohmann::json j_info = {
{"name", out.name},
{"city", out.city},
{"province", out.province},
{"country", out.country},
{"account", out.account},
{"wxid", out.wxid},
{"mobile", out.mobile},
{"headImage", out.head_img},
{"signature", out.signature},
{"dataSavePath", out.data_save_path},
{"currentDataPath", out.current_data_path},
{"dbKey", out.db_key},
{"publicKey", out.public_key},
{"privateKey", out.private_key},
};
ret["data"] = j_info;
return ret.dump();
}
std::string MiscController::GetSNSFirstPage(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::GetSNSNextPage(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::AddFavFromMsg(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::AddFavFromImage(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::DecodeImage(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::GetVoiceByMsgId(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::DoOcrTask(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::LockWeChat(std::string params) {
int64_t success = wechat::WeChatService::GetInstance().LockWeChat();
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::UnlockWeChat(std::string params) {
int64_t success = wechat::WeChatService::GetInstance().UnlockWeChat();
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::ClickEnterWeChat(std::string params) {
int64_t success = wechat::WeChatService::GetInstance().EnterWeChat();
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::GetLoginUrl(std::string params) {
std::string login_url = wechat::WeChatService::GetInstance().GetLoginUrl();
nlohmann::json ret = {
{"code", 1}, {"data", {"loginUrl", login_url}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::TranslateVoice(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
int64_t msg_id = jsonutils::GetInt64Param(jp, "msgId");
int64_t success = wechat::WeChatService::GetInstance().TranslateVoice(msg_id);
nlohmann::json ret = {{"code", success}, {"data", {}}, {"msg", "success"}};
return ret.dump();
}
std::string MiscController::GetTranslateVoiceText(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
int64_t msg_id = jsonutils::GetInt64Param(jp, "msgId");
std::string content =
wechat::WeChatService::GetInstance().GetTranslateVoiceText(msg_id);
nlohmann::json ret_data = {
{"code", 1}, {"msg", "success"}, {"data", {{"transtext", content}}}};
return ret_data.dump();
}
std::string MiscController::OpenUrlByWeChat(std::string params) {
nlohmann::json jp = nlohmann::json::parse(params);
std::wstring url = jsonutils::GetWStringParam(jp, "url");
int flag = jsonutils::GetIntParam(jp, "flag");
int64_t success =
wechat::WeChatService::GetInstance().OpenUrlByWeChatBrowser(url, flag);
nlohmann::json ret = {
{"code", success}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::ConfirmReceipt(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
std::string MiscController::DownloadAttach(std::string params) {
nlohmann::json ret = {
{"code", 200}, {"data", {}}, {"msg", "Not Implemented"}};
return ret.dump();
}
} // namespace wxhelper

View File

@ -0,0 +1,110 @@
#ifndef WXHELPER_CHAT_CONTROLLER_H_
#define WXHELPER_CHAT_CONTROLLER_H_
#include "http_controller.h"
namespace wxhelper {
class MiscController : public http::HttpController<MiscController> {
public:
PATHS_BEGIN
ADD_PATH("/api/checkLogin", CheckLogin);
ADD_PATH("/api/userInfo", GetUserInfo);
ADD_PATH("/api/getSNSFirstPage", GetSNSFirstPage);
ADD_PATH("/api/getSNSNextPage", GetSNSNextPage);
ADD_PATH("/api/addFavFromMsg", AddFavFromMsg);
ADD_PATH("/api/addFavFromImage", AddFavFromImage);
ADD_PATH("/api/decodeImage", DecodeImage);
ADD_PATH("/api/getVoiceByMsgId", GetVoiceByMsgId);
ADD_PATH("/api/ocr", DoOcrTask);
ADD_PATH("/api/lockWeChat", LockWeChat);
ADD_PATH("/api/unlockWeChat", UnlockWeChat);
ADD_PATH("/api/clickEnterWeChat", ClickEnterWeChat);
ADD_PATH("/api/getLoginUrl", GetLoginUrl);
ADD_PATH("/api/translateVoice", TranslateVoice);
ADD_PATH("/api/getTranslateVoiceText", GetTranslateVoiceText);
ADD_PATH("/api/openUrlByWeChat", OpenUrlByWeChat);
ADD_PATH("/api/confirmReceipt", ConfirmReceipt);
ADD_PATH("/api/downloadAttach", DownloadAttach);
PATHS_END
public:
/// @brief 检查是否登录
/// @param params json
/// @return json
static std::string CheckLogin(std::string params);
/// @brief 获取登录用户信息
/// @param params json
/// @return json
static std::string GetUserInfo(std::string params);
/// @brief 朋友圈首页
/// @param params json
/// @return json
static std::string GetSNSFirstPage(std::string params);
/// @brief 朋友圈下一页
/// @param params json
/// @return json
static std::string GetSNSNextPage(std::string params);
/// @brief 收藏消息
/// @param params json
/// @return json
static std::string AddFavFromMsg(std::string params);
/// @brief 收藏图片
/// @param params json
/// @return json
static std::string AddFavFromImage(std::string params);
/// @brief 解码图片
/// @param params json
/// @return json
static std::string DecodeImage(std::string params);
/// @brief 获取语音文件
/// @param params json
/// @return json
static std::string GetVoiceByMsgId(std::string params);
/// @brief 图片ocr
/// @param params json
/// @return json
static std::string DoOcrTask(std::string params);
/// @brief 锁定微信
/// @param params json
/// @return json
static std::string LockWeChat(std::string params);
/// @brief 解锁微信
/// @param params json
/// @return json
static std::string UnlockWeChat(std::string params);
/// @brief 进入微信
/// @param params json
/// @return json
static std::string ClickEnterWeChat(std::string params);
/// @brief 获取登录url
/// @param params json
/// @return json
static std::string GetLoginUrl(std::string params);
/// @brief 语音转文本
/// @param params json
/// @return json
static std::string TranslateVoice(std::string params);
/// @brief 获取语音转文本结果
/// @param params json
/// @return json
static std::string GetTranslateVoiceText(std::string params);
/// @brief 通过浏览器打开url
/// @param params json
/// @return json
static std::string OpenUrlByWeChat(std::string params);
/// @brief 确认收款
/// @param params json
/// @return json
static std::string ConfirmReceipt(std::string params);
/// @brief 下载附件
/// @param params json
/// @return json
static std::string DownloadAttach(std::string params);
};
} // namespace wxhelper
#endif

360
app/wxhelper/src/offset.h Normal file
View File

@ -0,0 +1,360 @@
#ifndef WXHELPER_OFFSET_H_
#define WXHELPER_OFFSET_H_
#include <cstdint>
namespace wechat {
#define V_3_9_8_25 39825
#define V_3_9_9_43 39943
#define V_3_9_10_19 391019
#ifndef WECHAT_VERSION
#error " WECHAT_VERSION not defined ."
#endif
namespace offset {
#if WECHAT_VERSION == V_3_9_8_25
const uint64_t kGetAccountServiceMgr = 0x94e510;
const uint64_t kSyncMsg = 0xc39680;
const uint64_t kSyncMsgNext = 0xc39680;
const uint64_t kGetCurrentDataPath = 0x101a920;
const uint64_t kGetAppDataSavePath = 0x13a5b90;
const uint64_t kGetSendMessageMgr = 0x94cd10;
const uint64_t kSendTextMsg = 0x1091F70;
const uint64_t kFreeChatMsg = 0x94e590;
const uint64_t kDoAddMsg = 0x10d9450;
const uint64_t kSendImageMsg = 0x1087950;
const uint64_t kChatMsgInstanceCounter = 0x956e00;
const uint64_t kSendFileMsg = 0xea0850;
const uint64_t kGetAppMsgMgr = 0x951cb0;
const uint64_t kGetContactMgr = 0x93a570;
const uint64_t kGetContactList = 0xf6cb70;
const uint64_t k_sqlite3_exec = 0x26e4f20;
const uint64_t k_sqlite3_prepare = 0x26ecaa0;
const uint64_t k_sqlite3_open = 0x27242a0;
const uint64_t k_sqlite3_step = 0x26a8f30;
const uint64_t k_sqlite3_column_count = 0x26a9750;
const uint64_t k_sqlite3_column_name = 0x26aa150;
const uint64_t k_sqlite3_column_type = 0x26a9fa0;
const uint64_t k_sqlite3_column_blob = 0x26a9780;
const uint64_t k_sqlite3_column_bytes = 0x26a9870;
const uint64_t k_sqlite3_finalize = 0x26a7fe0;
const uint64_t kGPInstance = 0x3d8b4f8;
const uint64_t kMicroMsgDB = 0xb8;
const uint64_t kChatMsgDB = 0x2c8;
const uint64_t kMiscDB = 0x5f0;
const uint64_t kEmotionDB = 0x888;
const uint64_t kMediaDB = 0xF48;
const uint64_t kBizchatMsgDB = 0x1AC0;
const uint64_t kFunctionMsgDB = 0x1b98;
const uint64_t kDBName = 0x28;
const uint64_t kStorageStart = 0x0;
const uint64_t kStorageEnd = 0x0;
const uint64_t kMultiDBMgr = 0x3e00910;
const uint64_t kPublicMsgMgr = 0x3dfe098;
const uint64_t kFavoriteStorageMgr = 0x3e01478;
const uint64_t kChatRoomMgr = 0x8e9d30;
const uint64_t kGetChatRoomDetailInfo = 0xe73590;
const uint64_t kNewChatRoomInfo = 0x12006b0;
const uint64_t kFreeChatRoomInfo = 0x1200890;
const uint64_t kDoAddMemberToChatRoom = 0xe63c70;
const uint64_t kDoModChatRoomMemberNickName = 0xe6db00;
const uint64_t kDelMemberFromChatRoom = 0xe64290;
const uint64_t kGetMemberFromChatRoom = 0xe74de0;
const uint64_t kNewChatRoom = 0x11fde50;
const uint64_t kFreeChatRoom = 0x11fe030;
const uint64_t kTopMsg = 0xa5e4f0;
const uint64_t kRemoveTopMsg = 0xe787b0;
const uint64_t kInviteMember = 0xe63650;
const uint64_t kHookLog = 0x1304e60;
const uint64_t kCreateChatRoom = 0xe63340;
const uint64_t kQuitChatRoom = 0xe6e3b0;
const uint64_t kForwardMsg = 0x1091660;
const uint64_t kOnSnsTimeLineSceneFinish = 0x1a73150;
const uint64_t kSNSGetFirstPage = 0x1a51dd0;
const uint64_t kSNSGetNextPageScene = 0x1a77240;
const uint64_t kSNSDataMgr = 0xeebda0;
const uint64_t kSNSTimeLineMgr = 0x19e83a0;
const uint64_t kGetMgrByPrefixLocalId = 0xf0ea60;
const uint64_t kAddFavFromMsg = 0x1601520;
const uint64_t kGetChatMgr = 0x97e4d0;
const uint64_t kGetFavoriteMgr = 0x8c69b0;
const uint64_t kAddFavFromImage = 0x160b920;
const uint64_t kGetContact = 0xf67060;
const uint64_t kNewContact = 0x12e01f0;
const uint64_t kFreeContact = 0x12e08a0;
const uint64_t kNewMMReaderItem = 0x8c79a0;
const uint64_t kFreeMMReaderItem = 0x8c6da0;
const uint64_t kForwordPublicMsg = 0xddc6c0;
const uint64_t kParseAppMsgXml = 0x11b0a70;
const uint64_t kNewAppMsgInfo = 0x91a550;
const uint64_t kFreeAppMsgInfo = 0x8fd1a0;
const uint64_t kGetPreDownLoadMgr = 0x9996f0;
const uint64_t kPushAttachTask = 0x9c0080;
const uint64_t kGetCustomSmileyMgr = 0x915c00;
const uint64_t kSendCustomEmotion = 0xec0a40;
const uint64_t kNewJsApiShareAppMessage = 0x13be1a0;
const uint64_t kInitJsConfig = 0x137bc00;
const uint64_t kSendApplet = 0x13c0920;
const uint64_t kSendAppletSecond = 0x13c1150;
const uint64_t kGetAppInfoByWaid = 0x13c5790;
const uint64_t kCopyShareAppMessageRequest = 0x13c0670;
const uint64_t kNewWAUpdatableMsgInfo = 0x919ca0;
const uint64_t kFreeWAUpdatableMsgInfo = 0x8fc230;
const uint64_t kSendPatMsg = 0x195f340;
const uint64_t kGetOCRManager = 0x999780;
const uint64_t kDoOCRTask = 0x190b2a0;
const uint64_t kGetLockWechatMgr = 0xa727b0;
const uint64_t kRequestLockWechat = 0xa2cc70;
const uint64_t kRequestUnLockWechat = 0xa2cf10;
const uint64_t kOnLoginBtnClick = 0xe0cf70;
const uint64_t kGetQRCodeLoginMgr = 0xdff6d0;
const uint64_t kUpdateMsg = 0xf15c40;
const uint64_t kGetVoiceMgr = 0xbf78f0;
const uint64_t kChatMsg2NetSceneSendMsg = 0x96e8d0;
const uint64_t kTranslateVoice = 0x11217e0;
const uint64_t kNewWebViewPageConfig = 0x9512f0;
const uint64_t kFreeWebViewPageConfig = 0x951520;
const uint64_t kGetWebViewMgr = 0x9412d0;
const uint64_t kShowWebView = 0x1d236b0;
const uint64_t kSetUrl = 0x13dd410;
#elif WECHAT_VERSION == V_3_9_9_43
const uint64_t kGetAccountServiceMgr = 0xa7df30;
const uint64_t kSyncMsg = 0xc39680;
const uint64_t kSyncMsgNext = 0xc39680;
const uint64_t kGetCurrentDataPath = 0x11664e0;
const uint64_t kGetAppDataSavePath = 0x14f29c0;
const uint64_t kGetSendMessageMgr = 0xa7c730;
const uint64_t kSendTextMsg = 0x11de090;
const uint64_t kFreeChatMsg = 0xa7dfb0;
const uint64_t kDoAddMsg = 0x1225a60;
const uint64_t kSendImageMsg = 0x11d3a70;
const uint64_t kChatMsgInstanceCounter = 0xa86820;
const uint64_t kSendFileMsg = 0xfeb750;
const uint64_t kGetAppMsgMgr = 0xa816d0;
const uint64_t kGetContactMgr = 0xa69fd0;
const uint64_t kGetContactList = 0x10b8420;
const uint64_t k_sqlite3_exec = 0x288ea10;
const uint64_t k_sqlite3_prepare = 0x2896590;
const uint64_t k_sqlite3_open = 0x28cdd90;
const uint64_t k_sqlite3_step = 0x2852a20;
const uint64_t k_sqlite3_column_count = 0x2853240;
const uint64_t k_sqlite3_column_name = 0x2853c40;
const uint64_t k_sqlite3_column_type = 0x2853a90;
const uint64_t k_sqlite3_column_blob = 0x2853270;
const uint64_t k_sqlite3_column_bytes = 0x2853360;
const uint64_t k_sqlite3_finalize = 0x2851ad0;
const uint64_t kGPInstance = 0x4076558;
const uint64_t kMicroMsgDB = 0xb8;
const uint64_t kChatMsgDB = 0x2c8;
const uint64_t kMiscDB = 0x5f0;
const uint64_t kEmotionDB = 0x888;
const uint64_t kMediaDB = 0xF48;
const uint64_t kBizchatMsgDB = 0x1AC0;
const uint64_t kFunctionMsgDB = 0x1b98;
const uint64_t kDBName = 0x28;
const uint64_t kStorageStart = 0x0;
const uint64_t kStorageEnd = 0x0;
const uint64_t kMultiDBMgr = 0x40ecf98;
const uint64_t kPublicMsgMgr = 0x40ea558;
const uint64_t kFavoriteStorageMgr = 0x40edb28;
const uint64_t kHardLinkMgr = 0x40ecec0;
const uint64_t kChatRoomMgr = 0x8e9d30;
const uint64_t kGetChatRoomDetailInfo = 0xe73590;
const uint64_t kNewChatRoomInfo = 0x12006b0;
const uint64_t kFreeChatRoomInfo = 0x1200890;
const uint64_t kDoAddMemberToChatRoom = 0xe63c70;
const uint64_t kDoModChatRoomMemberNickName = 0xe6db00;
const uint64_t kDelMemberFromChatRoom = 0xe64290;
const uint64_t kGetMemberFromChatRoom = 0xe74de0;
const uint64_t kNewChatRoom = 0x11fde50;
const uint64_t kFreeChatRoom = 0x11fe030;
const uint64_t kTopMsg = 0xa5e4f0;
const uint64_t kRemoveTopMsg = 0xe787b0;
const uint64_t kInviteMember = 0xe63650;
const uint64_t kHookLog = 0x1304e60;
const uint64_t kCreateChatRoom = 0xe63340;
const uint64_t kQuitChatRoom = 0xe6e3b0;
const uint64_t kForwardMsg = 0x11dd780;
const uint64_t kOnSnsTimeLineSceneFinish = 0x1a73150;
const uint64_t kSNSGetFirstPage = 0x1a51dd0;
const uint64_t kSNSGetNextPageScene = 0x1a77240;
const uint64_t kSNSDataMgr = 0xeebda0;
const uint64_t kSNSTimeLineMgr = 0x19e83a0;
const uint64_t kGetMgrByPrefixLocalId = 0x105a010;
const uint64_t kAddFavFromMsg = 0x1601520;
const uint64_t kGetChatMgr = 0xaafd90;
const uint64_t kGetFavoriteMgr = 0x8c69b0;
const uint64_t kAddFavFromImage = 0x160b920;
const uint64_t kGetContact = 0xf67060;
const uint64_t kNewContact = 0x12e01f0;
const uint64_t kFreeContact = 0x12e08a0;
const uint64_t kNewMMReaderItem = 0x8c79a0;
const uint64_t kFreeMMReaderItem = 0x8c6da0;
const uint64_t kForwordPublicMsg = 0xddc6c0;
const uint64_t kParseAppMsgXml = 0x11b0a70;
const uint64_t kNewAppMsgInfo = 0x91a550;
const uint64_t kFreeAppMsgInfo = 0x8fd1a0;
const uint64_t kGetPreDownLoadMgr = 0x9996f0;
const uint64_t kPushAttachTask = 0x9c0080;
const uint64_t kGetCustomSmileyMgr = 0x915c00;
const uint64_t kSendCustomEmotion = 0xec0a40;
const uint64_t kNewJsApiShareAppMessage = 0x13be1a0;
const uint64_t kInitJsConfig = 0x137bc00;
const uint64_t kSendApplet = 0x13c0920;
const uint64_t kSendAppletSecond = 0x13c1150;
const uint64_t kGetAppInfoByWaid = 0x13c5790;
const uint64_t kCopyShareAppMessageRequest = 0x13c0670;
const uint64_t kNewWAUpdatableMsgInfo = 0x919ca0;
const uint64_t kFreeWAUpdatableMsgInfo = 0x8fc230;
const uint64_t kSendPatMsg = 0x195f340;
const uint64_t kGetOCRManager = 0x999780;
const uint64_t kDoOCRTask = 0x190b2a0;
const uint64_t kGetLockWechatMgr = 0xbadb10;
const uint64_t kRequestLockWechat = 0xb63770;
const uint64_t kRequestUnLockWechat = 0xb63a10;
const uint64_t kOnLoginBtnClick = 0xf4d0f0;
const uint64_t kGetQRCodeLoginMgr = 0xf3fa20;
const uint64_t kUpdateMsg = 0xf15c40;
const uint64_t kGetVoiceMgr = 0xbf78f0;
const uint64_t kChatMsg2NetSceneSendMsg = 0x96e8d0;
const uint64_t kTranslateVoice = 0x11217e0;
const uint64_t kNewWebViewPageConfig = 0x9512f0;
const uint64_t kFreeWebViewPageConfig = 0x951520;
const uint64_t kGetWebViewMgr = 0x9412d0;
const uint64_t kShowWebView = 0x1d236b0;
const uint64_t kSetUrl = 0x13dd410;
#elif WECHAT_VERSION == V_3_9_10_19
const uint64_t kGetAccountServiceMgr = 0x1c1fe70;
const uint64_t kSyncMsg = 0xc39680;
const uint64_t kSyncMsgNext = 0xc39680;
const uint64_t kGetCurrentDataPath = 0x2315ea0;
const uint64_t kGetAppDataSavePath = 0x26a7df0;
const uint64_t kGetSendMessageMgr = 0x1c1e670;
const uint64_t kSendTextMsg = 0x238ec70;
const uint64_t kFreeChatMsg = 0x1c1fef0;
const uint64_t kDoAddMsg = 0x23d6f50;
const uint64_t kSendImageMsg = 0x2384400;
const uint64_t kChatMsgInstanceCounter = 0x1c287e0;
const uint64_t kSendFileMsg = 0x2197a40;
const uint64_t kGetAppMsgMgr = 0x1c23610;
const uint64_t kGetContactMgr = 0x1c0bdc0;
const uint64_t kGetContactList = 0x22665a0;
const uint64_t k_sqlite3_exec = 0x3afba50;
const uint64_t k_sqlite3_prepare = 0x3b036d0;
const uint64_t k_sqlite3_open = 0x3b3aec0;
const uint64_t k_sqlite3_step = 0x3abfa50;
const uint64_t k_sqlite3_column_count = 0x3ac0270;
const uint64_t k_sqlite3_column_name = 0x3ac0c70;
const uint64_t k_sqlite3_column_type = 0x3ac0ac0;
const uint64_t k_sqlite3_column_blob = 0x3ac02a0;
const uint64_t k_sqlite3_column_bytes = 0x3ac0390;
const uint64_t k_sqlite3_finalize = 0x3abeb00;
const uint64_t kGPInstance = 0x5a415a0;
const uint64_t kMultiDBMgr = 0x5abc5c8;
const uint64_t kPublicMsgMgr = 0x5ab9b68;
const uint64_t kFavoriteStorageMgr = 0x5abd178;
const uint64_t kHardLinkMgr = 0x5abc4e8;
const uint64_t kChatRoomMgr = 0x1c4e1e0;
const uint64_t kGetChatRoomDetailInfo = 0x222cf00;
const uint64_t kNewChatRoomInfo = 0x25d0250;
const uint64_t kFreeChatRoomInfo = 0x25d0430;
const uint64_t kDoAddMemberToChatRoom = 0x221c900;
const uint64_t kDoModChatRoomMemberNickName = 0xe6db00;
const uint64_t kDelMemberFromChatRoom = 0x221cf40;
const uint64_t kGetMemberFromChatRoom = 0x222e750;
const uint64_t kNewChatRoom = 0x25cd670;
const uint64_t kFreeChatRoom = 0x25cd870;
const uint64_t kTopMsg = 0xa5e4f0;
const uint64_t kRemoveTopMsg = 0xe787b0;
const uint64_t kInviteMember = 0xe63650;
const uint64_t kHookLog = 0x1304e60;
const uint64_t kCreateChatRoom = 0xe63340;
const uint64_t kQuitChatRoom = 0xe6e3b0;
const uint64_t kForwardMsg = 0x11dd780;
const uint64_t kOnSnsTimeLineSceneFinish = 0x1a73150;
const uint64_t kSNSGetFirstPage = 0x1a51dd0;
const uint64_t kSNSGetNextPageScene = 0x1a77240;
const uint64_t kSNSDataMgr = 0xeebda0;
const uint64_t kSNSTimeLineMgr = 0x19e83a0;
const uint64_t kGetMgrByPrefixLocalId = 0x105a010;
const uint64_t kAddFavFromMsg = 0x1601520;
const uint64_t kGetChatMgr = 0xaafd90;
const uint64_t kGetFavoriteMgr = 0x8c69b0;
const uint64_t kAddFavFromImage = 0x160b920;
const uint64_t kGetContact = 0xf67060;
const uint64_t kNewContact = 0x12e01f0;
const uint64_t kFreeContact = 0x12e08a0;
const uint64_t kNewMMReaderItem = 0x8c79a0;
const uint64_t kFreeMMReaderItem = 0x8c6da0;
const uint64_t kForwordPublicMsg = 0xddc6c0;
const uint64_t kParseAppMsgXml = 0x11b0a70;
const uint64_t kNewAppMsgInfo = 0x91a550;
const uint64_t kFreeAppMsgInfo = 0x8fd1a0;
const uint64_t kGetPreDownLoadMgr = 0x9996f0;
const uint64_t kPushAttachTask = 0x9c0080;
const uint64_t kGetCustomSmileyMgr = 0x915c00;
const uint64_t kSendCustomEmotion = 0xec0a40;
const uint64_t kNewJsApiShareAppMessage = 0x13be1a0;
const uint64_t kInitJsConfig = 0x137bc00;
const uint64_t kSendApplet = 0x13c0920;
const uint64_t kSendAppletSecond = 0x13c1150;
const uint64_t kGetAppInfoByWaid = 0x13c5790;
const uint64_t kCopyShareAppMessageRequest = 0x13c0670;
const uint64_t kNewWAUpdatableMsgInfo = 0x919ca0;
const uint64_t kFreeWAUpdatableMsgInfo = 0x8fc230;
const uint64_t kSendPatMsg = 0x195f340;
const uint64_t kGetOCRManager = 0x999780;
const uint64_t kDoOCRTask = 0x190b2a0;
const uint64_t kGetLockWechatMgr = 0xbadb10;
const uint64_t kRequestLockWechat = 0xb63770;
const uint64_t kRequestUnLockWechat = 0xb63a10;
const uint64_t kOnLoginBtnClick = 0xf4d0f0;
const uint64_t kGetQRCodeLoginMgr = 0xf3fa20;
const uint64_t kUpdateMsg = 0xf15c40;
const uint64_t kGetVoiceMgr = 0xbf78f0;
const uint64_t kChatMsg2NetSceneSendMsg = 0x96e8d0;
const uint64_t kTranslateVoice = 0x11217e0;
const uint64_t kNewWebViewPageConfig = 0x9512f0;
const uint64_t kFreeWebViewPageConfig = 0x951520;
const uint64_t kGetWebViewMgr = 0x9412d0;
const uint64_t kShowWebView = 0x1d236b0;
const uint64_t kSetUrl = 0x13dd410;
#else
#ifdef WECHAT_VERSION
#error "Unsupported WeChat version."
#endif
#endif
} // namespace offset
} // namespace wechat
#endif

View File

@ -0,0 +1,121 @@
#ifndef WXHELPER_SQLITE_FUNCTION_H_
#define WXHELPER_SQLITE_FUNCTION_H_
#include <cstdint>
#include "offset.h"
namespace sqlite3 {
namespace offset = wechat::offset;
#define SQLITE_OK 0 /* Successful result */
/* beginning-of-error-codes */
#define SQLITE_ERROR 1 /* Generic error */
#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
#define SQLITE_PERM 3 /* Access permission denied */
#define SQLITE_ABORT 4 /* Callback routine requested an abort */
#define SQLITE_BUSY 5 /* The database file is locked */
#define SQLITE_LOCKED 6 /* A table in the database is locked */
#define SQLITE_NOMEM 7 /* A malloc() failed */
#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
#define SQLITE_FULL 13 /* Insertion failed because database is full */
#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
#define SQLITE_EMPTY 16 /* Internal use only */
#define SQLITE_SCHEMA 17 /* The database schema changed */
#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
#define SQLITE_MISMATCH 20 /* Data type mismatch */
#define SQLITE_MISUSE 21 /* Library used incorrectly */
#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
#define SQLITE_AUTH 23 /* Authorization denied */
#define SQLITE_FORMAT 24 /* Not used */
#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
#define SQLITE_NOTADB 26 /* File opened that is not a database file */
#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
/* end-of-error-codes */
#define SQLITE_INTEGER 1
#define SQLITE_FLOAT 2
#define SQLITE_BLOB 4
#define SQLITE_NULL 5
#define SQLITE_TEXT 3
typedef int (*sqlite3_callback)(void *, int, char **, char **);
typedef int(__cdecl *sqlite3_exec)(uint64_t, /* An open database */
const char *sql, /* SQL to be evaluated */
sqlite3_callback, /* Callback function */
void *, /* 1st argument to callback */
char **errmsg /* Error msg written here */
);
typedef int(__cdecl *sqlite3_prepare)(
uint64_t db, /* Database handle */
const char *zSql, /* SQL statement, UTF-8 encoded */
int nByte, /* Maximum length of zSql in bytes. */
uint64_t **ppStmt, /* OUT: Statement handle */
const char **pzTail /* OUT: Pointer to unused portion of zSql */
);
typedef int(__cdecl *sqlite3_open)(const char *filename, uint64_t **ppDb);
typedef int(__cdecl *sqlite3_sleep)(int);
typedef int(__cdecl *sqlite3_errcode)(uint64_t *db);
typedef int(__cdecl *sqlite3_close)(uint64_t *);
typedef int(__cdecl *sqlite3_step)(uint64_t *);
typedef int(__cdecl *sqlite3_column_count)(uint64_t *pStmt);
typedef const char *(__cdecl *sqlite3_column_name)(uint64_t *, int N);
typedef int(__cdecl *sqlite3_column_type)(uint64_t *, int iCol);
typedef const void *(__cdecl *sqlite3_column_blob)(uint64_t *, int iCol);
typedef int(__cdecl *sqlite3_column_bytes)(uint64_t *, int iCol);
typedef int(__cdecl *sqlite3_finalize)(uint64_t *pStmt);
/***************************sqlite3 end*************************************/
struct SqliteFunction {
SqliteFunction(){}
SqliteFunction(uint64_t base_addr) {
sqlite3_exec =
reinterpret_cast<sqlite3::sqlite3_exec>(base_addr + offset::k_sqlite3_exec);
sqlite3_prepare = reinterpret_cast<sqlite3::sqlite3_prepare>(
base_addr + offset::k_sqlite3_prepare);
sqlite3_open =
reinterpret_cast<sqlite3::sqlite3_open>(base_addr + offset::k_sqlite3_open);
sqlite3_step =
reinterpret_cast<sqlite3::sqlite3_step>(base_addr + offset::k_sqlite3_step);
sqlite3_column_count = reinterpret_cast<sqlite3::sqlite3_column_count>(
base_addr + offset::k_sqlite3_column_count);
sqlite3_column_name = reinterpret_cast<sqlite3::sqlite3_column_name>(
base_addr + offset::k_sqlite3_column_name);
sqlite3_column_type = reinterpret_cast<sqlite3::sqlite3_column_type>(
base_addr + offset::k_sqlite3_column_type);
sqlite3_column_blob = reinterpret_cast<sqlite3::sqlite3_column_blob>(
base_addr + offset::k_sqlite3_column_blob);
sqlite3_column_bytes = reinterpret_cast<sqlite3::sqlite3_column_bytes>(
base_addr + offset::k_sqlite3_column_bytes);
sqlite3_finalize = reinterpret_cast<sqlite3::sqlite3_finalize>(
base_addr + offset::k_sqlite3_finalize);
}
sqlite3_exec sqlite3_exec;
sqlite3_prepare sqlite3_prepare;
sqlite3_open sqlite3_open;
sqlite3_sleep sqlite3_sleep;
sqlite3_errcode sqlite3_errcode;
sqlite3_close sqlite3_close;
sqlite3_step sqlite3_step;
sqlite3_column_count sqlite3_column_count;
sqlite3_column_name sqlite3_column_name;
sqlite3_column_type sqlite3_column_type;
sqlite3_column_blob sqlite3_column_blob;
sqlite3_column_bytes sqlite3_column_bytes;
sqlite3_finalize sqlite3_finalize;
};
} // namespace sqlite3
#endif

View File

@ -0,0 +1,63 @@
#include "sync_msg_hook.h"
#include "base64.h"
#include "config.h"
#include "nlohmann/json.hpp"
#include "offset.h"
#include "spdlog/spdlog.h"
#include "thread_pool.h"
#include "utils.h"
#include "wxutils.h"
namespace wxhelper {
void SyncMsgHook::Init() {
int64_t addr = wxutils::GetWeChatWinBase() + wechat::offset::kDoAddMsg;
kDoAddMsg = (wechat::function::__DoAddMsg)addr;
origin_ = &kDoAddMsg;
detour_ = &HandleSyncMsg;
hook_flag_ = false;
}
void SyncMsgHook::HandleSyncMsg(int64_t param1, int64_t param2, int64_t param3) {
nlohmann::json msg;
msg["pid"] = GetCurrentProcessId();
msg["fromUser"] = wxutils::ReadSKBuiltinString(*(int64_t *)(param2 + 0x18));
msg["toUser"] = wxutils::ReadSKBuiltinString(*(int64_t *)(param2 + 0x28));
msg["content"] = wxutils::ReadSKBuiltinString(*(int64_t *)(param2 + 0x30));
msg["signature"] = wxutils::ReadWeChatStr(*(int64_t *)(param2 + 0x48));
msg["msgId"] = *(int64_t *)(param2 + 0x60);
msg["msgSequence"] = *(DWORD *)(param2 + 0x5C);
msg["createTime"] = *(DWORD *)(param2 + 0x58);
msg["displayFullContent"] = wxutils::ReadWeChatStr(*(int64_t *)(param2 + 0x50));
DWORD type = *(DWORD *)(param2 + 0x24);
msg["type"] = type;
if (type == 3) {
std::string img = wxutils::ReadSKBuiltinBuffer(*(int64_t *)(param2 + 0x40));
SPDLOG_INFO("encode size:{}", img.size());
msg["base64Img"] = base64_encode(img);
}
std::string jstr = msg.dump() + '\n';
hook::InnerMessageStruct *inner_msg = new hook::InnerMessageStruct;
inner_msg->buffer = new char[jstr.size() + 1];
memcpy(inner_msg->buffer, jstr.c_str(), jstr.size() + 1);
inner_msg->length = jstr.size();
std::string mode = Config::GetInstance().GetRecvMessageMode();
if (mode == "http") {
bool add = base::ThreadPool::GetInstance().AddWork(
hook::SendHttpMsgCallback, inner_msg);
SPDLOG_INFO("add http msg work:{}", add);
} else if (mode == "tcp") {
bool add = base::ThreadPool::GetInstance().AddWork(hook::SendTcpMsgCallback,
inner_msg);
SPDLOG_INFO("add tcp msg work:{}", add);
}
if (kDoAddMsg == nullptr){
int64_t addr = wxutils::GetWeChatWinBase() + wechat::offset::kDoAddMsg;
kDoAddMsg = (wechat::function::__DoAddMsg)addr;
}
kDoAddMsg(param1, param2, param3);
}
} // namespace wxhelper

View File

@ -0,0 +1,17 @@
#ifndef WXHELPER_SYNC_MSG_HOOK_H_
#define WXHELPER_SYNC_MSG_HOOK_H_
#include "hook.h"
#include "singleton.h"
#include "wechat_interface.h"
namespace wxhelper{
static wechat::function::__DoAddMsg kDoAddMsg= nullptr;
class SyncMsgHook : public hook::BaseHook,public base::Singleton<SyncMsgHook> {
public:
void Init();
private:
static void HandleSyncMsg(int64_t param1, int64_t param2, int64_t param3);
};
}
#endif

View File

@ -0,0 +1,399 @@
#include "wechat_db.h"
#include "base64.h"
#include "spdlog/spdlog.h"
#include "utils.h"
#include "wechat_interface.h"
#include "wxutils.h"
namespace wechat {
void FreeResult(std::vector<std::vector<wechat::SqlResult>> &data) {
if (data.empty()) {
return;
}
for (auto &row : data) {
for (auto &item : row) {
if (item.column_name) {
delete[] item.column_name;
item.column_name = nullptr;
}
if (item.content) {
delete[] item.content;
item.content = nullptr;
}
}
std::vector<wechat::SqlResult>().swap(row);
}
std::vector<std::vector<wechat::SqlResult>>().swap(data);
}
int GetDbInfoCallback(void *data, int argc, char **argv, char **name) {
DatabaseInfo *pdata = (DatabaseInfo *)data;
TableInfo tb = {0};
if (argv[1]) {
tb.name = new char[strlen(argv[1]) + 1];
memcpy(tb.name, argv[1], strlen(argv[1]) + 1);
} else {
tb.name = (char *)"NULL";
}
if (argv[2]) {
tb.table_name = new char[strlen(argv[2]) + 1];
memcpy(tb.table_name, argv[2], strlen(argv[2]) + 1);
} else {
tb.table_name = (char *)"NULL";
}
if (argv[3]) {
tb.rootpage = new char[strlen(argv[3]) + 1];
memcpy(tb.rootpage, argv[3], strlen(argv[3]) + 1);
} else {
tb.rootpage = (char *)"NULL";
}
if (argv[4]) {
tb.sql = new char[strlen(argv[4]) + 1];
memcpy(tb.sql, argv[4], strlen(argv[4]) + 1);
} else {
tb.sql = (char *)"NULL";
}
tb.name_len = strlen(tb.name);
tb.table_name_len = strlen(tb.table_name);
tb.sql_len = strlen(tb.sql);
tb.rootpage_len = strlen(tb.rootpage);
pdata->tables.push_back(tb);
pdata->count = pdata->tables.size();
return 0;
}
void WeChatDb::Init() {
std::lock_guard<std::recursive_mutex> lock(m);
base_addr_ = wxhelper::wxutils::GetWeChatWinBase();
func_ = sqlite3::SqliteFunction(base_addr_);
dbmap_ = {};
dbs_ = {};
}
int WeChatDb::ExecuteSQL(uint64_t db, const char *sql,
sqlite3::sqlite3_callback callback, void *data) {
return func_.sqlite3_exec(db, sql, callback, data, 0);
}
int64_t WeChatDb::GetDbHandleByDbName(wchar_t *dbname) {
if (dbmap_.size() == 0) {
GetWeChatDbHandles();
}
if (dbmap_.find(dbname) != dbmap_.end()) {
return dbmap_[dbname].handle;
}
return 0;
}
std::vector<void *> WeChatDb::GetWeChatDbHandles() {
std::lock_guard<std::recursive_mutex> lock(m);
dbs_.clear();
dbmap_.clear();
uint64_t p_contact_addr = *(uint64_t *)(base_addr_ + offset::kGPInstance);
std::vector<uint64_t> addr_vector{
0x180, 0x278, 0x3a0, 0x4c8, 0x5a0, 0x6e0, 0x838, 0x958, 0xa40,
0xb28, 0xd00, 0xe10, 0xef8, 0xfd0, 0x10e8, 0x1200, 0x13d0, 0x15a0,
0x1678, 0x17a8, 0x18c0, 0x1998, 0x1a70, 0x1b48, 0x1c48, 0x1d60, 0x1e38};
for (uint64_t elem : addr_vector) {
uint64_t db_addr = *(uint64_t *)(p_contact_addr + elem + 0x50);
if (db_addr == 0) {
continue;
}
std::wstring name =
std::wstring((wchar_t *)(*(uint64_t *)(p_contact_addr + elem + 0x78)),
*(uint32_t *)(p_contact_addr + elem + 0x80));
auto it = dbmap_.find(name);
if (it != dbmap_.end()) {
continue;
} else {
DatabaseInfo db{0};
db.db_name = (wchar_t *)(*(uint64_t *)(p_contact_addr + elem + 0x78));
db.db_name_len = *(int32_t *)(p_contact_addr + elem + 0x80);
db.handle = db_addr;
ExecuteSQL(db_addr, "select * from sqlite_master where type=\"table\";",
GetDbInfoCallback, &db);
dbs_.push_back(db);
dbmap_[name] = db;
}
}
// MsgX.db
uint64_t multi_db_mgr_addr = base_addr_ + offset::kMultiDBMgr;
uint64_t wrap_ptr = *(uint64_t *)(multi_db_mgr_addr);
uint64_t current_db_num = *(uint64_t *)(wrap_ptr + 0x68);
uint64_t begin_ptr = *(uint64_t *)(wrap_ptr + 0x50);
for (unsigned int i = 0; i < current_db_num; ++i) {
uint64_t next_addr = begin_ptr + i * 0x8;
uint64_t db_addr = *(uint64_t *)next_addr;
if (db_addr) {
uint64_t msg0_db_addr = *(uint64_t *)(db_addr + 0x78);
DatabaseInfo msg0_db{0};
msg0_db.db_name = (wchar_t *)(*(uint64_t *)(db_addr));
msg0_db.db_name_len = *(int32_t *)(db_addr + 0x8);
msg0_db.handle = msg0_db_addr;
msg0_db.extrainfo = *(uint64_t *)(*(uint64_t *)(db_addr + 0x28) + 0x1E8);
ExecuteSQL(msg0_db_addr,
"select * from sqlite_master where type=\"table\";",
GetDbInfoCallback, &msg0_db);
dbs_.push_back(msg0_db);
std::wstring msg_db_name =
std::wstring(msg0_db.db_name, msg0_db.db_name_len);
dbmap_[msg_db_name] = msg0_db;
// BufInfoStorage
uint64_t buf_info_addr = *(uint64_t *)(db_addr + 0x20);
if (buf_info_addr) {
AddDatebaseInfo(buf_info_addr);
}
}
}
// publicMsg.db
uint64_t public_msg_mgr_addr = base_addr_ + offset::kPublicMsgMgr;
uint64_t public_msg_mgr_ptr = *(uint64_t *)(public_msg_mgr_addr);
for (unsigned int i = 1; i < 4; ++i) {
uint64_t public_msg_ptr = *(uint64_t *)(public_msg_mgr_ptr + i * 0x8);
if (public_msg_ptr) {
AddDatebaseInfo(public_msg_ptr);
}
}
// Favorite.db
uint64_t favoite = base_addr_ + offset::kFavoriteStorageMgr;
uint64_t item_ptr =
*(uint64_t *)(*(uint64_t *)(*(uint64_t *)(favoite) + 0x10) + 0x8);
if (item_ptr) {
AddDatebaseInfo(item_ptr);
}
// HardLinkMgr
uint64_t link = base_addr_ + offset::kHardLinkMgr;
uint64_t link_ptr = *(uint64_t *)(*(uint64_t *)(link) + 0x158);
for (unsigned int i = 0; i < 6; ++i) {
uint64_t hard_link_ptr = *(uint64_t *)(link_ptr + i * 0x8);
SPDLOG_INFO("hardlinkxxxdb :{}", hard_link_ptr);
if (hard_link_ptr) {
AddDatebaseInfo(hard_link_ptr);
}
}
SPDLOG_INFO("db number:{}", dbs_.size());
std::vector<void *> ret;
for (unsigned int i = 0; i < dbs_.size(); ++i) {
ret.push_back(&dbs_[i]);
}
return ret;
}
int WeChatDb::Select(uint64_t db_hanle, const std::string &sql,
std::vector<std::vector<std::string>> &query_result) {
std::vector<std::vector<wechat::SqlResult>> data;
int status = ExecSelect(db_hanle, sql, data);
if (status != SQLITE_OK) {
return 0;
}
if (data.size() == 0) {
return 1;
}
std::vector<std::string> index;
for (size_t i = 0; i < data[0].size(); i++) {
index.push_back(data[0][i].column_name);
}
query_result.push_back(index);
for (auto it : data) {
std::vector<std::string> item;
for (size_t i = 0; i < it.size(); i++) {
if (!it[i].is_blob) {
bool is_utf8 =
base::utils::IsTextUtf8(it[i].content, it[i].content_len);
if (is_utf8) {
std::string content(it[i].content);
item.push_back(content);
} else {
std::string base64_str =
base64_encode((BYTE *)it[i].content, it[i].content_len);
item.push_back(base64_str);
}
} else {
std::string b64_str =
base64_encode((BYTE *)it[i].content, it[i].content_len);
item.push_back(b64_str);
}
}
query_result.push_back(item);
}
FreeResult(data);
return 1;
}
int64_t WeChatDb::GetLocalIdByMsgId(uint64_t msgid, int64_t &dbIndex) {
char sql[260] = {0};
sprintf_s(sql, "select localId from MSG where MsgSvrID=%llu;", msgid);
wchar_t dbname[20] = {0};
for (int i = 0;; i++) {
swprintf_s(dbname, L"MSG%d.db", i);
uint64_t handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
SPDLOG_INFO("MSG db handle is null");
return 0;
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) continue;
dbIndex = dbmap_[dbname].extrainfo;
return stoi(result[1][0]);
}
return 0;
}
std::vector<std::string> WeChatDb::GetChatMsgByMsgId(uint64_t msgid) {
char sql[260] = {0};
sprintf_s(sql,
"select "
"localId,TalkerId,MsgSvrID,Type,SubType,IsSender,CreateTime,"
"Sequence,StatusEx,FlagEx,Status,MsgServerSeq,MsgSequence,"
"StrTalker,StrContent,BytesExtra from MSG where MsgSvrID=%llu;",
msgid);
wchar_t dbname[20] = {0};
for (int i = 0;; i++) {
swprintf_s(dbname, L"MSG%d.db", i);
UINT64 handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
SPDLOG_INFO("MSG db handle is null");
return {};
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) continue;
return result[1];
}
return {};
}
std::string WeChatDb::GetVoiceBuffByMsgId(uint64_t msgid) {
char sql[260] = {0};
sprintf_s(sql, "SELECT Buf from Media WHERE Reserved0=%llu;", msgid);
wchar_t dbname[20] = {0};
for (int i = 0;; i++) {
swprintf_s(dbname, L"MediaMSG%d.db", i);
UINT64 handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
SPDLOG_INFO("Media db handle is null");
return "";
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) continue;
return result[1][0];
}
return "";
}
std::string WeChatDb::GetPublicMsgCompressContentByMsgId(uint64_t msgid) {
char sql[260] = {0};
sprintf_s(sql, "SELECT CompressContent from PublicMsg WHERE MsgSvrID=%llu;",
msgid);
wchar_t dbname[20] = {0};
swprintf_s(dbname, 20, L"%s", L"PublicMsg.db");
UINT64 handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
SPDLOG_INFO("db handle not found,check msgid");
return "";
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) {
SPDLOG_INFO(
"this SQL statement executed normally, but the result was empty");
return "";
}
return result[1][0];
}
std::string WeChatDb::GetChatMsgStrContentByMsgId(uint64_t msgid) {
char sql[260] = {0};
sprintf_s(sql, "select StrContent from MSG where MsgSvrID=%llu;", msgid);
wchar_t dbname[20] = {0};
for (int i = 0;; i++) {
swprintf_s(dbname, L"MSG%d.db", i);
UINT64 handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
SPDLOG_INFO("MSG db handle is null");
return {};
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) continue;
return result[1][0];
}
return {};
}
void WeChatDb::AddDatebaseInfo(uint64_t storage) {
std::lock_guard<std::recursive_mutex> lock(m);
uint64_t storage_addr = *(uint64_t *)(storage + 0x50);
std::wstring name = std::wstring((wchar_t *)(*(uint64_t *)(storage + 0x78)),
*(int32_t *)(storage + 0x80));
auto it = dbmap_.find(name);
if (it == dbmap_.end()) {
DatabaseInfo db{0};
db.db_name = (wchar_t *)(*(uint64_t *)(storage + 0x78));
db.db_name_len = *(int32_t *)(storage + 0x80);
db.handle = storage_addr;
ExecuteSQL(storage_addr,
"select * from sqlite_master where type=\"table\";",
GetDbInfoCallback, &db);
dbs_.push_back(db);
dbmap_[name] = db;
}
}
int WeChatDb::ExecSelect(uint64_t db, const std::string &sql,
std::vector<std::vector<wechat::SqlResult>> &data) {
uint64_t *stmt;
int rc = func_.sqlite3_prepare(db, sql.c_str(), -1, &stmt, 0);
if (rc != SQLITE_OK) {
return rc;
}
while (func_.sqlite3_step(stmt) == SQLITE_ROW) {
int col_count = func_.sqlite3_column_count(stmt);
std::vector<wechat::SqlResult> res;
for (unsigned int i = 0; i < col_count; ++i) {
wechat::SqlResult temp = {0};
const char *col_name = func_.sqlite3_column_name(stmt, i);
int ntype = func_.sqlite3_column_type(stmt, i);
const void *p_blob_data = func_.sqlite3_column_blob(stmt, i);
int nlength = func_.sqlite3_column_bytes(stmt, i);
temp.column_name = new char[strlen(col_name) + 1];
memcpy(temp.column_name, col_name, strlen(col_name) + 1);
temp.column_name_len = strlen(col_name);
temp.content_len = nlength;
switch (ntype) {
case SQLITE_BLOB: {
temp.content = new char[nlength];
memcpy(temp.content, p_blob_data, nlength);
temp.is_blob = true;
break;
}
default: {
if (nlength != 0) {
temp.content = new char[nlength + 1];
memcpy(temp.content, p_blob_data, nlength + 1);
} else {
temp.content = new char[2];
ZeroMemory(temp.content, 2);
}
temp.is_blob = false;
break;
}
}
res.push_back(temp);
}
data.push_back(res);
}
func_.sqlite3_finalize(stmt);
return SQLITE_OK;
}
} // namespace wechat

View File

@ -0,0 +1,48 @@
#ifndef WXHELPER_WECHAT_DB_H_
#define WXHELPER_WECHAT_DB_H_
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "singleton.h"
#include "sqlite_function.h"
#include "wechat_interface.h"
namespace wechat {
class WeChatDb : public base::Singleton<WeChatDb> {
public:
void Init();
std::vector<void *> GetWeChatDbHandles();
int Select(uint64_t db_hanle, const std::string &sql,
std::vector<std::vector<std::string>> &query_result);
int64_t GetLocalIdByMsgId(uint64_t msgid, int64_t &dbIndex);
std::vector<std::string> GetChatMsgByMsgId(uint64_t msgid);
std::string GetVoiceBuffByMsgId(uint64_t msgid);
std::string GetPublicMsgCompressContentByMsgId(uint64_t msgid);
std::string GetChatMsgStrContentByMsgId(uint64_t msgid);
int64_t GetDbHandleByDbName(wchar_t *dbname);
private:
void AddDatebaseInfo(uint64_t storage);
int ExecSelect(uint64_t db, const std::string &sql,
std::vector<std::vector<wechat::SqlResult>> &data);
int ExecuteSQL(uint64_t db, const char *sql,
sqlite3::sqlite3_callback callback, void *data);
private:
std::unordered_map<std::wstring, DatabaseInfo> dbmap_;
std::vector<DatabaseInfo> dbs_;
sqlite3::SqliteFunction func_;
uint64_t base_addr_;
mutable std::recursive_mutex m;
};
} // namespace wechat
#endif

View File

@ -0,0 +1,285 @@
#ifndef WXHELPER_WECHAT_INNER_H_
#define WXHELPER_WECHAT_INNER_H_
#include <string>
#include <vector>
#include <cstdint>
namespace wechat {
struct TableInfo {
char *name;
int64_t name_len;
char *table_name;
int64_t table_name_len;
char *sql;
int64_t sql_len;
char *rootpage;
int64_t rootpage_len;
};
struct DatabaseInfo {
uint64_t handle = 0;
wchar_t *db_name = NULL;
int64_t db_name_len = 0;
std::vector<TableInfo> tables;
int64_t count = 0;
int64_t extrainfo = 0;
};
struct SqlResult {
char *column_name;
int64_t column_name_len;
char *content;
int64_t content_len;
bool is_blob;
};
struct SelfInfoInner {
std::string name;
std::string city;
std::string province;
std::string country;
std::string account;
std::string wxid;
std::string mobile;
std::string head_img;
std::string data_save_path;
std::string signature;
std::string current_data_path;
std::string db_key;
std::string public_key;
std::string private_key;
};
struct ContactInner {
std::string wxid;
std::string custom_account;
std::string encrypt_name;
std::string nickname;
std::string pinyin;
std::string pinyin_all;
std::string remark;
std::string remark_pinyin;
std::string remark_pinyin_all;
std::string label_ids;
int32_t type;
int32_t verify_flag;
int32_t reserved1;
int32_t reserved2;
ContactInner() {
wxid = "";
custom_account = "";
encrypt_name = "";
nickname = "";
pinyin = "";
pinyin_all = "";
remark = "";
remark_pinyin = "";
remark_pinyin_all = "";
label_ids = "";
type = -1;
verify_flag = -1;
reserved1 = -1;
reserved2 = -1;
}
};
struct ChatRoomInfoInner {
std::string chat_room_id;
std::string notice;
std::string admin;
std::string xml;
ChatRoomInfoInner() {
chat_room_id = "";
notice = "";
admin = "";
xml = "";
}
};
struct VectorInner {
#ifdef _DEBUG
int64_t head;
#endif
int64_t start;
int64_t finsh;
int64_t end;
};
struct ChatRoomMemberInner {
std::string chat_room_id;
std::string admin;
std::string admin_nickname;
std::string member_nickname;
std::string member;
ChatRoomMemberInner()
: chat_room_id(""),
admin(""),
admin_nickname(""),
member_nickname(""),
member("") {}
};
struct ContactProfileInner {
std::string wxid;
std::string account;
std::string v3;
std::string nickname;
std::string head_image;
ContactProfileInner()
: wxid(""), account(""), v3(""), nickname(""), head_image("") {}
};
namespace function {
//hook
typedef uint64_t(*__DoAddMsg)(uint64_t, uint64_t, uint64_t);
//hook end
typedef uint64_t (*__GetAccountService)();
typedef uint64_t (*__GetDataSavePath)(uint64_t);
typedef uint64_t (*__GetCurrentDataPath)(uint64_t);
typedef uint64_t (*__GetSendMessageMgr)();
typedef uint64_t (*__SendTextMsg)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t, uint64_t);
typedef uint64_t (*__FreeChatMsg)(uint64_t);
typedef uint64_t (*__SendImageMsg)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__NewChatMsg)(uint64_t);
typedef uint64_t (*__SendFile)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetAppMsgMgr)();
typedef uint64_t (*__OperatorNew)(uint64_t);
typedef uint64_t (*__Free)();
typedef uint64_t (*__GetContactMgr)();
typedef uint64_t (*__GetContactList)(uint64_t, uint64_t);
typedef uint64_t (*__GetChatRoomMgr)();
typedef uint64_t (*__NewChatRoomInfo)(uint64_t);
typedef uint64_t (*__FreeChatRoomInfo)(uint64_t);
typedef uint64_t (*__GetChatRoomDetailInfo)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__DoAddMemberToChatRoom)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__DoModChatRoomMemberNickName)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__DoDelMemberFromChatRoom)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetMemberFromChatRoom)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__NewChatRoom)(uint64_t);
typedef uint64_t (*__FreeChatRoom)(uint64_t);
typedef uint64_t (*__DoTopMsg)(uint64_t, uint64_t);
typedef uint64_t (*__RemoveTopMsg)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__InviteMemberToChatRoom)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__CreateChatRoom)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__QuitChatRoom)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__ForwardMsg)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetSNSFirstPage)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetSNSNextPageScene)(uint64_t, uint64_t);
typedef uint64_t (*__GetSNSDataMgr)();
typedef uint64_t (*__GetSnsTimeLineMgr)();
typedef uint64_t (*__GetMgrByPrefixLocalId)(uint64_t, uint64_t);
typedef uint64_t (*__AddFavFromMsg)(uint64_t, uint64_t);
typedef uint64_t (*__GetChatMgr)();
typedef uint64_t (*__GetFavoriteMgr)();
typedef uint64_t (*__AddFavFromImage)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetContact)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__NewContact)(uint64_t);
typedef uint64_t (*__FreeContact)(uint64_t);
typedef uint64_t (*__NewMMReaderItem)(uint64_t);
typedef uint64_t (*__FreeMMReaderItem)(uint64_t);
typedef uint64_t (*__ForwordPublicMsg)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__NewAppMsgInfo)(uint64_t);
typedef uint64_t (*__FreeAppMsgInfo)(uint64_t);
typedef uint64_t (*__ParseAppMsgXml)(uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetPreDownLoadMgr)();
typedef uint64_t (*__PushAttachTask)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetCustomSmileyMgr)();
typedef uint64_t (*__SendCustomEmotion)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__JsApiShareAppMessage)(uint64_t);
typedef uint64_t (*__InitJsConfig)(uint64_t, uint64_t);
typedef uint64_t (*__SendApplet)(uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__SendAppletSecond)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t);
typedef uint64_t (*__GetAppInfoByWaid)(uint64_t, uint64_t);
typedef uint64_t (*__CopyShareAppMessageRequest)(uint64_t, uint64_t);
typedef uint64_t (*__NewWAUpdatableMsgInfo)(uint64_t);
typedef uint64_t (*__FreeWAUpdatableMsgInfo)(uint64_t);
typedef uint64_t (*__SendPatMsg)(uint64_t, uint64_t);
typedef uint64_t (*__GetOCRManager)();
typedef uint64_t (*__DoOCRTask)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t);
typedef uint64_t (*__GetLockWechatMgr)();
typedef uint64_t (*__RequestLockWechat)(uint64_t);
typedef uint64_t (*__RequestUnLockWechat)(uint64_t);
typedef uint64_t (*__OnLoginBtnClick)(uint64_t);
typedef uint64_t (*__GetQRCodeLoginMgr)();
typedef uint64_t (*__UpdateMsg)(uint64_t,uint64_t,uint64_t);
typedef uint64_t (*__GetVoiceMgr)();
typedef uint64_t (*__ChatMsg2NetSceneSendMsg)(uint64_t,uint64_t);
typedef uint64_t (*__TranslateVoice)(uint64_t,uint64_t,uint64_t);
typedef uint64_t (*__ShowWebView)(uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t);
typedef uint64_t (*__NewWebViewPageConfig)(uint64_t);
typedef uint64_t (*__FreeWebViewPageConfig)(uint64_t);
typedef uint64_t (*__GetWebViewMgr)();
typedef uint64_t (*__SetUrl)(uint64_t,uint64_t,uint64_t);
} // namespace function
namespace prototype {
struct WeChatString {
wchar_t *ptr;
int32_t length;
int32_t max_length;
int64_t c_ptr = 0;
int32_t c_len = 0;
WeChatString() { WeChatString(NULL); }
WeChatString(const std::wstring &s) {
ptr = (wchar_t *)(s.c_str());
length = static_cast<int32_t>(s.length());
max_length = static_cast<int32_t>(s.length());
}
WeChatString(const wchar_t *pStr) { WeChatString((wchar_t *)pStr); }
WeChatString(int tmp) {
ptr = NULL;
length = 0x0;
max_length = 0x0;
}
WeChatString(wchar_t *pStr) {
ptr = pStr;
length = static_cast<int32_t>(wcslen(pStr));
max_length = static_cast<int32_t>(wcslen(pStr));
}
void set_value(const wchar_t *pStr) {
ptr = (wchar_t *)pStr;
length = static_cast<int32_t>(wcslen(pStr));
max_length = static_cast<int32_t>(wcslen(pStr) * 2);
}
};
struct WeChatStr {
char *ptr;
int64_t buf;
int64_t len;
int64_t maxlen;
WeChatStr(const char *p) {
ptr = (char *)p;
buf = 0;
len = strlen(p);
maxlen = len | 0xF;
}
WeChatStr() {
ptr = NULL;
buf = 0;
len = 0;
maxlen = 0xF;
}
};
} // namespace prototype
} // namespace wechat
#endif

View File

@ -0,0 +1,924 @@
#include "wechat_service.h"
#include "json_utils.h"
#include "memory.h"
#include "spdlog/spdlog.h"
#include "tinyxml2.h"
#include "utils.h"
#include "wechat_db.h"
#include "wxutils.h"
namespace offset = wechat::offset;
namespace prototype = wechat::prototype;
namespace func = wechat::function;
namespace utils = base::utils;
namespace jsonutils = wxhelper::jsonutils;
namespace wxutils = wxhelper::wxutils;
prototype::WeChatString* BuildWechatString(const std::wstring& ws) {
prototype::WeChatString* p =
base::utils::WxHeapAlloc<prototype::WeChatString>(
sizeof(prototype::WeChatString));
wchar_t* p_chat_room_id =
base::utils::WxHeapAlloc<wchar_t>((ws.size() + 1) * 2);
wmemcpy(p_chat_room_id, ws.c_str(), ws.size() + 1);
p->ptr = p_chat_room_id;
p->length = static_cast<int32_t>(ws.size());
p->max_length = static_cast<int32_t>(ws.size());
p->c_len = 0;
p->c_ptr = 0;
return p;
}
wechat::WeChatService::~WeChatService() {}
void wechat::WeChatService::Init() { base_addr_ = wxutils::GetWeChatWinBase(); }
int64_t wechat::WeChatService::CheckLogin() {
int64_t success = -1;
uint64_t accout_service_addr = base_addr_ + offset::kGetAccountServiceMgr;
func::__GetAccountService GetSevice =
(func::__GetAccountService)accout_service_addr;
uint64_t service_addr = GetSevice();
if (service_addr) {
success = *(uint64_t*)(service_addr + 0x7F8);
}
return success;
}
int64_t wechat::WeChatService::GetSelfInfo(SelfInfoInner& out) {
int64_t success = -1;
uint64_t accout_service_addr = base_addr_ + offset::kGetAccountServiceMgr;
uint64_t get_app_data_save_path_addr =
base_addr_ + offset::kGetAppDataSavePath;
uint64_t get_current_data_path_addr =
base_addr_ + offset::kGetCurrentDataPath;
func::__GetAccountService GetSevice =
(func::__GetAccountService)accout_service_addr;
func::__GetDataSavePath GetDataSavePath =
(func::__GetDataSavePath)get_app_data_save_path_addr;
func::__GetCurrentDataPath GetCurrentDataPath =
(func::__GetCurrentDataPath)get_current_data_path_addr;
uint64_t service_addr = GetSevice();
if (service_addr) {
if (*(int64_t*)(service_addr + 0x80) == 0 ||
*(int64_t*)(service_addr + 0x80 + 0x10) == 0) {
out.wxid = std::string();
} else {
if (*(int64_t*)(service_addr + 0x80 + 0x18) == 0xF) {
out.wxid = std::string((char*)(service_addr + 0x80),
*(int64_t*)(service_addr + 0x80 + 0x10));
} else {
out.wxid = std::string(*(char**)(service_addr + 0x80),
*(int64_t*)(service_addr + 0x80 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x108) == 0 ||
*(int64_t*)(service_addr + 0x108 + 0x10) == 0) {
out.account = std::string();
} else {
if (*(int64_t*)(service_addr + 0x108 + 0x18) == 0xF) {
out.account = std::string((char*)(service_addr + 0x108),
*(int64_t*)(service_addr + 0x108 + 0x10));
} else {
out.account = std::string(*(char**)(service_addr + 0x108),
*(int64_t*)(service_addr + 0x108 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x128) == 0 ||
*(int64_t*)(service_addr + 0x128 + 0x10) == 0) {
out.mobile = std::string();
} else {
if (*(int64_t*)(service_addr + 0x128 + 0x18) == 0xF) {
out.mobile = std::string((char*)(service_addr + 0x128),
*(int64_t*)(service_addr + 0x128 + 0x10));
} else {
out.mobile = std::string(*(char**)(service_addr + 0x128),
*(int64_t*)(service_addr + 0x128 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x148) == 0 ||
*(int64_t*)(service_addr + 0x148 + 0x10) == 0) {
out.signature = std::string();
} else {
if (*(int64_t*)(service_addr + 0x148 + 0x18) == 0xF) {
out.signature = std::string((char*)(service_addr + 0x148),
*(int64_t*)(service_addr + 0x148 + 0x10));
} else {
out.signature = std::string(*(char**)(service_addr + 0x148),
*(int64_t*)(service_addr + 0x148 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x168) == 0 ||
*(int64_t*)(service_addr + 0x168 + 0x10) == 0) {
out.country = std::string();
} else {
if (*(int64_t*)(service_addr + 0x168 + 0x18) == 0xF) {
out.country = std::string((char*)(service_addr + 0x168),
*(int64_t*)(service_addr + 0x168 + 0x10));
} else {
out.country = std::string(*(char**)(service_addr + 0x168),
*(int64_t*)(service_addr + 0x168 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x188) == 0 ||
*(int64_t*)(service_addr + 0x188 + 0x10) == 0) {
out.province = std::string();
} else {
if (*(int64_t*)(service_addr + 0x188 + 0x18) == 0xF) {
out.province = std::string((char*)(service_addr + 0x188),
*(int64_t*)(service_addr + 0x188 + 0x10));
} else {
out.province = std::string(*(char**)(service_addr + 0x188),
*(int64_t*)(service_addr + 0x188 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x1A8) == 0 ||
*(int64_t*)(service_addr + 0x1A8 + 0x10) == 0) {
out.city = std::string();
} else {
if (*(int64_t*)(service_addr + 0x1A8 + 0x18) == 0xF) {
out.city = std::string((char*)(service_addr + 0x1A8),
*(int64_t*)(service_addr + 0x1A8 + 0x10));
} else {
out.city = std::string(*(char**)(service_addr + 0x1A8),
*(int64_t*)(service_addr + 0x1A8 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x1E8) == 0 ||
*(int64_t*)(service_addr + 0x1E8 + 0x10) == 0) {
out.name = std::string();
} else {
if (*(int64_t*)(service_addr + 0x1E8 + 0x18) == 0xF) {
out.name = std::string((char*)(service_addr + 0x1E8),
*(int64_t*)(service_addr + 0x1E8 + 0x10));
} else {
out.name = std::string(*(char**)(service_addr + 0x1E8),
*(int64_t*)(service_addr + 0x1E8 + 0x10));
}
}
if (*(int64_t*)(service_addr + 0x450) == 0 ||
*(int64_t*)(service_addr + 0x450 + 0x10) == 0) {
out.head_img = std::string();
} else {
out.head_img = std::string(*(char**)(service_addr + 0x450),
*(int64_t*)(service_addr + 0x450 + 0x10));
}
if (*(int64_t*)(service_addr + 0x7B8) == 0 ||
*(int64_t*)(service_addr + 0x7B8 + 0x10) == 0) {
out.public_key = std::string();
} else {
out.public_key = std::string(*(char**)(service_addr + 0x7B8),
*(int64_t*)(service_addr + 0x7B8 + 0x10));
}
if (*(int64_t*)(service_addr + 0x7D8) == 0 ||
*(int64_t*)(service_addr + 0x7D8 + 0x10) == 0) {
out.private_key = std::string();
} else {
out.private_key = std::string(*(char**)(service_addr + 0x7D8),
*(int64_t*)(service_addr + 0x7D8 + 0x10));
}
if (*(int64_t*)(service_addr + 0x6E0) == 0 ||
*(int64_t*)(service_addr + 0x6E8) == 0) {
out.db_key = std::string();
} else {
int64_t byte_addr = *(int64_t*)(service_addr + 0x6E0);
int64_t len = *(int64_t*)(service_addr + 0x6E8);
out.db_key =
base::utils::Bytes2Hex((BYTE*)byte_addr, static_cast<int>(len));
}
uint64_t flag = *(uint64_t*)(service_addr + 0x7F8);
if (flag == 1) {
prototype::WeChatString current_data_path;
GetCurrentDataPath(reinterpret_cast<ULONG_PTR>(&current_data_path));
if (current_data_path.ptr) {
out.current_data_path = base::utils::WstringToUtf8(
std::wstring(current_data_path.ptr, current_data_path.length));
} else {
out.current_data_path = std::string();
}
}
}
prototype::WeChatString data_save_path;
GetCurrentDataPath(reinterpret_cast<ULONG_PTR>(&data_save_path));
if (data_save_path.ptr) {
out.data_save_path = base::utils::WstringToUtf8(
std::wstring(data_save_path.ptr, data_save_path.length));
} else {
out.data_save_path = std::string();
}
success = 1;
return success;
}
int64_t wechat::WeChatService::SendTextMsg(const std::wstring& wxid,
const std::wstring& msg) {
prototype::WeChatString to_user(wxid);
prototype::WeChatString text_msg(msg);
uint64_t send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
uint64_t send_text_msg_addr = base_addr_ + offset::kSendTextMsg;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
char chat_msg[0x460] = {0};
uint64_t temp[3] = {0};
func::__GetSendMessageMgr mgr;
mgr = (func::__GetSendMessageMgr)send_message_mgr_addr;
func::__SendTextMsg send;
send = (func::__SendTextMsg)send_text_msg_addr;
func::__FreeChatMsg free;
free = (func::__FreeChatMsg)free_chat_msg_addr;
mgr();
uint64_t success = send(reinterpret_cast<uint64_t>(&chat_msg),
reinterpret_cast<uint64_t>(&to_user),
reinterpret_cast<uint64_t>(&text_msg),
reinterpret_cast<uint64_t>(&temp), 1, 1, 0, 0);
free(reinterpret_cast<uint64_t>(&chat_msg));
return 0;
}
int64_t wechat::WeChatService::SendImageMsg(const std::wstring& wxid,
const std::wstring& image_path) {
int64_t success = -1;
prototype::WeChatString to_user(wxid);
prototype::WeChatString image_full_path(image_path);
uint64_t send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
uint64_t send_img_addr = base_addr_ + offset::kSendImageMsg;
uint64_t new_chat_msg_addr = base_addr_ + offset::kChatMsgInstanceCounter;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
func::__NewChatMsg new_chat_msg = (func::__NewChatMsg)new_chat_msg_addr;
func::__GetSendMessageMgr mgr =
(func::__GetSendMessageMgr)send_message_mgr_addr;
func::__SendImageMsg send_img = (func::__SendImageMsg)send_img_addr;
func::__FreeChatMsg free = (func::__FreeChatMsg)free_chat_msg_addr;
char chat_msg[0x460] = {0};
char chat_msg_temp[0x460] = {0};
uint64_t p_chat_msg_temp =
new_chat_msg(reinterpret_cast<uint64_t>(&chat_msg_temp));
uint64_t temp1 = 0;
uint64_t temp2 = 0;
uint64_t temp3 = 1;
uint64_t* flag[10] = {};
flag[0] = reinterpret_cast<uint64_t*>(temp3);
flag[8] = &temp1;
flag[9] = &temp2;
flag[1] = reinterpret_cast<uint64_t*>(p_chat_msg_temp);
uint64_t p_chat_msg = new_chat_msg(reinterpret_cast<uint64_t>(&chat_msg));
uint64_t send_mgr = mgr();
success = send_img(send_mgr, p_chat_msg, reinterpret_cast<uint64_t>(&to_user),
reinterpret_cast<uint64_t>(&image_full_path),
reinterpret_cast<uint64_t>(&flag));
free(p_chat_msg);
free(p_chat_msg_temp);
return success;
}
int64_t wechat::WeChatService::SendFileMsg(const std::wstring& wxid,
const std::wstring& file_path) {
int64_t success = -1;
prototype::WeChatString* to_user = (prototype::WeChatString*)HeapAlloc(
GetProcessHeap(), 0, sizeof(prototype::WeChatString));
wchar_t* ptr_wxid =
(wchar_t*)HeapAlloc(GetProcessHeap(), 0, (wxid.length() + 1) * 2);
wmemcpy(ptr_wxid, wxid.c_str(), wxid.length() + 1);
to_user->ptr = ptr_wxid;
to_user->length = static_cast<DWORD>(wxid.length());
to_user->max_length = static_cast<DWORD>(wxid.length());
to_user->c_len = 0;
to_user->c_ptr = 0;
prototype::WeChatString* file_full_path = (prototype::WeChatString*)HeapAlloc(
GetProcessHeap(), 0, sizeof(prototype::WeChatString));
wchar_t* ptr_path =
(wchar_t*)HeapAlloc(GetProcessHeap(), 0, (file_path.length() + 1) * 2);
wmemcpy(ptr_path, file_path.c_str(), file_path.length() + 1);
file_full_path->ptr = ptr_path;
file_full_path->length = static_cast<DWORD>(file_path.length());
file_full_path->max_length = static_cast<DWORD>(file_path.length());
file_full_path->c_len = 0;
file_full_path->c_ptr = 0;
uint64_t get_app_msg_mgr_addr = base_addr_ + offset::kGetAppMsgMgr;
uint64_t send_file_addr = base_addr_ + offset::kSendFileMsg;
uint64_t new_chat_msg_addr = base_addr_ + offset::kChatMsgInstanceCounter;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
func::__NewChatMsg new_chat_msg = (func::__NewChatMsg)new_chat_msg_addr;
func::__GetAppMsgMgr get_app_mgr = (func::__GetAppMsgMgr)get_app_msg_mgr_addr;
func::__SendFile send_file = (func::__SendFile)send_file_addr;
func::__FreeChatMsg free = (func::__FreeChatMsg)free_chat_msg_addr;
char* chat_msg = (char*)HeapAlloc(GetProcessHeap(), 0, 0x460);
uint64_t* temp1 =
(uint64_t*)HeapAlloc(GetProcessHeap(), 0, sizeof(uint64_t) * 4);
uint64_t* temp2 =
(uint64_t*)HeapAlloc(GetProcessHeap(), 0, sizeof(uint64_t) * 4);
uint64_t* temp3 =
(uint64_t*)HeapAlloc(GetProcessHeap(), 0, sizeof(uint64_t) * 4);
ZeroMemory(temp1, sizeof(uint64_t) * 4);
ZeroMemory(temp2, sizeof(uint64_t) * 4);
ZeroMemory(temp3, sizeof(uint64_t) * 4);
uint64_t app_mgr = get_app_mgr();
success = send_file(app_mgr, reinterpret_cast<uint64_t>(chat_msg),
reinterpret_cast<uint64_t>(to_user),
reinterpret_cast<uint64_t>(file_full_path), 1,
reinterpret_cast<uint64_t>(temp1), 0,
reinterpret_cast<uint64_t>(temp2), 0,
reinterpret_cast<uint64_t>(temp3), 0, 0xC);
free(reinterpret_cast<uint64_t>(chat_msg));
HeapFree(GetProcessHeap(), 0, to_user);
HeapFree(GetProcessHeap(), 0, file_full_path);
HeapFree(GetProcessHeap(), 0, temp1);
HeapFree(GetProcessHeap(), 0, temp2);
HeapFree(GetProcessHeap(), 0, temp3);
return success;
}
int64_t wechat::WeChatService::GetContacts(std::vector<ContactInner>& vec) {
int64_t success = -1;
int64_t base_addr = wxutils::GetWeChatWinBase();
uint64_t get_contact_mgr_addr = base_addr + offset::kGetContactMgr;
uint64_t get_contact_list_addr = base_addr + offset::kGetContactList;
func::__GetContactMgr get_contact_mgr =
(func::__GetContactMgr)get_contact_mgr_addr;
func::__GetContactList get_contact_list =
(func::__GetContactList)get_contact_list_addr;
uint64_t mgr = get_contact_mgr();
uint64_t contact_vec[3] = {0, 0, 0};
success = get_contact_list(mgr, reinterpret_cast<uint64_t>(&contact_vec));
uint64_t start = contact_vec[0];
uint64_t end = contact_vec[2];
while (start < end) {
wechat::ContactInner temp;
temp.wxid = wxutils::ReadWstringThenConvert(start + 0x10);
temp.custom_account = wxutils::ReadWstringThenConvert(start + 0x30);
temp.encrypt_name = wxutils::ReadWstringThenConvert(start + 0x50);
temp.remark = wxutils::ReadWstringThenConvert(start + 0x80);
temp.remark_pinyin = wxutils::ReadWstringThenConvert(start + 0x148);
temp.remark_pinyin_all = wxutils::ReadWstringThenConvert(start + 0x168);
temp.label_ids = wxutils::ReadWstringThenConvert(start + 0xc0);
temp.nickname = wxutils::ReadWstringThenConvert(start + 0xA0);
temp.pinyin = wxutils::ReadWstringThenConvert(start + 0x108);
temp.pinyin_all = wxutils::ReadWstringThenConvert(start + 0x128);
temp.verify_flag = *(int32_t*)(start + 0x70);
temp.type = *(int32_t*)(start + 0x74);
temp.reserved1 = *(int32_t*)(start + 0x1F0);
temp.reserved2 = *(int32_t*)(start + 0x1F4);
vec.push_back(temp);
start += 0x6A8;
}
return success;
}
int64_t wechat::WeChatService::GetChatRoomDetailInfo(
const std::wstring& room_id, ChatRoomInfoInner& room_info) {
int64_t success = -1;
prototype::WeChatString chat_room_id(room_id);
int64_t base_addr = wxutils::GetWeChatWinBase();
uint64_t get_chat_room_mgr_addr = base_addr + offset::kChatRoomMgr;
uint64_t get_chat_room_detail_addr = base_addr + offset::kGetChatRoomDetailInfo;
uint64_t create_chat_room_info_addr = base_addr + offset::kNewChatRoomInfo;
uint64_t free_chat_room_info_addr = base_addr + offset::kFreeChatRoomInfo;
func::__GetChatRoomMgr get_chat_room_mgr = (func::__GetChatRoomMgr)get_chat_room_mgr_addr;
func::__NewChatRoomInfo new_chat_room_info = (func::__NewChatRoomInfo)create_chat_room_info_addr;
func::__FreeChatRoomInfo free_chat_room_info = (func::__FreeChatRoomInfo)free_chat_room_info_addr;
func::__GetChatRoomDetailInfo get_chat_room_detail = (func::__GetChatRoomDetailInfo)get_chat_room_detail_addr;
char chat_room_info[0x144] = {0};
uint64_t new_room_info = new_chat_room_info(reinterpret_cast<uint64_t>(&chat_room_info));
uint64_t mgr = get_chat_room_mgr();
success = get_chat_room_detail(mgr,reinterpret_cast<uint64_t>(&chat_room_id),new_room_info,1);
room_info.chat_room_id = wxutils::ReadWstringThenConvert(new_room_info + 0x8);
room_info.notice = wxutils::ReadWstringThenConvert(new_room_info + 0x28);
room_info.admin = wxutils::ReadWstringThenConvert(new_room_info + 0x48);
room_info.xml = wxutils::ReadWstringThenConvert(new_room_info + 0x78);
free_chat_room_info(new_room_info);
return success;
}
int64_t wechat::WeChatService::AddMemberToChatRoom(
const std::wstring& room_id, const std::vector<std::wstring>& members) {
int64_t success = -1;
uint64_t get_chat_room_mgr_addr = base_addr_ + offset::kChatRoomMgr;
uint64_t add_members_addr = base_addr_ + offset::kDoAddMemberToChatRoom;
func::__GetChatRoomMgr get_chat_room_mgr =
(func::__GetChatRoomMgr)get_chat_room_mgr_addr;
func::__DoAddMemberToChatRoom add_members =
(func::__DoAddMemberToChatRoom)add_members_addr;
prototype::WeChatString *chat_room_id = (prototype::WeChatString *)HeapAlloc(
GetProcessHeap(), 0, sizeof(prototype::WeChatString));
wchar_t *p_chat_room_id =
(wchar_t *)HeapAlloc(GetProcessHeap(), 0, (room_id.size() + 1) * 2);
wmemcpy(p_chat_room_id, room_id.c_str(), room_id.size() + 1);
chat_room_id->ptr = p_chat_room_id;
chat_room_id->length = static_cast<int32_t>(room_id.size());
chat_room_id->max_length = static_cast<int32_t>(room_id.size());
chat_room_id->c_len = 0;
chat_room_id->c_ptr = 0;
std::vector<prototype::WeChatString> member_list;
uint64_t temp[2] = {0};
wechat::VectorInner *list = (wechat::VectorInner *)&member_list;
int64_t members_ptr = (int64_t)&list->start;
for (int i = 0; i < members.size(); i++) {
prototype::WeChatString member(members[i]);
member_list.push_back(member);
}
uint64_t mgr = get_chat_room_mgr();
success =
add_members(mgr, members_ptr, reinterpret_cast<uint64_t>(chat_room_id),
reinterpret_cast<uint64_t>(&temp));
return success;
}
int64_t wechat::WeChatService::ModChatRoomMemberNickName(
const std::wstring& room_id, const std::wstring& wxid,
const std::wstring& nickname) {
return 0;
}
int64_t wechat::WeChatService::DelMemberFromChatRoom(
const std::wstring& room_id, const std::vector<std::wstring>& members) {
int64_t success = -1;
uint64_t get_chat_room_mgr_addr = base_addr_ + offset::kChatRoomMgr;
uint64_t del_members_addr = base_addr_ + offset::kDelMemberFromChatRoom;
func::__GetChatRoomMgr get_chat_room_mgr =
(func::__GetChatRoomMgr)get_chat_room_mgr_addr;
func::__DoDelMemberFromChatRoom del_members =
(func::__DoDelMemberFromChatRoom)del_members_addr;
prototype::WeChatString* chat_room_id = BuildWechatString(room_id);
std::vector<prototype::WeChatString> member_list;
uint64_t temp[2] = {0};
wechat::VectorInner* list = (wechat::VectorInner*)&member_list;
int64_t members_ptr = (int64_t)&list->start;
for (int i = 0; i < members.size(); i++) {
prototype::WeChatString member(members[i]);
member_list.push_back(member);
}
uint64_t mgr = get_chat_room_mgr();
success =
del_members(mgr, members_ptr, reinterpret_cast<uint64_t>(chat_room_id));
return success;
}
int64_t wechat::WeChatService::GetMemberFromChatRoom(
const std::wstring& room_id, ChatRoomMemberInner& member) {
int64_t success = -1;
uint64_t get_chat_room_mgr_addr = base_addr_ + offset::kChatRoomMgr;
uint64_t get_members_addr = base_addr_ + offset::kGetMemberFromChatRoom;
uint64_t new_chat_room_addr = base_addr_ + offset::kNewChatRoom;
uint64_t free_chat_room_addr = base_addr_ + offset::kFreeChatRoom;
func::__GetChatRoomMgr get_chat_room_mgr =
(func::__GetChatRoomMgr)get_chat_room_mgr_addr;
func::__GetMemberFromChatRoom get_members =
(func::__GetMemberFromChatRoom)get_members_addr;
func::__NewChatRoom new_chat_room = (func::__NewChatRoom)new_chat_room_addr;
func::__FreeChatRoom free_chat_room =
(func::__FreeChatRoom)free_chat_room_addr;
prototype::WeChatString chat_room_id(room_id);
char chat_room_info[0x308] = {0};
uint64_t addr = new_chat_room(reinterpret_cast<uint64_t>(&chat_room_info));
uint64_t mgr = get_chat_room_mgr();
success = get_members(mgr, reinterpret_cast<uint64_t>(&chat_room_id), addr);
member.chat_room_id = wxutils::ReadWstringThenConvert(addr + 0x10);
member.admin = wxutils::ReadWstringThenConvert(addr + 0x78);
member.member_nickname = wxutils::ReadWstringThenConvert(addr + 0x50);
member.admin_nickname = wxutils::ReadWstringThenConvert(addr + 0xA0);
member.member = wxutils::ReadWeChatStr(addr + 0x30);
free_chat_room(addr);
return success;
}
int64_t wechat::WeChatService::SetTopMsg(uint64_t msg_id) { return 0; }
int64_t wechat::WeChatService::RemoveTopMsg(const std::wstring& room_id,
ULONG64 msg_id) {
return 0;
}
int64_t wechat::WeChatService::InviteMemberToChatRoom(
const std::wstring& room_id, const std::vector<std::wstring>& wxids) {
return 0;
}
int64_t wechat::WeChatService::CreateChatRoom(
const std::vector<std::wstring>& wxids) {
return 0;
}
int64_t wechat::WeChatService::QuitChatRoom(const std::wstring& room_id) {
return 0;
}
int64_t wechat::WeChatService::ForwardMsg(uint64_t msg_id,
const std::wstring& wxid) {
int64_t success = -1;
uint64_t forward_addr = base_addr_ + offset::kForwardMsg;
func::__ForwardMsg forward_msg = (func::__ForwardMsg)forward_addr;
int64_t index = 0;
int64_t local_id =
wechat::WeChatDb::GetInstance().GetLocalIdByMsgId(msg_id, index);
if (local_id <= 0 || index >> 32 == 0) {
success = -2;
return success;
}
LARGE_INTEGER l;
l.HighPart = index >> 32;
l.LowPart = (DWORD)local_id;
prototype::WeChatString* recv = BuildWechatString(wxid);
success = forward_msg(reinterpret_cast<uint64_t>(recv), l.QuadPart, 0x4, 0x0);
return success;
}
int64_t wechat::WeChatService::GetSNSFirstPage() { return 0; }
int64_t wechat::WeChatService::GetSNSNextPage(uint64_t sns_id) { return 0; }
int64_t wechat::WeChatService::AddFavFromMsg(uint64_t msg_id) { return 0; }
int64_t wechat::WeChatService::AddFavFromImage(const std::wstring& wxid,
const std::wstring& image_path) {
return 0;
}
int64_t wechat::WeChatService::SendAtText(
const std::wstring& room_id, const std::vector<std::wstring>& wxids,
const std::wstring& msg) {
int64_t success = -1;
std::vector<prototype::WeChatString> wxid_list;
wechat::VectorInner* list = (wechat::VectorInner*)&wxid_list;
std::wstring at_msg = L"";
int number = 0;
for (unsigned int i = 0; i < wxids.size(); i++) {
std::wstring nickname;
std::wstring at_all = L"notify@all";
if (at_all.compare(wxids[i]) == 0) {
nickname = L"\u6240\u6709\u4eba";
} else {
// nickname = GetContactOrChatRoomNickname(wxids[i]);
}
if (nickname.length() == 0) {
continue;
}
prototype::WeChatString id(wxids[i]);
wxid_list.push_back(id);
at_msg = at_msg + L"@" + nickname + L" ";
number++;
}
if (number < 1) {
success = -2;
return success;
}
at_msg += msg;
INT64 head = (INT64)&list->start;
prototype::WeChatString to_user(room_id);
prototype::WeChatString text_msg(at_msg);
uint64_t send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
uint64_t send_text_msg_addr = base_addr_ + offset::kSendTextMsg;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
char chat_msg[0x460] = {0};
func::__GetSendMessageMgr mgr =
(func::__GetSendMessageMgr)send_message_mgr_addr;
func::__SendTextMsg send = (func::__SendTextMsg)send_text_msg_addr;
func::__FreeChatMsg free = (func::__FreeChatMsg)free_chat_msg_addr;
mgr();
success = send(reinterpret_cast<uint64_t>(&chat_msg),
reinterpret_cast<uint64_t>(&to_user),
reinterpret_cast<uint64_t>(&text_msg), head, 1, 1, 0, 0);
free(reinterpret_cast<uint64_t>(&chat_msg));
return 0;
}
std::wstring wechat::WeChatService::GetContactOrChatRoomNickname(
const std::wstring& wxid) {
int64_t success = -1;
prototype::WeChatString to_user(wxid);
uint64_t get_contact_mgr_addr = base_addr_ + offset::kGetContactMgr;
uint64_t new_contact_addr = base_addr_ + offset::kNewContact;
uint64_t get_contact_addr = base_addr_ + offset::kGetContact;
uint64_t free_contact_addr = base_addr_ + offset::kFreeContact;
func::__GetContactMgr get_contact_mgr =
(func::__GetContactMgr)get_contact_mgr_addr;
func::__GetContact get_contact = (func::__GetContact)get_contact_addr;
func::__NewContact new_contact = (func::__NewContact)new_contact_addr;
func::__FreeContact free_contact = (func::__FreeContact)free_contact_addr;
char buff[0x6A9] = {0};
uint64_t contact = new_contact(reinterpret_cast<uint64_t>(&buff));
uint64_t mgr = get_contact_mgr();
success = get_contact(mgr, reinterpret_cast<uint64_t>(&to_user), contact);
if (success == 1) {
std::wstring nickname = wxutils::ReadWstring(contact + 0xA0);
free_contact(contact);
return nickname;
} else {
free_contact(contact);
return L"";
}
}
int64_t wechat::WeChatService::GetContactByWxid(const std::wstring& wxid,
ContactProfileInner& profile) {
return 0;
}
int64_t wechat::WeChatService::DoDownloadTask(uint64_t msg_id) { return 0; }
int64_t wechat::WeChatService::ForwardPublicMsg(const std::wstring& wxid,
const std::wstring& title,
const std::wstring& url,
const std::wstring& thumb_url,
const std::wstring& sender_id,
const std::wstring& sender_name,
const std::wstring& digest) {
return 0;
}
int64_t wechat::WeChatService::ForwardPublicMsgByMsgId(const std::wstring& wxid,
uint64_t msg_id) {
return 0;
}
int64_t wechat::WeChatService::DecodeImage(const std::wstring& file_path,
const std::wstring& save_dir) {
return 0;
}
int64_t wechat::WeChatService::GetVoiceByDB(ULONG64 msg_id,
const std::wstring& dir) {
return 0;
}
int64_t wechat::WeChatService::SendCustomEmotion(const std::wstring& file_path,
const std::wstring& wxid) {
return 0;
}
int64_t wechat::WeChatService::SendApplet(
const std::wstring& recv_wxid, const std::wstring& waid_suff,
const std::wstring& waid_w, const std::string& waid_s,
const std::string& wa_wxid, const std::string& json_param,
const std::string& head_image, const std::string& big_image,
const std::string& index_page) {
return 0;
}
int64_t wechat::WeChatService::SendPatMsg(const std::wstring& room_id,
const std::wstring& wxid) {
int64_t success = -1;
uint64_t send_pat_msg_addr = base_addr_ + offset::kSendPatMsg;
func::__SendPatMsg send_pat_msg = (func::__SendPatMsg)send_pat_msg_addr;
prototype::WeChatString chat_room(room_id);
prototype::WeChatString target(wxid);
success = send_pat_msg(reinterpret_cast<uint64_t>(&chat_room),
reinterpret_cast<uint64_t>(&target));
return success;
}
int64_t wechat::WeChatService::DoOCRTask(const std::wstring& img_path,
std::string& result) {
return 0;
}
int64_t wechat::WeChatService::LockWeChat() {
int64_t success = -1;
uint64_t lock_mgr_addr = base_addr_ + offset::kGetLockWechatMgr;
uint64_t request_lock_addr = base_addr_ + offset::kRequestLockWechat;
func::__GetLockWechatMgr get_lock_mgr =
(func::__GetLockWechatMgr)lock_mgr_addr;
func::__RequestLockWechat request_lock =
(func::__RequestLockWechat)request_lock_addr;
uint64_t mgr = get_lock_mgr();
success = request_lock(mgr);
return success;
}
int64_t wechat::WeChatService::UnlockWeChat() {
int64_t success = -1;
uint64_t lock_mgr_addr = base_addr_ + offset::kGetLockWechatMgr;
uint64_t request_unlock_addr = base_addr_ + offset::kRequestUnLockWechat;
func::__GetLockWechatMgr get_lock_mgr =
(func::__GetLockWechatMgr)lock_mgr_addr;
func::__RequestUnLockWechat request_unlock =
(func::__RequestUnLockWechat)request_unlock_addr;
uint64_t mgr = get_lock_mgr();
success = request_unlock(mgr);
return success;
}
int64_t wechat::WeChatService::EnterWeChat() {
int64_t success = -1;
int64_t base_addr = wxutils::GetWeChatWinBase();
uint64_t click_cb_addr = base_addr + offset::kOnLoginBtnClick;
func::__OnLoginBtnClick cb = (func::__OnLoginBtnClick)click_cb_addr;
auto vec =
base::memory::ScanAndMatchValue(base_addr + 0x34e0c18, 0x1000, 0x8);
for (int i = 0; i < vec.size(); i++) {
int64_t ptr = vec.at(i);
if (*(int64_t*)ptr == base_addr + 0x34e0c18) {
int64_t login_wnd = ptr;
success = cb(ptr);
break;
}
}
return success;
}
int64_t wechat::WeChatService::SendMultiAtText(
const std::wstring& room_id,
const std::vector<std::pair<std::wstring, std::wstring>>& at) {
int64_t success = -1;
std::vector<prototype::WeChatString> wxid_list;
wechat::VectorInner* list = (wechat::VectorInner*)&wxid_list;
std::wstring at_msg = L"";
int number = 0;
for (unsigned int i = 0; i < at.size(); i++) {
std::wstring nickname;
std::wstring at_all = L"notify@all";
if (at_all.compare(at[i].first) == 0) {
nickname = L"\u6240\u6709\u4eba";
} else {
// nickname = GetContactOrChatRoomNickname(at[i].first);
nickname = L"";
}
if (nickname.length() == 0) {
continue;
}
prototype::WeChatString id(at[i].first);
wxid_list.push_back(id);
at_msg = at_msg + L"@" + nickname + L" " + at[i].second + L" ";
number++;
}
if (number < 1) {
success = -2;
return success;
}
int64_t head = (int64_t)&list->start;
prototype::WeChatString to_user(room_id);
prototype::WeChatString text_msg(at_msg);
uint64_t send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
uint64_t send_text_msg_addr = base_addr_ + offset::kSendTextMsg;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
char chat_msg[0x460] = {0};
func::__GetSendMessageMgr mgr =
(func::__GetSendMessageMgr)send_message_mgr_addr;
func::__SendTextMsg send = (func::__SendTextMsg)send_text_msg_addr;
func::__FreeChatMsg free = (func::__FreeChatMsg)free_chat_msg_addr;
mgr();
success = send(reinterpret_cast<uint64_t>(&chat_msg),
reinterpret_cast<uint64_t>(&to_user),
reinterpret_cast<uint64_t>(&text_msg), head, 1, 1, 0, 0);
free(reinterpret_cast<uint64_t>(&chat_msg));
return success;
}
std::string wechat::WeChatService::GetLoginUrl() {
uint64_t login_mgr_addr = base_addr_ + offset::kGetQRCodeLoginMgr;
func::__GetQRCodeLoginMgr get = (func::__GetQRCodeLoginMgr)login_mgr_addr;
uint64_t addr = get();
std::string login_url = wxutils::ReadWeChatStr(addr + 0x68);
return "http://weixin.qq.com/x/" + login_url;
}
void wechat::WeChatService::SetBaseAddr(uint64_t addr) {}
void wechat::WeChatService::SetJsApiAddr(uint64_t addr) {}
int64_t wechat::WeChatService::TranslateVoice(uint64_t msg_id) {
int64_t success = -1;
uint64_t get_by_local_id_addr = base_addr_ + offset::kGetMgrByPrefixLocalId;
func::__GetMgrByPrefixLocalId get_by_local_id =
(func::__GetMgrByPrefixLocalId)get_by_local_id_addr;
uint64_t get_chat_mgr_addr = base_addr_ + offset::kGetChatMgr;
func::__GetChatMgr get_chat_mgr = (func::__GetChatMgr)get_chat_mgr_addr;
uint64_t free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
func::__FreeChatMsg free_chat_msg = (func::__FreeChatMsg)free_chat_msg_addr;
uint64_t new_chat_msg_addr = base_addr_ + offset::kChatMsgInstanceCounter;
func::__NewChatMsg new_chat_msg = (func::__NewChatMsg)new_chat_msg_addr;
uint64_t update_addr = base_addr_ + offset::kUpdateMsg;
func::__UpdateMsg update = (func::__UpdateMsg)update_addr;
uint64_t get_voice_mgr_addr = base_addr_ + offset::kGetVoiceMgr;
func::__GetVoiceMgr get_voice_mgr = (func::__GetVoiceMgr)get_voice_mgr_addr;
uint64_t to_msg_addr = base_addr_ + offset::kChatMsg2NetSceneSendMsg;
func::__ChatMsg2NetSceneSendMsg to_msg =
(func::__ChatMsg2NetSceneSendMsg)to_msg_addr;
uint64_t trans_addr = base_addr_ + offset::kTranslateVoice;
func::__TranslateVoice translate_voice = (func::__TranslateVoice)trans_addr;
char temp_msg[0x460] = {0};
char* chat_msg = base::utils::WxHeapAlloc<char>(0x460);
int64_t index = 0;
int64_t local_id =
wechat::WeChatDb::GetInstance().GetLocalIdByMsgId(msg_id, index);
if (local_id <= 0 || index >> 32 == 0) {
success = -2;
return success;
}
LARGE_INTEGER l;
l.HighPart = index >> 32;
l.LowPart = (DWORD)local_id;
uint64_t p_chat_msg = new_chat_msg(reinterpret_cast<uint64_t>(chat_msg));
get_chat_mgr();
get_by_local_id(l.QuadPart, p_chat_msg);
uint64_t mgr = get_chat_mgr();
update(mgr, p_chat_msg, 0);
uint64_t voice_mgr = get_voice_mgr();
uint64_t msg = to_msg(reinterpret_cast<uint64_t>(&temp_msg), p_chat_msg);
success = translate_voice(voice_mgr, msg, 0);
return success;
}
std::string wechat::WeChatService::GetTranslateVoiceText(uint64_t msg_id) {
std::string content =
wechat::WeChatDb::GetInstance().GetChatMsgStrContentByMsgId(msg_id);
if (content.empty()) {
return {};
}
tinyxml2::XMLDocument doc;
if (doc.Parse(content.c_str(), content.size()) != 0) {
SPDLOG_INFO("tinyxml2 parse error");
return {};
}
tinyxml2::XMLElement* msg = doc.FirstChildElement("msg");
if (msg != nullptr) {
tinyxml2::XMLElement* voicetrans = msg->FirstChildElement("voicetrans");
if (voicetrans != nullptr) {
const char* value = voicetrans->Attribute("transtext", nullptr);
return value;
}
}
return "";
}
int64_t wechat::WeChatService::OpenUrlByWeChatBrowser(const std::wstring& url,
int flag) {
int64_t success = -1;
uint64_t config_addr = base_addr_ + offset::kNewWebViewPageConfig;
func::__NewWebViewPageConfig config =
(func::__NewWebViewPageConfig)config_addr;
uint64_t free_config_addr = base_addr_ + offset::kFreeWebViewPageConfig;
func::__FreeWebViewPageConfig free_config =
(func::__FreeWebViewPageConfig)free_config_addr;
uint64_t web_view_mgr_addr = base_addr_ + offset::kGetWebViewMgr;
func::__GetWebViewMgr web_view_mgr = (func::__GetWebViewMgr)web_view_mgr_addr;
uint64_t show_addr = base_addr_ + offset::kShowWebView;
func::__ShowWebView show_web_view = (func::__ShowWebView)show_addr;
uint64_t set_url_addr = base_addr_ + offset::kSetUrl;
func::__SetUrl set_url = (func::__SetUrl)set_url_addr;
int a = flag >> 4;
int b = flag & 0x1;
int c = flag & 0x2;
int d = flag & 0x4;
int e = flag & 0x8;
char* web_config = (char*)HeapAlloc(GetProcessHeap(), 0, 0xA20);
uint64_t ptr = config(reinterpret_cast<uint64_t>(web_config));
set_url(ptr + 0x868, reinterpret_cast<uint64_t>(url.c_str()), url.size());
web_view_mgr();
success = show_web_view(ptr, a, b, c, d, e);
free_config(ptr);
return success;
}

View File

@ -0,0 +1,99 @@
#ifndef WXHELPER_WECHAT_SERVICE_H_
#define WXHELPER_WECHAT_SERVICE_H_
#include <windows.h>
#include <string>
#include <vector>
#include "singleton.h"
#include "wechat_interface.h"
namespace wechat {
class WeChatService : public base::Singleton<WeChatService> {
friend class base::Singleton<WeChatService>;
~WeChatService();
public:
void Init();
void SetBaseAddr(uint64_t addr);
void SetJsApiAddr(uint64_t addr);
int64_t CheckLogin();
int64_t GetSelfInfo(SelfInfoInner& out);
int64_t SendTextMsg(const std::wstring& wxid, const std::wstring& msg);
int64_t SendImageMsg(const std::wstring& wxid,
const std::wstring& image_path);
int64_t SendFileMsg(const std::wstring& wxid, const std::wstring& file_path);
int64_t GetContacts(std::vector<ContactInner>& vec);
int64_t GetChatRoomDetailInfo(const std::wstring& room_id,
ChatRoomInfoInner& room_info);
int64_t AddMemberToChatRoom(const std::wstring& room_id,
const std::vector<std::wstring>& members);
int64_t ModChatRoomMemberNickName(const std::wstring& room_id,
const std::wstring& wxid,
const std::wstring& nickname);
int64_t DelMemberFromChatRoom(const std::wstring& room_id,
const std::vector<std::wstring>& members);
int64_t GetMemberFromChatRoom(const std::wstring& room_id,
ChatRoomMemberInner& member);
int64_t SetTopMsg(uint64_t msg_id);
int64_t RemoveTopMsg(const std::wstring& room_id, ULONG64 msg_id);
int64_t InviteMemberToChatRoom(const std::wstring& room_id,
const std::vector<std::wstring>& wxids);
int64_t CreateChatRoom(const std::vector<std::wstring>& wxids);
int64_t QuitChatRoom(const std::wstring& room_id);
int64_t ForwardMsg(uint64_t msg_id, const std::wstring& wxid);
int64_t GetSNSFirstPage();
int64_t GetSNSNextPage(uint64_t sns_id);
int64_t AddFavFromMsg(uint64_t msg_id);
int64_t AddFavFromImage(const std::wstring& wxid,
const std::wstring& image_path);
int64_t SendAtText(const std::wstring& room_id,
const std::vector<std::wstring>& wxids,
const std::wstring& msg);
std::wstring GetContactOrChatRoomNickname(const std::wstring& wxid);
int64_t GetContactByWxid(const std::wstring& wxid,
ContactProfileInner& profile);
int64_t DoDownloadTask(uint64_t msg_id);
int64_t ForwardPublicMsg(const std::wstring& wxid, const std::wstring& title,
const std::wstring& url,
const std::wstring& thumb_url,
const std::wstring& sender_id,
const std::wstring& sender_name,
const std::wstring& digest);
int64_t ForwardPublicMsgByMsgId(const std::wstring& wxid, uint64_t msg_id);
int64_t DecodeImage(const std::wstring& file_path,
const std::wstring& save_dir);
int64_t GetVoiceByDB(ULONG64 msg_id, const std::wstring& dir);
int64_t SendCustomEmotion(const std::wstring& file_path,
const std::wstring& wxid);
int64_t SendApplet(const std::wstring& recv_wxid,
const std::wstring& waid_suff, const std::wstring& waid_w,
const std::string& waid_s, const std::string& wa_wxid,
const std::string& json_param,
const std::string& head_image,
const std::string& big_image,
const std::string& index_page);
int64_t SendPatMsg(const std::wstring& room_id, const std::wstring& wxid);
int64_t DoOCRTask(const std::wstring& img_path, std::string& result);
int64_t LockWeChat();
int64_t UnlockWeChat();
int64_t EnterWeChat();
int64_t SendMultiAtText(
const std::wstring& room_id,
const std::vector<std::pair<std::wstring, std::wstring>>& at);
std::string GetLoginUrl();
int64_t TranslateVoice(uint64_t msg_id);
std::string GetTranslateVoiceText(uint64_t msg_id);
int64_t OpenUrlByWeChatBrowser(const std::wstring& url, int flag);
private:
uint64_t base_addr_;
uint64_t js_api_addr_;
};
} // namespace wechat
#endif

View File

@ -0,0 +1,29 @@
#include <winsock2.h>
#include "wxhelper.h"
#include "config.h"
#include "http_server.h"
#include "thread_pool.h"
#include "utils.h"
#include "wxutils.h"
#include "wechat_db.h"
#include "sync_msg_hook.h"
#include "wechat_service.h"
namespace wxhelper {
void WxHelper::init(HMODULE module) {
Config::GetInstance().init();
if (Config::GetInstance().GetHideDll()) {
base::utils::HideModule(module);
}
wechat::WeChatDb::GetInstance().Init();
wechat::WeChatService::GetInstance().Init();
SyncMsgHook::GetInstance().Init();
http::HttpServer::GetInstance().init(
Config::GetInstance().GetHttpServerHost(),
Config::GetInstance().GetHttpServerPort());
http::HttpServer::GetInstance().Start();
base::ThreadPool::GetInstance().Create(2, 8);
}
void WxHelper::finally() { http::HttpServer::GetInstance().Stop(); }
} // namespace wxhelper

View File

@ -0,0 +1,14 @@

#ifndef WXHELPER_WXHELPER_H_
#define WXHELPER_WXHELPER_H_
#include <Windows.h>
#include "singleton.h"
namespace wxhelper {
class WxHelper : public base::Singleton<WxHelper>{
public:
void init(HMODULE module);
void finally();
};
}
#endif

110
app/wxhelper/src/wxutils.cc Normal file
View File

@ -0,0 +1,110 @@
#include "wxutils.h"
#include "utils.h"
#define BUFSIZE 1024
#define JPEG0 0xFF
#define JPEG1 0xD8
#define JPEG2 0xFF
#define PNG0 0x89
#define PNG1 0x50
#define PNG2 0x4E
#define BMP0 0x42
#define BMP1 0x4D
#define GIF0 0x47
#define GIF1 0x49
#define GIF2 0x46
namespace wxhelper {
namespace wxutils {
#ifdef _WIN64
int64_t GetWeChatWinBase() {
return (int64_t)GetModuleHandleA("WeChatWin.dll");
}
#else
int32_t GetWeChatWinBase() {
return (int32_t)GetModuleHandleA("WeChatWin.dll");
}
#endif
std::string ReadSKBuiltinString(INT64 addr) {
INT64 inner_string = *(INT64 *)(addr + 0x8);
if (inner_string == 0) {
return std::string();
}
return ReadWeChatStr(inner_string);
}
std::string ReadSKBuiltinBuffer(INT64 addr) {
INT64 len = *(INT64 *)(addr + 0x10);
if (len == 0) {
return std::string();
}
INT64 inner_string = *(INT64 *)(addr + 0x8);
if (inner_string == 0) {
return std::string();
}
return ReadWeChatStr(inner_string);
}
std::string ReadWeChatStr(INT64 addr) {
INT64 len = *(INT64 *)(addr + 0x10);
if (len == 0) {
return std::string();
}
INT64 max_len = *(INT64 *)(addr + 0x18);
if ((max_len | 0xF) == 0xF) {
return std::string((char *)addr, len);
}
char *char_from_user = *(char **)(addr);
return std::string(char_from_user, len);
}
std::string ImageXor(std::string buf) {
const char *origin = buf.c_str();
short key = 0;
if ((*origin ^ JPEG0) == (*(origin + 1) ^ JPEG1)) {
key = *origin ^ JPEG0;
} else if ((*origin ^ PNG1) == (*(origin + 1) ^ PNG2)) {
key = *origin ^ PNG1;
} else if ((*origin ^ GIF0) == (*(origin + 1) ^ GIF1)) {
key = *origin ^ GIF0;
} else if ((*origin ^ BMP0) == (*(origin + 1) ^ BMP1)) {
key = *origin ^ BMP0;
} else {
key = -1;
}
if (key > 0) {
char *img_buf = new char[buf.size()];
for (unsigned int i = 0; i < buf.size(); i++) {
img_buf[i] = *(origin + i) ^ key;
}
std::string str(img_buf);
delete[] img_buf;
img_buf = NULL;
return str;
}
return std::string();
}
std::wstring ReadWstring(INT64 addr) {
DWORD len = *(DWORD *)(addr + 0x8);
if (len == 0) {
return std::wstring();
}
wchar_t *str = *(wchar_t **)(addr);
if (str == NULL) {
return std::wstring();
}
return std::wstring(str, len);
}
std::string ReadWstringThenConvert(INT64 addr) {
std::wstring wstr = ReadWstring(addr);
return base::utils::WstringToUtf8(wstr);
}
int DecodeImage(const wchar_t *file_path, const wchar_t *save_dir) {
return -1;
}
} // namespace wxutils
} // namespace wxhelper

View File

@ -0,0 +1,24 @@
#ifndef WXHELPER_WXUTILS_H_
#define WXHELPER_WXUTILS_H_
#include <windows.h>
#include <string>
namespace wxhelper {
namespace wxutils {
#ifdef _WIN64
int64_t GetWeChatWinBase();
#else
int32_t GetWeChatWinBase();
#endif
std::string ReadSKBuiltinString(INT64 addr);
std::string ReadSKBuiltinBuffer(INT64 addr);
std::string ReadWeChatStr(INT64 addr);
std::string ImageXor(std::string buf);
std::wstring ReadWstring(INT64 addr);
std::string ReadWstringThenConvert(INT64 addr);
int DecodeImage(const wchar_t* file_path, const wchar_t* save_dir);
} // namespace wxutils
} // namespace wxhelper
#endif

108
cmake/detours.cmake Normal file
View File

@ -0,0 +1,108 @@
cmake_minimum_required(VERSION 3.10...3.27)
#
project(detours VERSION 4.0.1 LANGUAGES C CXX)
MACRO(GET_WIN32_WINNT version)
IF(WIN32 AND CMAKE_SYSTEM_VERSION)
SET(ver ${CMAKE_SYSTEM_VERSION})
STRING(REGEX MATCH "^([0-9]+).([0-9])" ver ${ver})
STRING(REGEX MATCH "^([0-9]+)" verMajor ${ver})
# Check for Windows 10, b/c we'll need to convert to hex 'A'.
IF("${verMajor}" MATCHES "10")
SET(verMajor "A")
STRING(REGEX REPLACE "^([0-9]+)" ${verMajor} ver ${ver})
ENDIF("${verMajor}" MATCHES "10")
# Remove all remaining '.' characters.
STRING(REPLACE "." "" ver ${ver})
# Prepend each digit with a zero.
STRING(REGEX REPLACE "([0-9A-Z])" "0\\1" ver ${ver})
SET(${version} "0x${ver}")
ENDIF()
ENDMACRO()
# DEBUG
set(DETOURS_CONFIG ${CMAKE_BUILD_TYPE})
if("${DETOURS_CONFIG}" STREQUAL "Debug")
set(DETOURS_DEBUG 1)
else()
set(DETOURS_DEBUG 0)
endif()
####################################################
#
set(CMAKE_CXX_FLAGS "/nologo /W4 /WX /we4777 /we4800 /Zi /MT /Gy /Gm- /Zl /Od /DDETOUR_DEBUG=${DETOURS_DEBUG}")
if(WIN32)
IF(MSVC_VERSION GREATER_EQUAL 1700)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D DETOURS_CL_17_OR_NEWER")
ENDIF()
GET_WIN32_WINNT(ver)
message(STATUS "Windows OS Version: ${ver}")
if(ver EQUAL 0x0700)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _USING_V110_SDK71_ /D DETOURS_WIN_7")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _WIN32_WINNT=${ver}")
else()
message(FATAL_ERROR "Only Win32 platforms are supported.")
endif()
if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i386")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _X86_ ")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i686")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _AMD64_ ")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "IA64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _IA64_ ")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "x86")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _X86_ ")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "x86_64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _AMD64_ ")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "AMD64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _AMD64_ ")
else()
message("Unknown architecture (x86, amd64, ia64, arm, arm64)")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D DETOURS_VERSION=0x4c0c1 /D WIN32_LEAN_AND_MEAN")
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D _CRT_SECURE_NO_WARNINGS /EHsc")
else()
# TODO: Shall we support gcc with MinGW, Cygwin or Clang based building system on Windows?
endif()
if(ENABLE_VERBOSELOG)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D ENABLE_VERBOSELOG")
endif()
#
set(SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/detours.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/modules.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disasm.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/image.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/creatwth.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disolx86.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disolx64.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disolia64.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disolarm.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/disolarm64.cpp
)
#
add_library(detours ${SOURCES})
target_include_directories(detours INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/src)

View File

@ -132,7 +132,7 @@ data 接口返回的数据
"dataSavePath": "C:\\wechatDir\\WeChat Files\\",
"dbKey": "965715e30e474da09250cb5aa047e3940ffa1c8f767c4263b132bb512933db49",
"headImage": "https://wx.qlogo.cn/mmhead/ver_1/MiblV0loY0GILewQ4u2121",
"mobile": "13949175447",
"mobile": "13913913913",
"name": "xxx",
"province": "Henan",
"signature": "xxx",

0
doc/3.9.7.25.md Normal file
View File

462
doc/3.9.7.29.md Normal file
View File

@ -0,0 +1,462 @@
## 3.9.7.29版本http接口文档文档仅供参考。
### 简单说明:
所有接口只支持post方法。
全部使用json格式。
格式: http://host:port/api/xxxx
host: 绑定的host
port: 监听的端口
xxxx: 对应的功能路径
返回结构的json格式
``` javascript
{
"code": 1,
"data": {},
"msg": "success"
}
```
code 错误码
msg 成功/错误信息
data 接口返回的数据
接口与3.9.5.81基本无变化优化了httpclient连接。
config.ini 配置文件可以配置http服务端口和隐藏dll
```
Port=19088
HiddenDll=0 //1隐藏 0不隐藏
```
#### 0.检查微信登录**
###### 接口功能
> 检查微信是否登录
###### 接口地址
> [/api/checkLogin](/api/checkLogin)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,1 成功, 0失败|
|result|string|成功提示|
|data|string|响应内容|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{
"code": 1,
"msg": "success",
"data":null
}
```
#### 1.获取登录用户信息**
###### 接口功能
> 获取登录用户信息
###### 接口地址
> [/api/userInfo](/api/userInfo)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,1 成功, 0失败|
|result|string|成功提示|
|data|object|响应内容|
|&#8194;&#8194;account|string|账号|
|&#8194;&#8194;headImage|string|头像|
|&#8194;&#8194;city|string|城市|
|&#8194;&#8194;country|string|国家|
|&#8194;&#8194;currentDataPath|string|当前数据目录,登录的账号目录|
|&#8194;&#8194;dataSavePath|string|微信保存目录|
|&#8194;&#8194;mobile|string|手机|
|&#8194;&#8194;name|string|昵称|
|&#8194;&#8194;province|string|省|
|&#8194;&#8194;wxid|string|wxid|
|&#8194;&#8194;signature|string|个人签名|
|&#8194;&#8194;dbKey|string|数据库的SQLCipher的加密key可以使用该key配合decrypt.py解密数据库
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{
"code": 1,
"data": {
"account": "xxx",
"city": "Zhengzhou",
"country": "CN",
"currentDataPath": "C:\\WeChat Files\\wxid_xxx\\",
"dataSavePath": "C:\\wechatDir\\WeChat Files\\",
"dbKey": "965715e30e474da09250cb5aa047e3940ffa1c8f767c4263b132bb512933db49",
"headImage": "https://wx.qlogo.cn/mmhead/ver_1/MiblV0loY0GILewQ4u2121",
"mobile": "13913913913",
"name": "xxx",
"province": "Henan",
"signature": "xxx",
"wxid": "wxid_22222"
},
"msg": "success"
}
```
#### 2.发送文本消息**
###### 接口功能
> 发送文本消息
###### 接口地址
> [/api/sendTextMsg](/api/sendTextMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|wxid |true |string| 接收人wxid |
|msg|true |string|消息文本内容|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,不为0成功, 0失败|
|msg|string|成功提示|
|data|object|null|
###### 接口示例
入参:
``` javascript
{
"wxid": "filehelper",
"msg": "1112222"
}
```
响应:
``` javascript
{"code":345686720,"msg":"success","data":null}
```
#### 3.hook消息**
###### 接口功能
> hook接收文本消息图片消息群消息.该接口将hook的消息通过tcp回传给本地的端口。
enableHttp=1时使用urltimeout参数配置服务端的接收地址。请求为postContent-Type 为json。
enableHttp=0时使用ipport的tcp服务回传消息。
###### 接口地址
> [/api/hookSyncMsg](/api/hookSyncMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|port |true |string| 本地服务端端口,用来接收消息内容 |
|ip |true |string| 服务端ip地址用来接收消息内容可以是任意ip,即tcp客户端连接的服务端的ip|
|url |true |string| http的请求地址enableHttp=1时不能为空 |
|timeout |true |string| 超时时间单位ms|
|enableHttp |true |number| 0/1 1.启用http 0.不启用http|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|data|object|null|
|msg|string|成功提示|
###### 接口示例
入参:
``` javascript
{
"port": "19099",
"ip":"127.0.0.1",
"url":"http://localhost:8080",
"timeout":"3000",
"enableHttp":"0"
}
```
响应:
``` javascript
{"code":0,"msg":"success","data":null}
```
#### 4.取消hook消息**
###### 接口功能
> 取消hook消息
###### 接口地址
> [/api/unhookSyncMsg](/api/unhookSyncMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|data|object|null|
|msg|string|成功提示|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{"code":0,"msg":"success","data":null}
```
#### 5.好友列表**
###### 接口功能
> 好友列表
###### 接口地址
> [/api/getContactList](/api/getContactList)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|data|object|好友信息|
|&#8194;&#8194;customAccount|string|自定义账号|
|&#8194;&#8194;encryptName|string|昵称|
|&#8194;&#8194;nickname|string|昵称|
|&#8194;&#8194;pinyin|string|简拼|
|&#8194;&#8194;pinyinAll|string|全拼|
|&#8194;&#8194;reserved1|number|未知|
|&#8194;&#8194;reserved2|number|未知|
|&#8194;&#8194;type|number|未知|
|&#8194;&#8194;verifyFlag|number|未知|
|&#8194;&#8194;wxid|string|wxid|
|msg|string|成功提示|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{
"code": 1,
"data": [
{
"customAccount": "",
"encryptName": "v3_020b3826fd03010000000000e04128fddf4d90000000501ea9a3dba12f95f6b60a0536a1adb6b40fc4086288f46c0b89e6c4eb8062bb1661b4b6fbab708dc4f89d543d7ade135b2be74c14b9cfe3accef377b9@stranger",
"nickname": "文件传输助手",
"pinyin": "WJCSZS",
"pinyinAll": "wenjianchuanshuzhushou",
"reserved1": 1,
"reserved2": 1,
"type": 3,
"verifyFlag": 0,
"wxid": "filehelper"
}
].
"msg": "success"
```
#### 6.获取数据库信息**
###### 接口功能
> 获取数据库信息和句柄
###### 接口地址
> [/api/getDBInfo](/api/getDBInfo)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|msg|string|返回信息|
|data|array|好友信息|
|&#8194;&#8194;databaseName|string|数据库名称|
|&#8194;&#8194;handle|number|句柄|
|&#8194;&#8194;tables|array|表信息|
|&#8194;&#8194;&#8194;&#8194;name|string|表名|
|&#8194;&#8194;&#8194;&#8194;rootpage|string|rootpage|
|&#8194;&#8194;&#8194;&#8194;sql|string|ddl语句|
|&#8194;&#8194;&#8194;&#8194;tableName|string|表名|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{
"code": 1,
"data": [
{
"databaseName": "MicroMsg.db",
"handle": 1755003930784,
"tables": [
{
"name": "Contact",
"rootpage": "2",
"sql": "CREATE TABLE Contact(UserName TEXT PRIMARY KEY ,Alias TEXT,EncryptUserName TEXT,DelFlag INTEGER DEFAULT 0,Type INTEGER DEFAULT 0,VerifyFlag INTEGER DEFAULT 0,Reserved1 INTEGER DEFAULT 0,Reserved2 INTEGER DEFAULT 0,Reserved3 TEXT,Reserved4 TEXT,Remark TEXT,NickName TEXT,LabelIDList TEXT,DomainList TEXT,ChatRoomType int,PYInitial TEXT,QuanPin TEXT,RemarkPYInitial TEXT,RemarkQuanPin TEXT,BigHeadImgUrl TEXT,SmallHeadImgUrl TEXT,HeadImgMd5 TEXT,ChatRoomNotify INTEGER DEFAULT 0,Reserved5 INTEGER DEFAULT 0,Reserved6 TEXT,Reserved7 TEXT,ExtraBuf BLOB,Reserved8 INTEGER DEFAULT 0,Reserved9 INTEGER DEFAULT 0,Reserved10 TEXT,Reserved11 TEXT)",
"tableName": "Contact"
}
]
}
],
"msg":"success"
}
```
#### 7.查询数据库**
###### 接口功能
> 查询数据库
###### 接口地址
> [/api/execSql](/api/execSql)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|dbHandle |true |number| |
|sql |true |string| 执行的sql |
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|msg|string|返回信息|
|data|array|sqlite返回的结果|
###### 接口示例
入参:
``` javascript
{
"dbHandle":2006119800400,
"sql":"select * from MSG where localId =301;"
}
```
响应:
``` javascript
{
"code": 1,
"data": [
[
"localId",
"TalkerId",
"MsgSvrID",
"Type",
"SubType",
"IsSender",
"CreateTime",
"Sequence",
"StatusEx",
"FlagEx",
"Status",
"MsgServerSeq",
"MsgSequence",
"StrTalker",
"StrContent",
"DisplayContent",
"Reserved0",
"Reserved1",
"Reserved2",
"Reserved3",
"Reserved4",
"Reserved5",
"Reserved6",
"CompressContent",
"BytesExtra",
"BytesTrans"
],
[
"301",
"1",
"8824834301214701891",
"1",
"0",
"0",
"1685401473",
"1685401473000",
"0",
"0",
"2",
"1",
"795781866",
"wxid_123",
"testtest",
"",
"0",
"2",
"",
"",
"",
"",
"",
"",
"CgQIEBAAGo0BCAcSiAE8bXNnc291cmNlPJPHNpZ25hdHVyZT52MV9wd12bTZyRzwvc2lnbmF0dXJPgoJPHRtcF9ub2RlPgoJCTxwsaXNoZXItaWQ+Jmx0OyFbQ0RBVEFbXV0mZ3Q7PC9wdWJsaXNoZXItaWQ+Cgk8L3RtcF9ub2RlPgo8L21zZ3NvdXJjZT4KGiQIAhIgNDE1MDA0NjRhZTRmMjk2NjhjMzY2ZjFkOTdmMjAwNDg=",
""
]
],
"msg": "success"
}
```

1004
doc/3.9.8.25.md Normal file

File diff suppressed because it is too large Load Diff

341
doc/3.9.9.43.md Normal file
View File

@ -0,0 +1,341 @@
#### 编译构建
环境:
cl.exe目录= c:/cl.exe
ml64.exe目录 =c:/ml64.exe
vcpkg目录 = c:/vcpkg
wxhelper目录 = c:/wxhelper
```
cd wxhelper/app/3rdparty
git clone https://github.com/microsoft/Detours.git
git clone https://github.com/gabime/spdlog.git
git clone https://github.com/nlohmann/json.git
或者使用vcpkg 安装相应库
vcpkg install detours:x64-windows
vcpkg install nlohmann-json:x64-windows
vcpkg install spdlog:x64-windows
cd wxhelper/cmake
copy detours.cmake wxhelper/app/3rdparty/Detours/CMakeLists.txt
cd wxhelper
mkdir build
cd build
cmake -DCMAKE_C_COMPILER=cl.exe \
-DCMAKE_CXX_COMPILER=cl.exe \
-DCMAKE_ASM_MASM_COMPILER=ml64.exe \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_INSTALL_PREFIX=C:/wxhelper/install/x64-debug \
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=C:/vcpkg/scripts/buildsystems/vcpkg.cmake \
-SC:c:/wxhelper \
-BC:c:/wxhelper/build/x64-debug\
-G Ninja
cmake --build ..
```
如果有错误按错误提示修正即可。
## 3.9.9.43版本http接口文档文档仅供参考。
### 简单说明:
所有接口只支持post方法。
全部使用json格式。
格式: http://host:port/api/xxxx
host: 绑定的host
port: 监听的端口
xxxx: 对应的功能路径
返回结构的json格式
``` javascript
{
"code": 1,
"data": {},
"msg": "success"
}
```
code 错误码
msg 成功/错误信息
data 接口返回的数据
### 配置文件
wechat目录下config.ini 配置文件的默认配置
// HiddenDll 0.不隐藏注入dll 1.隐藏dll
// HttpServerPort dll自身提供的http服务的端口
// HttpServerHost dll自身提供的http服务的监听地址
// RecvMessageMode开启消息hook时使用接收消息的方式. tcp | http
// tcp模式下通过tcp连接发送消息,http模式下通过http发送消息
// RecvTcpIp 接收消息绑定的ip
// RecvTcpPorttcp模式下绑定的端口
// RecvHttpUrlhttp模式下推送的接口地址
// RecvHttpTimeout http模式下的超时时间
HiddenDll=0,
HttpServerPort=80,
HttpServerHost=http://0.0.0.0,
RecvMessageMode=tcp,
RecvTcpIp=127.0.0.1,
RecvTcpPort=19099,
RecvHttpUrl=127.0.0.1,
RecvHttpTimeout=3000,
#### 1.hook消息**
###### 接口功能
> hook接收文本消息图片消息群消息.该接口将hook的消息通过tcp回传给本地的端口。
enableHttp=1时使用urltimeout参数配置服务端的接收地址。请求为postContent-Type 为json。
enableHttp=0时使用ipport的tcp服务回传消息。
###### 接口地址
> [/api/hookSyncMsg](/api/hookSyncMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|data|object|null|
|msg|string|成功提示|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{"code":0,"msg":"success","data":null}
```
#### 2.取消hook消息**
###### 接口功能
> 取消hook消息
###### 接口地址
> [/api/unhookSyncMsg](/api/unhookSyncMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|data|object|null|
|msg|string|成功提示|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{"code":0,"msg":"success","data":null}
```
#### 3.获取数据库信息**
###### 接口功能
> 获取数据库信息和句柄
###### 接口地址
> [/api/getDBInfo](/api/getDBInfo)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|msg|string|返回信息|
|data|array|好友信息|
|&#8194;&#8194;databaseName|string|数据库名称|
|&#8194;&#8194;handle|number|句柄|
|&#8194;&#8194;tables|array|表信息|
|&#8194;&#8194;&#8194;&#8194;name|string|表名|
|&#8194;&#8194;&#8194;&#8194;rootpage|string|rootpage|
|&#8194;&#8194;&#8194;&#8194;sql|string|ddl语句|
|&#8194;&#8194;&#8194;&#8194;tableName|string|表名|
###### 接口示例
入参:
``` javascript
```
响应:
``` javascript
{
"code": 1,
"data": [
{
"databaseName": "MicroMsg.db",
"handle": 1755003930784,
"tables": [
{
"name": "Contact",
"rootpage": "2",
"sql": "CREATE TABLE Contact(UserName TEXT PRIMARY KEY ,Alias TEXT,EncryptUserName TEXT,DelFlag INTEGER DEFAULT 0,Type INTEGER DEFAULT 0,VerifyFlag INTEGER DEFAULT 0,Reserved1 INTEGER DEFAULT 0,Reserved2 INTEGER DEFAULT 0,Reserved3 TEXT,Reserved4 TEXT,Remark TEXT,NickName TEXT,LabelIDList TEXT,DomainList TEXT,ChatRoomType int,PYInitial TEXT,QuanPin TEXT,RemarkPYInitial TEXT,RemarkQuanPin TEXT,BigHeadImgUrl TEXT,SmallHeadImgUrl TEXT,HeadImgMd5 TEXT,ChatRoomNotify INTEGER DEFAULT 0,Reserved5 INTEGER DEFAULT 0,Reserved6 TEXT,Reserved7 TEXT,ExtraBuf BLOB,Reserved8 INTEGER DEFAULT 0,Reserved9 INTEGER DEFAULT 0,Reserved10 TEXT,Reserved11 TEXT)",
"tableName": "Contact"
}
]
}
],
"msg":"success"
}
```
#### 4.查询数据库**
###### 接口功能
> 查询数据库
###### 接口地址
> [/api/execSql](/api/execSql)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|dbHandle |true |number| |
|sql |true |string| 执行的sql |
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,0成功, 非0失败|
|msg|string|返回信息|
|data|array|sqlite返回的结果|
###### 接口示例
入参:
``` javascript
{
"dbHandle":2006119800400,
"sql":"select * from MSG where localId =301;"
}
```
响应:
``` javascript
{
"code": 1,
"data": [
[
"localId",
"TalkerId",
"MsgSvrID",
"Type",
"SubType",
"IsSender",
"CreateTime",
"Sequence",
"StatusEx",
"FlagEx",
"Status",
"MsgServerSeq",
"MsgSequence",
"StrTalker",
"StrContent",
"DisplayContent",
"Reserved0",
"Reserved1",
"Reserved2",
"Reserved3",
"Reserved4",
"Reserved5",
"Reserved6",
"CompressContent",
"BytesExtra",
"BytesTrans"
],
[
"301",
"1",
"8824834301214701891",
"1",
"0",
"0",
"1685401473",
"1685401473000",
"0",
"0",
"2",
"1",
"795781866",
"wxid_123",
"testtest",
"",
"0",
"2",
"",
"",
"",
"",
"",
"",
"CgQIEBAAGo0BCAcSiAE8bXNnc291cmNlPJPHNpZ25hdHVyZT52MV9wd12bTZyRzwvc2lnbmF0dXJPgoJPHRtcF9ub2RlPgoJCTxwsaXNoZXItaWQ+Jmx0OyFbQ0RBVEFbXV0mZ3Q7PC9wdWJsaXNoZXItaWQ+Cgk8L3RtcF9ub2RlPgo8L21zZ3NvdXJjZT4KGiQIAhIgNDE1MDA0NjRhZTRmMjk2NjhjMzY2ZjFkOTdmMjAwNDg=",
""
]
],
"msg": "success"
}
```
#### 5.发送文本消息**
###### 接口功能
> 发送文本消息
###### 接口地址
> [/api/sendTextMsg](/api/sendTextMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|wxid |true |string| 接收人wxid |
|msg|true |string|消息文本内容|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,不为0成功, 0失败|
|msg|string|成功提示|
|data|object|null|
###### 接口示例
入参:
``` javascript
{
"wxid": "filehelper",
"msg": "1112222"
}
```
响应:
``` javascript
{"code":345686720,"msg":"success","data":null}
```

View File

@ -1,640 +0,0 @@
{
"info": {
"name": "Wechat Hook 395",
"_postman_id": "d2b6a4f2-6d7d-4a21-9bbf-65b5a5a3a5a",
"description": "A collection of Wechat Hook 395 API requests.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "checkLogin",
"request": {
"url": {
"raw": "http://127.0.0.1:19088/api/checkLogin",
"protocol": "http",
"host": [
"127.0.0.1"
],
"port": "19088",
"path": [
"api",
"checkLogin"
]
},
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to check login status."
}
},
{
"name": "userInfo",
"request": {
"url": {
"raw": "http://127.0.0.1:19088/api/userInfo",
"protocol": "http",
"host": [
"127.0.0.1"
],
"port": "19088",
"path": [
"api",
"userInfo"
]
},
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to get user information."
}
},
{
"name": "sendTextMsg",
"request": {
"url": {
"raw": "http://127.0.0.1:19088/api/sendTextMsg",
"protocol": "http",
"host": [
"127.0.0.1"
],
"port": "19088",
"path": [
"api",
"sendTextMsg"
]
},
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"filehelper\",\"msg\": \"12www\"}"
},
"description": "API to send text messages."
}
},
{
"name": "sendImagesMsg",
"request": {
"url": "http://127.0.0.1:19088/api/sendImagesMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"filehelper\",\"imagePath\": \"C:\\pic.png\"}"
},
"description": "API to send image messages."
}
},
{
"name": "sendFileMsg",
"request": {
"url": "http://127.0.0.1:19088/api/sendFileMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"filehelper\",\"filePath\": \"C:\\test.zip\"}"
},
"description": "API to send file messages."
}
},
{
"name": "hookSyncMsg",
"request": {
"url": "http://127.0.0.1:19088/api/hookSyncMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"port\": \"19099\",\"ip\": \"127.0.0.1\",\"url\": \"http://localhost:8080\",\"timeout\": \"3000\",\"enableHttp\": \"0\"}"
},
"description": "API to hook sync messages."
}
},
{
"name": "unhookSyncMsg",
"request": {
"url": "http://127.0.0.1:19088/api/unhookSyncMsg",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to unhook sync messages."
}
},
{
"name": "getContactList",
"request": {
"url": "http://127.0.0.1:19088/api/getContactList",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to get the contact list."
}
},
{
"name": "getDBInfo",
"request": {
"url": "http://127.0.0.1:19088/api/getDBInfo",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to get database information."
}
},
{
"name": "execSql",
"request": {
"url": "http://127.0.0.1:19088/api/execSql",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"dbHandle\": 1713425147584,\"sql\": \"select * from MSG where localId =100;\"}"
},
"description": "API to execute SQL queries."
}
},
{
"name": "getChatRoomDetailInfo",
"request": {
"url": "http://127.0.0.1:19088/api/getChatRoomDetailInfo",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123333@chatroom\"}"
},
"description": "API to get chat room detail information."
}
},
{
"name": "addMemberToChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/addMemberToChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\",\"memberIds\": \"wxid_123\"}"
},
"description": "API to add member to chat room."
}
},
{
"name": "delMemberFromChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/delMemberFromChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"21363231004@chatroom\",\"memberIds\": \"wxid_123\"}"
},
"description": "API to delete member from chat room."
}
},
{
"name": "modifyNickname",
"request": {
"url": "http://127.0.0.1:19088/api/modifyNickname",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\",\"wxid\": \"wxid_123\",\"nickName\": \"test\"}"
},
"description": "API to modify a nickname in a chat room."
}
},
{
"name": "getMemberFromChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/getMemberFromChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\"}"
},
"description": "API to get members from a chat room."
}
},
{
"name": "topMsg",
"request": {
"url": "http://127.0.0.1:19088/api/topMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"msgId\": 1222222}"
},
"description": "API to top a message."
}
},
{
"name": "removeTopMsg",
"request": {
"url": "http://127.0.0.1:19088/api/removeTopMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\",\"msgId\": 123}"
},
"description": "API to remove a topped message."
}
},
{
"name": "InviteMemberToChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/InviteMemberToChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\",\"memberIds\": \"wxid_123\"}"
},
"description": "API to invite members to a chat room."
}
},
{
"name": "hookLog",
"request": {
"url": "http://127.0.0.1:19088/api/hookLog",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to hook logs."
}
},
{
"name": "unhookLog",
"request": {
"url": "http://127.0.0.1:19088/api/unhookLog",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to unhook logs."
}
},
{
"name": "createChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/createChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"memberIds\": \"wxid_8yn4k908tdqp22,wxid_oyb662qhop4422\"}"
},
"description": "API to create a chat room."
}
},
{
"name": "quitChatRoom",
"request": {
"url": "http://127.0.0.1:19088/api/quitChatRoom",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"chatRoomId\": \"123@chatroom\"}"
},
"description": "API to quit a chat room."
}
},
{
"name": "forwardMsg",
"request": {
"url": "http://127.0.0.1:19088/api/forwardMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"filehelper\",\"msgId\": \"12331\"}"
},
"description": "API to forward a message."
}
},
{
"name": "getSNSFirstPage",
"request": {
"url": "http://127.0.0.1:19088/api/getSNSFirstPage",
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"description": "API to get the first page of SNS data."
}
},
{
"name": "getSNSNextPage",
"request": {
"url": "http://127.0.0.1:19088/api/getSNSNextPage",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"snsId\": \"\"}"
},
"description": "API to get the next page of SNS data."
}
},
{
"name": "addFavFromMsg",
"request": {
"url": "http://127.0.0.1:19088/api/addFavFromMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"msgId\": \"1222222\"}"
},
"description": "API to add a favorite from a message."
}
},
{
"name": "addFavFromImage",
"request": {
"url": "http://127.0.0.1:19088/api/addFavFromImage",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"\",\"imagePath\": \"\"}"
},
"description": "API to add a favorite from an image."
}
},
{
"name": "getContactProfile",
"request": {
"url": "http://127.0.0.1:19088/api/getContactProfile",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxid\": \"\"}"
},
"description": "API to get contact profile."
}
},
{
"name": "sendAtText",
"request": {
"url": "http://127.0.0.1:19088/api/sendAtText",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"wxids\": \"notify@all\",\"chatRoomId\": \"123@chatroom\",\"msg\": \"你好啊\"}"
},
"description": "API to send an at-text message."
}
},
{
"name": "forwardPublicMsg",
"request": {
"url": "http://127.0.0.1:19088/api/forwardPublicMsg",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"appName\": \"\",\"userName\": \"\",\"title\": \"\",\"url\": \"\",\"thumbUrl\": \"\",\"digest\": \"\",\"wxid\": \"filehelper\"}"
},
"description": "API to forward a public message."
}
},
{
"name": "forwardPublicMsgByMsgId",
"request": {
"url": "http://127.0.0.1:19088/api/forwardPublicMsgByMsgId",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"msgId\": 123,\"wxid\": \"filehelper\"}"
},
"description": "API to forward a public message by message ID."
}
},
{
"name": "downloadAttach",
"request": {
"url": "http://127.0.0.1:19088/api/downloadAttach",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"msgId\": 123}"
},
"description": "API to download an attachment."
}
},
{
"name": "decodeImage",
"request": {
"url": "http://127.0.0.1:19088/api/decodeImage",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"filePath\": \"C:\\66664816980131.dat\",\"storeDir\": \"C:\\test\"}"
},
"description": "API to decode an image."
}
},
{
"name": "getVoiceByMsgId",
"request": {
"url": "http://127.0.0.1:19088/api/getVoiceByMsgId",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": "Specify that the request body is in JSON format."
}
],
"body": {
"mode": "raw",
"raw": "{\"msgId\": 7880439644200,\"storeDir\": \"c:\\test\"}"
},
"description": "API to get voice by message ID."
}
}
]
}

View File

@ -1,11 +0,0 @@
package main
import (
"go_client/tcpserver"
"log"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tcpserver.Listen(19099)
}

View File

@ -1,44 +0,0 @@
package tcpserver
import (
"bufio"
"log"
"net"
"strconv"
)
func Listen(port int) {
p := strconv.Itoa(port)
adress := "127.0.0.1:" + p
ln, err := net.Listen("tcp", adress)
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Println("tcp server started")
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handle(conn)
}
}
func handle(conn net.Conn) {
defer func() {
if err := recover(); err != nil {
log.Println("发生了未处理的异常", err)
}
}()
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
line := scanner.Bytes()
log.Println("收到消息:", string(line))
}
if err := scanner.Err(); err != nil {
log.Println("错误:", err)
}
}

View File

@ -1,33 +0,0 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@ -1,21 +0,0 @@
环境为jdk17
执行之后会在当前项目所处磁盘根路径生成一个exec文件夹,然后会把src/main/resources/exec下的文件放在那避免因为路径问题出错
java_client/src/main/resources/exec/c.exe 为注入器,只不过把名字改短了,更新的话换成最新版,改个名字就行, wxhelper.dll同理
项目启动之后,会生成一个tcp服务端,用来接受hook信息,然后把接收的信息放在队列中,之后用一个线程去循环处理消息.
具体实现可以看
```com.example.wxhk.tcp.vertx```包下的三个文件
com.example.wxhk.tcp.vertx.VertxTcp 这个是tcp服务端,接受信息
com.example.wxhk.tcp.vertx.InitWeChat 微信环境初始化
com.example.wxhk.tcp.vertx.ArrHandle 循环消息处理
com.example.wxhk.server.WxSmgServer 为消息处理接口,实现其中的方法即可
![image](https://github.com/sglmsn/wxhelper/assets/36943585/59d49401-a492-46a9-8ed9-dab7fb1822b4)
启动项目需要去修改配置文件的微信路径

View File

@ -1,185 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>wxhk</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wxhk</name>
<description>wxhk</description>
<properties>
<java.version>21</java.version>
<vertx-web-client.version>4.5.3</vertx-web-client.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-thymeleaf</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.105.Final</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>${vertx-web-client.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>${vertx-web-client.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>${vertx-web-client.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-mysql-client</artifactId>
<version>${vertx-web-client.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.dromara.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>6.0.0.M3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!-- 排除文件配置 -->
<!-- <excludes> -->
<!-- <exclude>*.**</exclude> -->
<!-- <exclude>*/**.xml</exclude> -->
<!-- </excludes> -->
<!-- 包含文件配置,现在只打包 com 文件夹 -->
<includes>
<include>
**/com/example/wxhk/**
</include>
</includes>
<archive>
<manifest>
<!-- 配置加入依赖包 -->
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<useUniqueVersions>false</useUniqueVersions>
<!-- Spring Boot 启动类(自行修改) -->
<mainClass>com.example.wxhk.WxhkApplication</mainClass>
</manifest>
<manifestEntries>
<!-- 外部资源路径加入 manifest.mf 的 Class-Path -->
<Class-Path>resources/</Class-Path>
</manifestEntries>
</archive>
<!-- jar 输出目录 -->
<outputDirectory>${project.build.directory}/pack/</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<!-- 复制依赖 -->
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<!-- 依赖包 输出目录 -->
<outputDirectory>${project.build.directory}/pack/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<!-- 复制资源 -->
<executions>
<execution>
<id>copy-resources</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<!-- 资源文件 输出目录 -->
<outputDirectory>${project.build.directory}/pack/resources</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,22 +0,0 @@
package com.example.wxhk;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WxhkApplication {
public static final Vertx vertx;
static {
vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(5).setEventLoopPoolSize(5));
}
//ConsoleInject.exe -i WeChat.exe -p D:\wxhelper.dll
//ConsoleApplication.exe -I 4568 -p C:\wxhelper.dll -m 17484 -P 1888
public static void main(String[] args) {
SpringApplication.run(WxhkApplication.class, args);
}
}

View File

@ -1,37 +0,0 @@
package com.example.wxhk.constant;
/**
* 接受到的微信消息类型
*
* @author wt
* @date 2023/05/26
*/
public enum WxMsgType {
/**
*
*/
私聊信息(1),
好友请求(37),
收到名片(42),
表情(47),
转账和收款(49),
收到转账之后或者文件助手等信息(51),
入群(10000),
/**
* 扫码触发,会触发2次, 有一次有编号,一次没有,还有登陆之后也有,很多情况都会调用这个
*/
扫码触发(10002),
;
Integer type;
WxMsgType(Integer type) {
this.type = type;
}
public Integer getType() {
return type;
}
}

View File

@ -1,14 +0,0 @@
package com.example.wxhk.controller;
import org.dromara.hutool.log.Log;
public class WxMsgController {
protected static final Log log = Log.get();
void init() {
}
}

View File

@ -1,11 +0,0 @@
package com.example.wxhk.infe;
/**
* http 响应
* @author wt
* @date 2023/06/01
*/
public interface Resp extends java.io.Serializable{
}

View File

@ -1,17 +0,0 @@
package com.example.wxhk.infe;
import io.vertx.core.json.JsonObject;
/**
* http接口请求的基础接口
*
* @author wt
* @date 2023/06/01
*/
public interface SendMsg<T> extends java.io.Serializable{
default JsonObject toJson(){
return JsonObject.mapFrom(this);
}
}

View File

@ -1,54 +0,0 @@
package com.example.wxhk.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 私聊
*
* @author wt
* @date 2023/05/26
*/
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class PrivateChatMsg implements Serializable {
String path;
/**
* 内容
*/
private String content;
/**
* 当是群聊的时候 为群id,否则为微信id
*/
private String fromGroup;
/**
* 微信id
*/
private String fromUser;
private Integer isSendMsg;
/**
* 1通过手机发送
*/
private Integer isSendByPhone;
private Long msgId;
private Integer pid;
private String sign;
private String signature;
private String time;
private Integer timestamp;
/**
* 对用户,如果是文件助手是filehelper
*/
private String toUser;
/**
* 类型
*/
private Integer type;
}

View File

@ -1,21 +0,0 @@
package com.example.wxhk.model.dto;
import java.math.BigDecimal;
/**
* 支付信息
*
* @author wt
* @param receiverUsername 付款人
* @param decimal 收款金额
* @param remark 备注
* @param transcationid
* @param transferid
* @date 2023/06/06
*/
public record PayoutInformation(String receiverUsername, BigDecimal decimal, String remark,String transcationid,String transferid) implements java.io.Serializable {
public PayoutInformation(String receiverUsername, BigDecimal decimal, String remark) {
this(receiverUsername, decimal, remark, null, null);
}
}

View File

@ -1,20 +0,0 @@
package com.example.wxhk.model.request;
import com.example.wxhk.infe.SendMsg;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 添加wxid 好友
* @author wt
* @date 2023/06/01
*/
@Data
@Accessors(chain = true)
public class AddFriends implements SendMsg<AddFriends> {
String wxid;
/**
* 验证信息
*/
String msg;
}

View File

@ -1,27 +0,0 @@
package com.example.wxhk.model.request;
import com.example.wxhk.infe.SendMsg;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 确认收款
* @author wt
* @date 2023/06/01
*/
@Data
@Accessors(chain = true)
public class ConfirmThePayment implements SendMsg<ConfirmThePayment> {
/**
* 转账人微信id从hook的消息中获取
*/
String wxid;
/**
* 从hook的消息中获取对应的字段内容
*/
String transcationId;
/**
* 从hook的消息中获取对应的字段内容
*/
String transferId;
}

View File

@ -1,19 +0,0 @@
package com.example.wxhk.model.request;
import com.example.wxhk.infe.SendMsg;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 通过手机或者qq查找微信
* @author wt
* @date 2023/06/01
*/
@Data
@Accessors(chain = true)
public class FindWeChat implements SendMsg<FindWeChat> {
/**
* 通过 手机或qq查询信息
*/
String keyword;
}

View File

@ -1,23 +0,0 @@
package com.example.wxhk.model.request;
import com.example.wxhk.infe.SendMsg;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 转发消息
* @author wt
* @date 2023/06/01
*/
@Data
@Accessors(chain = true)
public class ForwardMessages implements SendMsg<ForwardMessages> {
/**
* 消息接收人wxid
*/
String wxid;
/**
* 消息id
*/
String msgid;
}

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