Merge remote-tracking branch 'origin/dev-3.9.5.81'

This commit is contained in:
hugy 2023-07-07 14:03:40 +08:00
commit 91bd8f5977
40 changed files with 22661 additions and 28 deletions

View File

@ -1,36 +1,48 @@
cmake_minimum_required(VERSION 3.0.0)
# include(ExternalProject)
project(wxhelper VERSION 1.0.0)
enable_language(ASM_MASM)
# 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)
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 )
include_directories(c:/soft/vcpkg/installed/x86-windows/include)
add_subdirectory(spdlog)
add_subdirectory(source)
# add_subdirectory(3rd)
# add_subdirectory(source)
# find_package(spdlog CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
find_package(unofficial-mongoose CONFIG REQUIRED)
# find_package(spdlog CONFIG REQUIRED)
# find_package(minhook CONFIG REQUIRED)
find_path(DETOURS_INCLUDE_DIRS "detours/detours.h")
find_library(DETOURS_LIBRARY detours REQUIRED)
add_library(wxhelper SHARED ${CPP_FILES} )
add_library(wxhelper SHARED ${CPP_FILES} ${ASM_FILES} )
#target_include_directories(wxhelper PUBLIC 3rd/mongoose )
target_link_libraries(wxhelper PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(wxhelper PRIVATE unofficial::mongoose::mongoose)
# target_link_libraries(wxhelper PRIVATE spdlog::spdlog spdlog::spdlog_header_only)
# target_link_libraries(wxhelper PRIVATE minhook::minhook)
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

516
doc/3.9.5.81.md Normal file
View File

@ -0,0 +1,516 @@
#### 编译构建
环境:
cl.exe目录= c:/cl.exe
ml64.exe目录 =c:/ml64.exe
vcpkg目录 = c:/vcpkg
wxhelper目录 = c:/wxhelper
```
vcpkg install detours:x64-windows
vcpkg install nlohmann-json:x64-windows
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.5.81版本http接口文档文档仅供参考。
### 简单说明:
所有接口只支持post方法。
全部使用json格式。
格式: http://host:port/api/xxxx
host: 绑定的host
port: 监听的端口
xxxx: 对应的功能路径
返回结构的json格式
``` javascript
{
"code": 1,
"data": {},
"msg": "success"
}
```
code 错误码
msg 成功/错误信息
data 接口返回的数据
#### 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|响应内容|
|  account|string|账号|
|  headImage|string|头像|
|  city|string|城市|
|  country|string|国家|
|  currentDataPath|string|当前数据目录,登录的账号目录|
|  dataSavePath|string|微信保存目录|
|  mobile|string|手机|
|  name|string|昵称|
|  province|string|省|
|  wxid|string|wxid|
|  signature|string|个人签名|
|  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": "13949175447",
"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|好友信息|
|  customAccount|string|自定义账号|
|  encryptName|string|昵称|
|  nickname|string|昵称|
|  pinyin|string|简拼|
|  pinyinAll|string|全拼|
|  reserved1|number|未知|
|  reserved2|number|未知|
|  type|number|未知|
|  verifyFlag|number|未知|
|  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|好友信息|
|  databaseName|string|数据库名称|
|  handle|number|句柄|
|  tables|array|表信息|
|    name|string|表名|
|    rootpage|string|rootpage|
|    sql|string|ddl语句|
|    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"
}
```
#### 8.发送文件消息**
###### 接口功能
> 发送文件消息
###### 接口地址
> [/api/sendFileMsg](/api/sendFileMsg)
###### HTTP请求方式
> POST JSON
###### 请求参数
|参数|必选|类型|说明|
|---|---|---|---|
|wxid |true |string| 接收人wxid |
|filePath|true |string|文件绝对路径|
###### 返回字段
|返回字段|字段类型|说明 |
|---|---|---|
|code|int|返回状态,不为0成功, 0失败|
|msg|string|成功提示|
|data|object|null|
###### 接口示例
入参:
``` javascript
{
"wxid": "filehelper",
"filePath": "c:\\test.zip"
}
```
响应:
``` javascript
{"code":345686720,"msg":"success","data":null}
```

View File

@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.0.0)
project(ConsoleApplication VERSION 1.0.0)
project(injector VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 17)
@ -9,12 +9,12 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D '_UNICODE' /D 'UNICODE'")
file(GLOB INJECT_CPP_FILES ${PROJECT_SOURCE_DIR}/*.cc ${PROJECT_SOURCE_DIR}/*.cpp)
add_executable (ConsoleApplication ${INJECT_CPP_FILES})
add_executable (injector ${INJECT_CPP_FILES})
SET_TARGET_PROPERTIES(ConsoleApplication PROPERTIES LINKER_LANGUAGE C
SET_TARGET_PROPERTIES(injector PROPERTIES LINKER_LANGUAGE C
ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
OUTPUT_NAME "ConsoleApplication"
OUTPUT_NAME "injector"
PREFIX "")

View File

@ -570,7 +570,7 @@ HMODULE GetDLLHandle(wchar_t* wDllName, DWORD dPid)
return result;
}
BOOL EnableDebugPrivilege()
BOOL EnableDebugPrivilege()
{
HANDLE TokenHandle = NULL;
TOKEN_PRIVILEGES TokenPrivilege;
@ -649,7 +649,7 @@ LPVOID FillAsmCode(HANDLE handle) {
int InjectDllAndStartHttp(wchar_t* szPName, wchar_t* szDllPath, DWORD port)
{
if(!EnableDebugPrivilege()){
if (!EnableDebugPrivilege()) {
return 0;
}
int result = 0;
@ -662,7 +662,7 @@ int InjectDllAndStartHttp(wchar_t* szPName, wchar_t* szDllPath, DWORD port)
size_t ulDllLength;
wchar_t* dllName = (wchar_t*)L"wxhelper.dll";
size_t dllNameLen = wcslen(dllName) * 2 + 2;
char* funcName = (char* )"http_start";
char* funcName = (char*)"http_start";
size_t funcNameLen = strlen(funcName) + 1;
HANDLE hStartHttp = NULL;
@ -773,7 +773,7 @@ error:
int InjectDllAndStartHttpByPid(unsigned int pid, wchar_t* szDllPath, DWORD port)
{
if(!EnableDebugPrivilege()){
if (!EnableDebugPrivilege()) {
return 0;
}
int result = 0;
@ -785,7 +785,7 @@ int InjectDllAndStartHttpByPid(unsigned int pid, wchar_t* szDllPath, DWORD port
size_t ulDllLength;
wchar_t* dllName = (wchar_t*)L"wxhelper.dll";
size_t dllNameLen = wcslen(dllName) * 2 + 2;
char* funcName = (char* )"http_start";
char* funcName = (char*)"http_start";
size_t funcNameLen = strlen(funcName) + 1;
HANDLE hStartHttp = NULL;
@ -895,7 +895,7 @@ error:
int InjectDll(wchar_t* szPName, wchar_t* szDllPath)
{
if(!EnableDebugPrivilege()){
if (!EnableDebugPrivilege()) {
return 0;
}
int result = 0;
@ -949,7 +949,7 @@ int InjectDll(wchar_t* szPName, wchar_t* szDllPath)
int InjectDllByPid(unsigned int pid, wchar_t* szDllPath)
{
if(!EnableDebugPrivilege()){
if (!EnableDebugPrivilege()) {
return 0;
}
int result = 0;
@ -981,7 +981,7 @@ int InjectDllByPid(unsigned int pid, wchar_t* szDllPath)
OutputDebugStringA("[DBG] dll inject success");
printf("dll inject success");
printf("dll path : %s ", szDllPath);
printf("pid : %d ", pid);
printf("dll path : %d ", pid);
result = 1;
}
else
@ -1052,7 +1052,7 @@ int main(int argc, char** argv)
int port = 0;
ULONG pid = 0;
unsigned int injectPid =0;
unsigned int injectPid = 0;
while ((param = getopt(argc, argv, "i:p:u:d:m:P:I:h")) != -1)
{
@ -1105,7 +1105,7 @@ int main(int argc, char** argv)
}
if (injectPid != 0 && cDllPath[0] != 0)
{
if(cDllPath[0] != '\0')
if (cDllPath[0] != '\0')
{
if (port == 0) {
std::wstring wsPath = Utf8ToUnicode(cDllPath);
@ -1120,7 +1120,7 @@ int main(int argc, char** argv)
}
}
}
if (cInjectprogram[0] != 0 && cDllPath[0] != 0)
{

312
src/base64.cpp Normal file
View File

@ -0,0 +1,312 @@
#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)
Copyright (C) 2004-2017, 2020, 2021 Ren<EFBFBD><EFBFBD> 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
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
Ren<EFBFBD><EFBFBD> Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#include "base64.h"
#include <algorithm>
#include <stdexcept>
//
// Depending on the url parameter in base64_chars, one of
// two sets of base64 characters needs to be chosen.
// They differ in their last two characters.
//
static const char *base64_chars[2] = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"+/",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-_"};
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 '_'
else
//
// 2020-10-23: Throw std::exception rather than const char*
//(Pablo Martin-Gomez, https://github.com/Bouska)
//
throw std::runtime_error("Input is not valid base64-encoded data.");
}
static std::string insert_linebreaks(std::string str, size_t distance)
{
//
// Provided by https://github.com/JomaCorpFX, adapted by me.
//
if (!str.length())
{
return "";
}
size_t pos = distance;
while (pos < str.size())
{
str.insert(pos, "\n");
pos += distance + 1;
}
return str;
}
template <typename String, unsigned int line_length>
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)
{
return encode_with_line_breaks<String, 64>(s);
}
template <typename String>
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)
{
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)
{
size_t len_encoded = (in_len + 2) / 3 * 4;
unsigned char trailing_char = url ? '.' : '=';
//
// Choose set of base64 characters. They differ
// for the last two positions, depending on the url
// parameter.
// A bool (as is the parameter url) is guaranteed
// to evaluate to either 0 or 1 in C++ therefore,
// the correct character set is chosen by subscripting
// base64_chars with url.
//
const char *base64_chars_ = base64_chars[url];
std::string ret;
ret.reserve(len_encoded);
unsigned int pos = 0;
while (pos < in_len)
{
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);
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)
{
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
{
ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]);
ret.push_back(trailing_char);
}
}
else
{
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]);
ret.push_back(trailing_char);
ret.push_back(trailing_char);
}
pos += 3;
}
return ret;
}
template <typename String>
static std::string decode(String encoded_string, bool remove_linebreaks)
{
//
// decode(<28><>) 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 (remove_linebreaks)
{
std::string copy(encoded_string);
copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end());
return base64_decode(copy, false);
}
size_t length_of_string = encoded_string.length();
size_t pos = 0;
//
// The approximate length (bytes) of the decoded string might be one or
// two bytes smaller, depending on the amount of trailing equal signs
// in the encoded string. This approximation is needed to reserve
// enough space in the string to be returned.
//
size_t approx_length_of_decoded_string = length_of_string / 4 * 3;
std::string ret;
ret.reserve(approx_length_of_decoded_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.
//
// The last chunk might be padded with equal signs or dots
// in order to make it 4 bytes in size as well, but this
// is not required as per RFC 2045.
//
// All chunks except the last one produce three output bytes.
//
// 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]);
//
// 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)));
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.
)
{
//
// 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]);
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] != '.')
{
//
// 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])));
}
}
pos += 4;
}
return ret;
}
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)
{
return encode(s, url);
}
std::string base64_encode_pem(std::string const &s)
{
return encode_pem(s);
}
std::string base64_encode_mime(std::string const &s)
{
return encode_mime(s);
}
#if __cplusplus >= 201703L
//
// Interface with std::string_view rather than const std::string&
// Requires C++17
// Provided by Yannic Bonenberger (https://github.com/Yannic)
//
std::string base64_encode(std::string_view s, bool url)
{
return encode(s, url);
}
std::string base64_encode_pem(std::string_view s)
{
return encode_pem(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)
{
return decode(s, remove_linebreaks);
}
#endif // __cplusplus >= 201703L

35
src/base64.h Normal file
View File

@ -0,0 +1,35 @@
//
// base64 encoding and decoding with C++.
// Version: 2.rc.08 (release candidate)
//
#pragma once
#ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A
#define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A
#include <string>
#if __cplusplus >= 201703L
#include <string_view>
#endif // __cplusplus >= 201703L
std::string base64_encode(std::string const &s, bool url = false);
std::string base64_encode_pem(std::string const &s);
std::string base64_encode_mime(std::string const &s);
std::string base64_decode(std::string const &s, bool remove_linebreaks = false);
std::string base64_encode(unsigned char const *, size_t len, bool url = false);
#if __cplusplus >= 201703L
//
// Interface with std::string_view rather than const std::string&
// Requires C++17
// Provided by Yannic Bonenberger (https://github.com/Yannic)
//
std::string base64_encode(std::string_view s, bool url = false);
std::string base64_encode_pem(std::string_view s);
std::string base64_encode_mime(std::string_view s);
std::string base64_decode(std::string_view s, bool remove_linebreaks = false);
#endif // __cplusplus >= 201703L
#endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */

14
src/config.cc Normal file
View File

@ -0,0 +1,14 @@
#include "pch.h"
#include "config.h"
namespace wxhelper {
Config::Config(/* args */) {}
Config::~Config() {}
void Config::Initialize() {
port_ = GetPrivateProfileInt("config", "Port", 19088, "./config.ini");
}
int Config::GetPort() { return port_; }
} // namespace wxhelper

17
src/config.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef WXHELPER_CONFIG_H_
#define WXHELPER_CONFIG_H_
namespace wxhelper {
class Config {
public:
Config();
~Config();
void Initialize();
int GetPort();
private:
int port_;
};
} // namespace wxhelper
#endif

510
src/db.cc Normal file
View File

@ -0,0 +1,510 @@
#include "pch.h"
#include "db.h"
#include "base64.h"
#include "wechat_function.h"
#include "utils.h"
namespace offset = wxhelper::V3_9_5_81::offset;
namespace wxhelper {
void DB::init(UINT64 base) {
base_addr_ = base;
dbmap_ = {};
dbs_ = {};
}
void FreeResult(std::vector<std::vector<common::SqlResult>> &data) {
if (data.size() == 0) {
return;
}
for (unsigned int i = 0; i < data.size(); i++) {
for (unsigned j = 0; j < data[i].size(); j++) {
common::SqlResult *sr = (common::SqlResult *)&data[i][j];
if (sr->column_name) {
delete[] sr->column_name;
sr->column_name = NULL;
}
if (sr->content) {
delete[] sr->content;
sr->content = NULL;
}
}
data[i].clear();
}
data.clear();
}
int DB::SelectDataInner(UINT64 db, const char *sql,
std::vector<std::vector<common::SqlResult>> &data) {
common::sqlite3_prepare p_sqlite3_prepare =
(common::sqlite3_prepare)(base_addr_ + offset::k_sqlite3_prepare);
common::sqlite3_step p_sqlite3_step =
(common::sqlite3_step)(base_addr_ + offset::k_sqlite3_step);
common::sqlite3_column_count p_sqlite3_column_count =
(common::sqlite3_column_count)(base_addr_ + offset::k_sqlite3_column_count);
common::sqlite3_column_name p_sqlite3_column_name =
(common::sqlite3_column_name)(base_addr_ + offset::k_sqlite3_column_name);
common::sqlite3_column_type p_sqlite3_column_type =
(common::sqlite3_column_type)(base_addr_ + offset::k_sqlite3_column_type);
common::sqlite3_column_blob p_sqlite3_column_blob =
(common::sqlite3_column_blob)(base_addr_ + offset::k_sqlite3_column_blob);
common::sqlite3_column_bytes p_sqlite3_column_bytes =
(common::sqlite3_column_bytes)(base_addr_ + offset::k_sqlite3_column_bytes);
common::sqlite3_finalize p_sqlite3_finalize =
(common::sqlite3_finalize)(base_addr_ + offset::k_sqlite3_finalize);
UINT64 *stmt;
int rc = p_sqlite3_prepare(db, sql, -1, &stmt, 0);
if (rc != SQLITE_OK) {
return NULL;
}
while (p_sqlite3_step(stmt) == SQLITE_ROW) {
int col_count = p_sqlite3_column_count(stmt);
std::vector<common::SqlResult> tempStruct;
for (int i = 0; i < col_count; i++) {
common::SqlResult temp = {0};
const char *ColName = p_sqlite3_column_name(stmt, i);
int nType = p_sqlite3_column_type(stmt, i);
const void *pReadBlobData = p_sqlite3_column_blob(stmt, i);
int nLength = p_sqlite3_column_bytes(stmt, i);
temp.column_name = new char[strlen(ColName) + 1];
memcpy(temp.column_name, ColName, strlen(ColName) + 1);
temp.column_name_len = strlen(ColName);
temp.content_len = nLength;
switch (nType) {
case SQLITE_BLOB: {
temp.content = new char[nLength];
memcpy(temp.content, pReadBlobData, nLength);
temp.is_blob = true;
break;
}
default: {
if (nLength != 0) {
temp.content = new char[nLength + 1];
memcpy(temp.content, pReadBlobData, nLength + 1);
} else {
temp.content = new char[2];
ZeroMemory(temp.content, 2);
}
temp.is_blob = false;
break;
}
}
tempStruct.push_back(temp);
}
data.push_back(tempStruct);
}
p_sqlite3_finalize(stmt);
return 1;
}
int DB::Select(UINT64 db_hanle, const char *sql,
std::vector<std::vector<std::string>> &query_result) {
std::vector<std::vector<common::SqlResult>> data;
int status = SelectDataInner(db_hanle, sql, data);
if (status == 0) {
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 = 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;
}
int SelectDbInfo(void *data, int argc, char **argv, char **name) {
std::vector<common::SqlResult> result;
for (int i = 0; i < argc; i++) {
common::SqlResult temp = {0};
temp.column_name = new char[strlen(name[i]) + 1];
memcpy(temp.column_name, name[i], strlen(name[i]) + 1);
temp.column_name_len = strlen(name[i]);
if (argv[i]) {
temp.content = new char[strlen(argv[i]) + 1];
memcpy(temp.content, argv[i], strlen(argv[i]) + 1);
temp.content_len = strlen(argv[i]);
} else {
temp.content = new char[2];
ZeroMemory(temp.content, 2);
temp.content_len = 0;
}
result.push_back(temp);
}
return 1;
}
int DB::ExecuteSQL(UINT64 db, const char *sql, UINT64 callback, void *data) {
UINT64 sqlite3_exec_addr = base_addr_ + offset::k_sqlite3_exec;
common::sqlite3_exec fn_sqlite3_exec = (common::sqlite3_exec)sqlite3_exec_addr;
int status = fn_sqlite3_exec(db, sql, (common::sqlite3_callback)callback, data, 0);
return status;
}
int GetDbInfo(void *data, int argc, char **argv, char **name) {
common::DatabaseInfo *pdata = (common::DatabaseInfo *)data;
common::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;
}
std::vector<void *> DB::GetDbHandles() {
dbs_.clear();
dbmap_.clear();
UINT64 p_contact_addr = *(UINT64 *)(base_addr_ + offset::kGPInstance);
UINT64 micro_msg_db_addr = *(UINT64 *)(p_contact_addr + offset::kMicroMsgDB);
UINT64 chat_msg_db_addr = *(UINT64 *)(p_contact_addr + offset::kChatMsgDB);
UINT64 misc_db_addr = *(UINT64 *)(p_contact_addr + offset::kMiscDB);
UINT64 emotion_db_addr = *(UINT64 *)(p_contact_addr + offset::kEmotionDB);
UINT64 media_db_addr = *(UINT64 *)(p_contact_addr + offset::kMediaDB);
UINT64 bizchat_msg_db_addr =
*(UINT64 *)(p_contact_addr + offset::kBizchatMsgDB);
UINT64 function_msg_db_addr =
*(UINT64 *)(p_contact_addr + offset::kFunctionMsgDB);
// microMsg.db
common::DatabaseInfo micro_msg_db{0};
micro_msg_db.db_name = (wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kMicroMsgDB + offset::kDBName));
micro_msg_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kMicroMsgDB + offset::kDBName + 0x8);
micro_msg_db.handle = micro_msg_db_addr;
ExecuteSQL(micro_msg_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &micro_msg_db);
dbs_.push_back(micro_msg_db);
std::wstring micro_msg_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kMicroMsgDB + offset::kDBName)));
dbmap_[micro_msg_name] = micro_msg_db;
// chatMsg.db
common::DatabaseInfo chat_msg_db{0};
chat_msg_db.db_name = (wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kChatMsgDB + offset::kDBName));
chat_msg_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kChatMsgDB + offset::kDBName + 0x8);
chat_msg_db.handle = chat_msg_db_addr;
ExecuteSQL(chat_msg_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &chat_msg_db);
dbs_.push_back(chat_msg_db);
std::wstring chat_msg_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kChatMsgDB + offset::kDBName)));
dbmap_[chat_msg_name] = chat_msg_db;
// misc.db
common::DatabaseInfo misc_db{0};
misc_db.db_name =
(wchar_t *)(*(UINT64 *)(p_contact_addr + offset::kMiscDB + offset::kDBName));
misc_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kMiscDB + offset::kDBName + 0x8);
misc_db.handle = misc_db_addr;
ExecuteSQL(misc_db_addr, "select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &misc_db);
dbs_.push_back(misc_db);
std::wstring misc_name = std::wstring((
wchar_t *)(*(UINT64 *)(p_contact_addr + offset::kMiscDB + offset::kDBName)));
dbmap_[misc_name] = misc_db;
// emotion.db
common::DatabaseInfo emotion_db{0};
emotion_db.db_name = (wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kEmotionDB + offset::kDBName));
emotion_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kEmotionDB + offset::kDBName + 0x8);
emotion_db.handle = emotion_db_addr;
ExecuteSQL(emotion_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &emotion_db);
dbs_.push_back(emotion_db);
std::wstring emotion_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kEmotionDB + offset::kDBName)));
dbmap_[emotion_name] = emotion_db;
// media.db
common::DatabaseInfo media_db{0};
media_db.db_name = (wchar_t *)(*(UINT64 *)(p_contact_addr + offset::kMediaDB +
offset::kDBName));
media_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kMediaDB + offset::kDBName + 0x8);
media_db.handle = media_db_addr;
ExecuteSQL(media_db_addr, "select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &media_db);
dbs_.push_back(media_db);
std::wstring media_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kMediaDB + offset::kDBName)));
dbmap_[media_name] = media_db;
// functionMsg.db
common::DatabaseInfo function_msg_db{0};
function_msg_db.db_name = (wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName));
function_msg_db.db_name_len = *(
DWORD *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName + 0x8);
function_msg_db.handle = function_msg_db_addr;
ExecuteSQL(function_msg_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &function_msg_db);
dbs_.push_back(function_msg_db);
std::wstring function_msg_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName)));
dbmap_[function_msg_name] = function_msg_db;
if (bizchat_msg_db_addr) {
// functionMsg.db maybe null
common::DatabaseInfo bizchat_msg_db{0};
bizchat_msg_db.db_name = (wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName));
bizchat_msg_db.db_name_len =
*(DWORD *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName +
0x8);
bizchat_msg_db.handle = bizchat_msg_db_addr;
ExecuteSQL(bizchat_msg_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &bizchat_msg_db);
dbs_.push_back(bizchat_msg_db);
std::wstring bizchat_msg_name = std::wstring((wchar_t *)(*(
UINT64 *)(p_contact_addr + offset::kFunctionMsgDB + offset::kDBName)));
dbmap_[bizchat_msg_name] = bizchat_msg_db;
}
UINT64 multi_db_mgr_addr = base_addr_ + offset::kMultiDBMgr;
UINT64 public_msg_mgr_addr = base_addr_ + offset::kPublicMsgMgr;
UINT64 favorite_storage_mgr_addr = base_addr_ + offset::kFavoriteStorageMgr;
// MsgX.db
UINT64 wrap_ptr = *(UINT64 *)(multi_db_mgr_addr);
UINT64 current_db_num = *(UINT64 *)(wrap_ptr + 0x68);
UINT64 begin_ptr = *(UINT64 *)(wrap_ptr + 0x50);
for (unsigned int i = 0; i < current_db_num; i++) {
UINT64 next_addr = begin_ptr + i * 0x8;
UINT64 db_addr = *(UINT64 *)next_addr;
if (db_addr) {
UINT64 msg0_db_addr = *(UINT64 *)(db_addr + 0x78);
common::DatabaseInfo msg0_db{0};
msg0_db.db_name = (wchar_t *)(*(UINT64 *)(db_addr));
msg0_db.db_name_len = *(DWORD *)(db_addr + 0x8);
msg0_db.handle = msg0_db_addr;
ExecuteSQL(msg0_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &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 buf_info_addr = *(UINT64 *)(db_addr + 0x20);
UINT64 buf_info_handle = *(UINT64 *)(buf_info_addr + 0x50);
common::DatabaseInfo media_msg0_db{0};
media_msg0_db.db_name = (wchar_t *)(*(UINT64 *)(buf_info_addr + 0x78));
media_msg0_db.db_name_len = *(DWORD *)(buf_info_addr + 0x80);
media_msg0_db.handle = buf_info_handle;
ExecuteSQL(buf_info_handle,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &media_msg0_db);
dbs_.push_back(media_msg0_db);
std::wstring media_msg_db_name =
std::wstring(media_msg0_db.db_name,media_msg0_db.db_name_len);
dbmap_[media_msg_db_name] = media_msg0_db;
}
}
// publicMsg.db
UINT64 public_msg_mgr_ptr =*(UINT64 *)(public_msg_mgr_addr);
for (unsigned int i = 1; i < 4; i++) {
UINT64 public_msg_ptr = *(UINT64 *)(public_msg_mgr_ptr + i * 0x8);
if (public_msg_ptr) {
UINT64 public_msg_db_addr = *(UINT64 *)(public_msg_ptr + 0x50);
common::DatabaseInfo public_msg_db{0};
public_msg_db.db_name = (wchar_t *)(*(UINT64 *)(public_msg_ptr + 0x78));
public_msg_db.db_name_len = *(DWORD *)(public_msg_ptr + 0x80);
public_msg_db.handle = public_msg_db_addr;
ExecuteSQL(public_msg_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &public_msg_db);
dbs_.push_back(public_msg_db);
std::wstring public_msg_db_name =
std::wstring(public_msg_db.db_name , public_msg_db.db_name_len);
dbmap_[public_msg_db_name] = public_msg_db;
}
}
// Favorite.db
UINT64 favItems_ptr =
*(UINT64 *)(*(UINT64 *)(*(UINT64 *)(favorite_storage_mgr_addr) + 0x10) + 0x8);
if (favItems_ptr) {
UINT64 favorite_db_addr = *(UINT64 *)(favItems_ptr + 0x50);
common::DatabaseInfo favorite_db{0};
favorite_db.db_name = (wchar_t *)(*(UINT64 *)(favItems_ptr + 0x78));
favorite_db.db_name_len = *(DWORD *)(favItems_ptr + 0x80);
favorite_db.handle = favorite_db_addr;
ExecuteSQL(favorite_db_addr,
"select * from sqlite_master where type=\"table\";",
(UINT64)GetDbInfo, &favorite_db);
dbs_.push_back(favorite_db);
std::wstring public_msg_db_name =
std::wstring(favorite_db.db_name,favorite_db.db_name_len);
dbmap_[public_msg_db_name] = favorite_db;
}
common::DatabaseInfo db_end = {0};
dbs_.push_back(db_end);
std::vector<void *> ret_array;
for (unsigned int i = 0; i < dbs_.size() - 1; i++){
ret_array.push_back(&dbs_[i]);
}
return ret_array;
}
UINT64 DB::GetDbHandleByDbName(wchar_t *dbname) {
if (dbmap_.size() == 0) {
GetDbHandles();
}
if (dbmap_.find(dbname) != dbmap_.end()) {
return dbmap_[dbname].handle;
}
return 0;
}
INT64 DB::GetLocalIdByMsgId(ULONG64 msgid, INT64 &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 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> DB::GetChatMsgByMsgId(ULONG64 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);
DWORD handle = GetDbHandleByDbName(dbname);
if (handle == 0) {
// LOG(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 DB::GetVoiceBuffByMsgId(ULONG64 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) {
// LOG(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 DB::GetPublicMsgCompressContentByMsgId(ULONG64 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) {
return "";
}
std::vector<std::vector<std::string>> result;
int ret = Select(handle, (const char *)sql, result);
if (result.size() == 0) {
return "";
}
return result[1][0];
}
} // namespace wxhelper

39
src/db.h Normal file
View File

@ -0,0 +1,39 @@
#ifndef WXHELPER_DB_H_
#define WXHELPER_DB_H_
#include <string>
#include <vector>
#include "wechat_function.h"
#include "windows.h"
#include "singleton.h"
namespace wxhelper {
class DB :public Singleton<DB>{
public:
void init(UINT64 base);
int ExecuteSQL(UINT64 db, const char *sql, UINT64 callback, void *data);
int Select(UINT64 db_hanle, const char *sql,
std::vector<std::vector<std::string>> &query_result);
std::vector<void *> GetDbHandles();
UINT64 GetDbHandleByDbName(wchar_t *dbname);
INT64 GetLocalIdByMsgId(ULONG64 msgid, INT64 &dbIndex);
std::vector<std::string> GetChatMsgByMsgId(ULONG64 msgid);
std::string GetVoiceBuffByMsgId(ULONG64 msgid);
std::string GetPublicMsgCompressContentByMsgId(ULONG64 msgid);
private:
int SelectDataInner(UINT64 db, const char *sql,
std::vector<std::vector<common::SqlResult>> &data);
private:
std::map<std::wstring, common::DatabaseInfo> dbmap_;
std::vector<common::DatabaseInfo> dbs_;
UINT64 base_addr_;
};
} // namespace wxhelper
#endif

28
src/dllMain.cc Normal file
View File

@ -0,0 +1,28 @@
#include "pch.h"
#include "global_context.h"
#include "utils.h"
using namespace wxhelper;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call,
LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH: {
DisableThreadLibraryCalls(hModule);
GlobalContext::GetInstance().initialize(hModule);
break;
}
case DLL_THREAD_ATTACH: {
break;
}
case DLL_THREAD_DETACH: {
break;
}
case DLL_PROCESS_DETACH: {
GlobalContext::GetInstance().finally();
break;
}
}
return TRUE;
}

61
src/export.asm Normal file
View File

@ -0,0 +1,61 @@
;#################################################################
.code
;#################################################################
;#################################################################
;检测wechat登录状态
;param: get_account_service_addr 函数地址
;#################################################################
_GetAccountService PROC,
get_account_service_addr:QWORD ; 函数地址
sub rsp,28h
call rcx
add rsp,28h
ret
_GetAccountService ENDP
;#################################################################
;获取wechat数据保存路径
;param: addr 函数地址
;return路径地址
;#################################################################
_GetDataSavePath PROC,
get_data_path_addr:QWORD, ; 函数地址
out_path:QWORD ; 输出
sub rsp,40h
mov rax,rcx
mov rcx,rdx
call rax
add rsp,40h
ret
_GetDataSavePath ENDP
;#################################################################
;获取wechat当前数据保存路径
;param: addr 函数地址
;return路径地址
;#################################################################
_GetCurrentDataPath PROC,
get_current_path_addr: QWORD, ; 函数地址
out_path: QWORD ; 输出
sub rsp,28h
mov rax,rcx
mov rcx,rdx
call rax
add rsp,28h
ret
_GetCurrentDataPath ENDP
END

8
src/export.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef WXHELPER_EXPORT_H_
#define WXHELPER_EXPORT_H_
extern "C" UINT64 _GetAccountService(UINT64 addr);
extern "C" UINT64 _GetDataSavePath(UINT64 addr,ULONG_PTR out);
extern "C" UINT64 _GetCurrentDataPath(UINT64 addr,ULONG_PTR out);
extern "C" UINT64 _SendTextMsg(UINT64 mgr_addr,UINT64 send_text_addr,UINT64 free_addr,UINT64 receiver,UINT64 msg,UINT64 chat_msg);
#endif

39
src/global_context.cc Normal file
View File

@ -0,0 +1,39 @@
#include "pch.h"
#include "global_context.h"
#include "thread_pool.h"
#include "db.h"
namespace wxhelper {
GlobalContext::~GlobalContext() {
if (config.has_value()) {
config.reset();
}
if (log.has_value()) {
log.reset();
}
}
void GlobalContext::initialize(HMODULE module) {
state =GlobalContextState::INITIALIZING;
module_ = module;
// Utils::Hide(module);
UINT64 base = Utils::GetWeChatWinBase();
config.emplace();
config->Initialize();
log.emplace();
log->Initialize();
http_server = std::unique_ptr<HttpServer>( new HttpServer(config->GetPort()));
http_server->HttpStart();
ThreadPool::GetInstance().Create(2, 8);
mgr = std::unique_ptr<Manager>(new Manager(base));
DB::GetInstance().init(base);
state =GlobalContextState::INITIALIZED;
}
void GlobalContext::finally() {
if (http_server) {
http_server->HttpClose();
}
}
} // namespace wxhelper

41
src/global_context.h Normal file
View File

@ -0,0 +1,41 @@
#ifndef GLOBAL_CONTEXT_H_
#define GLOBAL_CONTEXT_H_
#include "config.h"
#include "http_server.h"
#include "log.h"
#include "singleton.h"
#include "manager.h"
namespace wxhelper {
enum class GlobalContextState { NOT_INITIALIZED, INITIALIZING, INITIALIZED };
class GlobalContext : public Singleton<GlobalContext> {
friend class Singleton<GlobalContext>;
~GlobalContext();
public:
void initialize(HMODULE module);
void finally();
public:
std::optional<Config> config;
std::optional<Log> log;
std::unique_ptr<HttpServer> http_server;
std::unique_ptr<Manager> mgr;
// std::optional<ContactMgr> contact_mgr;
// std::optional<MiscMgr> misc_mgr;
// std::optional<SendMessageMgr> send_mgr;
// std::optional<AccountMgr> account_mgr;
// std::optional<ChatRoomMgr> chat_room_mgr;
// std::optional<SNSMgr> sns_mgr;
GlobalContextState state = GlobalContextState::NOT_INITIALIZED;
private:
HMODULE module_;
};
} // namespace wxhelper
#endif

200
src/hooks.cc Normal file
View File

@ -0,0 +1,200 @@

#include "pch.h"
#include "hooks.h"
#include "thread_pool.h"
#include "wechat_function.h"
#include <WS2tcpip.h>
#include "base64.h"
#include "http_client.h"
namespace offset = wxhelper::V3_9_5_81::offset;
namespace common = wxhelper::common;
namespace wxhelper {
namespace hooks {
static int kServerPort = 19099;
static bool kMsgHookFlag = false;
static char kServerIp[16] = "127.0.0.1";
static bool kEnableHttp = false;
static UINT64 (*R_DoAddMsg)(UINT64, UINT64, UINT64) = (UINT64(*)(
UINT64, UINT64, UINT64))(Utils::GetWeChatWinBase() + offset::kDoAddMsg);
VOID CALLBACK SendMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work) {
common::InnerMessageStruct *msg = (common::InnerMessageStruct *)context;
if (msg == NULL) {
SPDLOG_INFO("add work:msg is null");
return;
}
std::unique_ptr<common::InnerMessageStruct> sms(msg);
nlohmann::json j_msg =
nlohmann::json::parse(msg->buffer, msg->buffer + msg->length, nullptr, false);
if (j_msg.is_discarded() == true) {
return;
}
std::string jstr = j_msg.dump() + "\n";
if (kServerPort == 0) {
SPDLOG_ERROR("http server port error :{}", kServerPort);
return;
}
WSADATA was_data = {0};
int ret = WSAStartup(MAKEWORD(2, 2), &was_data);
if (ret != 0) {
SPDLOG_ERROR("WSAStartup failed:{}", ret);
return;
}
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)kServerPort);
InetPtonA(AF_INET, kServerIp, &client_addr.sin_addr.s_addr);
if (connect(client_socket, reinterpret_cast<sockaddr *>(&client_addr),
sizeof(sockaddr)) < 0) {
SPDLOG_ERROR("socket connect fail");
goto clean;
}
char recv_buf[1024] = {0};
ret = send(client_socket, jstr.c_str(), jstr.size(), 0);
if (ret < 0) {
SPDLOG_ERROR("socket send fail ,ret:{}", ret);
goto clean;
}
ret = shutdown(client_socket, SD_SEND);
if (ret == SOCKET_ERROR) {
SPDLOG_ERROR("shutdown failed with erro:{}", ret);
goto clean;
}
ret = recv(client_socket, recv_buf, sizeof(recv_buf), 0);
if (ret < 0) {
SPDLOG_ERROR("socket recv fail ,ret:{}", ret);
goto clean;
}
clean:
closesocket(client_socket);
WSACleanup();
return;
}
VOID CALLBACK SendHttpMsgCallback(PTP_CALLBACK_INSTANCE instance, PVOID context,
PTP_WORK Work) {
common::InnerMessageStruct *msg = (common::InnerMessageStruct *)context;
if (msg == NULL) {
SPDLOG_INFO("http msg is null");
return;
}
std::unique_ptr<common::InnerMessageStruct> sms(msg);
nlohmann::json j_msg =
nlohmann::json::parse(msg->buffer, msg->buffer + msg->length, nullptr, false);
if (j_msg.is_discarded() == true) {
return;
}
std::string jstr = j_msg.dump() + "\n";
// HttpClient::GetInstance().SendRequest(jstr);
}
void HandleSyncMsg(INT64 param1, INT64 param2, INT64 param3) {
nlohmann::json msg;
msg["pid"] = GetCurrentProcessId();
msg["fromUser"] = Utils::ReadSKBuiltinString(*(INT64 *)(param2 + 0x18));
msg["toUser"] = Utils::ReadSKBuiltinString(*(INT64 *)(param2 + 0x28));
msg["content"] = Utils::ReadSKBuiltinString(*(INT64 *)(param2 + 0x30));
msg["signature"] = Utils::ReadWeChatStr(*(INT64 *)(param2 + 0x48));
msg["msgId"] = *(INT64 *)(param2 + 0x58);
msg["msgSequence"] = *(DWORD *)(param2 + 0x20);
msg["fromUserName"] = Utils::ReadWeChatStr(*(INT64 *)(param2 + 0x50));
DWORD type = *(DWORD *)(param2 + 0x24);
msg["type"] = type;
if (type == 3) {
int a = 1;
std::string img =
Utils::ReadSKBuiltinBuffer(*(INT64 *)(param2 + 0x40));
SPDLOG_INFO("encode size:{}",img.size());
msg["base64Img"] = base64_encode(img);
a = 2;
}
std::string jstr = msg.dump() + '\n';
common::InnerMessageStruct *inner_msg = new common::InnerMessageStruct;
inner_msg->buffer = new char[jstr.size() + 1];
memcpy(inner_msg->buffer, jstr.c_str(), jstr.size() + 1);
inner_msg->length = jstr.size();
if(kEnableHttp){
bool add = ThreadPool::GetInstance().AddWork(SendHttpMsgCallback,inner_msg);
SPDLOG_INFO("add http msg work:{}",add);
}else{
bool add = ThreadPool::GetInstance().AddWork(SendMsgCallback,inner_msg);
SPDLOG_INFO("add msg work:{}",add);
}
R_DoAddMsg(param1,param2,param3);
}
int HookSyncMsg(std::string client_ip, int port, std::string url,
uint64_t timeout, bool enable) {
if (kMsgHookFlag) {
SPDLOG_INFO("recv msg hook already called");
return 2;
}
kEnableHttp = enable;
if (kEnableHttp) {
HttpClient::GetInstance().SetConfig(url, timeout);
}
if (client_ip.size() < 1) {
return -2;
}
kServerPort = port;
strcpy_s(kServerIp, client_ip.c_str());
UINT64 base = Utils::GetWeChatWinBase();
if (!base) {
SPDLOG_INFO("base addr is null");
return -1;
}
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
UINT64 do_add_msg_addr = base + offset::kDoAddMsg;
DetourAttach(&(PVOID&)R_DoAddMsg, &HandleSyncMsg);
LONG ret = DetourTransactionCommit();
if(ret == NO_ERROR){
kMsgHookFlag = true;
}
return ret;
}
int UnHookSyncMsg() {
if (!kMsgHookFlag) {
kMsgHookFlag = false;
kEnableHttp = false;
strcpy_s(kServerIp, "127.0.0.1");
SPDLOG_INFO("hook sync msg reset");
return NO_ERROR;
}
UINT64 base = Utils::GetWeChatWinBase();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
UINT64 do_add_msg_addr = base + offset::kDoAddMsg;
DetourDetach(&(PVOID&)R_DoAddMsg, &HandleSyncMsg);
LONG ret = DetourTransactionCommit();
if (ret == NO_ERROR) {
kMsgHookFlag = false;
kEnableHttp = false;
strcpy_s(kServerIp, "127.0.0.1");
}
return ret;
}
} // namespace hooks
} // namespace wxhelper

15
src/hooks.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef WXHELPER_HOOKS_H_
#define WXHELPER_HOOKS_H_
#include "Windows.h"
#include "wechat_function.h"
namespace wxhelper {
namespace hooks {
int HookSyncMsg(std::string client_ip, int port, std::string url, uint64_t timeout,
bool enable);
int UnHookSyncMsg();
} // namespace hooks
} // namespace wxhelper
#endif

65
src/http_client.cc Normal file
View File

@ -0,0 +1,65 @@
#include "pch.h"
#include "http_client.h"
namespace wxhelper {
void HttpClient::SendRequest(std::string content) {
struct mg_mgr mgr;
Data data ;
data.done = false;
data.post_data = content;
mg_mgr_init(&mgr);
mg_http_connect(&mgr, url_.c_str(), OnHttpEvent, &data);
while (!data.done){
mg_mgr_poll(&mgr, 500);
}
mg_mgr_free(&mgr);
}
void HttpClient::OnHttpEvent(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
const char * s_url = GetInstance().url_.c_str();
Data data = *(Data*)fn_data;
if (ev == MG_EV_OPEN) {
// Connection created. Store connect expiration time in c->data
*(uint64_t *) c->data = mg_millis() + GetInstance().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
int 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
data.done = true; // Tell event loop to stops
} else if (ev == MG_EV_ERROR) {
data.done = true; // Error, tell event loop to stop
}
}
void HttpClient::SetConfig(std::string url,uint64_t timeout){
url_=url;
timeout_=timeout;
}
} // namespace wxhelper

24
src/http_client.h Normal file
View File

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

54
src/http_server.cc Normal file
View File

@ -0,0 +1,54 @@
#include "pch.h"
#include "http_server_callback.h"
#include "http_server.h"
namespace wxhelper {
HttpServer::HttpServer(int port) {
port_ = port;
running_ = false;
mg_mgr_init(&mgr_);
}
HttpServer::~HttpServer() {
if (thread_ != nullptr) {
CloseHandle(thread_);
}
mg_mgr_free(&mgr_);
}
bool HttpServer::HttpStart() {
if (running_) {
return true;
}
#ifdef _DEBUG
Utils::CreateConsole();
#endif
running_ = true;
thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartHttpServer, this,
NULL, 0);
return true;
}
bool HttpServer::HttpClose() {
if (!running_) {
return true;
}
#ifdef _DEBUG
Utils::CloseConsole();
#endif
running_ = false;
if (thread_) {
WaitForSingleObject(thread_, -1);
CloseHandle(thread_);
thread_ = NULL;
}
return true;
}
int HttpServer::GetPort() { return port_; }
bool HttpServer::GetRunning() { return running_; }
const mg_mgr* HttpServer::GetMgr() { return &mgr_; }
} // namespace wxhelper

29
src/http_server.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef WXHELPER_HTTP_SERVER_H_
#define WXHELPER_HTTP_SERVER_H_
#include "mongoose.h"
namespace wxhelper {
class HttpServer {
public:
explicit HttpServer(int port);
HttpServer(const HttpServer&) = delete;
HttpServer(HttpServer &&)=delete;
HttpServer& operator=(const HttpServer&) = delete;
~HttpServer();
bool HttpStart();
bool HttpClose();
int GetPort();
bool GetRunning();
const mg_mgr* GetMgr();
private:
int port_;
bool running_;
struct mg_mgr mgr_;
HANDLE thread_;
};
} // namespace wxhelper
#endif

261
src/http_server_callback.cc Normal file
View File

@ -0,0 +1,261 @@
#include "pch.h"
#include "http_server_callback.h"
#include "http_server.h"
#include "export.h"
#include "global_context.h"
#include "hooks.h"
#include "db.h"
#define STR2LL(str) (wxhelper::Utils::IsDigit(str) ? stoll(str) : 0)
namespace common = wxhelper::common;
INT64 GetINT64Param(nlohmann::json data, std::string key) {
INT64 result;
try {
result = data[key].get<INT64>();
} catch (nlohmann::json::exception) {
result = STR2LL(data[key].get<std::string>());
}
return result;
}
std::string GetStringParam(nlohmann::json data, std::string key) {
return data[key].get<std::string>();
}
std::wstring GetWStringParam(nlohmann::json data, std::string key) {
return wxhelper::Utils::UTF8ToWstring(data[key].get<std::string>());
}
void StartHttpServer(wxhelper::HttpServer *server) {
int port = server->GetPort();
std::string lsten_addr = "http://0.0.0.0:" + std::to_string(port);
if (mg_http_listen(const_cast<mg_mgr *>(server->GetMgr()), lsten_addr.c_str(),
EventHandler,
const_cast<mg_mgr *>(server->GetMgr())) == NULL) {
SPDLOG_INFO("http server listen fail.port:{}", port);
#ifdef _DEBUG
MG_INFO(("http server listen fail.port: %d", port));
#endif
return;
}
for (;;) {
mg_mgr_poll(const_cast<mg_mgr *>(server->GetMgr()), 1000);
}
}
void 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);
} 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);
}
(void)fn_data;
}
void HandleHttpRequest(struct mg_connection *c, void *ev_data) {
struct mg_http_message *hm = (struct mg_http_message *)ev_data;
std::string ret = R"({"code":200,"msg":"success"})";
try {
ret = HttpDispatch(c, hm);
} catch (nlohmann::json::exception &e) {
nlohmann::json res = {{"code", "500"}, {"msg", e.what()}, {"data", NULL}};
ret = res.dump();
}
if (ret != "") {
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s\n",
ret.c_str());
}
}
void HandleWebsocketRequest(struct mg_connection *c, void *ev_data) {
// Got websocket frame. Received data is wm->data. Echo it back!
struct mg_ws_message *wm = (struct mg_ws_message *)ev_data;
mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT);
}
std::string HttpDispatch(struct mg_connection *c, struct mg_http_message *hm) {
std::string ret;
if (mg_vcasecmp(&hm->method, "GET") == 0) {
nlohmann::json ret_data = {{"code", 200},
{"data", {}},
{"msg", "not support get method,use post."}};
ret = ret_data.dump();
return ret;
}
nlohmann::json j_param = nlohmann::json::parse(
hm->body.ptr, hm->body.ptr + hm->body.len, nullptr, false);
if (hm->body.len != 0 && j_param.is_discarded() == true) {
nlohmann::json ret_data = {
{"code", 200}, {"data", {}}, {"msg", "json string is invalid."}};
ret = ret_data.dump();
return ret;
}
if (wxhelper::GlobalContext::GetInstance().state !=
wxhelper::GlobalContextState::INITIALIZED) {
nlohmann::json ret_data = {
{"code", 200}, {"data", {}}, {"msg", "global context is initializing"}};
ret = ret_data.dump();
return ret;
}
if (mg_http_match_uri(hm, "/api/checkLogin")) {
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->CheckLogin();
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/userInfo")) {
common::SelfInfoInner self_info;
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->GetSelfInfo(self_info);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
if (success) {
nlohmann::json j_info = {
{"name", self_info.name},
{"city", self_info.city},
{"province", self_info.province},
{"country", self_info.country},
{"account", self_info.account},
{"wxid", self_info.wxid},
{"mobile", self_info.mobile},
{"headImage", self_info.head_img},
{"signature", self_info.signature},
{"dataSavePath", self_info.data_save_path},
{"currentDataPath", self_info.current_data_path},
{"dbKey", self_info.db_key},
};
ret_data["data"] = j_info;
}
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/sendTextMsg")) {
std::wstring wxid = GetWStringParam(j_param, "wxid");
std::wstring msg = GetWStringParam(j_param, "msg");
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->SendTextMsg(wxid, msg);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/hookSyncMsg")) {
INT64 success = wxhelper::hooks::HookSyncMsg("127.0.0.1",19099,"",3000,false);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/sendImagesMsg")) {
std::wstring wxid = GetWStringParam(j_param, "wxid");
std::wstring path = GetWStringParam(j_param, "imagePath");
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->SendImageMsg(wxid, path);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/sendFileMsg")) {
std::wstring wxid = GetWStringParam(j_param, "wxid");
std::wstring path = GetWStringParam(j_param, "filePath");
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->SendFileMsg(wxid, path);
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/getContactList")) {
std::vector<common::ContactInner> vec;
INT64 success = wxhelper::GlobalContext::GetInstance().mgr->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},
};
ret_data["data"].push_back(item);
}
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/unhookSyncMsg")) {
INT64 success = wxhelper::hooks::UnHookSyncMsg();
nlohmann::json ret_data = {
{"code", success}, {"data", {}}, {"msg", "success"}};
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/getDBInfo")) {
std::vector<void *> v_ptr = wxhelper::DB::GetInstance().GetDbHandles();
nlohmann::json ret_data = {{"data", nlohmann::json::array()}};
for (unsigned int i = 0; i < v_ptr.size(); i++) {
nlohmann::json db_info;
db_info["tables"] = nlohmann::json::array();
common::DatabaseInfo *db =
reinterpret_cast<common::DatabaseInfo *>(v_ptr[i]);
db_info["handle"] = db->handle;
std::wstring dbname(db->db_name);
db_info["databaseName"] = wxhelper::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";
ret = ret_data.dump();
return ret;
} else if (mg_http_match_uri(hm, "/api/execSql")) {
UINT64 db_handle = GetINT64Param(j_param, "dbHandle");
std::string sql = GetStringParam(j_param, "sql");
std::vector<std::vector<std::string>> items;
int success = wxhelper::DB::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";
ret = ret_data.dump();
return ret;
}
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);
}
ret = ret_data.dump();
return ret;
} else {
nlohmann::json ret_data = {
{"code", 200}, {"data", {}}, {"msg", "not support url"}};
ret = ret_data.dump();
return ret;
}
nlohmann::json ret_data = {
{"code", 200}, {"data", {}}, {"msg", "unreachable code."}};
ret = ret_data.dump();
return ret;
}

View File

@ -0,0 +1,17 @@
#ifndef WXHELPER_HTTP_SERVER_CALLBACK_H_
#define WXHELPER_HTTP_SERVER_CALLBACK_H_
#include <string>
#include "http_server.h"
#include "mongoose.h"
void StartHttpServer(wxhelper::HttpServer *server);
void EventHandler(struct mg_connection *c, int ev, void *ev_data,
void *fn_data);
void HandleHttpRequest(struct mg_connection *c, void *ev_data);
void HandleWebsocketRequest(struct mg_connection *c, void *ev_data);
std::string HttpDispatch(struct mg_connection *c, struct mg_http_message *hm);
#endif

21
src/log.cc Normal file
View File

@ -0,0 +1,21 @@
#include "pch.h"
#include "log.h"
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
namespace wxhelper {
Log::Log() {}
Log::~Log() {}
void Log::Initialize() {
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::debug);
spdlog::set_pattern("%Y-%m-%d %H:%M:%S [%l] [%t] - <%s>|<%#>|<%!>,%v");
}
} // namespace wxhelper

15
src/log.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef WXHELPER_LOG_H_
#define WXHELPER_LOG_H_
namespace wxhelper {
class Log {
private:
public:
Log();
~Log();
void Initialize();
};
} // namespace wxhelper
#endif

2751
src/lz4.c Normal file

File diff suppressed because it is too large Load Diff

862
src/lz4.h 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

345
src/manager.cc Normal file
View File

@ -0,0 +1,345 @@
#include "pch.h"
#include "manager.h"
#include "export.h"
#include "wechat_function.h"
namespace offset = wxhelper::V3_9_5_81::offset;
namespace prototype = wxhelper::V3_9_5_81::prototype;
namespace func = wxhelper::V3_9_5_81::function;
namespace wxhelper {
Manager::Manager(UINT64 base) : base_addr_(base) {}
Manager::~Manager() {}
INT64 Manager::CheckLogin() {
INT64 success = -1;
UINT64 accout_service_addr = base_addr_ + offset::kGetAccountServiceMgr;
func::__GetAccountService GetSevice = (func::__GetAccountService)accout_service_addr;
// UINT64 service_addr = _GetAccountService(accout_service_addr);
UINT64 service_addr = GetSevice();
if (service_addr) {
success = *(UINT64 *)(service_addr + 0x7F8);
}
return success;
}
INT64 Manager::GetSelfInfo(common::SelfInfoInner &out) {
INT64 success = -1;
UINT64 accout_service_addr = base_addr_ + offset::kGetAccountServiceMgr;
UINT64 get_app_data_save_path_addr = base_addr_ + offset::kGetAppDataSavePath;
UINT64 get_current_data_path_addr = base_addr_ + offset::kGetCurrentDataPath;
// UINT64 service_addr = _GetAccountService(accout_service_addr);
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 service_addr = GetSevice();
if (service_addr) {
if (*(INT64 *)(service_addr + 0x80) == 0 ||
*(INT64 *)(service_addr + 0x80 + 0x10) == 0) {
out.wxid = std::string();
} else {
if (*(INT64 *)(service_addr + 0x80 + 0x18) == 0xF) {
out.wxid = std::string((char *)(service_addr + 0x80),
*(INT64 *)(service_addr + 0x80 + 0x10));
} else {
out.wxid = std::string(*(char **)(service_addr + 0x80),
*(INT64 *)(service_addr + 0x80 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x108) == 0 ||
*(INT64 *)(service_addr + 0x108 + 0x10) == 0) {
out.account = std::string();
} else {
if (*(INT64 *)(service_addr + 0x108 + 0x18) == 0xF) {
out.account = std::string((char *)(service_addr + 0x108),
*(INT64 *)(service_addr + 0x108 + 0x10));
} else {
out.account = std::string(*(char **)(service_addr + 0x108),
*(INT64 *)(service_addr + 0x108 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x128) == 0 ||
*(INT64 *)(service_addr + 0x128 + 0x10) == 0) {
out.mobile = std::string();
} else {
if (*(INT64 *)(service_addr + 0x128 + 0x18) == 0xF) {
out.mobile = std::string((char *)(service_addr + 0x128),
*(INT64 *)(service_addr + 0x128 + 0x10));
} else {
out.mobile = std::string(*(char **)(service_addr + 0x128),
*(INT64 *)(service_addr + 0x128 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x148) == 0 ||
*(INT64 *)(service_addr + 0x148 + 0x10) == 0) {
out.signature = std::string();
} else {
if (*(INT64 *)(service_addr + 0x148 + 0x18) == 0xF) {
out.signature = std::string((char *)(service_addr + 0x148),
*(INT64 *)(service_addr + 0x148 + 0x10));
} else {
out.signature = std::string(*(char **)(service_addr + 0x148),
*(INT64 *)(service_addr + 0x148 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x168) == 0 ||
*(INT64 *)(service_addr + 0x168 + 0x10) == 0) {
out.country = std::string();
} else {
if (*(INT64 *)(service_addr + 0x168 + 0x18) == 0xF) {
out.country = std::string((char *)(service_addr + 0x168),
*(INT64 *)(service_addr + 0x168 + 0x10));
} else {
out.country = std::string(*(char **)(service_addr + 0x168),
*(INT64 *)(service_addr + 0x168 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x188) == 0 ||
*(INT64 *)(service_addr + 0x188 + 0x10) == 0) {
out.province = std::string();
} else {
if (*(INT64 *)(service_addr + 0x188 + 0x18) == 0xF) {
out.province = std::string((char *)(service_addr + 0x188),
*(INT64 *)(service_addr + 0x188 + 0x10));
} else {
out.province = std::string(*(char **)(service_addr + 0x188),
*(INT64 *)(service_addr + 0x188 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x1A8) == 0 ||
*(INT64 *)(service_addr + 0x1A8 + 0x10) == 0) {
out.city = std::string();
} else {
if (*(INT64 *)(service_addr + 0x1A8 + 0x18) == 0xF) {
out.city = std::string((char *)(service_addr + 0x1A8),
*(INT64 *)(service_addr + 0x1A8 + 0x10));
} else {
out.city = std::string(*(char **)(service_addr + 0x1A8),
*(INT64 *)(service_addr + 0x1A8 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x1E8) == 0 ||
*(INT64 *)(service_addr + 0x1E8 + 0x10) == 0) {
out.name = std::string();
} else {
if (*(INT64 *)(service_addr + 0x1E8 + 0x18) == 0xF) {
out.name = std::string((char *)(service_addr + 0x1E8),
*(INT64 *)(service_addr + 0x1E8 + 0x10));
} else {
out.name = std::string(*(char **)(service_addr + 0x1E8),
*(INT64 *)(service_addr + 0x1E8 + 0x10));
}
}
if (*(INT64 *)(service_addr + 0x450) == 0 ||
*(INT64 *)(service_addr + 0x450 + 0x10) == 0) {
out.head_img = std::string();
} else {
out.head_img = std::string(*(char **)(service_addr + 0x450),
*(INT64 *)(service_addr + 0x450 + 0x10));
}
if (*(INT64 *)(service_addr + 0x6E0) == 0 ||
*(INT64 *)(service_addr + 0x6E8) == 0) {
out.db_key = std::string();
} else {
INT64 byte_addr = *(INT64 *)(service_addr + 0x6E0);
INT64 len = *(INT64 *)(service_addr + 0x6E8);
out.db_key = Utils::Bytes2Hex((BYTE *)byte_addr, static_cast<int>(len));
}
UINT64 flag = *(UINT64 *)(service_addr + 0x7F8);
if (flag == 1) {
prototype::WeChatString current_data_path;
// _GetCurrentDataPath(get_current_data_path_addr,
// reinterpret_cast<ULONG_PTR>(&current_data_path));
GetCurrentDataPath(reinterpret_cast<ULONG_PTR>(&current_data_path));
if (current_data_path.ptr) {
out.current_data_path = Utils::WstringToUTF8(
std::wstring(current_data_path.ptr, current_data_path.length));
} else {
out.current_data_path = std::string();
}
}
}
prototype::WeChatString data_save_path;
// _GetDataSavePath(get_app_data_save_path_addr,
// reinterpret_cast<ULONG_PTR>(&data_save_path));
GetCurrentDataPath(reinterpret_cast<ULONG_PTR>(&data_save_path));
if (data_save_path.ptr) {
out.data_save_path = Utils::WstringToUTF8(
std::wstring(data_save_path.ptr, data_save_path.length));
} else {
out.data_save_path = std::string();
}
success = 1;
return success;
}
INT64 Manager::SendTextMsg(const std::wstring& wxid, const std::wstring& msg){
INT64 success = -1;
prototype::WeChatString to_user(wxid);
prototype::WeChatString text_msg(msg);
UINT64 send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
UINT64 send_text_msg_addr = base_addr_ + offset::kSendTextMsg;
UINT64 free_chat_msg_addr = base_addr_ + offset::kFreeChatMsg;
char chat_msg[0x460] = {0};
UINT64 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();
send(reinterpret_cast<UINT64>(&chat_msg), reinterpret_cast<UINT64>(&to_user),
reinterpret_cast<UINT64>(&text_msg), reinterpret_cast<UINT64>(&temp), 1,
1, 0, 0);
free(reinterpret_cast<UINT64>(&chat_msg));
success = 1;
return success;
}
INT64 Manager::SendImageMsg(const std::wstring& wxid, const std::wstring& image_path){
INT64 success = -1;
prototype::WeChatString to_user(wxid);
prototype::WeChatString image_full_path(image_path);
UINT64 send_message_mgr_addr = base_addr_ + offset::kGetSendMessageMgr;
UINT64 send_img_addr = base_addr_ + offset::kSendImageMsg;
UINT64 new_chat_msg_addr = base_addr_ + offset::kChatMsgInstanceCounter;
UINT64 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 p_chat_msg_temp = new_chat_msg(reinterpret_cast<UINT64>(&chat_msg_temp));
UINT64 temp1 =0;
UINT64 temp2 =0;
UINT64* flag[10] = {};
flag[8] = &temp1;
flag[9] = &temp2;
flag[1] = reinterpret_cast<UINT64*>(p_chat_msg_temp);
UINT64 p_chat_msg = new_chat_msg(reinterpret_cast<UINT64>(&chat_msg));
UINT64 send_mgr = mgr();
send_img(send_mgr, p_chat_msg,
reinterpret_cast<UINT64>(&to_user),
reinterpret_cast<UINT64>(&image_full_path),
reinterpret_cast<UINT64>(&flag));
free(p_chat_msg);
free(p_chat_msg_temp);
success = 1;
return success;
}
INT64 Manager::SendFileMsg(const std::wstring& wxid, const std::wstring& file_path){
INT64 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 get_app_msg_mgr_addr = base_addr_ + offset::kGetAppMsgMgr;
UINT64 send_file_addr = base_addr_ + offset::kSendFileMsg;
UINT64 new_chat_msg_addr = base_addr_ + offset::kChatMsgInstanceCounter;
UINT64 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* temp1 = (UINT64*)HeapAlloc(GetProcessHeap(),0,sizeof(UINT64)*4);
UINT64* temp2 = (UINT64*)HeapAlloc(GetProcessHeap(),0,sizeof(UINT64)*4);
UINT64* temp3 = (UINT64*)HeapAlloc(GetProcessHeap(),0,sizeof(UINT64)*4);
UINT64* temp4 = (UINT64*)HeapAlloc(GetProcessHeap(),0,sizeof(UINT64)*4);
ZeroMemory(temp1,sizeof(UINT64)*4);
ZeroMemory(temp2,sizeof(UINT64)*4);
ZeroMemory(temp3,sizeof(UINT64)*4);
ZeroMemory(temp4,sizeof(UINT64)*4);
*temp4=0x1F;
UINT64 app_mgr = get_app_mgr();
send_file(app_mgr, reinterpret_cast<UINT64>(chat_msg),
reinterpret_cast<UINT64>(to_user),
reinterpret_cast<UINT64>(file_full_path), 1,
reinterpret_cast<UINT64>(temp1), 0, reinterpret_cast<UINT64>(temp2),
0, reinterpret_cast<UINT64>(temp3), 0, 0);
free(reinterpret_cast<UINT64>(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);
HeapFree(GetProcessHeap(),0,temp4);
success = 1;
return success;
}
INT64 Manager::GetContacts(std::vector<common::ContactInner> &vec) {
INT64 success = -1;
UINT64 get_contact_mgr_addr = base_addr_ + offset::kGetContactMgr;
UINT64 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 mgr = get_contact_mgr();
UINT64 contact_vec[3] = {0, 0, 0};
success = get_contact_list(mgr, reinterpret_cast<UINT64>(&contact_vec));
UINT64 start = contact_vec[0];
UINT64 end = contact_vec[2];
while (start < end) {
common::ContactInner temp;
temp.wxid = Utils::ReadWstringThenConvert(start + 0x10);
temp.custom_account = Utils::ReadWstringThenConvert(start + 0x30);
temp.encrypt_name = Utils::ReadWstringThenConvert(start + 0x50);
temp.nickname = Utils::ReadWstringThenConvert(start + 0xA0);
temp.pinyin = Utils::ReadWstringThenConvert(start + 0x108);
temp.pinyin_all = Utils::ReadWstringThenConvert(start + 0x128);
temp.verify_flag = *(DWORD *)(start + 0x70);
temp.type = *(DWORD *)(start + 0x74);
temp.reserved1 = *(DWORD *)(start + 0x1F0);
temp.reserved2 = *(DWORD *)(start + 0x1F4);
vec.push_back(temp);
start += 0x698;
}
return success;
}
} // namespace wxhelper`

21
src/manager.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef WXHELPER_MANAGER_H_
#define WXHELPER_MANAGER_H_
#include "Windows.h"
#include "wechat_function.h"
namespace wxhelper {
class Manager {
public:
explicit Manager(UINT64 base);
~Manager();
INT64 CheckLogin();
INT64 GetSelfInfo(common::SelfInfoInner& out);
INT64 SendTextMsg(const std::wstring& wxid, const std::wstring& msg);
INT64 SendImageMsg(const std::wstring& wxid, const std::wstring& image_path);
INT64 SendFileMsg(const std::wstring& wxid, const std::wstring& file_path);
INT64 GetContacts(std::vector<common::ContactInner> &vec);
private:
UINT64 base_addr_;
};
} // namespace wxhelper
#endif

8413
src/mongoose.c Normal file

File diff suppressed because it is too large Load Diff

1729
src/mongoose.h Normal file

File diff suppressed because it is too large Load Diff

27
src/pch.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef PCH_H
#define PCH_H
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include <iostream>
#include <vector>
#include <map>
#include <strstream>
#include <string>
#include <optional>
#include <sstream>
#include <fstream>
#include <time.h>
#include <WinSock2.h>
#include "Windows.h"
#include "utils.h"
#include <nlohmann/json.hpp>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <detours/detours.h>
#include <heapapi.h>
#endif // PCH_H

21
src/singleton.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef WXHELPER_SINGLETON_H_
#define WXHELPER_SINGLETON_H_
template <typename T>
class Singleton {
protected:
Singleton() {}
~Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(Singleton&&) = delete;
public:
static T& GetInstance() {
static T instance{};
return instance;
}
};
#endif

48
src/thread_pool.cc Normal file
View File

@ -0,0 +1,48 @@

#include "pch.h"
#include "thread_pool.h"
#include "Windows.h"
namespace wxhelper {
ThreadPool::~ThreadPool() {
if(cleanup_group_){
CloseThreadpoolCleanupGroupMembers(cleanup_group_, true, NULL);
CloseThreadpoolCleanupGroup(cleanup_group_);
}
DestroyThreadpoolEnvironment(&env_);
if (pool_){
CloseThreadpool(pool_);
}
}
bool ThreadPool::Create(unsigned long min, unsigned long max) {
InitializeThreadpoolEnvironment(&env_);
pool_ = CreateThreadpool(NULL);
if (NULL == pool_) {
return false;
}
SetThreadpoolThreadMaximum(pool_, max);
BOOL ret = SetThreadpoolThreadMinimum(pool_, min);
if (FALSE == ret) {
return false;
}
cleanup_group_ = CreateThreadpoolCleanupGroup();
if (NULL == cleanup_group_) {
return false;
}
SetThreadpoolCallbackPool(&env_, pool_);
SetThreadpoolCallbackCleanupGroup(&env_, cleanup_group_, NULL);
return true;
}
bool ThreadPool::AddWork(PTP_WORK_CALLBACK callback,PVOID opt) {
PTP_WORK work = CreateThreadpoolWork(callback, opt, &env_);
if (NULL == work) {
return false;
}
SubmitThreadpoolWork(work);
return true;
}
} // namespace wxhelper

23
src/thread_pool.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef WXHELPER_THREAD_POOL_H_
#define WXHELPER_THREAD_POOL_H_
#include "Windows.h"
#include "singleton.h"
namespace wxhelper {
class ThreadPool :public Singleton<ThreadPool>{
public:
~ThreadPool();
bool Create(unsigned long min = 1, unsigned long max = 4);
bool AddWork(PTP_WORK_CALLBACK callback,PVOID opt);
private:
PTP_POOL pool_;
PTP_CLEANUP_GROUP cleanup_group_;
TP_CALLBACK_ENVIRON env_;
};
} // namespace wxhelper
#endif

2994
src/tinyxml2.cpp Normal file

File diff suppressed because it is too large Load Diff

2380
src/tinyxml2.h Normal file

File diff suppressed because it is too large Load Diff

322
src/utils.cc Normal file
View File

@ -0,0 +1,322 @@
#include "pch.h"
#include "utils.h"
#include <winternl.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 {
std::wstring Utils::UTF8ToWstring(const std::string &str) {
return Utils::AnsiToWstring(str, CP_UTF8);
}
std::string Utils::WstringToUTF8(const std::wstring &str) {
return Utils::WstringToAnsi(str, CP_UTF8);
}
std::wstring Utils::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 Utils::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();
}
UINT64 Utils::GetWeChatWinBase() {
return (UINT64)GetModuleHandleA("WeChatWin.dll");
}
bool Utils::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 Utils::CloseConsole() {
fclose(stdin);
fclose(stdout);
fclose(stderr);
FreeConsole();
}
std::string Utils::EncodeHexString(const std::string &str) {
const std::string hex_table = "0123456789abcdef";
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 Utils::Hex2String(const std::string &hex_str) {
std::string ret;
const std::string hex_table = "0123456789abcdef";
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 Utils::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;
}
void Utils::Hex2Bytes(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 Utils::IsDigit(std::string str) {
if (str.length() == 0) {
return false;
}
for (auto it : str) {
if (it < '0' || it > '9') {
return false;
}
}
return true;
}
bool Utils::FindOrCreateDirectoryW(const wchar_t *path) {
WIN32_FIND_DATAW fd;
HANDLE hFind = ::FindFirstFileW(path, &fd);
if (hFind != INVALID_HANDLE_VALUE &&
(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
FindClose(hFind);
return true;
}
if (!::CreateDirectoryW(path, NULL)) {
return false;
}
return true;
}
void Utils::HookAnyAddress(DWORD hook_addr, LPVOID jmp_addr, char *origin) {
BYTE jmp_code[5] = {0};
jmp_code[0] = 0xE9;
*(DWORD *)&jmp_code[1] = (DWORD)jmp_addr - hook_addr - 5;
DWORD old_protext = 0;
VirtualProtect((LPVOID)hook_addr, 5, PAGE_EXECUTE_READWRITE, &old_protext);
ReadProcessMemory(GetCurrentProcess(), (LPVOID)hook_addr, origin, 5, 0);
memcpy((void *)hook_addr, jmp_code, 5);
VirtualProtect((LPVOID)hook_addr, 5, old_protext, &old_protext);
}
void Utils::UnHookAnyAddress(DWORD hook_addr, char *origin) {
DWORD old_protext = 0;
VirtualProtect((LPVOID)hook_addr, 5, PAGE_EXECUTE_READWRITE, &old_protext);
WriteProcessMemory(GetCurrentProcess(), (LPVOID)hook_addr, origin, 5, 0);
VirtualProtect((LPVOID)hook_addr, 5, old_protext, &old_protext);
}
std::wstring Utils::GetTimeW(long long timestamp) {
wchar_t *wstr = new wchar_t[20];
memset(wstr, 0, 20 * 2);
tm tm_out;
localtime_s(&tm_out, &timestamp);
swprintf_s(wstr, 20, L"%04d-%02d-%02d %02d:%02d:%02d", 1900 + tm_out.tm_year,
tm_out.tm_mon + 1, tm_out.tm_mday, tm_out.tm_hour, tm_out.tm_min,
tm_out.tm_sec);
std::wstring str_time(wstr);
delete[] wstr;
return str_time;
}
std::string Utils::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();
}
bool Utils::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);
}
void Utils::Hide(HMODULE module) {
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);
}
std::string Utils::ReadSKBuiltinString(INT64 addr) {
INT64 inner_string = *(INT64 *)(addr + 0x8);
if (inner_string == 0) {
return std::string();
}
return ReadWeChatStr(inner_string);
}
std::string Utils::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 Utils::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 Utils::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 Utils::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 Utils::ReadWstringThenConvert(INT64 addr){
std::wstring wstr = ReadWstring(addr);
return WstringToUTF8(wstr);
}
} // namespace wxhelper

87
src/utils.h Normal file
View File

@ -0,0 +1,87 @@
#ifndef WXHELPER_UTILS_H_
#define WXHELPER_UTILS_H_
#include <windows.h>
#include <string>
#include <vector>
#define STRING2INT(str) (Utils::IsDigit(str) ? stoi(str) : 0)
#define WS2LPWS(wstr) (LPWSTR) wstr.c_str()
namespace wxhelper {
class Utils {
public:
static std::wstring UTF8ToWstring(const std::string &str);
static std::string WstringToUTF8(const std::wstring &str);
static std::wstring AnsiToWstring(const std::string &input,
INT64 locale = CP_ACP);
static std::string WstringToAnsi(const std::wstring &input,
INT64 locale = CP_ACP);
static UINT64 GetWeChatWinBase();
static bool CreateConsole();
static void CloseConsole();
static std::string EncodeHexString(const std::string &str);
static std::string Hex2String(const std::string &hex_str);
static std::string Bytes2Hex(const BYTE *bytes, const int length);
static void Hex2Bytes(const std::string &hex, BYTE *bytes);
static bool IsDigit(std::string str);
static bool FindOrCreateDirectoryW(const wchar_t *path);
static void HookAnyAddress(DWORD hook_addr, LPVOID jmp_addr, char *origin);
static void UnHookAnyAddress(DWORD hook_addr, char *origin);
static std::wstring GetTimeW(long long timestamp);
static std::string WCharToUTF8(wchar_t *wstr);
static bool IsTextUtf8(const char * str,INT64 length) ;
static void Hide(HMODULE module);
static std::string ReadSKBuiltinString(INT64 addr);
static std::string ReadSKBuiltinBuffer(INT64 addr);
static std::string ReadWeChatStr(INT64 addr);
static std::string ImageXor(std::string buf);
static std::wstring ReadWstring(INT64 addr);
static std::string ReadWstringThenConvert(INT64 addr);
template <typename T1, typename T2>
static 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>
static 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;
}
};
} // namespace wxhelper
#endif

277
src/wechat_function.h Normal file
View File

@ -0,0 +1,277 @@
#ifndef WXHELPER_WECHAT_FUNCTION_H_
#define WXHELPER_WECHAT_FUNCTION_H_
namespace wxhelper {
namespace common {
/***************************sqlite3***************************************/
#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, /* 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 db, /* Database handle */
const char* zSql, /* SQL statement, UTF-8 encoded */
int nByte, /* Maximum length of zSql in bytes. */
UINT64** ppStmt, /* OUT: Statement handle */
const char** pzTail /* OUT: Pointer to unused portion of zSql */
);
typedef int(__cdecl* sqlite3_open)(const char* filename, UINT64** ppDb);
typedef int(__cdecl* sqlite3_sleep)(int);
typedef int(__cdecl* sqlite3_errcode)(UINT64* db);
typedef int(__cdecl* sqlite3_close)(UINT64*);
typedef int(__cdecl* sqlite3_step)(UINT64*);
typedef int(__cdecl* sqlite3_column_count)(UINT64* pStmt);
typedef const char*(__cdecl* sqlite3_column_name)(UINT64*, int N);
typedef int(__cdecl* sqlite3_column_type)(UINT64*, int iCol);
typedef const void*(__cdecl* sqlite3_column_blob)(UINT64*, int iCol);
typedef int(__cdecl* sqlite3_column_bytes)(UINT64*, int iCol);
typedef int(__cdecl* sqlite3_finalize)(UINT64* pStmt);
/***************************sqlite3 end*************************************/
struct TableInfo {
char *name;
INT64 name_len;
char *table_name;
INT64 table_name_len;
char *sql;
INT64 sql_len;
char *rootpage;
INT64 rootpage_len;
};
struct DatabaseInfo {
UINT64 handle = 0;
wchar_t *db_name = NULL;
INT64 db_name_len = 0;
std::vector<TableInfo> tables;
INT64 count = 0;
INT64 extrainfo = 0;
};
struct SqlResult {
char *column_name;
INT64 column_name_len;
char *content;
INT64 content_len;
BOOL is_blob;
};
struct InnerMessageStruct {
char *buffer;
int length;
~InnerMessageStruct() {
if (this->buffer != NULL) {
delete[] this->buffer;
this->buffer = NULL;
}
}
};
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;
};
struct ContactInner {
std::string wxid;
std::string custom_account;
std::string encrypt_name;
std::string nickname;
std::string pinyin;
std::string pinyin_all;
DWORD type;
DWORD verify_flag;
DWORD reserved1;
DWORD reserved2;
ContactInner(){
wxid = "";
custom_account = "";
encrypt_name = "";
nickname ="";
pinyin ="";
pinyin_all ="";
type = -1;
verify_flag = -1;
reserved1 = -1;
reserved2 = -1;
}
};
} // namespace common
namespace V3_9_5_81 {
namespace function {
typedef UINT64(*__GetAccountService)();
typedef UINT64(*__GetDataSavePath)(UINT64);
typedef UINT64(*__GetCurrentDataPath)(UINT64);
typedef UINT64(*__GetSendMessageMgr)();
typedef UINT64 (*__SendTextMsg)(UINT64, UINT64, UINT64, UINT64, UINT64, UINT64,
UINT64, UINT64);
typedef UINT64 (*__FreeChatMsg)(UINT64);
typedef UINT64 (*__SendImageMsg)(UINT64, UINT64, UINT64, UINT64, UINT64);
typedef UINT64 (*__NewChatMsg)(UINT64);
typedef UINT64 (*__SendFile)(UINT64, UINT64, UINT64, UINT64, UINT64,UINT64, UINT64, UINT64, UINT64, UINT64, UINT64, UINT64);
typedef UINT64(*__GetAppMsgMgr)();
typedef UINT64(*__OperatorNew)(UINT64);
typedef UINT64(*__Free)();
typedef UINT64 (*__GetContactMgr)();
typedef UINT64 (*__GetContactList)(UINT64,UINT64);
} // namespace function
namespace prototype {
#include <string>
#include <vector>
struct WeChatString {
wchar_t *ptr;
DWORD length;
DWORD max_length;
INT64 c_ptr = 0;
DWORD c_len = 0;
WeChatString() { WeChatString(NULL); }
WeChatString(const std::wstring &s) {
ptr = (wchar_t *)(s.c_str());
length = static_cast<DWORD>(s.length());
max_length = static_cast<DWORD>(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<DWORD>(wcslen(pStr));
max_length = static_cast<DWORD>(wcslen(pStr));
}
void set_value(const wchar_t *pStr) {
ptr = (wchar_t *)pStr;
length = static_cast<DWORD>(wcslen(pStr));
max_length = static_cast<DWORD>(wcslen(pStr) * 2);
}
};
} // namespace prototype
namespace offset {
const UINT64 kGetAccountServiceMgr = 0x8c1230;
const UINT64 kSyncMsg = 0xc39680;
const UINT64 kSyncMsgNext = 0xc39680;
const UINT64 kGetCurrentDataPath = 0xf5d130;
const UINT64 kGetAppDataSavePath = 0x12d7040;
const UINT64 kGetSendMessageMgr = 0x8c00e0;
const UINT64 kSendTextMsg = 0xfcd8d0;
const UINT64 kFreeChatMsg = 0x8aaa00;
const UINT64 kDoAddMsg = 0x1010d80;
const UINT64 kSendImageMsg = 0xfc3d30;
const UINT64 kChatMsgInstanceCounter = 0x8c7fd0;
const UINT64 kSendFileMsg = 0xdd27f0;
const UINT64 kGetAppMsgMgr = 0x8c33f0;
const UINT64 kGetContactMgr = 0x8ae3d0;
const UINT64 kGetContactList = 0xeab270;
const UINT64 k_sqlite3_exec = 0x252e340;
const UINT64 k_sqlite3_prepare = 0x2535eb0;
const UINT64 k_sqlite3_open = 0x256d6b0;
const UINT64 k_sqlite3_backup_init= 0x24e8450;
const UINT64 k_sqlite3_errcode = 0x256bfb0;
const UINT64 k_sqlite3_close = 0x256a110;
const UINT64 k_sqlite3_step = 0x24f2350;
const UINT64 k_sqlite3_column_count = 0x24f2b70;
const UINT64 k_sqlite3_column_name = 0x24f3570;
const UINT64 k_sqlite3_column_type = 0x24f33c0;
const UINT64 k_sqlite3_column_blob = 0x24f2ba0;
const UINT64 k_sqlite3_column_bytes = 0x24f2c90;
const UINT64 k_sqlite3_finalize = 0x24f1400;
const UINT64 kGPInstance = 0x3a6f908;
const UINT64 kMicroMsgDB= 0xb8;
const UINT64 kChatMsgDB = 0x2c8;
const UINT64 kMiscDB = 0x5f0;
const UINT64 kEmotionDB = 0x838;
const UINT64 kMediaDB = 0xef8;
const UINT64 kBizchatMsgDB = 0x1a70;
const UINT64 kFunctionMsgDB = 0x1b48;
const UINT64 kDBName = 0x28;
const UINT64 kStorageStart = 0x0;
const UINT64 kStorageEnd= 0x0;
const UINT64 kMultiDBMgr= 0x3acfb68;
const UINT64 kPublicMsgMgr= 0x3acc268;
const UINT64 kFavoriteStorageMgr= 0x3acf0d0;
} // namespace offset
} // namespace V3_9_5_81
} // namespace wxhelper
#endif