Files
crown/Update/Worker.cpp
T
admin 5932fdcea3 更新前关闭同套程序进程,避免 EXE 被占用导致覆盖失败
更新包同时包含 CrownServer.exe 和 CrownClient.exe,运行中的 EXE 无法被覆盖。CrownServer/CrownClient 拉起更新器前先结束对方进程,先投递 WM_CLOSE 给保存机会,超时后强制结束;Update 新增 Utils::CloseProcesses,手动运行更新器时同样关闭,进程名与超时见 Config.h。
2026-10-18 18:41:33 +08:00

382 lines
12 KiB
C++

#include "Worker.h"
#include "Api.h"
#include "Config.h"
#include "Http.h"
#include "Unzip.h"
#include "Utils.h"
#include <windows.h>
#include <process.h>
#include <string>
#include <vector>
#pragma comment(lib, "shlwapi.lib")
namespace updater {
namespace {
void CollectFiles(const std::wstring& dir, const std::wstring& relBase,
std::vector<std::wstring>& files, std::vector<std::wstring>& dirs) {
WIN32_FIND_DATAW data;
std::wstring pattern = dir;
if (!pattern.empty() && pattern.back() != L'\\') pattern += L'\\';
pattern += L"*";
HANDLE handle = FindFirstFileW(pattern.c_str(), &data);
if (handle == INVALID_HANDLE_VALUE) return;
do {
std::wstring name = data.cFileName;
if (name == L"." || name == L"..") continue;
std::wstring rel = relBase.empty() ? name : relBase + L"\\" + name;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
dirs.push_back(rel);
CollectFiles(dir + L"\\" + name, rel, files, dirs);
} else {
files.push_back(rel);
}
} while (FindNextFileW(handle, &data));
FindClose(handle);
}
std::vector<std::wstring> SplitProcessNames(const std::wstring& text) {
std::vector<std::wstring> names;
std::wstring current;
for (size_t i = 0; i < text.size(); ++i) {
wchar_t c = text[i];
if (c == L',' || c == L';') {
std::wstring name = Utils::Trim(current);
if (!name.empty()) names.push_back(name);
current.clear();
} else {
current += c;
}
}
std::wstring name = Utils::Trim(current);
if (!name.empty()) names.push_back(name);
return names;
}
bool SameHash(const std::wstring& expected, const std::string& actual) {
std::string want = Utils::WideToUtf8(expected);
if (want.empty()) return true;
return Utils::ToLowerAscii(want) == Utils::ToLowerAscii(actual);
}
}
Worker::Worker() : cancel_(false), running_(false) {}
Worker::~Worker() {
Cancel();
if (thread_) {
WaitForSingleObject(thread_, 5000);
CloseHandle(thread_);
thread_ = nullptr;
}
}
unsigned __stdcall Worker::ThreadEntry(void* param) {
Worker* worker = static_cast<Worker*>(param);
worker->Run();
_endthreadex(0);
return 0;
}
void Worker::Cancel() {
cancel_.store(true);
}
void Worker::Emit(int percent, const std::wstring& text) {
if (onState_) onState_(percent, text);
}
void Worker::Finish(bool success, const std::wstring& text) {
running_.store(false);
if (onFinish_) onFinish_(success, text);
}
void Worker::Start(const UpdateOptions& options, StateCallback onState, FinishCallback onFinish) {
options_ = options;
onState_ = onState;
onFinish_ = onFinish;
cancel_.store(false);
running_.store(true);
if (thread_) {
CloseHandle(thread_);
thread_ = nullptr;
}
thread_ = reinterpret_cast<void*>(_beginthreadex(nullptr, 0, &Worker::ThreadEntry, this, 0, nullptr));
if (!thread_) {
running_.store(false);
Finish(false, L"无法创建工作线程");
}
}
bool Worker::CopyToTarget(const std::wstring& staging, const std::wstring& targetDir,
std::wstring& err) {
std::vector<std::wstring> files;
std::vector<std::wstring> dirs;
CollectFiles(staging, L"", files, dirs);
if (!Utils::CreateDirRecursive(targetDir)) {
err = L"无法创建目录:" + targetDir;
return false;
}
for (size_t i = 0; i < dirs.size(); ++i) {
std::wstring dst = Utils::JoinPath(targetDir, dirs[i]);
if (!Utils::CreateDirRecursive(dst)) {
err = L"无法创建目录:" + dst;
return false;
}
}
for (size_t i = 0; i < files.size(); ++i) {
if (cancel_.load()) {
err = L"已取消";
return false;
}
int percent = 92 + static_cast<int>((i + 1) * 6 / (files.size() + 1));
Emit(percent, L"正在更新文件 (" + std::to_wstring(i + 1) + L"/" +
std::to_wstring(files.size()) + L")");
std::wstring src = Utils::JoinPath(staging, files[i]);
std::wstring dst = Utils::JoinPath(targetDir, files[i]);
if (Utils::FileExists(dst)) {
if (CopyFileW(src.c_str(), dst.c_str(), FALSE)) continue;
// 目标文件可能被占用,改用延时替换
std::wstring tmp = dst + L".updater.tmp";
Utils::DeleteFileForce(tmp);
if (!CopyFileW(src.c_str(), tmp.c_str(), FALSE)) {
err = L"无法写入文件:" + dst;
return false;
}
if (!Utils::ReplaceInUse(tmp, dst)) {
Utils::DeleteFileForce(tmp);
err = L"文件被占用,无法替换:" + dst;
return false;
}
continue;
}
if (!CopyFileW(src.c_str(), dst.c_str(), TRUE)) {
err = L"无法写入文件:" + dst;
return false;
}
}
return true;
}
void Worker::Run() {
std::wstring targetDir = options_.targetDir;
if (targetDir.empty()) targetDir = UPDATER_TARGET_DIR;
if (targetDir.empty()) targetDir = Utils::GetModuleDir();
Emit(2, L"正在准备更新...");
#if UPDATER_WAIT_EXIT_SEC > 0
std::wstring waitName = options_.launchExe.empty() ? UPDATER_LAUNCH_EXE : options_.launchExe;
if (!waitName.empty()) {
Emit(3, L"正在等待主程序退出...");
Utils::WaitForProcessExit(waitName, UPDATER_WAIT_EXIT_SEC);
}
#endif
if (cancel_.load()) { Finish(false, L"已取消"); return; }
Emit(5, L"正在检查更新...");
Api::Result result = Api::CheckUpdate(options_.appKey, options_.clientVersion);
if (!result.ok) {
Finish(false, result.error);
return;
}
UpdateInfo& info = result.info;
if (!info.hasUpdate) {
Finish(true, L"当前已是最新版本,无需更新");
return;
}
// 更新包同时包含多个 EXE,正在运行的无法被覆盖。
// 手动运行更新器时这些进程可能还在跑,必须先让它们退出
std::vector<std::wstring> closeNames = SplitProcessNames(UPDATER_CLOSE_PROCESSES);
for (size_t i = 0; i < closeNames.size(); ++i) {
if (cancel_.load()) { Finish(false, L"已取消"); return; }
Emit(8, L"正在关闭 " + closeNames[i] + L"...");
if (!Utils::CloseProcesses(closeNames[i], UPDATER_CLOSE_TIMEOUT_SEC)) {
Emit(8, L"无法关闭 " + closeNames[i] + L",更新可能无法完成");
}
}
// 选择要下载的包:全量模式取完整包,补丁模式优先取补丁包
std::wstring url;
unsigned long long size = 0;
std::wstring hash;
std::wstring modeText;
bool stripRoot = false;
if (options_.fullMode) {
url = info.fullPackageUrl;
size = info.fullPackageSize;
hash = info.fullPackageHash;
modeText = L"完整包";
stripRoot = true;
if (url.empty()) {
url = info.downloadUrl;
size = info.downloadSize;
hash = info.downloadHash;
}
} else {
if (info.isPatch && !info.patchUrl.empty()) {
url = info.patchUrl;
size = info.patchSize;
hash = info.patchHash;
modeText = L"补丁包";
} else {
// 没有补丁包信息时,download_url 就是完整包(服务端 update_type 恒为 patch,不能用来判断)
url = info.downloadUrl;
size = info.downloadSize;
hash = info.downloadHash;
modeText = L"完整包";
stripRoot = true;
}
}
if (url.empty()) {
Finish(false, L"服务器没有返回下载地址");
return;
}
std::wstring versionText = info.latestVersion.empty() ? L"" : L" (" + info.latestVersion + L")";
Emit(8, L"开始下载" + modeText + versionText + L"...");
std::wstring tempDir = Utils::GetTempDir();
std::wstring package = Utils::MakeUniqueTempFile(tempDir, L"updater_pkg");
std::wstring err;
int lastPercent = -1;
unsigned long long lastTick = 0;
bool ok = Http::Download(url, package,
[this, &lastPercent, &lastTick, size](unsigned long long received,
unsigned long long total) {
if (cancel_.load()) return false;
unsigned long long base = total > 0 ? total : size;
int percent = 8;
if (base > 0) {
double ratio = static_cast<double>(received) / static_cast<double>(base);
if (ratio > 1.0) ratio = 1.0;
percent = 8 + static_cast<int>(ratio * 62.0);
}
unsigned long long now = GetTickCount64();
if (percent != lastPercent || now - lastTick > 300) {
lastPercent = percent;
lastTick = now;
Emit(percent, L"正在下载 " + Utils::FormatSize(received) +
(base > 0 ? (L" / " + Utils::FormatSize(base)) : L""));
}
return true;
},
err);
if (!ok) {
Utils::DeleteFileForce(package);
Finish(false, cancel_.load() ? L"已取消" : (L"下载失败:" + err));
return;
}
if (cancel_.load()) {
Utils::DeleteFileForce(package);
Finish(false, L"已取消");
return;
}
#if UPDATER_VERIFY_HASH
if (!hash.empty()) {
Emit(72, L"正在校验文件...");
std::string actual = Utils::Sha256HexFile(package);
if (!SameHash(hash, actual)) {
Utils::DeleteFileForce(package);
Finish(false, L"文件校验失败,已中止更新");
return;
}
}
#endif
Emit(75, L"正在解压...");
std::wstring staging = Utils::MakeUniqueTempFile(tempDir, L"updater_dir");
DeleteFileW(staging.c_str());
if (!Utils::CreateDirRecursive(staging)) {
Utils::DeleteFileForce(package);
Finish(false, L"无法创建临时目录");
return;
}
Unzip unzip;
std::vector<std::wstring> written;
std::wstring unzipErr;
if (!unzip.Open(package, unzipErr)) {
Utils::DeleteFileForce(package);
Finish(false, unzipErr);
return;
}
bool extracted = unzip.ExtractAll(
staging, stripRoot,
[this](unsigned long long done, unsigned long long total, const std::wstring& name) {
if (cancel_.load()) return false;
int percent = 75;
if (total > 0) {
double ratio = static_cast<double>(done) / static_cast<double>(total);
percent = 75 + static_cast<int>(ratio * 17.0);
}
Emit(percent, L"正在解压 " + name);
return true;
},
written, unzipErr);
unzip.Close();
Utils::DeleteFileForce(package);
(void)written;
if (!extracted) {
Finish(false, cancel_.load() ? L"已取消" : unzipErr);
return;
}
Emit(92, L"正在应用更新...");
std::wstring copyErr;
if (!CopyToTarget(staging, targetDir, copyErr)) {
Finish(false, copyErr);
return;
}
Emit(98, L"正在清理临时文件...");
std::vector<std::wstring> stagedFiles;
std::vector<std::wstring> stagedDirs;
CollectFiles(staging, L"", stagedFiles, stagedDirs);
for (size_t i = 0; i < stagedFiles.size(); ++i) {
Utils::DeleteFileForce(Utils::JoinPath(staging, stagedFiles[i]));
}
for (size_t i = stagedDirs.size(); i > 0; --i) {
RemoveDirectoryW(Utils::JoinPath(staging, stagedDirs[i - 1]).c_str());
}
RemoveDirectoryW(staging.c_str());
Emit(100, L"更新完成");
#if defined(UPDATER_LAUNCH_EXE)
std::wstring launch = options_.launchExe.empty() ? UPDATER_LAUNCH_EXE : options_.launchExe;
if (!launch.empty()) {
Utils::LaunchProcess(Utils::JoinPath(targetDir, launch), L"", targetDir);
}
#endif
Finish(true, L"更新完成" + versionText);
}
}