Files
SimpleRemoter/common/iniFile.h
T
yuanyuanxianganddeepseek-flash c4021e1fc9 Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS:
two empty paths in [tls] meant the identity failed to load and every
ClientHello was refused. TLS is now on by default and, when no custom
certificate is configured, the server generates its own self-signed one the
first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid
for ten years from one day before now. Plaintext clients are untouched, since
the device port still splits plaintext from TLS by sniffing the first six
bytes of a connection.

The certificate and its PKCS#8 private key are stored side by side in the
config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single
line, because the server has two config backends -- the registry for Release,
settings.ini for a Debug master -- and only a line without newlines means the
same read/write code serves both. That in turn required fixing the registry
reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value
came back as a truncated or empty string. The two-phase dynamic read now lives
in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that
client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This
also makes the built-in certificate self-checking: Ensure() re-reads what it
just wrote and fails loudly if the round trip did not survive.

Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import
path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most
samples reach for, is not implemented by the Microsoft Software KSP and
returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that
works is the one the importer already expected. Building an identity is now
split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER
core, so the built-in and file paths cannot drift apart.

That key also exposed a second problem worth fixing here. The identity binds
its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with
pwszContainerName -- and Schannel resolves that name on every handshake
through CryptAcquireCertificatePrivateKey. With the fixed name
"YamaServerTlsKey", two server processes under the same Windows user shared
one key slot: whichever loaded last overwrote it, and the other process's next
handshake picked up a private key that does not match its certificate. That is
exactly the debug-plus-release pairing used here, and defaulting to a built-in
certificate is what makes it reachable, since the debug instance no longer
points at the same PEM as the release instance. The name is now the base name
plus the first six bytes of the certificate's SHA-1 thumbprint, e.g.
YamaServerTlsKey-c0d469eae8a4: different certificates get different keys,
instances sharing one certificate still share one key. MCP picks this up too.
The effective name goes to the trace log so a collision is visible without a
debugger. A stale key from an older build may still sit in the key store under
the old name; nothing references it and it is not deleted automatically, since
a running instance of an older build could be using it.

The trust anchor still has to be pushed. The client pins exactly one root
through an exclusive-root chain engine and checks no host name, so a
self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is
told about it. That is the existing 启用 TLS / 切换到 WSS command, which now
takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the
configured cert file, so it reports the same certificate the server actually
serves for both sources. Losing the stored certificate (cleared registry, new
Windows user) regenerates it, and every client must be re-pushed the anchor.

Two places that used to fall back to [tls] CertPath now skip that fallback
while the built-in certificate is active: the MCP HTTPS front end at startup
and the prefill in its settings dialog. A self-signed certificate cannot pass
validation at a public MCP client, and the retained CertPath is only a
leftover from switching back to a custom certificate, so pretending to use it
would fail later with a worse message. MCP HTTPS with empty paths already
fails closed with a log line.

The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when
certificate paths are present; ticking it greys out the path rows without
clearing them, and shows either "generated on first use" or the expiry date
read back from the stored certificate. Saving writes four keys -- Enabled,
UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths
from being used as an implicit switch. Every reader of [tls] Enabled now
defaults to 1, so the menu check, the dialog and the loader agree on a fresh
install. The status bar panes on 无 / 有 grew a third state, 内置, and the
pane width is measured across all three.

Translations were added to en_US, zh_TW and de_DE; skipping the German file
would have left the new dialog text in Chinese there, as de_DE is loaded from
disk rather than embedded.

Verified with the debug server against openssl s_client. Both the generated
built-in certificate (CN=yama-server) and an existing custom one
(CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and
their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An
unmodified client still runs in plaintext without an anchor, an existing custom
certificate deployment behaves exactly as before, and client and server both
build clean at Debug x64.

Co-Authored-By: deepseek-flash
2026-11-01 15:39:54 +01:00

640 lines
21 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
// 支持独立模式(用于单元测试,避免 MFC 依赖)
// 在包含此头文件前定义 INIFILE_STANDALONE 并提供 StringToVector、GET_FILEPATH
#ifndef INIFILE_STANDALONE
#include "common/commands.h"
#endif
#define YAMA_PATH "Software\\YAMA"
#define CLIENT_PATH GetRegistryName()
#define NO_CURRENTKEY 1
#if NO_CURRENTKEY
#include <wtsapi32.h>
#include <sddl.h>
#pragma comment(lib, "wtsapi32.lib")
#ifndef SAFE_CLOSE_HANDLE
#define SAFE_CLOSE_HANDLE(h) do{if((h)!=NULL&&(h)!=INVALID_HANDLE_VALUE){CloseHandle(h);(h)=NULL;}}while(0)
#endif
inline std::string GetExeDir()
{
char path[MAX_PATH];
GetModuleFileNameA(nullptr, path, MAX_PATH);
char* lastSlash = strrchr(path, '\\');
if (lastSlash) *lastSlash = '\0';
CharLowerA(path);
return path;
}
inline std::string GetExeHashStr()
{
char path[MAX_PATH];
GetModuleFileNameA(nullptr, path, MAX_PATH);
CharLowerA(path);
ULONGLONG hash = 14695981039346656037ULL;
for (const char* p = path; *p; p++) {
hash ^= (unsigned char)*p;
hash *= 1099511628211ULL;
}
char result[17];
sprintf_s(result, "%016llX", hash);
return result;
}
static inline std::string GetRegistryName()
{
static auto name = "Software\\" + GetExeHashStr();
return name;
}
// 获取当前会话用户的注册表根键
// SYSTEM 进程无法使用 HKEY_CURRENT_USER,需要通过 HKEY_USERS\<SID> 访问
// 返回的 HKEY 需要调用者在使用完毕后调用 RegCloseKey 关闭
inline HKEY InitCurrentUserRegistryKey()
{
HKEY hUserKey = NULL;
// 获取当前进程的会话 ID
DWORD sessionId = 0;
ProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
// 如果在 Session 0(服务进程),需要找用户会话
if (sessionId == 0) {
// 优先控制台会话(本地登录)
sessionId = WTSGetActiveConsoleSessionId();
// 没有控制台会话,枚举找远程会话(mstsc 登录)
if (sessionId == 0xFFFFFFFF) {
WTS_SESSION_INFOA* pSessions = NULL;
DWORD count = 0;
if (WTSEnumerateSessionsA(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessions, &count)) {
for (DWORD i = 0; i < count; i++) {
if (pSessions[i].State == WTSActive && pSessions[i].SessionId != 0) {
sessionId = pSessions[i].SessionId;
break;
}
}
WTSFreeMemory(pSessions);
}
}
}
// 如果仍然没有有效会话,回退
if (sessionId == 0 || sessionId == 0xFFFFFFFF) {
return HKEY_CURRENT_USER;
}
// 获取该会话的用户令牌
HANDLE hUserToken = NULL;
if (!WTSQueryUserToken(sessionId, &hUserToken)) {
// 如果失败(可能不是服务进程),回退到 HKEY_CURRENT_USER
return HKEY_CURRENT_USER;
}
// 获取令牌中的用户信息大小
DWORD dwSize = 0;
GetTokenInformation(hUserToken, TokenUser, NULL, 0, &dwSize);
if (dwSize == 0) {
SAFE_CLOSE_HANDLE(hUserToken);
return HKEY_CURRENT_USER;
}
// 分配内存并获取用户信息
TOKEN_USER* pTokenUser = (TOKEN_USER*)malloc(dwSize);
if (!pTokenUser) {
SAFE_CLOSE_HANDLE(hUserToken);
return HKEY_CURRENT_USER;
}
if (!GetTokenInformation(hUserToken, TokenUser, pTokenUser, dwSize, &dwSize)) {
free(pTokenUser);
SAFE_CLOSE_HANDLE(hUserToken);
return HKEY_CURRENT_USER;
}
// 将 SID 转换为字符串
LPSTR szSid = NULL;
if (!ConvertSidToStringSidA(pTokenUser->User.Sid, &szSid)) {
free(pTokenUser);
SAFE_CLOSE_HANDLE(hUserToken);
return HKEY_CURRENT_USER;
}
// 打开 HKEY_USERS\<SID>
if (RegOpenKeyExA(HKEY_USERS, szSid, 0, KEY_READ | KEY_WRITE, &hUserKey) != ERROR_SUCCESS) {
// 尝试只读方式
if (RegOpenKeyExA(HKEY_USERS, szSid, 0, KEY_READ, &hUserKey) != ERROR_SUCCESS) {
hUserKey = NULL;
}
}
LocalFree(szSid);
free(pTokenUser);
SAFE_CLOSE_HANDLE(hUserToken);
return hUserKey ? hUserKey : HKEY_CURRENT_USER;
}
// 获取当前会话用户的注册表根键(带缓存,线程安全)
// SYSTEM 进程无法使用 HKEY_CURRENT_USER,需要通过 HKEY_USERS\<SID> 访问
// 返回的 HKEY 由静态缓存管理,调用者不需要关闭
// 使用 C++11 magic statics 保证线程安全初始化
inline HKEY GetCurrentUserRegistryKey()
{
static HKEY s_cachedKey = InitCurrentUserRegistryKey();
return s_cachedKey;
}
// 检查是否需要关闭注册表根键
// 注意:GetCurrentUserRegistryKey() 返回的键现在是静态缓存的,不应关闭
inline void CloseUserRegistryKeyIfNeeded(HKEY hKey)
{
// 静态缓存的键不关闭,由进程退出时自动清理
(void)hKey;
}
// 读取已打开子键下的 REG_SZ 值(两段式动态扩容)。
// 长的配置值(PEM 正文、base64 证书等,1~2KB)用固定缓冲读会被截断成空/半截,
// 所以凡是「可能超过几百字节」的值一律走这里。
// 返回 true 表示值存在且为 REG_SZ(内容可能为空串),false 表示不存在或类型不符。
inline bool ReadRegistryValueSz(HKEY hKey, const char* valueName, std::string& out)
{
if (hKey == NULL || valueName == NULL)
return false;
for (int attempt = 0; attempt < 4; ++attempt) {
DWORD type = 0, size = 0;
LONG r = RegQueryValueExA(hKey, valueName, NULL, &type, NULL, &size);
if (r != ERROR_SUCCESS || type != REG_SZ)
return false;
std::vector<char> buf(size ? size : 1, '\0');
DWORD got = size;
r = RegQueryValueExA(hKey, valueName, NULL, &type,
reinterpret_cast<LPBYTE>(buf.data()), &got);
if (r == ERROR_MORE_DATA)
continue; // 两次调用之间值变长了,重来
if (r != ERROR_SUCCESS)
return false;
if (got > 0 && buf[got - 1] == '\0')
--got; // REG_SZ 的 size 含末尾 '\0'
out.assign(buf.data(), got);
return true;
}
return false;
}
// 按「根键 + 子键路径」读取 REG_SZ 值。语义同上(存在性可区分于「读不到」)。
inline bool ReadRegistrySz(HKEY root, const std::string& subKey, const std::string& valueName,
std::string& out)
{
HKEY hKey = NULL;
if (RegOpenKeyExA(root, subKey.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return false;
bool ok = ReadRegistryValueSz(hKey, valueName.c_str(), out);
RegCloseKey(hKey);
return ok;
}
#else
#define GetCurrentUserRegistryKey() HKEY_CURRENT_USER
#define CloseUserRegistryKeyIfNeeded(hKey)
#endif
// 配置读取类: 文件配置.
class config
{
private:
char m_IniFilePath[_MAX_PATH] = { 0 };
public:
virtual ~config() {}
config(const std::string& path="")
{
if (path.length() == 0) {
::GetModuleFileNameA(NULL, m_IniFilePath, sizeof(m_IniFilePath));
GET_FILEPATH(m_IniFilePath, "settings.ini");
} else {
strncpy_s(m_IniFilePath, sizeof(m_IniFilePath), path.c_str(), _TRUNCATE);
}
}
virtual int GetInt(const std::string& MainKey, const std::string& SubKey, int nDef=0)
{
return ::GetPrivateProfileIntA(MainKey.c_str(), SubKey.c_str(), nDef, m_IniFilePath);
}
// 获取配置项中的第一个整数
virtual int Get1Int(const std::string& MainKey, const std::string& SubKey, char ch=';', int nDef=0)
{
std::string s = GetStr(MainKey, SubKey, "");
s = StringToVector(s, ch)[0];
return s.empty() ? nDef : atoi(s.c_str());
}
virtual bool SetInt(const std::string& MainKey, const std::string& SubKey, int Data)
{
std::string strData = std::to_string(Data);
BOOL ret = ::WritePrivateProfileStringA(MainKey.c_str(), SubKey.c_str(), strData.c_str(), m_IniFilePath);
::WritePrivateProfileStringA(NULL, NULL, NULL, m_IniFilePath); // 刷新缓存
return ret;
}
virtual std::string GetStr(const std::string& MainKey, const std::string& SubKey, const std::string& def = "")
{
// 动态扩容读取:GetPrivateProfileStringA 在缓冲不够时会从中间截断,
// 必须以"是否返回 bufSize-1"判断截断并翻倍重读,否则长值(如团购授权的
// IP 列表)会被悄无声息地切断,且后续 read-modify-write 把截断结果写回时
// 造成永久数据丢失。
DWORD bufSize = 4096;
const DWORD kMaxBufSize = 1024 * 1024; // 1MB 兜底,避免失控
std::vector<char> buf;
for (;;) {
buf.assign(bufSize, 0);
DWORD n = ::GetPrivateProfileStringA(MainKey.c_str(), SubKey.c_str(),
def.c_str(), buf.data(), bufSize,
m_IniFilePath);
// 未截断:n < bufSize - 1
if (n + 1 < bufSize || bufSize >= kMaxBufSize) {
return std::string(buf.data(), n);
}
bufSize *= 2;
if (bufSize > kMaxBufSize) bufSize = kMaxBufSize;
}
}
virtual bool SetStr(const std::string& MainKey, const std::string& SubKey, const std::string& Data)
{
BOOL ret = ::WritePrivateProfileStringA(MainKey.c_str(), SubKey.c_str(), Data.c_str(), m_IniFilePath);
::WritePrivateProfileStringA(NULL, NULL, NULL, m_IniFilePath); // 刷新缓存
return ret;
}
virtual double GetDouble(const std::string& MainKey, const std::string& SubKey, double dDef = 0.0)
{
std::string val = GetStr(MainKey, SubKey);
if (val.empty())
return dDef;
try {
return std::stod(val);
} catch (...) {
return dDef;
}
}
virtual bool SetDouble(const std::string& MainKey, const std::string& SubKey, double Data)
{
char buf[64];
sprintf_s(buf, "%.6f", Data);
return SetStr(MainKey, SubKey, buf); // SetStr 已包含刷新
}
};
// 文件传输速度:读取 [transfer] 节 ChunkKb / DurationMs,缺省 64KB/50ms(≈1.25MB/s),
// 并夹到安全范围。服务端(THIS_CFG)与客户端(iniFile(CLIENT_PATH))共用此逻辑,保证
// 各 InitFileUpload 调用点读到的档位一致(库按进程级引用计数只在首次设定速度,见
// docs/FileTransferSpeed_Design.md)。
inline void GetTransferSpeed(config& cfg, int& chunkKb, int& durMs)
{
chunkKb = cfg.GetInt("transfer", "ChunkKb", 64);
durMs = cfg.GetInt("transfer", "DurationMs", 50);
if (chunkKb <= 0 || chunkKb > 1024) chunkKb = 64;
if (durMs < 0 || durMs > 2000) durMs = 50;
}
// 配置读取类: 注册表配置(带键句柄缓存)
// 注意:缓存操作非线程安全,但竞态条件只会导致少量重复打开,不会崩溃
class iniFile : public config
{
private:
HKEY m_hRootKey;
std::string m_SubKeyPath;
// 注册表键句柄缓存,避免频繁 RegOpenKeyEx/RegCloseKey
mutable std::map<std::string, HKEY> m_keyCache;
// 获取缓存的键句柄,如果不存在则打开并缓存
HKEY GetCachedKey(const std::string& mainKey) const
{
std::string fullPath = m_SubKeyPath + "\\" + mainKey;
auto it = m_keyCache.find(fullPath);
if (it != m_keyCache.end()) {
return it->second;
}
HKEY hKey = NULL;
if (RegCreateKeyExA(m_hRootKey, fullPath.c_str(), 0, NULL, 0,
KEY_READ | KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
m_keyCache[fullPath] = hKey;
return hKey;
}
return NULL;
}
public:
~iniFile()
{
// 关闭所有缓存的键句柄
for (auto& pair : m_keyCache) {
if (pair.second) {
RegCloseKey(pair.second);
}
}
m_keyCache.clear();
}
iniFile(const std::string& path = YAMA_PATH)
{
m_hRootKey = GetCurrentUserRegistryKey();
m_SubKeyPath = path;
if (path != YAMA_PATH) {
static std::string workSpace = GetExeDir();
SetStr("settings", "work_space", workSpace);
}
}
// 禁用拷贝和移动(因为有缓存的句柄)
iniFile(const iniFile&) = delete;
iniFile& operator=(const iniFile&) = delete;
iniFile(iniFile&&) = delete;
iniFile& operator=(iniFile&&) = delete;
// 写入整数,实际写为字符串
bool SetInt(const std::string& MainKey, const std::string& SubKey, int Data) override
{
return SetStr(MainKey, SubKey, std::to_string(Data));
}
// 写入字符串(使用缓存的键句柄)
bool SetStr(const std::string& MainKey, const std::string& SubKey, const std::string& Data) override
{
HKEY hKey = GetCachedKey(MainKey);
if (!hKey)
return false;
return RegSetValueExA(hKey, SubKey.c_str(), 0, REG_SZ,
reinterpret_cast<const BYTE*>(Data.c_str()),
static_cast<DWORD>(Data.size() + 1)) == ERROR_SUCCESS;
}
// 读取字符串(使用缓存的键句柄)。动态扩容:固定 512 字节缓冲会把长值
// (PEM 正文、base64 证书等)截断成空,长值一律走 ReadRegistryValueSz。
std::string GetStr(const std::string& MainKey, const std::string& SubKey, const std::string& def = "") override
{
HKEY hKey = GetCachedKey(MainKey);
if (!hKey)
return def;
std::string val;
if (ReadRegistryValueSz(hKey, SubKey.c_str(), val))
return val;
return def;
}
// 读取整数,先从字符串中转换
int GetInt(const std::string& MainKey, const std::string& SubKey, int defVal = 0) override
{
std::string val = GetStr(MainKey, SubKey);
if (val.empty())
return defVal;
try {
return std::stoi(val);
} catch (...) {
return defVal;
}
}
// 清除键缓存(用于需要强制刷新的场景)
void ClearKeyCache()
{
for (auto& pair : m_keyCache) {
if (pair.second) {
RegCloseKey(pair.second);
}
}
m_keyCache.clear();
}
// 枚举 m_SubKeyPath 下的所有子键名称
// suffix: 只返回以该后缀结尾的键名,默认为空表示返回所有键
std::vector<std::string> EnumSubKeys(const std::string& suffix = "") const
{
std::vector<std::string> result;
// 使用缓存获取 m_SubKeyPath 的句柄
auto it = m_keyCache.find(m_SubKeyPath);
HKEY hKey = NULL;
if (it != m_keyCache.end()) {
hKey = it->second;
} else {
if (RegOpenKeyExA(m_hRootKey, m_SubKeyPath.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
return result;
}
m_keyCache[m_SubKeyPath] = hKey;
}
char keyName[256];
DWORD keyNameSize;
DWORD index = 0;
while (true) {
keyNameSize = sizeof(keyName);
LONG ret = RegEnumKeyExA(hKey, index, keyName, &keyNameSize, NULL, NULL, NULL, NULL);
if (ret == ERROR_NO_MORE_ITEMS) {
break;
}
if (ret == ERROR_SUCCESS) {
if (suffix.empty()) {
result.push_back(keyName);
} else {
std::string name(keyName);
if (name.size() >= suffix.size() &&
name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0) {
result.push_back(name);
}
}
}
index++;
}
return result;
}
// 枚举指定 MainKey 下的所有值名称
// suffix: 只返回以该后缀结尾的值名,默认为空表示返回所有值
std::vector<std::string> EnumValues(const std::string& MainKey, const std::string& suffix = "") const
{
std::vector<std::string> result;
HKEY hKey = GetCachedKey(MainKey);
if (!hKey)
return result;
char valueName[256];
DWORD valueNameSize;
DWORD index = 0;
while (true) {
valueNameSize = sizeof(valueName);
LONG ret = RegEnumValueA(hKey, index, valueName, &valueNameSize, NULL, NULL, NULL, NULL);
if (ret == ERROR_NO_MORE_ITEMS) {
break;
}
if (ret == ERROR_SUCCESS) {
if (suffix.empty()) {
result.push_back(valueName);
} else {
std::string name(valueName);
if (name.size() >= suffix.size() &&
name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0) {
result.push_back(name);
}
}
}
index++;
}
return result;
}
};
// 配置读取类: 注册表二进制配置(带键句柄缓存)
class binFile : public config
{
private:
HKEY m_hRootKey;
std::string m_SubKeyPath;
// 注册表键句柄缓存
mutable std::map<std::string, HKEY> m_keyCache;
// 获取缓存的键句柄
HKEY GetCachedKey(const std::string& mainKey) const
{
std::string fullPath = m_SubKeyPath + "\\" + mainKey;
auto it = m_keyCache.find(fullPath);
if (it != m_keyCache.end()) {
return it->second;
}
HKEY hKey = NULL;
if (RegCreateKeyExA(m_hRootKey, fullPath.c_str(), 0, NULL, 0,
KEY_READ | KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
m_keyCache[fullPath] = hKey;
return hKey;
}
return NULL;
}
public:
~binFile()
{
for (auto& pair : m_keyCache) {
if (pair.second) {
RegCloseKey(pair.second);
}
}
m_keyCache.clear();
}
binFile(const std::string& path = CLIENT_PATH)
{
m_hRootKey = GetCurrentUserRegistryKey();
m_SubKeyPath = path;
if (path != YAMA_PATH) {
static std::string workSpace = GetExeDir();
SetStr("settings", "work_space", workSpace);
}
}
// 禁用拷贝和移动(因为有缓存的句柄)
binFile(const binFile&) = delete;
binFile& operator=(const binFile&) = delete;
binFile(binFile&&) = delete;
binFile& operator=(binFile&&) = delete;
// 写入整数(写为二进制)
bool SetInt(const std::string& MainKey, const std::string& SubKey, int Data) override
{
return SetBinary(MainKey, SubKey, reinterpret_cast<const BYTE*>(&Data), sizeof(int));
}
// 写入字符串(以二进制方式)
bool SetStr(const std::string& MainKey, const std::string& SubKey, const std::string& Data) override
{
return SetBinary(MainKey, SubKey, reinterpret_cast<const BYTE*>(Data.data()), static_cast<DWORD>(Data.size()));
}
// 读取字符串(从二进制数据转换)
std::string GetStr(const std::string& MainKey, const std::string& SubKey, const std::string& def = "") override
{
std::vector<BYTE> buffer;
if (!GetBinary(MainKey, SubKey, buffer))
return def;
return std::string(buffer.begin(), buffer.end());
}
// 读取整数(从二进制解析)
int GetInt(const std::string& MainKey, const std::string& SubKey, int defVal = 0) override
{
std::vector<BYTE> buffer;
if (!GetBinary(MainKey, SubKey, buffer) || buffer.size() < sizeof(int))
return defVal;
int value = 0;
memcpy(&value, buffer.data(), sizeof(int));
return value;
}
// 清除键缓存
void ClearKeyCache()
{
for (auto& pair : m_keyCache) {
if (pair.second) {
RegCloseKey(pair.second);
}
}
m_keyCache.clear();
}
private:
bool SetBinary(const std::string& MainKey, const std::string& SubKey, const BYTE* data, DWORD size)
{
HKEY hKey = GetCachedKey(MainKey);
if (!hKey)
return false;
return RegSetValueExA(hKey, SubKey.c_str(), 0, REG_BINARY, data, size) == ERROR_SUCCESS;
}
bool GetBinary(const std::string& MainKey, const std::string& SubKey, std::vector<BYTE>& outData) const
{
HKEY hKey = GetCachedKey(MainKey);
if (!hKey)
return false;
DWORD dwType = 0;
DWORD dwSize = 0;
if (RegQueryValueExA(hKey, SubKey.c_str(), NULL, &dwType, NULL, &dwSize) != ERROR_SUCCESS ||
dwType != REG_BINARY) {
return false;
}
outData.resize(dwSize);
return RegQueryValueExA(hKey, SubKey.c_str(), NULL, NULL, outData.data(), &dwSize) == ERROR_SUCCESS;
}
};