Files
crown/Update/Utils.cpp
T

479 lines
17 KiB
C++

#include "Utils.h"
#include <bcrypt.h>
#include <tlhelp32.h>
#include <objidl.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <algorithm>
#include <cstdio>
#include <cwchar>
#include <vector>
#pragma comment(lib, "bcrypt.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "uuid.lib")
namespace updater {
std::wstring Utils::Utf8ToWide(const std::string& s) {
if (s.empty()) return std::wstring();
int len = MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), nullptr, 0);
if (len <= 0) return std::wstring();
std::wstring out(static_cast<size_t>(len), L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), &out[0], len);
return out;
}
std::string Utils::WideToUtf8(const std::wstring& s) {
if (s.empty()) return std::string();
int len = WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast<int>(s.size()),
nullptr, 0, nullptr, nullptr);
if (len <= 0) return std::string();
std::string out(static_cast<size_t>(len), '\0');
WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast<int>(s.size()), &out[0], len,
nullptr, nullptr);
return out;
}
std::wstring Utils::CodePageToWide(const std::string& s, UINT codePage) {
if (s.empty()) return std::wstring();
int len = MultiByteToWideChar(codePage, 0, s.data(), static_cast<int>(s.size()), nullptr, 0);
if (len <= 0) return std::wstring();
std::wstring out(static_cast<size_t>(len), L'\0');
MultiByteToWideChar(codePage, 0, s.data(), static_cast<int>(s.size()), &out[0], len);
return out;
}
bool Utils::IsValidUtf8(const std::string& s) {
size_t i = 0;
while (i < s.size()) {
unsigned char c = static_cast<unsigned char>(s[i]);
size_t extra;
unsigned int cp;
if (c < 0x80) { i++; continue; }
if ((c & 0xE0) == 0xC0) { extra = 1; cp = c & 0x1F; }
else if ((c & 0xF0) == 0xE0) { extra = 2; cp = c & 0x0F; }
else if ((c & 0xF8) == 0xF0) { extra = 3; cp = c & 0x07; }
else return false;
if (i + extra >= s.size()) return false;
for (size_t k = 1; k <= extra; ++k) {
unsigned char cc = static_cast<unsigned char>(s[i + k]);
if ((cc & 0xC0) != 0x80) return false;
cp = (cp << 6) | (cc & 0x3F);
}
if (cp > 0x10FFFF) return false;
if (cp >= 0xD800 && cp <= 0xDFFF) return false;
if (extra == 1 && cp < 0x80) return false;
if (extra == 2 && cp < 0x800) return false;
if (extra == 3 && cp < 0x10000) return false;
i += extra + 1;
}
return true;
}
std::wstring Utils::DecodeEntryName(const std::string& raw) {
if (IsValidUtf8(raw)) return Utf8ToWide(raw);
return CodePageToWide(raw, 936);
}
std::wstring Utils::GetModuleDir() {
wchar_t buf[MAX_PATH] = {0};
GetModuleFileNameW(nullptr, buf, MAX_PATH);
std::wstring full(buf);
size_t pos = full.find_last_of(L"\\/");
if (pos == std::wstring::npos) return L".";
return full.substr(0, pos);
}
std::wstring Utils::GetTempDir() {
wchar_t buf[MAX_PATH] = {0};
if (GetTempPathW(MAX_PATH, buf) == 0) return L".";
std::wstring path(buf);
while (!path.empty() && (path.back() == L'\\' || path.back() == L'/')) path.pop_back();
return path;
}
std::wstring Utils::JoinPath(const std::wstring& dir, const std::wstring& rel) {
if (dir.empty()) return rel;
if (rel.empty()) return dir;
wchar_t last = dir.back();
if (last == L'\\' || last == L'/') return dir + rel;
return dir + L"\\" + rel;
}
std::wstring Utils::GetParentDir(const std::wstring& path) {
size_t pos = path.find_last_of(L"\\/");
if (pos == std::wstring::npos) return std::wstring();
return path.substr(0, pos);
}
std::wstring Utils::Trim(const std::wstring& s) {
size_t b = 0, e = s.size();
while (b < e && (s[b] == L' ' || s[b] == L'\t' || s[b] == L'\r' || s[b] == L'\n')) ++b;
while (e > b && (s[e - 1] == L' ' || s[e - 1] == L'\t' || s[e - 1] == L'\r' || s[e - 1] == L'\n')) --e;
return s.substr(b, e - b);
}
std::wstring Utils::NormalizeSlashes(std::wstring path) {
std::replace(path.begin(), path.end(), L'/', L'\\');
return path;
}
bool Utils::CreateDirRecursive(const std::wstring& dir) {
if (dir.empty()) return false;
if (DirExists(dir)) return true;
std::wstring parent = GetParentDir(dir);
if (!parent.empty() && parent != dir) CreateDirRecursive(parent);
return CreateDirectoryW(dir.c_str(), nullptr) != FALSE || GetLastError() == ERROR_ALREADY_EXISTS;
}
bool Utils::FileExists(const std::wstring& path) {
DWORD attr = GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY);
}
bool Utils::DirExists(const std::wstring& path) {
DWORD attr = GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
bool Utils::DeleteFileForce(const std::wstring& path) {
SetFileAttributesW(path.c_str(), FILE_ATTRIBUTE_NORMAL);
return DeleteFileW(path.c_str()) != FALSE;
}
std::wstring Utils::MakeUniqueTempFile(const std::wstring& dir, const std::wstring& prefix) {
for (int i = 0; i < 100; ++i) {
wchar_t name[MAX_PATH];
swprintf_s(name, MAX_PATH, L"%s_%lu_%d.tmp", prefix.c_str(), GetCurrentProcessId(), i);
std::wstring full = JoinPath(dir, name);
HANDLE h = CreateFileW(full.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h != INVALID_HANDLE_VALUE) {
CloseHandle(h);
DeleteFileW(full.c_str());
return full;
}
if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_ALREADY_EXISTS) break;
}
wchar_t name[MAX_PATH];
swprintf_s(name, MAX_PATH, L"%s_%lu.tmp", prefix.c_str(), GetTickCount());
return JoinPath(dir, name);
}
std::wstring Utils::FormatSize(unsigned long long bytes) {
const wchar_t* units[] = {L"B", L"KB", L"MB", L"GB"};
double value = static_cast<double>(bytes);
int unit = 0;
while (value >= 1024.0 && unit < 3) {
value /= 1024.0;
++unit;
}
wchar_t buf[64];
if (unit == 0) swprintf_s(buf, 64, L"%llu %s", bytes, units[unit]);
else swprintf_s(buf, 64, L"%.1f %s", value, units[unit]);
return std::wstring(buf);
}
std::wstring Utils::FormatSpeed(unsigned long long bytesPerSec) {
return FormatSize(bytesPerSec) + L"/s";
}
std::string Utils::Sha256Hex(const void* data, size_t size) {
std::string result;
BCRYPT_ALG_HANDLE hAlg = nullptr;
if (BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) return result;
BCRYPT_HASH_HANDLE hHash = nullptr;
if (BCryptCreateHash(hAlg, &hHash, nullptr, 0, nullptr, 0, 0) < 0) {
BCryptCloseAlgorithmProvider(hAlg, 0);
return result;
}
if (data && size) BCryptHashData(hHash, const_cast<PUCHAR>(static_cast<const BYTE*>(data)),
static_cast<ULONG>(size), 0);
BYTE hash[32] = {0};
if (BCryptFinishHash(hHash, hash, sizeof(hash), 0) >= 0) {
static const char* hex = "0123456789abcdef";
for (int i = 0; i < 32; ++i) {
result += hex[(hash[i] >> 4) & 0xF];
result += hex[hash[i] & 0xF];
}
}
BCryptDestroyHash(hHash);
BCryptCloseAlgorithmProvider(hAlg, 0);
return result;
}
std::string Utils::Sha256HexFile(const std::wstring& path) {
HANDLE hFile = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) return std::string();
BCRYPT_ALG_HANDLE hAlg = nullptr;
if (BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) {
CloseHandle(hFile);
return std::string();
}
BCRYPT_HASH_HANDLE hHash = nullptr;
if (BCryptCreateHash(hAlg, &hHash, nullptr, 0, nullptr, 0, 0) < 0) {
BCryptCloseAlgorithmProvider(hAlg, 0);
CloseHandle(hFile);
return std::string();
}
const DWORD bufSize = 64 * 1024;
std::vector<BYTE> buffer(bufSize);
DWORD read = 0;
while (ReadFile(hFile, buffer.data(), bufSize, &read, nullptr) && read > 0) {
BCryptHashData(hHash, buffer.data(), read, 0);
}
CloseHandle(hFile);
BYTE hash[32] = {0};
std::string result;
if (BCryptFinishHash(hHash, hash, sizeof(hash), 0) >= 0) {
static const char* hex = "0123456789abcdef";
for (int i = 0; i < 32; ++i) {
result += hex[(hash[i] >> 4) & 0xF];
result += hex[hash[i] & 0xF];
}
}
BCryptDestroyHash(hHash);
BCryptCloseAlgorithmProvider(hAlg, 0);
return result;
}
std::string Utils::ToLowerAscii(const std::string& s) {
std::string out = s;
std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) {
return static_cast<char>((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c);
});
return out;
}
std::wstring Utils::UrlEncode(const std::wstring& s) {
std::string utf8 = WideToUtf8(s);
static const char* hex = "0123456789ABCDEF";
std::string out;
for (unsigned char c : utf8) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.' || c == '~') {
out += static_cast<char>(c);
} else {
out += '%';
out += hex[(c >> 4) & 0xF];
out += hex[c & 0xF];
}
}
return Utf8ToWide(out);
}
bool Utils::IsAbsoluteUrl(const std::wstring& url) {
if (url.size() >= 7 && _wcsnicmp(url.c_str(), L"http://", 7) == 0) return true;
if (url.size() >= 8 && _wcsnicmp(url.c_str(), L"https://", 8) == 0) return true;
return false;
}
bool Utils::LaunchProcess(const std::wstring& exe, const std::wstring& args,
const std::wstring& workDir) {
if (exe.empty()) return false;
// 用 CreateProcess 而不是 ShellExecute:后者在目标不存在时会弹系统错误对话框,
// 更新器会一直卡在等用户点确定的状态,退出码也就回不来了
std::wstring cmd = L"\"" + exe + L"\"";
if (!args.empty()) cmd += L" " + args;
std::vector<wchar_t> cmdBuf(cmd.begin(), cmd.end());
cmdBuf.push_back(L'\0');
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWNORMAL;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
BOOL ok = CreateProcessW(nullptr, cmdBuf.data(), nullptr, nullptr, FALSE, 0, nullptr,
workDir.empty() ? nullptr : workDir.c_str(), &si, &pi);
if (!ok) return false;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return true;
}
bool Utils::WaitForProcessExit(const std::wstring& processName, int timeoutSec) {
DWORD ticks = GetTickCount();
DWORD limit = static_cast<DWORD>(timeoutSec) * 1000;
while (GetTickCount() - ticks < limit) {
bool found = false;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap != INVALID_HANDLE_VALUE) {
PROCESSENTRY32W pe = {0};
pe.dwSize = sizeof(pe);
if (Process32FirstW(snap, &pe)) {
do {
if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) { found = true; break; }
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
}
if (!found) return true;
Sleep(300);
}
return false;
}
namespace {
// 向属于指定 PID 的窗口投递 WM_CLOSE,让程序有机会保存数据后自行退出
BOOL CALLBACK PostCloseToProcessWindows(HWND hwnd, LPARAM lparam) {
DWORD pid = 0;
GetWindowThreadProcessId(hwnd, &pid);
if (pid != 0 && pid == static_cast<DWORD>(lparam)) {
PostMessageW(hwnd, WM_CLOSE, 0, 0);
}
return TRUE;
}
std::vector<DWORD> FindProcessIds(const std::wstring& processName) {
std::vector<DWORD> pids;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return pids;
PROCESSENTRY32W pe = {0};
pe.dwSize = sizeof(pe);
if (Process32FirstW(snap, &pe)) {
do {
if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
pids.push_back(pe.th32ProcessID);
}
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
return pids;
}
bool IsProcessAlive(DWORD pid) {
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!h) return false;
DWORD code = 0;
bool alive = (GetExitCodeProcess(h, &code) != FALSE && code == STILL_ACTIVE);
CloseHandle(h);
return alive;
}
} // namespace
bool Utils::CloseProcesses(const std::wstring& processName, int timeoutSec) {
std::vector<DWORD> pids = FindProcessIds(processName);
if (pids.empty()) return true;
// 先请它们自己退出,给保存数据的机会
for (size_t i = 0; i < pids.size(); ++i) {
EnumWindows(PostCloseToProcessWindows, static_cast<LPARAM>(pids[i]));
}
DWORD ticks = GetTickCount();
DWORD limit = static_cast<DWORD>(timeoutSec) * 1000;
while (GetTickCount() - ticks < limit) {
bool alive = false;
for (size_t i = 0; i < pids.size(); ++i) {
if (IsProcessAlive(pids[i])) { alive = true; break; }
}
if (!alive) return true;
Sleep(100);
}
// 超时仍未退出的强制结束:运行中的 EXE 无法被覆盖,
// 不结束掉的话整个更新会在复制文件时失败
for (size_t i = 0; i < pids.size(); ++i) {
if (!IsProcessAlive(pids[i])) continue;
HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
if (h) {
TerminateProcess(h, 0);
CloseHandle(h);
}
}
// 强制结束后再确认一次
ticks = GetTickCount();
while (GetTickCount() - ticks < 3000) {
bool alive = false;
for (size_t i = 0; i < pids.size(); ++i) {
if (IsProcessAlive(pids[i])) { alive = true; break; }
}
if (!alive) return true;
Sleep(100);
}
return false;
}
std::wstring Utils::GetDesktopDir() {
PWSTR path = nullptr;
if (SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &path) != S_OK) return std::wstring();
std::wstring dir = path;
CoTaskMemFree(path);
return dir;
}
bool Utils::CreateDesktopShortcut(const std::wstring& targetPath, const std::wstring& linkName) {
if (linkName.empty() || !FileExists(targetPath)) return false;
std::wstring dir = GetDesktopDir();
if (dir.empty()) return false;
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
bool needUninit = SUCCEEDED(hr);
// RPC_E_CHANGED_MODE 说明调用方已经初始化过 COM,用它的,不要在这里反初始化
if (!needUninit && hr != RPC_E_CHANGED_MODE) return false;
bool ok = false;
IShellLinkW* link = nullptr;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, reinterpret_cast<void**>(&link)))) {
link->SetPath(targetPath.c_str());
link->SetWorkingDirectory(GetParentDir(targetPath).c_str());
IPersistFile* persist = nullptr;
if (SUCCEEDED(link->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&persist)))) {
std::wstring shortcut = JoinPath(dir, linkName + L".lnk");
ok = SUCCEEDED(persist->Save(shortcut.c_str(), TRUE));
persist->Release();
}
link->Release();
}
if (needUninit) CoUninitialize();
return ok;
}
bool Utils::ReplaceInUse(const std::wstring& srcTmp, const std::wstring& target) {
if (MoveFileExW(srcTmp.c_str(), target.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE) {
return true;
}
std::wstring old = target + L".old";
MoveFileExW(target.c_str(), old.c_str(), MOVEFILE_REPLACE_EXISTING);
if (MoveFileExW(srcTmp.c_str(), target.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE) {
// 正在运行的映像无法直接删除(例如更新器替换自身),交给系统重启时清理
if (DeleteFileW(old.c_str()) == FALSE) {
MoveFileExW(old.c_str(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT);
}
return true;
}
if (MoveFileExW(srcTmp.c_str(), target.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT) != FALSE) {
return false;
}
return false;
}
}