feat: 3.9.5.81 基础收发功能

This commit is contained in:
hugy 2023-06-26 18:23:47 +08:00
parent 66ea9d5428
commit 5a9f91b425
38 changed files with 21363 additions and 28 deletions

View File

@ -1,36 +1,48 @@
cmake_minimum_required(VERSION 3.0.0) cmake_minimum_required(VERSION 3.0.0)
# include(ExternalProject)
project(wxhelper VERSION 1.0.0) 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 17)
set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D '_UNICODE' /D 'UNICODE' ") 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) 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) # find_package(spdlog CONFIG REQUIRED)
# add_subdirectory(source)
find_package(nlohmann_json CONFIG REQUIRED) find_package(nlohmann_json CONFIG REQUIRED)
find_package(unofficial-mongoose CONFIG REQUIRED)
# find_package(spdlog CONFIG REQUIRED) find_path(DETOURS_INCLUDE_DIRS "detours/detours.h")
# find_package(minhook CONFIG REQUIRED) 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 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 spdlog::spdlog spdlog::spdlog_header_only) target_link_libraries(wxhelper PRIVATE ${DETOURS_LIBRARY})
# target_link_libraries(wxhelper PRIVATE minhook::minhook)
SET_TARGET_PROPERTIES(wxhelper PROPERTIES LINKER_LANGUAGE C SET_TARGET_PROPERTIES(wxhelper PROPERTIES LINKER_LANGUAGE C
ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib

225
doc/3.9.5.81.md Normal file
View File

@ -0,0 +1,225 @@
#### 编译构建
环境:
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,
"result": "ok"
}
```
#### 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失败|
|result|string|成功提示|
###### 接口示例
入参:
``` 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|返回状态,1成功, 0失败|
|result|string|成功提示|
###### 接口示例
入参:
``` javascript
{
"port": "19099"
"ip":"127.0.0.1",
"url":"http://localhost:8080",
"timeout":"3000",
"enableHttp":"0"
}
```
响应:
``` javascript
{"code":200,"msg":"success","data":null}
```

View File

@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.0.0) cmake_minimum_required(VERSION 3.0.0)
project(ConsoleApplication VERSION 1.0.0) project(injector VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 17) 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) 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 ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin
OUTPUT_NAME "ConsoleApplication" OUTPUT_NAME "injector"
PREFIX "") PREFIX "")

View File

@ -981,7 +981,7 @@ int InjectDllByPid(unsigned int pid, wchar_t* szDllPath)
OutputDebugStringA("[DBG] dll inject success"); OutputDebugStringA("[DBG] dll inject success");
printf("dll inject success"); printf("dll inject success");
printf("dll path : %s ", szDllPath); printf("dll path : %s ", szDllPath);
printf("pid : %d ", pid); printf("dll path : %d ", pid);
result = 1; result = 1;
} }
else else

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

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

37
src/global_context.cc Normal file
View File

@ -0,0 +1,37 @@
#include "pch.h"
#include "global_context.h"
#include "thread_pool.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));
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

178
src/hooks.cc Normal file
View File

@ -0,0 +1,178 @@

#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();
return ret;
}
int UnHookSyncMsg() { return 1; }
} // 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

154
src/http_server_callback.cc Normal file
View File

@ -0,0 +1,154 @@
#include "pch.h"
#include "http_server_callback.h"
#include "http_server.h"
#include "export.h"
#include "global_context.h"
#include "hooks.h"
namespace common = wxhelper::common;
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 {
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

218
src/manager.cc Normal file
View File

@ -0,0 +1,218 @@
#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);
wchar_t** msg_pptr = &text_msg.ptr;
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;
}
} // namespace wxhelper`

18
src/manager.h Normal file
View File

@ -0,0 +1,18 @@
#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);
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

26
src/pch.h Normal file
View File

@ -0,0 +1,26 @@
#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>
#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

305
src/utils.cc Normal file
View File

@ -0,0 +1,305 @@
#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, DWORD 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, DWORD 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,int 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();
}
} // 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()
#define READ_WSTRING(addr, offset) ((*(DWORD *)(addr + offset + 0x4) == 0) ? std::wstring(L"") : std::wstring((wchar_t *)(*(DWORD *)(addr + offset)), *(DWORD *)(addr + offset + 0x4)))
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,
DWORD locale = CP_ACP);
static std::string WstringToAnsi(const std::wstring &input,
DWORD 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,int 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);
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

98
src/wechat_function.h Normal file
View File

@ -0,0 +1,98 @@
#ifndef WXHELPER_WECHAT_FUNCTION_H_
#define WXHELPER_WECHAT_FUNCTION_H_
namespace wxhelper {
namespace common {
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;
};
} // namespace common
namespace V3_9_5_81 {
namespace function {
typedef UINT64(*__GetAccountService)();
typedef UINT64(*__GetDataSavePath)(UINT64);
typedef UINT64(*__GetCurrentDataPath)(UINT64);
typedef void(*__GetSendMessageMgr)();
typedef UINT64 (*__SendTextMsg)(UINT64, UINT64, UINT64, UINT64, UINT64, UINT64,
UINT64, UINT64);
typedef void (*__FreeChatMsg)(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() * 2);
}
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) * 2);
}
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;
} // namespace offset
} // namespace V3_9_5_81
} // namespace wxhelper
#endif