1750 lines
111 KiB
C++
1750 lines
111 KiB
C++
// OctoUpdater.exe: brings an OctoWoW client up to date from a signed patch channel, then starts the game.
|
|
// Lives in the client root (next to .build.info). Config: OctoUpdater.cfg (url=..., channel=..., launch=0|1).
|
|
// Manifest format and step semantics: ops/patchserver/publish.py. Every downloaded byte is checked against the
|
|
// signed manifest; a CONTENT step's preconditions are the same exact checks install.py makes; .build.info is
|
|
// switched last, so an interrupted run leaves the client on its previous build (staged files are reused).
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <atomic>
|
|
#include <exception>
|
|
#include <windows.h>
|
|
#include <winhttp.h>
|
|
#include <bcrypt.h>
|
|
#include <tlhelp32.h>
|
|
#include <shobjidl.h>
|
|
#include <shlobj.h>
|
|
#include <objbase.h>
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <ctime>
|
|
#include <cstring>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <map>
|
|
#include <set>
|
|
#include <algorithm>
|
|
#include <stdexcept>
|
|
#include <filesystem>
|
|
#include <array>
|
|
#include <cstdarg>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#define ZSTD_STATIC_LINKING_ONLY
|
|
#include "zstd.h"
|
|
#include "zlib.h"
|
|
#include "pubkey.h"
|
|
#include "repair_shortcut.hpp"
|
|
#include "../smart_app_control.hpp"
|
|
#include "current_files.hpp"
|
|
#include "stock_base.hpp"
|
|
#include "../../../native/client_update_policy.hpp"
|
|
|
|
namespace fs = std::filesystem;
|
|
static fs::path g_root, g_work;
|
|
static FILE* g_log = nullptr;
|
|
|
|
static std::mutex g_say_mutex; // STORE block downloads run on worker threads
|
|
static void say(const char* fmt, ...) {
|
|
std::lock_guard<std::mutex> say_lock(g_say_mutex);
|
|
char buf[2048]; va_list a; va_start(a, fmt); vsnprintf(buf, sizeof buf, fmt, a); va_end(a);
|
|
std::printf("%s\n", buf); std::fflush(stdout);
|
|
if (g_log) { SYSTEMTIME t; GetLocalTime(&t); std::fprintf(g_log, "%04d-%02d-%02d %02d:%02d:%02d %s\n", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, buf); std::fflush(g_log); }
|
|
}
|
|
struct Fail : std::runtime_error { using std::runtime_error::runtime_error; };
|
|
|
|
// BEGIN updater CLI and exit wait
|
|
struct UpdaterOptions {
|
|
bool explicit_launch=false, no_launch=false, check_only=false, no_dialog=false, repair=false;
|
|
int p2p=-1; // --p2p / --no-p2p: save the peer-to-peer choice (p2p=1/0 in OctoUpdater.cfg); -1 = keep
|
|
DWORD wait_pid=0;
|
|
std::wstring directory;
|
|
std::vector<std::wstring> game_args;
|
|
};
|
|
|
|
static UpdaterOptions parse_updater_options(int argc, wchar_t** argv) {
|
|
UpdaterOptions out;
|
|
bool have_pid=false;
|
|
for (int i=1; i<argc; ++i) {
|
|
const std::wstring arg=argv[i];
|
|
if (arg==L"--launch") out.explicit_launch=true;
|
|
else if (arg==L"--no-launch") out.no_launch=true;
|
|
else if (arg==L"--check") out.check_only=true;
|
|
else if (arg==L"--no-dialog") out.no_dialog=true;
|
|
else if (arg==L"--repair") out.repair=true;
|
|
else if (arg==L"--p2p") out.p2p=1;
|
|
else if (arg==L"--no-p2p") out.p2p=0;
|
|
else if (arg==L"--dir") {
|
|
if (++i>=argc || !argv[i][0]) throw Fail("--dir requires a path");
|
|
out.directory=argv[i];
|
|
} else if (arg==L"--wait-pid") {
|
|
if (have_pid || ++i>=argc || !argv[i][0]) throw Fail("--wait-pid requires one positive DWORD PID");
|
|
have_pid=true;
|
|
uint64_t value=0;
|
|
for (const wchar_t* digit=argv[i]; *digit; ++digit) {
|
|
if (*digit<L'0' || *digit>L'9' || value>(0xffffffffULL-uint64_t(*digit-L'0'))/10)
|
|
throw Fail("--wait-pid requires one positive DWORD PID");
|
|
value=value*10+uint64_t(*digit-L'0');
|
|
}
|
|
if (!value) throw Fail("--wait-pid requires one positive DWORD PID");
|
|
out.wait_pid=DWORD(value);
|
|
} else out.game_args.push_back(arg);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
static void wait_for_client_exit(DWORD pid) {
|
|
if (!pid) return;
|
|
HANDLE process=OpenProcess(SYNCHRONIZE, FALSE, pid);
|
|
if (!process) {
|
|
if (GetLastError()==ERROR_INVALID_PARAMETER) return; // Already exited.
|
|
throw Fail("Cannot wait for the client to exit; no updates installed");
|
|
}
|
|
const DWORD result=WaitForSingleObject(process, 60000);
|
|
CloseHandle(process);
|
|
if (result==WAIT_OBJECT_0) return;
|
|
if (result==WAIT_TIMEOUT) throw Fail("Client did not exit within 60 seconds; no updates installed");
|
|
throw Fail("Waiting for the client failed; no updates installed");
|
|
}
|
|
// END updater CLI and exit wait
|
|
|
|
// BEGIN successful update cache boundary
|
|
// Network verification alone is not completion. An exception propagates before
|
|
// the publication callback; --check and a running-client skip do neither step.
|
|
template<class Process, class Publish>
|
|
static void complete_update_pass(bool check_only, bool skipped_running_client,
|
|
Process process, Publish publish) {
|
|
if (check_only || skipped_running_client) return;
|
|
if (!process()) return;
|
|
publish();
|
|
}
|
|
// END successful update cache boundary
|
|
|
|
|
|
static std::wstring widen(const std::string& s) { int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0); std::wstring w(n ? n - 1 : 0, L'\0'); if (n) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n); return w; }
|
|
static fs::path at(const std::string& rel) { // client-relative path; refuse anything escaping the root
|
|
if (rel.empty() || rel.find("..") != std::string::npos || rel[0] == '/' || rel[0] == '\\' || rel.find(':') != std::string::npos) throw Fail("bad path " + rel);
|
|
std::string p = rel; std::replace(p.begin(), p.end(), '/', '\\'); return g_root / widen(p);
|
|
}
|
|
|
|
// ---- SHA-256 (BCrypt)
|
|
struct Sha {
|
|
BCRYPT_ALG_HANDLE alg{}; BCRYPT_HASH_HANDLE h{};
|
|
Sha() { if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) || BCryptCreateHash(alg, &h, nullptr, 0, nullptr, 0, 0)) throw Fail("sha256 init"); }
|
|
~Sha() { if (h) BCryptDestroyHash(h); if (alg) BCryptCloseAlgorithmProvider(alg, 0); }
|
|
void add(const void* p, size_t n) { while (n) { ULONG k = ULONG(std::min<size_t>(n, 1u << 30)); BCryptHashData(h, (PUCHAR)p, k, 0); p = (const char*)p + k; n -= k; } }
|
|
std::vector<uint8_t> raw() { std::vector<uint8_t> d(32); BCryptFinishHash(h, d.data(), 32, 0); return d; }
|
|
std::string hex() { auto d = raw(); static const char* x = "0123456789abcdef"; std::string s; for (auto b : d) { s += x[b >> 4]; s += x[b & 15]; } return s; }
|
|
};
|
|
static std::string sha_file(const fs::path& p, uint64_t off = 0, uint64_t len = UINT64_MAX) {
|
|
HANDLE f = CreateFileW(p.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
|
|
if (f == INVALID_HANDLE_VALUE) return "";
|
|
LARGE_INTEGER o; o.QuadPart = LONGLONG(off); SetFilePointerEx(f, o, nullptr, FILE_BEGIN);
|
|
Sha s; std::vector<char> b(1 << 22); DWORD got = 0;
|
|
while (len && ReadFile(f, b.data(), DWORD(std::min<uint64_t>(len, b.size())), &got, nullptr) && got) { s.add(b.data(), got); len -= std::min<uint64_t>(len, got); }
|
|
CloseHandle(f); return s.hex();
|
|
}
|
|
|
|
// ---- RSA PKCS#1 v1.5 SHA-256 signature over the manifest
|
|
static bool verify(const std::string& data, const std::string& sig) {
|
|
BCRYPT_ALG_HANDLE alg{}; BCRYPT_KEY_HANDLE key{};
|
|
if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_RSA_ALGORITHM, nullptr, 0)) return false;
|
|
bool ok = !BCryptImportKeyPair(alg, nullptr, BCRYPT_RSAPUBLIC_BLOB, &key, (PUCHAR)kPatchPublicKey, sizeof kPatchPublicKey, 0);
|
|
if (ok) {
|
|
Sha s; s.add(data.data(), data.size()); auto d = s.raw();
|
|
BCRYPT_PKCS1_PADDING_INFO pad{BCRYPT_SHA256_ALGORITHM};
|
|
ok = !BCryptVerifySignature(key, &pad, d.data(), ULONG(d.size()), (PUCHAR)sig.data(), ULONG(sig.size()), BCRYPT_PAD_PKCS1);
|
|
BCryptDestroyKey(key);
|
|
}
|
|
BCryptCloseAlgorithmProvider(alg, 0); return ok;
|
|
}
|
|
|
|
// ---- HTTP(S) GET via WinHTTP, to memory or to a file
|
|
struct Url { std::wstring host, path; INTERNET_PORT port; bool tls; };
|
|
static Url crack(const std::string& u) {
|
|
std::wstring w = widen(u); URL_COMPONENTS c{}; c.dwStructSize = sizeof c; wchar_t host[256], path[2048];
|
|
c.lpszHostName = host; c.dwHostNameLength = 256; c.lpszUrlPath = path; c.dwUrlPathLength = 2048;
|
|
if (!WinHttpCrackUrl(w.c_str(), 0, 0, &c)) throw Fail("bad url " + u);
|
|
return {std::wstring(host, c.dwHostNameLength), std::wstring(path, c.dwUrlPathLength), c.nPort, c.nScheme == INTERNET_SCHEME_HTTPS};
|
|
}
|
|
// offset>0 asks for "Range: bytes=offset-". Returns false when the server answered 200 (whole file) instead of
|
|
// 206, so the caller must start its file over. A stalled connection fails after the receive timeout.
|
|
struct HttpError : Fail {
|
|
DWORD status;
|
|
HttpError(const std::string& message, DWORD code = 0) : Fail(message), status(code) {}
|
|
bool missing() const { return status == 404 || status == 410; }
|
|
bool permanent() const { return missing() || status == 403; }
|
|
};
|
|
struct TextEncoding { bool automatic = false; std::wstring name; };
|
|
|
|
template <class Sink> static bool http_get(const std::string& u, Sink&& sink, uint64_t offset = 0,
|
|
TextEncoding* text = nullptr) {
|
|
Url x = crack(u);
|
|
HINTERNET s = WinHttpOpen(L"OctoUpdater/2", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, nullptr, nullptr, 0);
|
|
if (!s) s = WinHttpOpen(L"OctoUpdater/2", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, nullptr, nullptr, 0);
|
|
HINTERNET c = s ? WinHttpConnect(s, x.host.c_str(), x.port, 0) : nullptr;
|
|
HINTERNET r = c ? WinHttpOpenRequest(c, L"GET", x.path.c_str(), nullptr, nullptr, nullptr, x.tls ? WINHTTP_FLAG_SECURE : 0) : nullptr;
|
|
auto done = [&] { if (r) WinHttpCloseHandle(r); if (c) WinHttpCloseHandle(c); if (s) WinHttpCloseHandle(s); };
|
|
try {
|
|
if (r) WinHttpSetTimeouts(r, 30000, 30000, 60000, 90000);
|
|
std::wstring headers;
|
|
if (offset) headers = L"Range: bytes=" + std::to_wstring(offset) + L"-";
|
|
if (text) {
|
|
DWORD modes = WINHTTP_DECOMPRESSION_FLAG_ALL;
|
|
text->automatic = r && WinHttpSetOption(r, WINHTTP_OPTION_DECOMPRESSION, &modes, sizeof modes);
|
|
headers = L"Accept-Encoding: gzip, deflate";
|
|
}
|
|
if (!r || !WinHttpSendRequest(r, headers.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : headers.c_str(),
|
|
headers.empty() ? 0 : DWORD(-1L), nullptr, 0, 0, 0) || !WinHttpReceiveResponse(r, nullptr))
|
|
throw HttpError("cannot reach " + u + " (error " + std::to_string(GetLastError()) + ")");
|
|
DWORD code = 0, n = sizeof code;
|
|
if (!WinHttpQueryHeaders(r, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, nullptr, &code, &n, nullptr))
|
|
throw HttpError("cannot read HTTP status for " + u);
|
|
if (code != 200 && !(offset && code == 206))
|
|
throw HttpError("HTTP " + std::to_string(code) + " for " + u, code);
|
|
if (text) {
|
|
wchar_t encoding[64];
|
|
n = sizeof encoding;
|
|
if (WinHttpQueryHeaders(r, WINHTTP_QUERY_CONTENT_ENCODING, nullptr, encoding, &n, nullptr))
|
|
text->name = encoding;
|
|
else if (GetLastError() != ERROR_WINHTTP_HEADER_NOT_FOUND)
|
|
throw Fail("cannot read Content-Encoding for " + u);
|
|
}
|
|
std::vector<char> b(1 << 20);
|
|
for (;;) {
|
|
DWORD got = 0;
|
|
if (!WinHttpReadData(r, b.data(), DWORD(b.size()), &got)) throw HttpError("download interrupted: " + u);
|
|
if (!got) break;
|
|
sink(b.data(), size_t(got));
|
|
}
|
|
done();
|
|
return code == 206 || !offset;
|
|
} catch (...) { done(); throw; }
|
|
}
|
|
|
|
static constexpr size_t MaxTextBytes = size_t(256) << 20;
|
|
static std::string decode_text(std::string body, const TextEncoding& encoding) {
|
|
if (encoding.name.empty() || !_wcsicmp(encoding.name.c_str(), L"identity")) return body;
|
|
bool gzip = !_wcsicmp(encoding.name.c_str(), L"gzip");
|
|
if (!gzip && _wcsicmp(encoding.name.c_str(), L"deflate")) throw Fail("unsupported list Content-Encoding");
|
|
// Some WinHTTP versions leave the header visible after decoding; all three
|
|
// signed text formats begin with OCTO-. Older Wine uses the bundled zlib.
|
|
if (encoding.automatic && body.starts_with("OCTO-")) return body;
|
|
z_stream z{};
|
|
if (inflateInit2(&z, gzip ? 31 : 15) != Z_OK) throw Fail("cannot open compressed list");
|
|
struct End { z_stream* z; ~End() { inflateEnd(z); } } end{&z};
|
|
z.next_in = reinterpret_cast<Bytef*>(body.data());
|
|
z.avail_in = static_cast<uInt>(body.size());
|
|
std::array<char, 65536> buffer;
|
|
std::string decoded;
|
|
int status;
|
|
do {
|
|
z.next_out = reinterpret_cast<Bytef*>(buffer.data());
|
|
z.avail_out = buffer.size();
|
|
status = inflate(&z, Z_NO_FLUSH);
|
|
if (status != Z_OK && status != Z_STREAM_END) throw Fail("invalid compressed list");
|
|
size_t count = buffer.size() - z.avail_out;
|
|
if (count > MaxTextBytes - decoded.size()) throw Fail("decoded list too large");
|
|
decoded.append(buffer.data(), count);
|
|
} while (status != Z_STREAM_END);
|
|
if (z.avail_in) throw Fail("unexpected bytes after compressed list");
|
|
return decoded;
|
|
}
|
|
|
|
// A fresh URL per network attempt avoids stale, independently cached metadata
|
|
// bodies and signatures. Keep immutable blobs and ranged downloads cacheable.
|
|
static std::string metadata_url(const std::string& base_url) {
|
|
GUID id{};
|
|
wchar_t text[39];
|
|
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,text,39))
|
|
throw Fail("cannot generate a fresh metadata request ID");
|
|
return base_url + "?t=" + std::to_string(std::time(nullptr)) + "-" + std::string(text+1,text+37);
|
|
}
|
|
|
|
static std::string get_text(const std::string& u, bool compressed = true) {
|
|
for (int attempt = 0;; ++attempt) try {
|
|
TextEncoding encoding;
|
|
std::string body;
|
|
size_t limit = compressed ? MaxTextBytes : 8192; // raw RSA signature
|
|
http_get(metadata_url(u), [&](const char* p, size_t n) {
|
|
if (n > limit - body.size()) throw Fail("response too large for " + u);
|
|
body.append(p, n);
|
|
}, 0, compressed ? &encoding : nullptr);
|
|
return compressed ? decode_text(std::move(body), encoding) : body;
|
|
} catch (const HttpError& e) {
|
|
if (e.permanent() || attempt >= 5) throw;
|
|
say(" %s - retrying", e.what()); Sleep(DWORD(3000 * (attempt + 1)));
|
|
}
|
|
}
|
|
|
|
// Download <url> to <dst>: continues a previous <dst>.part where it stopped, retries with back-off on network
|
|
// errors (a dropped connection costs nothing already received), checks size + SHA-256, then renames into place.
|
|
static uint64_t g_total = 0; static std::atomic<uint64_t> g_done{0}; // install-wide progress (0 total = per-file progress only)
|
|
static void download(const std::string& url, const fs::path& dst, uint64_t size, const std::string& sha) {
|
|
fs::path part = dst; part += ".part"; fs::create_directories(dst.parent_path());
|
|
int bad_hash = 0; uint64_t last_print = 0;
|
|
for (int attempt = 0;; ++attempt) {
|
|
std::error_code ec; uint64_t have = fs::exists(part, ec) ? fs::file_size(part, ec) : 0;
|
|
if (have > size) { fs::remove(part, ec); have = 0; }
|
|
try {
|
|
if (have < size) {
|
|
HANDLE f = CreateFileW(part.c_str(), FILE_APPEND_DATA, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (f == INVALID_HANDLE_VALUE) throw Fail("cannot write " + dst.string() + " (disk full or folder read-only?)");
|
|
uint64_t at0 = have; bool wrote_err = false;
|
|
auto sink = [&](const char* p, size_t n) {
|
|
DWORD w = 0; if (!WriteFile(f, p, DWORD(n), &w, nullptr) || w != n) { wrote_err = true; throw Fail("cannot write " + dst.string() + " (disk full?)"); }
|
|
have += n; if (g_total) g_done += n;
|
|
if (have - last_print >= (64u << 20)) { last_print = have;
|
|
if (g_total) say(" %.1f / %.1f GB (%d%%)", g_done.load() / 1e9, g_total / 1e9, int(100.0 * g_done.load() / g_total));
|
|
else if (size > (64u << 20)) say(" %llu / %llu MB", (unsigned long long)(have >> 20), (unsigned long long)(size >> 20)); }
|
|
};
|
|
bool resumed;
|
|
try { resumed = http_get(url, sink, have); } catch (...) { CloseHandle(f); throw; }
|
|
CloseHandle(f); (void)wrote_err;
|
|
if (!resumed) { // server sent the whole file: keep only that copy
|
|
if (g_total) g_done -= std::min(g_done.load(), at0);
|
|
std::vector<char> keep; { std::ifstream i(part, std::ios::binary); i.seekg(std::streamoff(at0)); keep.assign(std::istreambuf_iterator<char>(i), {}); }
|
|
std::ofstream(part, std::ios::binary | std::ios::trunc).write(keep.data(), std::streamsize(keep.size()));
|
|
have = keep.size();
|
|
}
|
|
}
|
|
if (have != size) throw HttpError("download ended early: " + dst.filename().string());
|
|
if (sha_file(part) != sha) {
|
|
fs::remove(part, ec); if (g_total) g_done -= std::min(g_done.load(), size);
|
|
if (++bad_hash > 2) throw Fail("download damaged three times: " + dst.filename().string());
|
|
say(" %s was damaged in transfer - downloading again", dst.filename().string().c_str()); continue;
|
|
}
|
|
if (!MoveFileExW(part.c_str(), dst.c_str(), MOVEFILE_REPLACE_EXISTING)) throw Fail("cannot place " + dst.string() + " (is the game running?)");
|
|
return;
|
|
} catch (const HttpError& e) {
|
|
if (e.permanent() || attempt >= 40) throw;
|
|
DWORD wait = DWORD(std::min(60, 3 << std::min(attempt, 4)));
|
|
say(" connection problem (%s) - continuing in %lu s from %.1f MB", e.what(), (unsigned long)wait, have / 1048576.0);
|
|
Sleep(wait * 1000);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- zstd decode (optionally with the parent file as prefix: zstd --patch-from)
|
|
struct Mapped {
|
|
HANDLE f = INVALID_HANDLE_VALUE, m = nullptr; const void* p = nullptr; uint64_t n = 0;
|
|
explicit Mapped(const fs::path& path) {
|
|
f = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (f == INVALID_HANDLE_VALUE) throw Fail("cannot open delta base");
|
|
LARGE_INTEGER s; GetFileSizeEx(f, &s); n = uint64_t(s.QuadPart);
|
|
m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); p = m ? MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0) : nullptr; if (!p) throw Fail("cannot map delta base");
|
|
}
|
|
~Mapped() { if (p) UnmapViewOfFile(p); if (m) CloseHandle(m); if (f != INVALID_HANDLE_VALUE) CloseHandle(f); }
|
|
};
|
|
static void unzstd(const fs::path& in, const fs::path& out, const fs::path* base) {
|
|
std::unique_ptr<Mapped> b; if (base) b = std::make_unique<Mapped>(*base);
|
|
ZSTD_DCtx* d = ZSTD_createDCtx(); ZSTD_DCtx_setParameter(d, ZSTD_d_windowLogMax, 31);
|
|
if (b && ZSTD_isError(ZSTD_DCtx_refPrefix(d, b->p, size_t(b->n)))) { ZSTD_freeDCtx(d); throw Fail("zstd prefix"); }
|
|
std::ifstream i(in, std::ios::binary); std::ofstream o(out, std::ios::binary | std::ios::trunc);
|
|
std::vector<char> ib(ZSTD_DStreamInSize()), ob(ZSTD_DStreamOutSize()); size_t last = 0;
|
|
while (i) {
|
|
i.read(ib.data(), std::streamsize(ib.size())); size_t got = size_t(i.gcount()); if (!got) break;
|
|
ZSTD_inBuffer zi{ib.data(), got, 0};
|
|
while (zi.pos < zi.size) {
|
|
ZSTD_outBuffer zo{ob.data(), ob.size(), 0}; last = ZSTD_decompressStream(d, &zo, &zi);
|
|
if (ZSTD_isError(last)) { ZSTD_freeDCtx(d); throw Fail(std::string("zstd: ") + ZSTD_getErrorName(last)); }
|
|
o.write(ob.data(), std::streamsize(zo.pos));
|
|
}
|
|
}
|
|
ZSTD_freeDCtx(d); if (last) throw Fail("zstd: truncated payload"); if (!o) throw Fail("write failed: " + out.string());
|
|
}
|
|
|
|
// ---- manifest
|
|
struct Step { std::string kind, id, parent, child; std::vector<std::vector<std::string>> lines; };
|
|
static std::vector<std::string> split(const std::string& l) { std::istringstream s(l); std::vector<std::string> v; for (std::string w; s >> w;) v.push_back(w); return v; }
|
|
struct Manifest {
|
|
std::vector<Step> steps;
|
|
current_files::RetiredPaths retired;
|
|
};
|
|
struct ListChannelMismatch : Fail { using Fail::Fail; };
|
|
static Manifest parse(const std::string& m, std::string* legacy_marker, size_t signature_bytes, const std::string& channel) {
|
|
bool channel_ok = false, policy_seen = false;
|
|
Manifest manifest;
|
|
auto& out = manifest.steps;
|
|
std::istringstream in(m); std::string l; bool head = false, end = false;
|
|
while (std::getline(in, l)) {
|
|
if (!l.empty() && l.back() == '\r') l.pop_back(); auto v = split(l); if (v.empty()) continue;
|
|
if (end) throw Fail("unexpected line after manifest END");
|
|
if (!out.empty() && out.back().kind == "POLICY" && v[0] != "RETIRE" && v[0] != "STEP" && v[0] != "END")
|
|
throw Fail("unexpected line in retired-paths policy");
|
|
if (v[0] == "OCTO-PATCH") { if (v.size() < 2 || v[1] != "1") throw Fail("unsupported manifest format"); head = true; }
|
|
else if (v[0] == "CHANNEL") {
|
|
if (!head || channel_ok || v.size() != 2 || !out.empty()) throw Fail("invalid update list channel header");
|
|
if (v[1] != channel) throw ListChannelMismatch("update list channel mismatch");
|
|
channel_ok = true;
|
|
}
|
|
else if (v[0] == "LEGACY-SIGNATURE") {
|
|
if (!legacy_marker || !channel_ok || !out.empty() || !legacy_marker->empty() ||
|
|
v.size() != 2 || v[1].size() != signature_bytes*2 ||
|
|
v[1].find_first_not_of("0123456789abcdef") != std::string::npos)
|
|
throw Fail("invalid legacy signature binding in compact list");
|
|
for (size_t i = 0; i < v[1].size(); i += 2)
|
|
legacy_marker->push_back(char(std::stoi(v[1].substr(i,2),nullptr,16)));
|
|
}
|
|
else if (v[0] == "END") end = true;
|
|
else if (v[0] == "STEP") {
|
|
if (v.size() < 3) throw Fail("bad STEP");
|
|
Step s{v[1], v[2]};
|
|
if (s.kind == "POLICY") {
|
|
if (policy_seen || v.size() != 3 || s.id != "retired-paths")
|
|
throw Fail("invalid retired-paths policy header");
|
|
policy_seen = true;
|
|
}
|
|
if (s.kind == "CONTENT" || s.kind == "STORE") {
|
|
if (v.size() < 5) throw Fail("bad STEP");
|
|
s.parent = v[3]; s.child = v[4];
|
|
}
|
|
out.push_back(std::move(s));
|
|
}
|
|
else if (v[0] == "RETIRE" || (!out.empty() && out.back().kind == "POLICY")) {
|
|
if (out.empty() || out.back().kind != "POLICY" || v[0] != "RETIRE" || v.size() != 2 ||
|
|
!manifest.retired.add(v[1])) throw Fail("invalid retired-paths declaration");
|
|
out.back().lines.push_back(v);
|
|
}
|
|
else { if (out.empty()) throw Fail("line outside step"); out.back().lines.push_back(v); }
|
|
}
|
|
if (!head || !channel_ok || !end || (legacy_marker && legacy_marker->empty())) throw Fail("incomplete manifest");
|
|
if (policy_seen) {
|
|
if (manifest.retired.empty()) throw Fail("empty retired-paths policy");
|
|
// Apply channel policy to the entire FILES history, even steps preceding
|
|
// the policy or already in the local ledger. Retain the step identities.
|
|
for (auto& step : out) {
|
|
if (step.kind == "FILES") {
|
|
std::erase_if(step.lines,[&](const auto& row) {
|
|
return row.at(0) == "PUT" && manifest.retired.matches(row.at(1));
|
|
});
|
|
} else if (step.kind == "CONTENT" || step.kind == "STORE") {
|
|
// Both the forward update and repair use these rows. Skipping
|
|
// an input or output would invalidate the signed build transition.
|
|
auto require_managed = [&](const std::string& path) {
|
|
if (manifest.retired.matches(path))
|
|
throw Fail(step.kind + " step " + step.id + " references retired path " + path);
|
|
};
|
|
for (const auto& row : step.lines) {
|
|
const auto& op = row.at(0);
|
|
if (op == "FILE" || op == "CONF" || op == "ACTIVATE" ||
|
|
op == "REQ_SHA" || op == "REQ_SPAN" || op == "REQ_ABSENT")
|
|
require_managed(row.at(1));
|
|
if (op == "FILE" && row.size() > 7 && row[6] == "zstd-patch")
|
|
require_managed(row[7]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return manifest;
|
|
}
|
|
|
|
static std::string g_base;
|
|
static std::string build_key(const fs::path& path = g_root / ".build.info") {
|
|
std::ifstream f(path); std::string l; std::getline(f, l);
|
|
while (std::getline(f, l)) { if (!l.empty() && l.back() == '\r') l.pop_back(); if (l.find_first_not_of(" \t") == std::string::npos) continue;
|
|
std::vector<std::string> c; std::string x; std::istringstream s(l); while (std::getline(s, x, '|')) c.push_back(x); if (c.size() > 2) return c[2]; }
|
|
throw Fail("cannot read .build.info");
|
|
}
|
|
// Fetch blob <sha>.zst into the work dir (reused when already complete), then decode it into <dst> and check <want>.
|
|
static void fetch(const std::string& bsha, uint64_t bsize, const fs::path& dst, const std::string& want, const fs::path* base) {
|
|
fs::path z = g_work / "blobs" / (bsha + ".zst"); fs::create_directories(z.parent_path());
|
|
if (!(fs::exists(z) && fs::file_size(z) == bsize && sha_file(z) == bsha)) download(g_base + "blobs/" + bsha + ".zst", z, bsize, bsha);
|
|
fs::create_directories(dst.parent_path()); unzstd(z, dst, base);
|
|
if (sha_file(dst) != want) { fs::remove(dst); throw Fail("decoded file does not match: " + dst.filename().string()); }
|
|
}
|
|
|
|
static bool newest_idx_is(const std::string& bucket, const std::string& name) {
|
|
std::vector<std::string> names; std::error_code ec;
|
|
for (auto& e : fs::directory_iterator(g_root / "Data" / "data", ec)) { auto n = e.path().filename().string(); if (n.size() > 4 && n.substr(n.size() - 4) == ".idx" && n.compare(0, 2, bucket) == 0) names.push_back(n); }
|
|
std::sort(names.begin(), names.end()); return !names.empty() && names.back() == name;
|
|
}
|
|
|
|
static void apply_content(const Step& s) {
|
|
say("Update %s: checking client files", s.id.c_str());
|
|
std::vector<std::string> bad;
|
|
for (auto& v : s.lines) {
|
|
if (v[0] == "REQ_SHA" && sha_file(at(v[1])) != v[2]) bad.push_back(v[1]);
|
|
else if (v[0] == "REQ_IDX" && !newest_idx_is(v[1], v[2])) bad.push_back("index " + v[1]);
|
|
else if (v[0] == "REQ_SPAN" && sha_file(at(v[1]), std::stoull(v[2]), std::stoull(v[3])) != v[4]) bad.push_back(v[1] + "@" + v[2]);
|
|
else if (v[0] == "REQ_ABSENT" && fs::exists(at(v[1]))) bad.push_back("unexpected " + v[1]);
|
|
if (bad.size() > 8) break;
|
|
}
|
|
if (!bad.empty()) { std::string m; for (auto& b : bad) m += "\n " + b; throw Fail("client files differ from what update " + s.id + " expects:" + m); }
|
|
fs::path stage = g_work / "stage" / s.id; std::vector<std::pair<fs::path, fs::path>> moves; const std::vector<std::string>* act = nullptr;
|
|
for (auto& v : s.lines) {
|
|
if (v[0] == "FILE") {
|
|
fs::path dst = stage / at(v[1]).lexically_relative(g_root);
|
|
if (!(fs::exists(dst) && sha_file(dst) == v[2])) {
|
|
say(" %s (%s MB download)", v[1].c_str(), std::to_string(std::stoull(v[5]) >> 20).c_str());
|
|
if (v[6] == "zstd-patch") { if (v.size() < 9 || sha_file(at(v[7])) != v[8]) throw Fail("delta base changed: " + v[7]); fs::path b = at(v[7]); fetch(v[4], std::stoull(v[5]), dst, v[2], &b); }
|
|
else fetch(v[4], std::stoull(v[5]), dst, v[2], nullptr);
|
|
}
|
|
moves.push_back({dst, at(v[1])});
|
|
} else if (v[0] == "ACTIVATE") act = &v;
|
|
}
|
|
if (!act) throw Fail("update has no activation");
|
|
fs::path bi = stage / ".build.info.child"; fetch((*act)[4], std::stoull((*act)[5]), bi, (*act)[3], nullptr);
|
|
for (auto& [from, to] : moves) {
|
|
fs::create_directories(to.parent_path());
|
|
if (!MoveFileExW(from.c_str(), to.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) throw Fail("cannot place " + to.string());
|
|
}
|
|
fs::path target = at((*act)[1]);
|
|
if (sha_file(target) != (*act)[2]) throw Fail(".build.info changed during the update");
|
|
fs::path backup = g_work / ("build.info." + s.parent.substr(0, 8)); fs::copy_file(target, backup, fs::copy_options::overwrite_existing);
|
|
if (!MoveFileExW(bi.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) || sha_file(target) != (*act)[3]) throw Fail("cannot switch .build.info");
|
|
std::error_code ec; fs::remove_all(stage, ec);
|
|
say("Update %s installed", s.id.c_str());
|
|
}
|
|
|
|
// ---- STORE steps (ops/patchserver/store_step.py is the reference): layout-independent content updates.
|
|
// New frames are appended to this client's own CASC store and merged into its own IDX generations, so a
|
|
// compacted/repacked store updates exactly like a fresh install.
|
|
extern "C" uint32_t hashlittle(const void* key, size_t length, uint32_t initval);
|
|
extern "C" void hashlittle2(const void* key, size_t length, uint32_t* pc, uint32_t* pb);
|
|
using Row = std::array<uint8_t, 18>;
|
|
struct Idx { fs::path path; uint32_t gen = 0; std::vector<uint8_t> raw; std::vector<Row> rows; uint64_t maxoff = 0; };
|
|
static std::vector<uint8_t> read_all(const fs::path& p) { std::ifstream f(p, std::ios::binary); return std::vector<uint8_t>(std::istreambuf_iterator<char>(f), {}); }
|
|
struct SignedList {
|
|
std::string name, body, signature;
|
|
fs::path cache_body() const { return g_work / name; }
|
|
fs::path cache_signature() const {
|
|
return g_work / (name == "manifest.txt" ? "manifest-legacy-cache.sig" : name + ".sig");
|
|
}
|
|
};
|
|
|
|
struct ListSignatureMismatch : Fail { using Fail::Fail; };
|
|
|
|
static SignedList fetch_verified_list(const std::string& name) {
|
|
SignedList list;
|
|
list.name = name;
|
|
list.signature = get_text(g_base + name + ".sig", false);
|
|
auto cached_sig = list.cache_signature();
|
|
if (list.name == "manifest.txt" && !fs::exists(cached_sig)) cached_sig = g_work / "manifest.txt.sig";
|
|
if (fs::exists(cached_sig) && fs::exists(list.cache_body())) {
|
|
auto sig = read_all(cached_sig);
|
|
if (std::string(sig.begin(),sig.end()) == list.signature) {
|
|
auto bytes = read_all(list.cache_body());
|
|
list.body.assign(bytes.begin(),bytes.end());
|
|
if (verify(list.body,list.signature)) return list;
|
|
}
|
|
}
|
|
say("Downloading the update list (%s)...", list.name.c_str());
|
|
for (unsigned attempt = 0; attempt < 2; ++attempt) {
|
|
if (attempt) {
|
|
// The body and its signature cross the public endpoint separately.
|
|
Sleep(350);
|
|
list.signature = get_text(g_base + list.name + ".sig", false);
|
|
if (verify(list.body,list.signature)) return list;
|
|
}
|
|
list.body = get_text(g_base + list.name);
|
|
if (verify(list.body,list.signature)) return list;
|
|
}
|
|
throw ListSignatureMismatch(name + " signature is not valid; nothing installed");
|
|
}
|
|
|
|
static SignedList fetch_signed_list() {
|
|
try {
|
|
return fetch_verified_list("manifest-store.txt");
|
|
} catch (const ListSignatureMismatch& e) {
|
|
say("Compact update list did not match its signature. Checking the signed legacy list.");
|
|
} catch (const HttpError& e) {
|
|
if (!e.missing()) throw;
|
|
say("Compact update list or signature is missing. Checking the signed legacy list.");
|
|
}
|
|
return fetch_verified_list("manifest.txt");
|
|
}
|
|
|
|
// Compact lists can replace a CONTENT entry with a later STORE for the same
|
|
// transition, even repeating that STORE. Count the transition once at its
|
|
// first position and compare the representation the updater actually uses.
|
|
static std::vector<const Step*> published_history(const Manifest& manifest) {
|
|
using Edge = std::pair<std::string,std::string>;
|
|
std::map<Edge,const Step*> stores;
|
|
for (const auto& step : manifest.steps)
|
|
if (step.kind == "STORE") stores[{step.parent,step.child}] = &step;
|
|
std::set<Edge> seen;
|
|
std::vector<const Step*> history;
|
|
for (const auto& step : manifest.steps) {
|
|
if (step.kind == "FILES") history.push_back(&step);
|
|
else if (step.kind == "CONTENT" || step.kind == "STORE") {
|
|
Edge edge{step.parent,step.child};
|
|
if (!seen.insert(edge).second) continue;
|
|
auto store = stores.find(edge);
|
|
history.push_back(store == stores.end() ? &step : store->second);
|
|
}
|
|
}
|
|
return history;
|
|
}
|
|
|
|
static bool preserves_history(const Manifest& previous, const Manifest& incoming) {
|
|
std::set<std::string> policies;
|
|
for (const auto& step : incoming.steps) if (step.kind == "POLICY")
|
|
for (const auto& row : step.lines) policies.insert(current_files::path_key(row.at(1)));
|
|
for (const auto& step : previous.steps) if (step.kind == "POLICY")
|
|
for (const auto& row : step.lines) if (!policies.contains(current_files::path_key(row.at(1)))) return false;
|
|
|
|
auto old_steps = published_history(previous), next_steps = published_history(incoming);
|
|
if (old_steps.size() > next_steps.size()) return false;
|
|
for (size_t i = 0; i < old_steps.size(); ++i) {
|
|
const Step& old = *old_steps[i];
|
|
const Step& next = *next_steps[i];
|
|
if (old.kind == "FILES") {
|
|
if (next.kind != "FILES" || old.id != next.id) return false;
|
|
auto row = next.lines.begin();
|
|
for (const auto& before : old.lines) {
|
|
if (before.at(0) == "PUT" && incoming.retired.matches(before.at(1))) continue;
|
|
if (row == next.lines.end() || *row++ != before) return false;
|
|
}
|
|
if (row != next.lines.end()) return false;
|
|
} else {
|
|
if (old.parent != next.parent || old.child != next.child) return false;
|
|
if (old.kind == "CONTENT" && next.kind == "STORE") continue; // published STORE retrofit
|
|
if (old.kind != next.kind || old.id != next.id || old.lines != next.lines) return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static std::string read_list_file(const fs::path& path) {
|
|
std::ifstream in(path,std::ios::binary);
|
|
return {std::istreambuf_iterator<char>(in), {}};
|
|
}
|
|
|
|
static void check_committed_list(const Manifest& incoming, const std::string& incoming_marker,
|
|
bool compact, const std::string& channel) {
|
|
const auto marker = g_work / "manifest.txt.sig";
|
|
if (!fs::exists(marker)) return;
|
|
auto committed = read_list_file(marker);
|
|
if (committed == incoming_marker) return; // authenticated by the incoming manifest
|
|
|
|
// Both formats share the legacy signature as their generation marker.
|
|
// Old updaters may have saved only that marker. A cached body is evidence
|
|
// only if its authenticated generation matches the last completed update.
|
|
for (bool cached_compact : {true,false}) {
|
|
const auto name = cached_compact ? "manifest-store.txt" : "manifest.txt";
|
|
const auto signature = cached_compact ? read_list_file(g_work / "manifest-store.txt.sig") : committed;
|
|
if (signature.empty() || !fs::exists(g_work / name)) continue;
|
|
const auto body = read_list_file(g_work / name);
|
|
if (!verify(body,signature)) continue;
|
|
std::string bound;
|
|
Manifest previous;
|
|
try { previous = parse(body,cached_compact ? &bound : nullptr,signature.size(),channel); }
|
|
catch (const ListChannelMismatch&) { continue; }
|
|
if (cached_compact && bound != committed) continue;
|
|
if (!preserves_history(previous,incoming))
|
|
throw Fail("signed update list is older than or conflicts with the last completed update; existing files preserved");
|
|
return;
|
|
}
|
|
if (!compact) throw Fail("cannot establish the signed legacy list follows the last completed update; existing files preserved");
|
|
}
|
|
|
|
static void save_list_cache(const fs::path& path, const std::string& data) {
|
|
auto tmp = path;
|
|
tmp += L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp";
|
|
try {
|
|
std::ofstream out(tmp,std::ios::binary | std::ios::trunc);
|
|
out.write(data.data(), data.size());
|
|
out.close();
|
|
if (!out || !MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
|
throw Fail("cannot save completed list cache: " + path.filename().string());
|
|
} catch (...) {
|
|
std::error_code ec;
|
|
fs::remove(tmp, ec);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
static void save_active_build(const std::string& key) {
|
|
auto target = g_work / "active-build.txt";
|
|
std::ifstream in(target);
|
|
std::string recorded; std::getline(in,recorded); in.close();
|
|
if (recorded != key) save_list_cache(target,key+"\n");
|
|
}
|
|
|
|
static std::vector<uint8_t> unhex(const std::string& h) { std::vector<uint8_t> v; for (size_t i = 0; i + 1 < h.size(); i += 2) v.push_back(uint8_t(std::stoi(h.substr(i, 2), nullptr, 16))); return v; }
|
|
static int bucket_of(const uint8_t* k) { uint8_t v = 0; for (int i = 0; i < 9; ++i) v ^= k[i]; return (v ^ (v >> 4)) & 15; }
|
|
static uint32_t rows_hash(const std::vector<Row>& rows) { uint32_t hi = 0, lo = 0; for (auto& r : rows) hashlittle2(r.data(), 18, &hi, &lo); return hi; }
|
|
static uint32_t rd32(const uint8_t* p) { uint32_t v; memcpy(&v, p, 4); return v; }
|
|
static std::array<Idx, 16> read_store_indexes(const fs::path& data) {
|
|
std::array<Idx, 16> out; std::error_code ec;
|
|
for (auto& e : fs::directory_iterator(data, ec)) {
|
|
auto n = e.path().filename().string(); if (n.size() != 14 || n.substr(10) != ".idx") continue;
|
|
int b = std::stoi(n.substr(0, 2), nullptr, 16); uint32_t g = uint32_t(std::stoul(n.substr(2, 8), nullptr, 16));
|
|
if (b < 16 && (out[b].path.empty() || g > out[b].gen)) { out[b].path = e.path(); out[b].gen = g; }
|
|
}
|
|
for (int b = 0; b < 16; ++b) {
|
|
Idx& x = out[b]; if (x.path.empty()) throw Fail("client store is missing index bucket " + std::to_string(b));
|
|
x.raw = read_all(x.path); auto& r = x.raw;
|
|
if (r.size() < 40 || rd32(&r[0]) != 16 || hashlittle(&r[8], 16, 0) != rd32(&r[4])) throw Fail("damaged index " + x.path.filename().string());
|
|
if (r[8] != 7 || r[10] != b || r[12] != 4 || r[13] != 5 || r[14] != 9 || r[15] != 30) throw Fail("unsupported index layout " + x.path.filename().string());
|
|
memcpy(&x.maxoff, &r[16], 8);
|
|
uint32_t n = rd32(&r[32]); if (n % 18 || 40 + uint64_t(n) > r.size()) throw Fail("damaged index " + x.path.filename().string());
|
|
x.rows.resize(n / 18); for (size_t i = 0; i < x.rows.size(); ++i) memcpy(x.rows[i].data(), &r[40 + 18 * i], 18);
|
|
if (rows_hash(x.rows) != rd32(&r[36])) throw Fail("damaged index " + x.path.filename().string());
|
|
}
|
|
return out;
|
|
}
|
|
static const Row* find_row(const std::array<Idx, 16>& ix, const uint8_t* key) { // first row of the prefix, as native lookup
|
|
auto& rows = ix[bucket_of(key)].rows;
|
|
auto it = std::lower_bound(rows.begin(), rows.end(), key, [](const Row& r, const uint8_t* k) { return memcmp(r.data(), k, 9) < 0; });
|
|
return (it != rows.end() && !memcmp(it->data(), key, 9)) ? &*it : nullptr;
|
|
}
|
|
static std::string archive_name(uint64_t seg) { char b[16]; snprintf(b, sizeof b, "data.%03llu", (unsigned long long)seg); return b; }
|
|
static std::vector<uint8_t> read_frame(const fs::path& data, const Row& r) {
|
|
uint64_t pos = 0; for (int i = 9; i < 14; ++i) pos = (pos << 8) | r[i]; uint32_t size = rd32(&r[14]);
|
|
std::ifstream f(data / archive_name(pos >> 30), std::ios::binary); f.seekg(std::streamoff(pos & ((1u << 30) - 1)));
|
|
std::vector<uint8_t> b(size); f.read((char*)b.data(), size); if (size_t(f.gcount()) != size) throw Fail("cannot read a delta base frame");
|
|
if (size >= 4 && !memcmp(b.data(), "BLTE", 4)) return b;
|
|
if (size < 34 || memcmp(b.data()+30,"BLTE",4)) throw Fail("invalid local BLTE frame");
|
|
return std::vector<uint8_t>(b.begin() + 30, b.end());
|
|
}
|
|
static std::array<uint8_t, 30> archive_header(const uint8_t* key16, uint32_t span, uint32_t offset) {
|
|
std::array<uint8_t, 30> h{}; for (int i = 0; i < 16; ++i) h[i] = key16[15 - i];
|
|
memcpy(&h[16], &span, 4); uint32_t c = hashlittle(h.data(), 22, 0x3D6BE971); memcpy(&h[22], &c, 4);
|
|
static const uint32_t T[16] = {0x049396B8, 0x72A82A9B, 0xEE626CCA, 0x9917754F, 0x15DE40B1, 0xF5A8A9B6, 0x421EAC7E, 0xA9D55C9A,
|
|
0x317FD40C, 0x04FAF80D, 0x3D6BE971, 0x52933CFD, 0x27F64B7D, 0xC6F5C11B, 0xD5757E3A, 0x6C388745};
|
|
uint32_t eo = T[(offset + 30) & 15] ^ (offset + 30); uint8_t e[4]; memcpy(e, &eo, 4); uint8_t x[4] = {};
|
|
for (int i = 0; i < 26; ++i) x[i & 3] ^= h[i];
|
|
for (int j = 0; j < 4; ++j) h[26 + j] = x[(26 + j) & 3] ^ e[(26 + j) & 3];
|
|
return h;
|
|
}
|
|
static void write_file(const fs::path& p, const std::vector<uint8_t>& d) {
|
|
HANDLE f = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
DWORD w = 0; bool ok = f != INVALID_HANDLE_VALUE && WriteFile(f, d.data(), DWORD(d.size()), &w, nullptr) && w == d.size() && FlushFileBuffers(f);
|
|
if (f != INVALID_HANDLE_VALUE) CloseHandle(f); if (!ok) throw Fail("cannot write " + p.string());
|
|
}
|
|
static void apply_store(const Step& s) {
|
|
say("Update %s: client content", s.id.c_str());
|
|
fs::path data = g_root / "Data" / "data", stage = g_work / "stage" / s.id; fs::create_directories(stage);
|
|
auto ix = read_store_indexes(data);
|
|
struct New { std::vector<uint8_t> key; fs::path file; };
|
|
std::vector<New> todo;
|
|
// FRAME ekey bytes sha bsha bsize zstd|zstd-frame [base]. Blocks are small (~0.4 MB) and each one is
|
|
// its own HTTPS request, so a long catch-up was dominated by per-request latency: fetch up to 8 at
|
|
// once. Delta bases are read from the store first (single thread); order and checks are unchanged.
|
|
struct Job { const std::vector<std::string>* v; fs::path dst, base; };
|
|
std::vector<Job> jobs;
|
|
for (auto& v : s.lines) {
|
|
if (v[0] != "FRAME") continue; auto key = unhex(v[1]); if (key.size() != 16) throw Fail("bad frame key");
|
|
if (find_row(ix, key.data())) continue;
|
|
fs::path dst = stage / (v[1] + ".blte");
|
|
Job j{&v, dst, {}};
|
|
if (!(fs::exists(dst) && sha_file(dst) == v[3]) && v[6] == "zstd-frame") {
|
|
auto bk = unhex(v.at(7)); const Row* br = bk.size() == 16 ? find_row(ix, bk.data()) : nullptr; if (!br) throw Fail("update base data missing from this client - its store files do not match its version. Repair it: run OctoUpdater.exe --repair (Linux: ./octo-install.sh --repair <client folder>), then start again");
|
|
j.base = stage / (v[1] + "." + v[7] + ".base"); write_file(j.base, read_frame(data, *br));
|
|
}
|
|
jobs.push_back(std::move(j));
|
|
todo.push_back({key, dst});
|
|
}
|
|
{
|
|
std::atomic<size_t> next{0}; std::mutex failed_mutex; std::exception_ptr failed;
|
|
auto work = [&] {
|
|
for (size_t i; (i = next++) < jobs.size();) {
|
|
{ std::lock_guard<std::mutex> l(failed_mutex); if (failed) return; }
|
|
try {
|
|
auto& j = jobs[i]; auto& v = *j.v;
|
|
if (!(fs::exists(j.dst) && sha_file(j.dst) == v[3])) {
|
|
say(" data %s (%s KB download)", v[1].substr(0, 8).c_str(), std::to_string(std::stoull(v[5]) >> 10).c_str());
|
|
fetch(v[4], std::stoull(v[5]), j.dst, v[3], j.base.empty() ? nullptr : &j.base);
|
|
}
|
|
if (!j.base.empty()) { std::error_code e; fs::remove(j.base, e); }
|
|
if (fs::file_size(j.dst) != std::stoull(v[2])) throw Fail("frame size differs");
|
|
} catch (...) { std::lock_guard<std::mutex> l(failed_mutex); if (!failed) failed = std::current_exception(); return; }
|
|
}
|
|
};
|
|
std::vector<std::thread> pool; size_t n = std::min<size_t>(8, jobs.size());
|
|
for (size_t t = 1; t < n; ++t) pool.emplace_back(work);
|
|
work(); for (auto& t : pool) t.join();
|
|
if (failed) std::rethrow_exception(failed);
|
|
}
|
|
// append: highest archive, or a new one when the 1 GiB segment would be crossed
|
|
uint64_t seg = 0; bool any = false; std::error_code ec;
|
|
for (auto& e : fs::directory_iterator(data, ec)) { auto n = e.path().filename().string(); if (n.size() == 8 && n.rfind("data.", 0) == 0 && isdigit(n[5])) { seg = std::max<uint64_t>(seg, std::stoull(n.substr(5))); any = true; } }
|
|
if (!any) throw Fail("client store has no archives");
|
|
uint64_t pos = fs::file_size(data / archive_name(seg));
|
|
std::map<int, std::vector<Row>> adds;
|
|
if (!todo.empty()) {
|
|
auto open = [&](bool fresh) { HANDLE h = CreateFileW((data / archive_name(seg)).c_str(), FILE_APPEND_DATA, 0, nullptr, fresh ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) throw Fail("cannot open " + archive_name(seg) + " (is the game running?)"); return h; };
|
|
HANDLE h = open(false);
|
|
for (auto& n : todo) {
|
|
auto blte = read_all(n.file); uint64_t span = blte.size() + 30;
|
|
if (pos + span > (1ull << 30)) { FlushFileBuffers(h); CloseHandle(h); ++seg; pos = 0; h = open(true); }
|
|
if (((seg << 30) | pos) >= ix[bucket_of(n.key.data())].maxoff) { CloseHandle(h); throw Fail("client store is full"); }
|
|
auto hd = archive_header(n.key.data(), uint32_t(span), uint32_t(pos)); DWORD w = 0;
|
|
if (!WriteFile(h, hd.data(), 30, &w, nullptr) || w != 30 || !WriteFile(h, blte.data(), DWORD(blte.size()), &w, nullptr) || w != blte.size()) { CloseHandle(h); throw Fail("cannot write game data"); }
|
|
Row r{}; memcpy(r.data(), n.key.data(), 9); uint64_t p = (seg << 30) | pos; for (int i = 0; i < 5; ++i) r[13 - i] = uint8_t(p >> (8 * i)); uint32_t sz = uint32_t(span); memcpy(&r[14], &sz, 4);
|
|
adds[bucket_of(n.key.data())].push_back(r); pos += span;
|
|
}
|
|
FlushFileBuffers(h); CloseHandle(h);
|
|
}
|
|
for (auto& [b, rows] : adds) { // new generation: old rows bit-identical, new rows sorted in (stable: old first)
|
|
Idx& x = ix[b]; std::vector<Row> all = x.rows; all.insert(all.end(), rows.begin(), rows.end());
|
|
std::stable_sort(all.begin(), all.end(), [](const Row& a, const Row& c) { return memcmp(a.data(), c.data(), 9) < 0; });
|
|
std::vector<uint8_t> out(40); uint32_t v16 = 16; memcpy(&out[0], &v16, 4); memcpy(&out[8], &x.raw[8], 16);
|
|
uint32_t hh = hashlittle(&out[8], 16, 0); memcpy(&out[4], &hh, 4);
|
|
uint32_t n = uint32_t(all.size() * 18), eh = rows_hash(all); memcpy(&out[32], &n, 4); memcpy(&out[36], &eh, 4);
|
|
for (auto& r : all) out.insert(out.end(), r.begin(), r.end());
|
|
size_t cap = std::max(x.raw.size(), ((out.size() + 32768 + 65535) / 65536) * 65536); out.resize(cap, 0);
|
|
char name[32]; snprintf(name, sizeof name, "%02x%08x.idx", b, x.gen + 1); write_file(data / name, out);
|
|
fs::remove(x.path, ec);
|
|
}
|
|
for (auto& v : s.lines) if (v[0] == "CONF") { fs::path t = at(v[1]); if (!(fs::exists(t) && sha_file(t) == v[2])) fetch(v[4], std::stoull(v[5]), t, v[2], nullptr); }
|
|
const std::vector<std::string>* act = nullptr; for (auto& v : s.lines) if (v[0] == "ACTIVATE") act = &v;
|
|
if (!act) throw Fail("update has no activation");
|
|
fs::path bi = stage / ".build.info.child"; fetch((*act)[4], std::stoull((*act)[5]), bi, (*act)[3], nullptr);
|
|
fs::path target = at((*act)[1]); if (sha_file(target) != (*act)[2]) throw Fail(".build.info changed during the update");
|
|
fs::copy_file(target, g_work / ("build.info." + s.parent.substr(0, 8)), fs::copy_options::overwrite_existing);
|
|
if (!MoveFileExW(bi.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) || sha_file(target) != (*act)[3]) throw Fail("cannot switch .build.info");
|
|
fs::remove(data / "shmem", ec); fs::remove_all(stage, ec);
|
|
say("Update %s installed (%zu new data blocks)", s.id.c_str(), todo.size());
|
|
}
|
|
|
|
// ---- store compaction (#131; ops/casc_compact.py is the reference). Every STORE step appends a complete new
|
|
// ENCODING/ROOT/DOWNLOAD/SIZE generation (~0.5-0.7 GB written per step); nothing ever freed the superseded ones,
|
|
// so player stores grew past 110 GB. Reachable = the active build config's ENCODING EKey + every EKey that ENCODING
|
|
// lists (content + encoded sections) + the archive segment-header records. Crash-safe order:
|
|
// 1. live spans of mostly-dead archives are appended to NEW archives (old index still valid meanwhile),
|
|
// 2. new IDX generations point at the new places and drop unreachable rows (old archives now unreferenced),
|
|
// 3. the old archives are truncated to their leading segment-header block (native CASC needs every number).
|
|
// Step 3 is idempotent: any archive no index row reaches beyond its header block is truncated on the next run.
|
|
static uint32_t be(const uint8_t* p, int n) { uint32_t v = 0; for (int i = 0; i < n; ++i) v = (v << 8) | p[i]; return v; }
|
|
static std::vector<uint8_t> blte_decode(const std::vector<uint8_t>& b) {
|
|
if (b.size() < 8 || memcmp(b.data(), "BLTE", 4)) throw Fail("ENCODING is not BLTE");
|
|
uint32_t hs = be(&b[4], 4); std::vector<uint8_t> out;
|
|
auto chunk = [&](const uint8_t* p, size_t n, size_t expect) {
|
|
if (!n) throw Fail("empty BLTE chunk");
|
|
if (p[0] == 'N') { out.insert(out.end(), p + 1, p + n); return; }
|
|
if (p[0] != 'Z') throw Fail(std::string("unsupported BLTE chunk mode ") + char(p[0]));
|
|
size_t at = out.size(); out.resize(at + expect); z_stream z{}; if (inflateInit(&z) != Z_OK) throw Fail("zlib init");
|
|
z.next_in = const_cast<uint8_t*>(p + 1); z.avail_in = uInt(n - 1); z.next_out = out.data() + at; z.avail_out = uInt(expect);
|
|
int r = inflate(&z, Z_FINISH); inflateEnd(&z); if (r != Z_STREAM_END || z.avail_out) throw Fail("zlib chunk");
|
|
};
|
|
if (!hs) { chunk(&b[8], b.size() - 8, 0); return out; }
|
|
if (b.size() < 12 || hs > b.size()) throw Fail("BLTE header");
|
|
uint32_t n = be(&b[9], 3); size_t pos = hs; if (12 + 24ull * n > hs) throw Fail("BLTE chunk table");
|
|
for (uint32_t i = 0; i < n; ++i) {
|
|
uint32_t cs = be(&b[12 + 24 * i], 4), ds = be(&b[16 + 24 * i], 4);
|
|
if (pos + cs > b.size()) throw Fail("BLTE truncated"); chunk(&b[pos], cs, ds); pos += cs;
|
|
}
|
|
return out;
|
|
}
|
|
// Every EKey prefix (9 bytes) the ENCODING table reaches; layout pinned like casc_asset_package.encoding_layout.
|
|
static void encoding_keys(const std::vector<uint8_t>& r, std::set<std::array<uint8_t, 9>>& ref) {
|
|
if (r.size() < 22 || r[0] != 'E' || r[1] != 'N' || r[2] != 1 || r[3] != 16 || r[4] != 16 || be(&r[5], 2) != 4 || be(&r[7], 2) != 4)
|
|
throw Fail("unsupported ENCODING layout");
|
|
uint32_t cn = be(&r[9], 4), en = be(&r[13], 4), es = be(&r[18], 4); size_t pos = 22 + size_t(es);
|
|
auto add = [&](const uint8_t* k) { std::array<uint8_t, 9> a; memcpy(a.data(), k, 9); ref.insert(a); };
|
|
for (int section = 0; section < 2; ++section) {
|
|
uint32_t count = section ? en : cn; size_t pages = pos + 32ull * count, end = pages + 4096ull * count;
|
|
if (!count || end > r.size()) throw Fail("truncated ENCODING");
|
|
for (uint32_t i = 0; i < count; ++i) {
|
|
const uint8_t* pg = &r[pages + 4096ull * i]; size_t p = 0;
|
|
while (p < 4096) {
|
|
if (!section) { uint8_t c = pg[p]; if (!c) break; if (p + 22 + 16ull * c > 4096) throw Fail("ENCODING entry crosses page");
|
|
for (int j = 0; j < c; ++j) add(pg + p + 22 + 16 * j); p += 22 + 16ull * c; }
|
|
else { static const uint8_t z[16] = {}; if (p + 25 > 4096 || !memcmp(pg + p, z, 16)) break; add(pg + p); p += 25; }
|
|
}
|
|
}
|
|
pos = end;
|
|
}
|
|
}
|
|
static std::string active_build_key() { // same reading as casc_compact.reachable: first data row's Build Key
|
|
std::ifstream f(g_root / ".build.info"); std::string head, vals; std::getline(f, head); std::getline(f, vals);
|
|
auto split = [](const std::string& s) { std::vector<std::string> v; std::string c; for (char ch : s) { if (ch == '|') { v.push_back(c); c.clear(); } else if (ch != '\r') c += ch; } v.push_back(c); return v; };
|
|
auto h = split(head), v = split(vals);
|
|
for (size_t i = 0; i < h.size() && i < v.size(); ++i) if (h[i].rfind("Build Key!", 0) == 0) return v[i];
|
|
throw Fail(".build.info has no Build Key");
|
|
}
|
|
static std::set<std::array<uint8_t,9>> reachable_keys(const fs::path& data, const std::array<Idx,16>& ix,
|
|
const std::string& key) {
|
|
std::ifstream cf(g_root / "Data" / "config" / key.substr(0, 2) / key.substr(2, 2) / key);
|
|
std::string ckey, ekey; for (std::string l; std::getline(cf, l);) if (l.rfind("encoding = ", 0) == 0) { std::istringstream s(l.substr(11)); s >> ckey >> ekey; }
|
|
if (ekey.size() != 32) throw Fail("build config has no encoding key");
|
|
auto ek = unhex(ekey); const Row* er = find_row(ix, ek.data()); if (!er) throw Fail("ENCODING missing from the store");
|
|
std::set<std::array<uint8_t, 9>> ref;
|
|
{ auto blob = read_frame(data, *er); encoding_keys(blte_decode(blob), ref); }
|
|
std::array<uint8_t, 9> ek9; memcpy(ek9.data(), ek.data(), 9); ref.insert(ek9);
|
|
return ref;
|
|
}
|
|
|
|
// Existing local archives and index generations depend on where this client
|
|
// stored its frames. Check the active spans and published reachable frames
|
|
// through the installed indexes, independent of the original install layout.
|
|
static void verify_store(const std::vector<Step>& steps, const std::string& key) {
|
|
auto data = g_root / "Data" / "data";
|
|
auto ix = read_store_indexes(data);
|
|
auto reachable = reachable_keys(data,ix,key);
|
|
std::map<uint64_t,uint64_t> lengths;
|
|
for (const auto& bucket : ix) for (const auto& row : bucket.rows) {
|
|
uint64_t address = 0;
|
|
for (int i = 9; i < 14; ++i) address = (address << 8) | row[i];
|
|
uint64_t segment = address >> 30, offset = address & ((1u << 30)-1);
|
|
auto length = lengths.find(segment);
|
|
if (length == lengths.end()) {
|
|
auto path = data / archive_name(segment);
|
|
std::error_code ec;
|
|
auto size = fs::file_size(path,ec);
|
|
if (ec) throw Fail("missing client archive " + path.filename().string());
|
|
length = lengths.emplace(segment,size).first;
|
|
}
|
|
if (offset + rd32(&row[14]) > length->second)
|
|
throw Fail("indexed frame extends beyond " + archive_name(segment));
|
|
}
|
|
std::map<std::array<uint8_t,9>,const std::vector<std::string>*> signed_frames;
|
|
for (const auto* step : current_files::lineage(steps,key)) for (const auto& v : step->lines) {
|
|
if (v.at(0) != "FRAME") continue;
|
|
auto raw = unhex(v.at(1));
|
|
if (raw.size() != 16) throw Fail("invalid signed frame key");
|
|
std::array<uint8_t,9> prefix;
|
|
std::copy_n(raw.begin(),prefix.size(),prefix.begin());
|
|
if (reachable.count(prefix)) signed_frames[prefix] = &v;
|
|
}
|
|
for (const auto& [prefix,line] : signed_frames) {
|
|
const auto* row = find_row(ix,prefix.data());
|
|
if (!row) throw Fail("active published frame is missing from this client: " + line->at(1));
|
|
auto bytes = read_frame(data,*row);
|
|
Sha sha; sha.add(bytes.data(),bytes.size());
|
|
if (bytes.size() != std::stoull(line->at(2)) || sha.hex() != line->at(3))
|
|
throw Fail("active published frame is damaged: " + line->at(1));
|
|
}
|
|
say("Verified %zu reachable published frames and archive spans in 16 index buckets",signed_frames.size());
|
|
}
|
|
|
|
static void compact_store() {
|
|
fs::path data = g_root / "Data" / "data"; std::error_code ec;
|
|
auto ix = read_store_indexes(data);
|
|
auto ref = reachable_keys(data,ix,active_build_key());
|
|
static const uint8_t seg_tail[6] = {0xe1, 0xfa, 0x57, 0xa8, 0x07, 0xb4}; // segment-header key e356c4a9..07a857fae1 reversed, bytes 3..8 of its index prefix
|
|
auto span_of = [](const Row& r) { uint64_t p = 0; for (int i = 9; i < 14; ++i) p = (p << 8) | r[i]; return std::make_pair(p, rd32(&r[14])); };
|
|
// first row per prefix (native lookup); live/dead bytes per archive
|
|
std::map<uint64_t, uint64_t> live, dead; std::map<std::array<uint8_t, 9>, Row> first;
|
|
for (auto& x : ix) for (auto& r : x.rows) { std::array<uint8_t, 9> k; memcpy(k.data(), r.data(), 9); first.emplace(k, r); }
|
|
for (auto& [k, r] : first) {
|
|
auto [p, sz] = span_of(r); uint64_t seg = p >> 30;
|
|
if (!memcmp(k.data() + 3, seg_tail, 6)) ref.insert(k);
|
|
(ref.count(k) ? live : dead)[seg] += sz;
|
|
}
|
|
uint64_t maxseg = 0; bool any = false;
|
|
for (auto& e : fs::directory_iterator(data, ec)) { auto n = e.path().filename().string(); if (n.size() == 8 && n.rfind("data.", 0) == 0 && isdigit(n[5])) { maxseg = std::max<uint64_t>(maxseg, std::stoull(n.substr(5))); any = true; } }
|
|
if (!any) return;
|
|
std::set<uint64_t> rewrite; uint64_t reclaim = 0;
|
|
for (auto& [seg, d] : dead) if (d > (64ull << 20) && d * 50 > live[seg] + d) { rewrite.insert(seg); reclaim += d; }
|
|
say("Store check: %.1f GB unused data in %zu archive(s)", reclaim / 1e9, rewrite.size());
|
|
// cut archives back to the last byte their index rows reach (also finishes a run interrupted after step 2)
|
|
auto trim = [&](const std::map<uint64_t, uint64_t>& used_end, uint64_t last) {
|
|
uint64_t freed = 0;
|
|
for (uint64_t s = 0; s <= last; ++s) {
|
|
fs::path p = data / archive_name(s); uint64_t size = fs::file_size(p, ec); if (ec) { ec.clear(); continue; }
|
|
auto it = used_end.find(s); uint64_t keep = it != used_end.end() ? it->second : 0;
|
|
// native archives open with up to 16 unindexed 30-byte segment headers ("Missing segment header" = damaged install)
|
|
{ static const uint8_t sk[13] = {0xe3, 0x56, 0xc4, 0xa9, 0xd1, 0xea, 0xd3, 0xb4, 0x07, 0xa8, 0x57, 0xfa, 0xe1};
|
|
std::ifstream f(p, std::ios::binary); char hb[480] = {}; f.read(hb, 480); uint64_t got = uint64_t(f.gcount()), n = 0;
|
|
while (n < 16 && (n + 1) * 30 <= got && !memcmp(hb + n * 30, sk, 13)) ++n; keep = std::max<uint64_t>(keep, n * 30); }
|
|
if (size <= keep) continue;
|
|
HANDLE t = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
LARGE_INTEGER li; li.QuadPart = LONGLONG(keep);
|
|
if (t == INVALID_HANDLE_VALUE || !SetFilePointerEx(t, li, nullptr, FILE_BEGIN) || !SetEndOfFile(t)) { if (t != INVALID_HANDLE_VALUE) CloseHandle(t); throw Fail("cannot shrink " + archive_name(s)); }
|
|
CloseHandle(t); freed += size - keep;
|
|
}
|
|
return freed;
|
|
};
|
|
if (rewrite.empty()) {
|
|
std::map<uint64_t, uint64_t> used_end;
|
|
for (auto& x : ix) for (auto& r : x.rows) { auto [p, sz] = span_of(r); auto& e = used_end[p >> 30]; e = std::max<uint64_t>(e, (p & ((1u << 30) - 1)) + sz); }
|
|
if (uint64_t f = trim(used_end, maxseg)) { fs::remove(data / "shmem", ec); say("Store trimmed: %.1f GB freed", f / 1e9); }
|
|
return;
|
|
}
|
|
// 1. copy live spans of the rewritten archives into new archives
|
|
std::map<std::array<uint8_t, 9>, Row> moved; uint64_t seg = maxseg, pos = fs::file_size(data / archive_name(seg));
|
|
HANDLE h = INVALID_HANDLE_VALUE; auto open = [&](bool fresh) { h = CreateFileW((data / archive_name(seg)).c_str(), FILE_APPEND_DATA, 0, nullptr, fresh ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) throw Fail("cannot open " + archive_name(seg) + " (is the game running?)"); };
|
|
if (rewrite.count(seg)) { ++seg; pos = 0; open(true); } else open(false);
|
|
std::vector<std::pair<Row, std::array<uint8_t, 9>>> todo;
|
|
for (auto& [k, r] : first) if (ref.count(k) && rewrite.count(span_of(r).first >> 30) && memcmp(k.data() + 3, seg_tail, 6)) todo.push_back({r, k});
|
|
std::sort(todo.begin(), todo.end(), [&](auto& a, auto& b) { return span_of(a.first).first < span_of(b.first).first; });
|
|
for (auto& [r, k] : todo) {
|
|
auto [p, sz] = span_of(r); std::vector<uint8_t> blob(sz);
|
|
{ std::ifstream f(data / archive_name(p >> 30), std::ios::binary); f.seekg(std::streamoff(p & ((1u << 30) - 1))); f.read((char*)blob.data(), sz);
|
|
if (size_t(f.gcount()) != sz) { CloseHandle(h); throw Fail("short archive span"); } }
|
|
uint8_t key16[16]; for (int i = 0; i < 16; ++i) key16[i] = blob[15 - i];
|
|
if (memcmp(key16, k.data(), 9)) { CloseHandle(h); throw Fail("archive span key differs from its index row"); }
|
|
if (pos + sz > (1ull << 30)) { FlushFileBuffers(h); CloseHandle(h); ++seg; pos = 0; open(true); }
|
|
if (((seg << 30) | pos) >= ix[bucket_of(k.data())].maxoff) { CloseHandle(h); throw Fail("client store is full"); }
|
|
auto hd = archive_header(key16, sz, uint32_t(pos)); memcpy(blob.data(), hd.data(), 30); DWORD w = 0;
|
|
if (!WriteFile(h, blob.data(), sz, &w, nullptr) || w != sz) { CloseHandle(h); throw Fail("cannot write game data (disk full?)"); }
|
|
Row nr = r; uint64_t np = (seg << 30) | pos; for (int i = 0; i < 5; ++i) nr[13 - i] = uint8_t(np >> (8 * i));
|
|
moved[k] = nr; pos += sz;
|
|
}
|
|
FlushFileBuffers(h); CloseHandle(h);
|
|
// 2. new index generations: one row per reachable prefix, moved rows point at their new place
|
|
std::map<uint64_t, uint64_t> used_end; // per archive: end of the last byte any new index row reaches
|
|
for (int b = 0; b < 16; ++b) {
|
|
Idx& x = ix[b]; std::vector<Row> all; std::set<std::array<uint8_t, 9>> seen;
|
|
for (auto& r : x.rows) { std::array<uint8_t, 9> k; memcpy(k.data(), r.data(), 9); if (!ref.count(k) || !seen.insert(k).second) continue;
|
|
auto m = moved.find(k); all.push_back(m != moved.end() ? m->second : first[k]); }
|
|
std::vector<uint8_t> out(40); uint32_t v16 = 16; memcpy(&out[0], &v16, 4); memcpy(&out[8], &x.raw[8], 16);
|
|
uint32_t hh = hashlittle(&out[8], 16, 0); memcpy(&out[4], &hh, 4);
|
|
uint32_t n = uint32_t(all.size() * 18), eh = rows_hash(all); memcpy(&out[32], &n, 4); memcpy(&out[36], &eh, 4);
|
|
for (auto& r : all) { out.insert(out.end(), r.begin(), r.end()); auto [p, sz] = span_of(r); auto& e = used_end[p >> 30]; e = std::max<uint64_t>(e, (p & ((1u << 30) - 1)) + sz); }
|
|
size_t cap = std::max(x.raw.size(), ((out.size() + 32768 + 65535) / 65536) * 65536); out.resize(cap, 0);
|
|
char name[32]; snprintf(name, sizeof name, "%02x%08x.idx", b, x.gen + 1); write_file(data / name, out); fs::remove(x.path, ec);
|
|
}
|
|
// 3. cut every archive back to the last byte the new index reaches (rewritten ones keep their header block)
|
|
uint64_t freed = trim(used_end, seg);
|
|
uint64_t copied = 0; for (auto& [k, r] : moved) copied += rd32(&r[14]);
|
|
fs::remove(data / "shmem", ec);
|
|
say("Store compacted: %zu archive(s) rewritten, %zu data blocks moved, %.1f GB freed", rewrite.size(), moved.size(), (double(freed) - double(copied)) / 1e9);
|
|
}
|
|
|
|
static std::set<std::string> applied() { std::set<std::string> a; std::ifstream f(g_work / "applied.txt"); for (std::string l; std::getline(f, l);) if (!l.empty()) a.insert(l); return a; }
|
|
static fs::path g_self;
|
|
static bool g_self_replaced = false; // a FILES step replaced this exe: hand over to the new one before launching
|
|
// A hit identifies the same verified file, expected digest, size, last write and
|
|
// NT change time. Replacing the file or restoring its mtime invalidates the entry.
|
|
static std::string file_stamp(const fs::path& path, uint64_t expected_size) {
|
|
HANDLE h = CreateFileW(path.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
|
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (h == INVALID_HANDLE_VALUE) return {};
|
|
BY_HANDLE_FILE_INFORMATION id{}; FILE_BASIC_INFO basic{};
|
|
bool ok = GetFileInformationByHandle(h,&id) && GetFileInformationByHandleEx(h,FileBasicInfo,&basic,sizeof basic);
|
|
CloseHandle(h);
|
|
uint64_t size = (uint64_t(id.nFileSizeHigh) << 32) | id.nFileSizeLow;
|
|
uint64_t index = (uint64_t(id.nFileIndexHigh) << 32) | id.nFileIndexLow;
|
|
if (!ok || (id.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || !index || !basic.ChangeTime.QuadPart ||
|
|
(expected_size != current_files::unknown_size && size != expected_size)) return {};
|
|
return std::to_string(size) + "/" + std::to_string(id.dwVolumeSerialNumber) + "/" + std::to_string(index) +
|
|
"/" + std::to_string(basic.LastWriteTime.QuadPart) + "/" + std::to_string(basic.ChangeTime.QuadPart);
|
|
}
|
|
|
|
class VerifiedFiles {
|
|
std::map<std::string,std::string> entries;
|
|
bool changed = false;
|
|
public:
|
|
VerifiedFiles() {
|
|
std::ifstream in(g_work / "verified.txt");
|
|
std::string line;
|
|
while (std::getline(in,line)) {
|
|
if (line.rfind("v2 ",0) != 0) continue; // older size-only records have no file identity
|
|
auto end = line.find(' ',3);
|
|
if (end != std::string::npos) entries[line.substr(end+1)] = line.substr(3,end-3);
|
|
}
|
|
}
|
|
bool matches(const std::string& path, uint64_t size, const std::string& sha, bool full) {
|
|
const auto key = current_files::path_key(path);
|
|
fs::path target = at(path);
|
|
std::error_code ec;
|
|
uint64_t actual = fs::file_size(target,ec);
|
|
if (ec || (size != current_files::unknown_size && actual != size)) return false;
|
|
auto stamp = file_stamp(target,size);
|
|
auto record = sha + "/" + stamp;
|
|
auto old = entries.find(key);
|
|
if (!full && !stamp.empty() && old != entries.end() && old->second == record) return true;
|
|
if (sha_file(target) != sha) return false;
|
|
if (!stamp.empty() && stamp == file_stamp(target,size) && (old == entries.end() || old->second != record)) {
|
|
entries[key] = record;
|
|
changed = true;
|
|
}
|
|
return true;
|
|
}
|
|
void save() {
|
|
if (!changed) return;
|
|
std::ostringstream data;
|
|
for (const auto& [key,record] : entries) data << "v2 " << record << ' ' << key << "\n";
|
|
save_list_cache(g_work / "verified.txt",data.str());
|
|
changed = false;
|
|
}
|
|
};
|
|
|
|
using current_files::Outputs;
|
|
using current_files::Output;
|
|
|
|
// Keep guarded first-time publications safe, including upgrades installed ahead
|
|
// of their ledger. A previously applied PUT is already a managed repair target.
|
|
static void check_put_history(const std::vector<Step>& steps, const std::set<std::string>& done,
|
|
const Outputs& previous, const Outputs& damaged) {
|
|
std::map<std::string,std::vector<const std::vector<std::string>*>> history;
|
|
for (const auto& step : steps) if (step.kind == "FILES" && !done.count(step.id)) {
|
|
for (const auto& v : step.lines) if (v.at(0) == "PUT") {
|
|
auto key = current_files::path_key(v.at(1));
|
|
if (damaged.count(key) && !previous.count(key)) history[key].push_back(&v);
|
|
}
|
|
}
|
|
for (const auto& [key,puts] : history) {
|
|
fs::path t = at(damaged.at(key).path);
|
|
std::string cur = fs::exists(t) ? sha_file(t) : "absent";
|
|
for (auto it = puts.begin(); it != puts.end(); ++it) {
|
|
const auto& v = **it;
|
|
if (cur == v.at(2)) continue;
|
|
if (v.at(6) != "any" && v[6] != cur) {
|
|
if (std::any_of(it+1,puts.end(),[&](const auto* later){return later->at(2)==cur;})) continue;
|
|
throw Fail(v[1] + " is not the expected version (local change?)");
|
|
}
|
|
cur = v[2];
|
|
}
|
|
}
|
|
}
|
|
|
|
static Outputs mismatches(const Outputs& wanted, VerifiedFiles& verified, bool full) {
|
|
Outputs damaged;
|
|
for (const auto& [key,f] : wanted)
|
|
if (!verified.matches(f.path,f.size,f.sha,full)) damaged.emplace(key,f);
|
|
return damaged;
|
|
}
|
|
|
|
static void restore_outputs(const Outputs& damaged, VerifiedFiles& verified) {
|
|
auto stage = g_work / "stage" / "current";
|
|
for (const auto& [key,f] : damaged) {
|
|
auto dst = stage / f.sha;
|
|
if (!fs::exists(dst) || sha_file(dst) != f.sha) {
|
|
say(" Restoring %s", f.path.c_str());
|
|
fetch(f.blob,f.blob_size,dst,f.sha,nullptr);
|
|
}
|
|
}
|
|
// Stage once per SHA; several installed paths can share one blob.
|
|
for (const auto& [key,f] : damaged) {
|
|
auto t = at(f.path);
|
|
auto temp = t; temp += L".octo-repair.tmp";
|
|
fs::create_directories(t.parent_path());
|
|
fs::copy_file(stage / f.sha,temp,fs::copy_options::overwrite_existing);
|
|
std::error_code ec;
|
|
if (fs::exists(t)) {
|
|
auto backup = g_work / "backup" / f.step / t.lexically_relative(g_root);
|
|
fs::create_directories(backup.parent_path());
|
|
fs::copy_file(t,backup,fs::copy_options::overwrite_existing);
|
|
}
|
|
bool self = fs::equivalent(t,g_self,ec);
|
|
auto old = g_self; old += L".old";
|
|
if (self && !MoveFileExW(t.c_str(),old.c_str(),MOVEFILE_REPLACE_EXISTING))
|
|
throw Fail("cannot move the running updater aside");
|
|
if (!MoveFileExW(temp.c_str(),t.c_str(),MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
|
if (self) MoveFileExW(old.c_str(),t.c_str(),MOVEFILE_REPLACE_EXISTING);
|
|
throw Fail("cannot restore " + f.path + " (is the game running?)");
|
|
}
|
|
if (self) g_self_replaced = true;
|
|
if (!verified.matches(f.path,f.size,f.sha,true)) throw Fail("restored file differs: " + f.path);
|
|
}
|
|
std::error_code ec;
|
|
fs::remove_all(stage,ec);
|
|
}
|
|
|
|
// ---- fresh install / repair from the signed file list <channel>/install.txt (written by ops/patchserver/install_list.py):
|
|
// OCTO-INSTALL 1 | RELEASE <id> | BASE <url relative to the channel>/ | F <sha256> <size> <client path, may contain spaces> | END
|
|
// Files arrive one by one into <path>.part (resumed after any break), are hash-checked, then renamed; .build.info
|
|
// comes last, so an unfinished install never looks like a client. _patch/verified.txt remembers checked files.
|
|
static std::string url_path(const std::string& p) {
|
|
std::string o; static const char* x = "0123456789ABCDEF";
|
|
for (unsigned char ch : p) { if (isalnum(ch) || strchr("-._~/", ch)) o += char(ch); else { o += '%'; o += x[ch >> 4]; o += x[ch & 15]; } }
|
|
return o;
|
|
}
|
|
static bool game_running();
|
|
// ---- peer-to-peer first download (optional): the signed <channel>/install-p2p.txt (ops/patchserver/p2p_list.py)
|
|
// OCTO-P2P 1 | RELEASE <id> | TORRENT <sha256> <size> <url> | ARIA2 <sha256> <size> <url> | END
|
|
// names the release torrent (web-seeded from the update server, file order = the install list's F order) and the
|
|
// aria2 BitTorrent engine (official 1.37.0 build, GPLv2; source next to it on the server). Both are SHA-256 pinned by
|
|
// the signed list before use. aria2 writes every selected file straight to its place (index-out); .build.info and
|
|
// the running updater are diverted to _patch/p2p/hold, so an unfinished install never looks like a client. Whatever
|
|
// it delivers is re-checked against install.txt afterwards; anything missing or wrong then comes over HTTP.
|
|
struct InstallFile { std::string sha, path; uint64_t size; bool retired; };
|
|
static std::string abs_url(const std::string& u) { return u.find("://") != std::string::npos ? u : g_base + u; }
|
|
static bool p2p_install(const std::vector<InstallFile>& files, const std::set<std::string>& want, const std::string& release,
|
|
std::map<std::string, std::string>& cfg) {
|
|
std::string list, sig;
|
|
try { list = get_text(g_base + "install-p2p.txt"); sig = get_text(g_base + "install-p2p.txt.sig", false); }
|
|
catch (const std::exception&) { return false; } // no torrent offered on this channel
|
|
if (!verify(list, sig)) { say("Peer-to-peer list signature is not valid - using direct download"); return false; }
|
|
std::string rel, tor[3], ari[3]; bool head = false, end = false; std::istringstream in(list);
|
|
for (std::string l; std::getline(in, l);) {
|
|
if (!l.empty() && l.back() == '\r') l.pop_back(); auto v = split(l); if (v.empty()) continue;
|
|
if (l == "OCTO-P2P 1") head = true; else if (v[0] == "RELEASE" && v.size() == 2) rel = v[1]; else if (l == "END") end = true;
|
|
else if ((v[0] == "TORRENT" || v[0] == "ARIA2") && v.size() == 4) { auto* d = v[0] == "TORRENT" ? tor : ari; d[0] = v[1]; d[1] = v[2]; d[2] = v[3]; }
|
|
}
|
|
if (!head || !end || rel != release || tor[0].empty() || ari[0].empty()) return false;
|
|
fs::path dir = g_work / "p2p", exe = dir / "aria2c.exe", torrent = dir / ("OctoWoW-" + release + ".torrent");
|
|
fs::create_directories(dir / "hold"); std::error_code ec;
|
|
for (auto [file, d] : {std::pair{exe, ari}, std::pair{torrent, tor}}) {
|
|
uint64_t size = std::stoull(d[1]);
|
|
if (!(fs::exists(file, ec) && fs::file_size(file, ec) == size && sha_file(file) == d[0])) download(abs_url(d[2]), file, size, d[0]);
|
|
}
|
|
// aria2 input file: the torrent, then each file's destination (1-based torrent index = install list order).
|
|
std::ofstream o(dir / "aria2-input.txt", std::ios::trunc); o << torrent.string() << "\n";
|
|
std::string sel;
|
|
for (size_t i = 0; i < files.size(); ++i) {
|
|
fs::path t = at(files[i].path); bool hold = files[i].path == ".build.info" || fs::equivalent(t, g_self, ec);
|
|
o << " index-out=" << i + 1 << "=" << (hold ? "_patch/p2p/hold/" + std::to_string(i + 1) : files[i].path) << "\n";
|
|
if (!hold && want.count(files[i].path)) sel += (sel.empty() ? "" : ",") + std::to_string(i + 1);
|
|
}
|
|
if (sel.empty()) return false;
|
|
o << " select-file=" << sel << "\n"; o.close();
|
|
// No control file from an earlier run but data already in place (e.g. an earlier attempt): let aria2 hash it.
|
|
bool control = false; for (auto& e : fs::directory_iterator(g_root, ec)) if (e.path().extension() == ".aria2") control = true;
|
|
std::wstring cmd = L"\"" + exe.wstring() + L"\" --input-file=\"" + (dir / "aria2-input.txt").wstring() + L"\" --dir=\"" + g_root.wstring() +
|
|
L"\" --seed-time=" + widen(cfg.count("p2p_seed_minutes") ? cfg["p2p_seed_minutes"] : "0") +
|
|
L" --max-overall-upload-limit=" + widen(cfg.count("p2p_upload_limit") ? cfg["p2p_upload_limit"] : "0") +
|
|
L" --file-allocation=trunc --allow-overwrite=true --auto-file-renaming=false --bt-save-metadata=false" +
|
|
L" --check-integrity=" + (control ? L"false" : L"true") + L" --auto-save-interval=30 --summary-interval=0" +
|
|
L" --bt-stop-timeout=" + widen(cfg.count("p2p_stall_seconds") ? cfg["p2p_stall_seconds"] : "300") + // no peers and no web seed: give up, HTTP takes over
|
|
L" --console-log-level=error --bt-max-peers=80 --max-tries=0 --retry-wait=10 --stop-with-process=" + std::to_wstring(GetCurrentProcessId()) +
|
|
L" --dht-file-path=\"" + (dir / "dht.dat").wstring() + L"\" --log=\"" + (dir / "aria2.log").wstring() + L"\" --log-level=notice";
|
|
if (cfg.count("p2p_args")) cmd += L" " + widen(cfg["p2p_args"]); // e.g. --listen-port=51413 --max-download-limit=5M
|
|
say("Downloading the client peer-to-peer (torrent, %zu files; our server seeds it too). Other players' downloads share pieces with yours.", files.size());
|
|
say("If Windows Firewall asks about aria2c, allow it for faster downloads (optional).");
|
|
STARTUPINFOW si{}; si.cb = sizeof si; PROCESS_INFORMATION pi{};
|
|
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, g_root.c_str(), &si, &pi)) { say("Cannot start the torrent engine - using direct download"); return false; }
|
|
WaitForSingleObject(pi.hProcess, INFINITE); DWORD code = 1; GetExitCodeProcess(pi.hProcess, &code); CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
|
|
say(code == 0 ? "Torrent download finished - checking every file" : "Torrent download stopped (code %lu) - checking what arrived; the rest comes directly", (unsigned long)code);
|
|
if (code == 0) { for (auto& e : fs::directory_iterator(g_root, ec)) if (e.path().extension() == ".aria2") fs::remove(e.path(), ec); fs::remove_all(dir / "hold", ec); }
|
|
return true;
|
|
}
|
|
// #16: a reused folder can still hold an older install's store files. read_store_indexes takes the newest index
|
|
// generation per bucket, so leftover .idx files hide the release's indexes ("update base data missing from this
|
|
// client"). After an install the client is exactly the release, so only the listed store files may stay.
|
|
static void prune_store(const std::vector<InstallFile>& files) {
|
|
fs::path data = g_root / "Data" / "data"; std::error_code ec; if (!fs::is_directory(data, ec)) return;
|
|
std::set<std::string> keep; for (auto& f : files) if (f.path.rfind("Data/data/", 0) == 0) keep.insert(f.path.substr(10));
|
|
size_t n = 0;
|
|
for (auto& e : fs::directory_iterator(data, ec)) {
|
|
auto name = e.path().filename().string(); auto ext = e.path().extension().string();
|
|
bool store = ext == ".idx" || ext == ".lru" || name == "shmem" ||
|
|
(name.size() == 8 && name.rfind("data.", 0) == 0 && isdigit(name[5]) && isdigit(name[6]) && isdigit(name[7]));
|
|
if (store && e.is_regular_file(ec) && !keep.count(name) && fs::remove(e.path(), ec)) ++n;
|
|
}
|
|
if (n) say("Removed %zu leftover store file(s) of an older install", n);
|
|
}
|
|
struct InstallList {
|
|
std::vector<InstallFile> files;
|
|
std::string base, release;
|
|
|
|
bool torrent_compatible() const {
|
|
// A torrent piece can span multiple files. Even --select-file can
|
|
// read or write a retired neighbor, so use HTTP for a stale base.
|
|
return std::none_of(files.begin(),files.end(),[](const auto& f){ return f.retired; });
|
|
}
|
|
};
|
|
|
|
static InstallList signed_install_list(const current_files::RetiredPaths& retired) {
|
|
std::string man = get_text(g_base + "install.txt"), sig = get_text(g_base + "install.txt.sig", false);
|
|
if (!verify(man, sig)) throw Fail("install file list signature is not valid; nothing installed");
|
|
InstallList list;
|
|
auto& [files,base,release] = list;
|
|
bool head = false, end = false;
|
|
std::istringstream in(man);
|
|
for (std::string l; std::getline(in, l);) {
|
|
if (!l.empty() && l.back() == '\r') l.pop_back(); if (l.empty()) continue;
|
|
if (l.rfind("OCTO-INSTALL ", 0) == 0) { if (l != "OCTO-INSTALL 1") throw Fail("unsupported install list format"); head = true; }
|
|
else if (l.rfind("RELEASE ", 0) == 0) release = l.substr(8);
|
|
else if (l.rfind("BASE ", 0) == 0) base = l.substr(5);
|
|
else if (l == "END") end = true;
|
|
else if (l.rfind("F ", 0) == 0) {
|
|
auto a = l.find(' ', 2), b = a == std::string::npos ? a : l.find(' ', a + 1);
|
|
if (b == std::string::npos) throw Fail("bad install list line");
|
|
auto path = l.substr(b + 1);
|
|
files.push_back({l.substr(2, a - 2), path, std::stoull(l.substr(a + 1, b - a - 1)), retired.matches(path)});
|
|
} else throw Fail("bad install list line");
|
|
}
|
|
if (!head || !end || base.empty() || base.find("..") != std::string::npos) throw Fail("incomplete install list");
|
|
return list;
|
|
}
|
|
|
|
// Old installers had no in-progress flag. A cache entry by itself is not proof
|
|
// of a partial install: establish that its existing store and managed files
|
|
// belong to the unchanged signed bootstrap before resuming the old download.
|
|
static bool legacy_partial_install(const InstallList& base, const Outputs& published, VerifiedFiles& verified) {
|
|
if (fs::exists(g_work / "manifest.txt.sig") || fs::exists(g_work / "active-build.txt")) return false;
|
|
if (!fs::exists(g_work / "verified.txt")) { // A preseed has no interrupted-install cache.
|
|
if (fs::exists(g_work / "compacted.txt") || fs::exists(g_work / "applied.txt")) return false;
|
|
if (stock_base::repairable(base.files,g_root/"Data"/"data",[&](const InstallFile& f) {
|
|
return verified.matches(f.path,f.size,f.sha,true);
|
|
},false).empty()) return false;
|
|
}
|
|
std::map<std::string,const InstallFile*> expected;
|
|
for (const auto& f : base.files) expected[current_files::path_key(f.path)] = &f;
|
|
std::set<std::string> present;
|
|
for (const auto& [key,output] : published) {
|
|
if (key == "octoupdater.exe" || key == "octoupdater.cfg") continue;
|
|
if (fs::exists(at(output.path))) present.insert(key);
|
|
}
|
|
for (auto key : {"_patch/applied.txt", "_patch/compacted.txt"})
|
|
if (fs::exists(at(key))) present.insert(key);
|
|
for (auto path : {"Data/data","Data/config"}) {
|
|
auto dir = at(path);
|
|
if (!fs::exists(dir)) continue;
|
|
for (const auto& e : fs::recursive_directory_iterator(dir)) {
|
|
if (!e.is_regular_file() || e.path().extension() == ".part") continue;
|
|
present.insert(current_files::path_key(e.path().lexically_relative(g_root).generic_string()));
|
|
}
|
|
}
|
|
if (present.empty()) return false;
|
|
for (const auto& key : present) {
|
|
auto it = expected.find(key);
|
|
if (it == expected.end() || !verified.matches(it->second->path,it->second->size,it->second->sha,true))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static const InstallFile* base_activation(const InstallList& base) {
|
|
for (const auto& f : base.files)
|
|
if (current_files::path_key(f.path) == ".build.info") return &f;
|
|
return nullptr;
|
|
}
|
|
|
|
static std::string recorded_base_key(const InstallFile* marker) {
|
|
std::ifstream in(g_work / "base-activation.txt");
|
|
std::string sha,key;
|
|
if (marker && in >> sha >> key && sha == marker->sha) return key;
|
|
return {};
|
|
}
|
|
|
|
// A compacted store can select unrelated byte offsets for exactly the same
|
|
// build. Restore physical publisher bytes only with the signed layout proof.
|
|
static void repair_stock(const InstallList& base, const std::string& key, const Outputs& content,
|
|
const std::vector<Step>& steps, VerifiedFiles& verified) {
|
|
auto marker = base_activation(base);
|
|
if (!marker) return;
|
|
bool marker_agrees = verified.matches(marker->path,marker->size,marker->sha,true);
|
|
auto activation = content.find(".build.info");
|
|
bool signed_base = activation != content.end() && activation->second.sha == marker->sha;
|
|
bool recorded_base = !key.empty() && recorded_base_key(marker) == key;
|
|
if (!marker_agrees && !signed_base && !recorded_base) return;
|
|
auto paths = stock_base::repairable(base.files,g_root/"Data"/"data",[&](const InstallFile& f) {
|
|
return verified.matches(f.path,f.size,f.sha,true);
|
|
},marker_agrees);
|
|
if (paths.empty()) return;
|
|
for (const auto& f : base.files) {
|
|
if (!paths.count(current_files::path_key(f.path)) || verified.matches(f.path,f.size,f.sha,true)) continue;
|
|
say(" Restoring signed stock file %s",f.path.c_str());
|
|
download(g_base+base.base+url_path(f.path),at(f.path),f.size,f.sha);
|
|
}
|
|
// A channel can start with a new compact base and no ACTIVATE history.
|
|
if (!marker_agrees && activation == content.end() && recorded_base) {
|
|
auto cfg_key = "data/config/"+key.substr(0,2)+"/"+key.substr(2,2)+"/"+key;
|
|
for (const auto& f : base.files) {
|
|
if (current_files::path_key(f.path) == cfg_key && !verified.matches(f.path,f.size,f.sha,true))
|
|
download(g_base+base.base+url_path(f.path),at(f.path),f.size,f.sha);
|
|
}
|
|
auto temp = g_work / "stage" / "base-activation";
|
|
download(g_base+base.base+url_path(marker->path),temp,marker->size,marker->sha);
|
|
if (build_key(temp) != key) throw Fail("base activation disagrees with recorded installed build");
|
|
verify_store(steps,key);
|
|
if (!MoveFileExW(temp.c_str(),at(marker->path).c_str(),MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
|
throw Fail("cannot restore signed base activation");
|
|
}
|
|
}
|
|
|
|
static void record_base(const InstallList& base, const std::string& key, VerifiedFiles& verified) {
|
|
auto marker = base_activation(base);
|
|
if (marker && verified.matches(marker->path,marker->size,marker->sha,true) && recorded_base_key(marker) != key) {
|
|
save_list_cache(g_work / "base-activation.txt",marker->sha+" "+key+"\n");
|
|
save_active_build(key);
|
|
}
|
|
}
|
|
|
|
static void install(bool repair, std::map<std::string,std::string>& cfg, const Outputs& overrides,
|
|
VerifiedFiles& verified, const InstallList& list) {
|
|
using F = InstallFile;
|
|
const auto& [files,base,release] = list;
|
|
say("%s release %s (%zu files)", repair ? "Checking all client files against" : "Preparing install of", release.c_str(), files.size());
|
|
std::vector<const F*> todo; uint64_t need = 0, partial = 0; std::error_code ec; size_t checked = 0;
|
|
for (auto& f : files) {
|
|
if (f.retired) continue; // leave the installed file and any partial download alone
|
|
fs::path t = at(f.path);
|
|
if (fs::equivalent(t, g_self, ec)) continue; // the running updater: FILES steps keep it current
|
|
auto key = current_files::path_key(f.path);
|
|
if (repair && (current_files::preserve_base_path(key) || overrides.count(key))) continue;
|
|
if (++checked % 500 == 0) say(" checked %zu files", checked);
|
|
if (verified.matches(f.path,f.size,f.sha,repair)) continue;
|
|
todo.push_back(&f); need += f.size;
|
|
fs::path part = t; part += ".part"; if (fs::exists(part, ec)) partial += std::min<uint64_t>(fs::file_size(part, ec), f.size);
|
|
}
|
|
if (todo.empty()) { if (!repair) prune_store(files); say("All client files are complete"); return; }
|
|
ULARGE_INTEGER freeb{}; fs::create_directories(g_root);
|
|
if (GetDiskFreeSpaceExW(g_root.c_str(), &freeb, nullptr, nullptr) && freeb.QuadPart < need - partial + (1ull << 30))
|
|
throw Fail("not enough disk space: need " + std::to_string((need - partial) / 1000000000 + 2) + " GB free in " + g_root.string());
|
|
if (game_running()) throw Fail("close the game before installing");
|
|
std::stable_partition(todo.begin(), todo.end(), [](const F* f) { return f->path != ".build.info"; }); // client marker last
|
|
if (!repair && cfg["p2p"] != "0" && list.torrent_compatible() && need - partial >= uint64_t(std::stod(cfg.count("p2p_min_gb") ? cfg["p2p_min_gb"] : "2") * 1e9)) { // big downloads go peer-to-peer first
|
|
std::set<std::string> want; for (auto* f : todo) want.insert(f->path);
|
|
bool ran = false;
|
|
try { ran = p2p_install(files, want, release, cfg); } catch (const std::exception& e) { say("Peer-to-peer download unavailable (%s) - using direct download", e.what()); }
|
|
if (ran) { // keep only what is still missing or wrong
|
|
std::vector<const F*> left; need = partial = 0; size_t n = 0;
|
|
for (auto* f : todo) {
|
|
fs::path t = at(f->path);
|
|
if (f->path != ".build.info" && fs::exists(t, ec) && fs::file_size(t, ec) == f->size) {
|
|
if (++n % 200 == 0) say(" checked %zu of %zu files", n, todo.size());
|
|
if (verified.matches(f->path,f->size,f->sha,true)) continue;
|
|
}
|
|
left.push_back(f); need += f->size;
|
|
fs::path part = t; part += ".part"; if (fs::exists(part, ec)) partial += std::min<uint64_t>(fs::file_size(part, ec), f->size);
|
|
}
|
|
todo.swap(left);
|
|
say("%zu file(s), %.1f GB left for direct download", todo.size(), (need - partial) / 1e9);
|
|
}
|
|
}
|
|
g_total = need; g_done = partial;
|
|
say("Downloading %zu files, %.1f GB%s. You can close this window at any time: the next start continues where it stopped.", todo.size(), (need - partial) / 1e9, partial ? " (continuing)" : "");
|
|
size_t downloaded = 0;
|
|
for (auto* f : todo) {
|
|
download(g_base + base + url_path(f->path), at(f->path), f->size, f->sha);
|
|
if (!verified.matches(f->path,f->size,f->sha,true)) throw Fail("download differs: " + f->path);
|
|
if (!repair && ++downloaded % 64 == 0) verified.save();
|
|
}
|
|
g_total = 0; if (!repair) { verified.save(); prune_store(files); }
|
|
say("Install of release %s complete", release.c_str());
|
|
}
|
|
|
|
static bool game_running() {
|
|
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32W e{}; e.dwSize = sizeof e; bool hit = false;
|
|
if (snap != INVALID_HANDLE_VALUE) { for (BOOL ok = Process32FirstW(snap, &e); ok; ok = Process32NextW(snap, &e)) if (!_wcsicmp(e.szExeFile, L"WowB.exe")) hit = true; CloseHandle(snap); }
|
|
return hit;
|
|
}
|
|
static std::map<std::string, std::string> config() { // client folder's cfg, else one next to the exe, else defaults
|
|
std::ifstream f(g_root / "OctoUpdater.cfg"); if (!f) f.open(g_self.parent_path() / "OctoUpdater.cfg");
|
|
return gateway::client_update::read_config(f);
|
|
}
|
|
// Save one key in the OctoUpdater.cfg that config() reads (client folder's, else the one next to the exe): replace its
|
|
// line or append it; every other line stays as it was.
|
|
static void save_config_key(const std::string& key, const std::string& value) {
|
|
fs::path p = g_root / "OctoUpdater.cfg"; std::error_code ec;
|
|
if (!fs::exists(p, ec) && fs::exists(g_self.parent_path() / "OctoUpdater.cfg", ec)) p = g_self.parent_path() / "OctoUpdater.cfg";
|
|
std::vector<std::string> lines; bool found = false;
|
|
{ std::ifstream in(p); for (std::string l; std::getline(in, l);) { if (!l.empty() && l.back() == '\r') l.pop_back();
|
|
if (l.rfind(key + "=", 0) == 0) { if (found) continue; l = key + "=" + value; found = true; } lines.push_back(l); } }
|
|
if (!found) lines.push_back(key + "=" + value);
|
|
std::ofstream o(p, std::ios::trunc | std::ios::binary); for (auto& l : lines) o << l << "\r\n";
|
|
if (!o) say("Could not save %s=%s in %s", key.c_str(), value.c_str(), p.string().c_str());
|
|
}
|
|
static std::error_code& ec_dummy() { static std::error_code e; return e; }
|
|
// Folder picker (Windows Vista+ dialog), starting at the suggested folder; empty path = cancelled.
|
|
static fs::path pick_folder(const fs::path& suggest) {
|
|
fs::path out; CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
|
|
IFileOpenDialog* d = nullptr;
|
|
if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&d)))) {
|
|
DWORD o = 0; d->GetOptions(&o); d->SetOptions(o | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
|
|
d->SetTitle(L"Choose where to install OctoWoW (about 82 GB free needed)"); d->SetOkButtonLabel(L"Install here");
|
|
std::error_code ec; fs::path start = suggest; while (!start.empty() && !fs::exists(start, ec)) start = start.parent_path();
|
|
IShellItem* f = nullptr; if (!start.empty() && SUCCEEDED(SHCreateItemFromParsingName(start.c_str(), nullptr, IID_PPV_ARGS(&f)))) { d->SetFolder(f); f->Release(); }
|
|
if (SUCCEEDED(d->Show(nullptr))) {
|
|
IShellItem* r = nullptr; PWSTR p = nullptr;
|
|
if (SUCCEEDED(d->GetResult(&r)) && SUCCEEDED(r->GetDisplayName(SIGDN_FILESYSPATH, &p))) { out = p; CoTaskMemFree(p); }
|
|
if (r) r->Release();
|
|
}
|
|
d->Release();
|
|
} else out = suggest; // no dialog available (old Wine/headless): use the suggestion
|
|
return out;
|
|
}
|
|
// Desktop shortcut "OctoWoW" -> <client>\OctoUpdater.exe (the updater checks for updates, then starts the game).
|
|
static void desktop_shortcut() {
|
|
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); PWSTR desk = nullptr; IShellLinkW* l = nullptr;
|
|
if (FAILED(SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &desk))) return;
|
|
fs::path lnk = fs::path(desk) / L"OctoWoW.lnk"; CoTaskMemFree(desk);
|
|
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&l)))) {
|
|
fs::path exe = g_root / "OctoUpdater.exe";
|
|
l->SetPath(exe.c_str()); l->SetWorkingDirectory(g_root.c_str()); l->SetDescription(L"OctoWoW (updates, then starts the game)");
|
|
fs::path icon = g_root / "_classic_beta_" / "WowB.exe"; l->SetIconLocation((fs::exists(icon, ec_dummy()) ? icon : exe).c_str(), 0);
|
|
IPersistFile* pf = nullptr; if (SUCCEEDED(l->QueryInterface(IID_PPV_ARGS(&pf)))) { if (SUCCEEDED(pf->Save(lnk.c_str(), TRUE))) say("Desktop shortcut OctoWoW created"); pf->Release(); }
|
|
l->Release();
|
|
}
|
|
}
|
|
// The store carries enUS data only: a client started on a non-English Windows (deDE, frFR...) picks that locale,
|
|
// finds ~17k locale files missing and asserts on a TACT key request (report 20261125-210717, #65). Pin the locales
|
|
// (and the portal, when absent) in WTF/Config.wtf before every launch; the client keeps the other lines.
|
|
static void ensure_client_config() {
|
|
if (game_running()) return; // a running client rewrites Config.wtf on exit
|
|
fs::path p = g_root / "_classic_beta_" / "WTF" / "Config.wtf"; std::error_code ec; fs::create_directories(p.parent_path(), ec);
|
|
std::vector<std::string> lines; { std::ifstream in(p); for (std::string l; std::getline(in, l);) { if (!l.empty() && l.back() == '\r') l.pop_back(); lines.push_back(l); } }
|
|
const std::pair<const char*, const char*> want[] = {{"textLocale", "enUS"}, {"audioLocale", "enUS"}, {"portal", nullptr}};
|
|
bool changed = false;
|
|
for (auto [k, v] : want) {
|
|
std::string pre = std::string("SET ") + k + " ", line = pre + "\"" + (v ? v : "play") + "\""; bool found = false;
|
|
for (auto& l : lines) if (l.rfind(pre, 0) == 0) { found = true; if (v && l != line) { say("Client setting %s was %s: set to %s", k, l.substr(pre.size()).c_str(), v); l = line; changed = true; } }
|
|
if (!found) { lines.push_back(line); changed = true; }
|
|
}
|
|
if (!changed) return;
|
|
std::ofstream o(p, std::ios::trunc | std::ios::binary); for (auto& l : lines) o << l << "\r\n";
|
|
}
|
|
|
|
static void launch_game(const std::vector<std::wstring>& args, bool dialog) {
|
|
const auto state = smart_app_control::read_policy();
|
|
const auto label = smart_app_control::describe(state);
|
|
const auto logs = g_root / "_classic_beta_" / "Logs";
|
|
std::error_code ec;
|
|
fs::create_directories(logs, ec);
|
|
std::ofstream(logs / "Gateway.log", std::ios::app) << "[OctoUpdater] Prelaunch Smart App Control: " << label << "\n";
|
|
say("Prelaunch Smart App Control: %s", label);
|
|
if (state == smart_app_control::State::Enforced) {
|
|
if (dialog) smart_app_control::show_help(nullptr, L"Smart App Control is on. Windows may block OctoWoW at startup.");
|
|
else say("Windows may block the self-signed gateway files. See %ls", smart_app_control::help_url);
|
|
}
|
|
fs::path dir = g_root / "_classic_beta_", exe = dir / "WowB.exe"; std::wstring cmd = L"\"" + exe.wstring() + L"\"";
|
|
for (const auto& arg : args) cmd += std::wstring(L" \"") + arg + L"\"";
|
|
STARTUPINFOW si{}; si.cb = sizeof si; PROCESS_INFORMATION pi{};
|
|
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, &pi)) { say("Cannot start %s", exe.string().c_str()); return; }
|
|
CloseHandle(pi.hThread); CloseHandle(pi.hProcess); say("Game started");
|
|
}
|
|
|
|
class UpdateLock {
|
|
HANDLE handle = INVALID_HANDLE_VALUE;
|
|
public:
|
|
explicit UpdateLock(bool check_only) {
|
|
if (check_only) return;
|
|
auto path = g_work / "updating.lock";
|
|
handle = CreateFileW(path.c_str(),GENERIC_READ | GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,
|
|
FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,nullptr);
|
|
if (handle == INVALID_HANDLE_VALUE) throw Fail("cannot lock this client folder for updating");
|
|
}
|
|
~UpdateLock() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
|
|
};
|
|
|
|
int wmain(int argc, wchar_t** argv) {
|
|
UpdaterOptions options;
|
|
try {
|
|
options=parse_updater_options(argc, argv);
|
|
wait_for_client_exit(options.wait_pid);
|
|
} catch (const std::exception& e) {
|
|
// Unlike a normal update failure, a failed exit wait must not fall
|
|
// through to self-relaunch, installation, or launch of the old client.
|
|
say("UPDATE FAILED: %s", e.what());
|
|
return 1;
|
|
}
|
|
wchar_t self[MAX_PATH]; GetModuleFileNameW(nullptr, self, MAX_PATH); g_self = self; g_root = g_self.parent_path();
|
|
{ fs::path old = g_self; old += L".old"; DeleteFileW(old.c_str()); }
|
|
// Where the client lives: this folder when it holds a client or a started install; otherwise (fresh install) the
|
|
// player picks a folder (--dir <path> for scripts; --no-dialog keeps this folder). A picked folder that has
|
|
// other files gets an OctoWoW subfolder.
|
|
auto started = [](const fs::path& d) { std::error_code e; return fs::exists(d / ".build.info", e) || fs::exists(d / "_patch" / "verified.txt", e) || fs::exists(d / "_classic_beta_", e); };
|
|
auto root_in = [&](fs::path d) {
|
|
if (started(d)) return d;
|
|
std::error_code ec; std::wstring name = d.filename().wstring(); for (auto& ch : name) ch = towlower(ch);
|
|
if (name == L"octowow") return d;
|
|
for (auto& e : fs::directory_iterator(d, ec)) {
|
|
auto n = e.path().filename().wstring(); std::wstring low = n; for (auto& ch : low) ch = towlower(ch);
|
|
if (fs::equivalent(e.path(), g_self, ec) || low == L"octoupdater.cfg" || low == L"_patch" || low.rfind(L"octoupdater", 0) == 0) continue;
|
|
return d / L"OctoWoW"; // other files here (e.g. Downloads, or an OctoWoW folder): keep the client apart
|
|
}
|
|
return d;
|
|
};
|
|
bool dialog_arg = !options.no_dialog; fs::path dir_arg = options.directory;
|
|
bool sub = false;
|
|
if (!dir_arg.empty()) { std::error_code ec; fs::create_directories(dir_arg, ec); g_root = root_in(fs::absolute(dir_arg)); sub = true; }
|
|
else if (!started(g_root)) {
|
|
fs::path pick = dialog_arg ? pick_folder(root_in(g_root)) : fs::path(L"-");
|
|
if (pick.empty()) { MessageBoxW(nullptr, L"No folder chosen - nothing was installed.", L"OctoWoW installer", MB_ICONINFORMATION); return 0; }
|
|
if (pick != L"-") g_root = root_in(pick); else g_root = root_in(g_root);
|
|
sub = !fs::equivalent(g_root, g_self.parent_path(), ec_dummy());
|
|
}
|
|
g_work = g_root / "_patch"; fs::create_directories(g_work); g_log = _wfopen((g_work / "updater.log").c_str(), L"a");
|
|
bool check_only = options.check_only, dialog = !options.no_dialog, repair = options.repair;
|
|
auto cfg = config();
|
|
bool launch = gateway::client_update::should_launch(cfg, options.explicit_launch, options.no_launch);
|
|
int rc = 0;
|
|
try {
|
|
if (cfg["url"].empty()) throw Fail("OctoUpdater.cfg has no url=");
|
|
g_base = cfg["url"]; if (g_base.back() != '/') g_base += '/'; g_base += cfg["channel"] + "/";
|
|
say("OctoWoW updater: %s", g_base.c_str());
|
|
UpdateLock lock(check_only);
|
|
auto list = fetch_signed_list();
|
|
std::string legacy_marker;
|
|
bool compact = list.name == "manifest-store.txt";
|
|
auto manifest = parse(list.body, compact ? &legacy_marker : nullptr, list.signature.size(), cfg["channel"]);
|
|
check_committed_list(manifest,compact ? legacy_marker : list.signature,compact,cfg["channel"]);
|
|
auto& [steps, retired] = manifest;
|
|
auto done = applied();
|
|
VerifiedFiles verified;
|
|
auto installing = g_work / "installing.txt";
|
|
bool has_activation = fs::exists(g_root / ".build.info");
|
|
bool installed_state = fs::exists(g_work / "compacted.txt") || fs::exists(g_work / "applied.txt") ||
|
|
fs::exists(g_work / "manifest.txt.sig") || fs::exists(g_work / "active-build.txt") ||
|
|
fs::exists(g_root / "Data" / "data");
|
|
InstallList base;
|
|
if ((!has_activation || repair) && !check_only) base = signed_install_list(retired);
|
|
bool fresh = !has_activation && !installed_state;
|
|
if (!has_activation && !check_only && !fresh) {
|
|
std::string progress;
|
|
{ std::ifstream f(installing); std::getline(f,progress); }
|
|
bool completed = fs::exists(g_work / "manifest.txt.sig") || fs::exists(g_work / "active-build.txt");
|
|
// installing.txt is removed only after a finished install. The base list itself carries
|
|
// _patch/active-build.txt, applied.txt and compacted.txt, and a torrent download writes them
|
|
// early while .build.info is held back to the end, so an interrupted P2P install looks
|
|
// "completed": the in-progress marker wins over those files.
|
|
if (!progress.empty()) {
|
|
if (progress != base.release)
|
|
say("Unfinished install of release %s in %s: installing release %s over it", progress.c_str(), g_root.string().c_str(), base.release.c_str());
|
|
else
|
|
say("Resuming the unfinished install in %s", g_root.string().c_str());
|
|
fresh = true;
|
|
} else if (!completed) {
|
|
std::set<std::string> ids;
|
|
for (const auto& step : steps) if (step.kind == "FILES") ids.insert(step.id);
|
|
fresh = legacy_partial_install(base,current_files::file_outputs(steps,ids),verified);
|
|
// An install that never completed (e.g. interrupted on an older base release) has no
|
|
// activation and no completion record, so it was never a working client: install the
|
|
// current base over it. Matching files are reused; store leftovers are pruned afterwards.
|
|
if (!fresh) {
|
|
say("Unfinished install in %s (no .build.info): installing the current base over it", g_root.string().c_str());
|
|
fresh = true;
|
|
}
|
|
}
|
|
}
|
|
if (!has_activation && !fresh && !check_only && !repair)
|
|
throw Fail("this OctoWoW client is missing .build.info - run OctoUpdater.exe --repair");
|
|
if (has_activation && !check_only && fs::exists(installing)) {
|
|
std::error_code ec; fs::remove(installing,ec);
|
|
}
|
|
if (fresh) say("No OctoWoW client in %s yet: installing it there", g_root.string().c_str());
|
|
if (options.p2p >= 0) { // player's choice from the command line, remembered for later installs/repairs
|
|
cfg["p2p"] = options.p2p ? "1" : "0"; save_config_key("p2p", cfg["p2p"]);
|
|
say("Peer-to-peer download %s (saved in OctoUpdater.cfg)", options.p2p ? "ON" : "OFF");
|
|
}
|
|
if (fresh && !check_only) {
|
|
if (!cfg.count("p2p") && dialog) { // ask once; the answer is saved
|
|
int a = MessageBoxW(nullptr,
|
|
L"Download the game peer-to-peer?\n\n"
|
|
L"Yes: faster. While the download runs, pieces you already have are shared with other players "
|
|
L"(upload). Sharing stops when the download is finished - nothing peer-to-peer runs afterwards.\n\n"
|
|
L"No: download only directly from the OctoWoW server. Nothing is shared.\n\n"
|
|
L"You can change this later: OctoUpdater.exe --p2p or --no-p2p (or p2p=1 / p2p=0 in OctoUpdater.cfg).",
|
|
L"OctoWoW installer", MB_YESNO | MB_ICONQUESTION);
|
|
cfg["p2p"] = a == IDYES ? "1" : "0"; save_config_key("p2p", cfg["p2p"]);
|
|
}
|
|
if (cfg["p2p"] == "0") say("Peer-to-peer download is off (p2p=0): direct download only");
|
|
if (game_running()) throw Fail("close the game before installing");
|
|
{ std::ofstream marker(installing); if (!(marker << base.release << "\n")) throw Fail("cannot record install progress"); }
|
|
install(false, cfg, {}, verified,base);
|
|
std::error_code ec; fs::remove(installing,ec);
|
|
done = applied();
|
|
if (fresh && sub) { desktop_shortcut(); say("Installed. From now on start %s (or the OctoWoW desktop shortcut)", (g_root / "OctoUpdater.exe").string().c_str()); }
|
|
} else if (fresh) throw Fail("no OctoWoW client here");
|
|
std::string key;
|
|
try { key = build_key(); } catch (const Fail&) { if (!repair || check_only) throw; }
|
|
bool known = std::any_of(steps.begin(),steps.end(),[&](const Step& step) {
|
|
return !key.empty() && (step.parent == key || step.child == key);
|
|
});
|
|
if (fresh) record_base(base,key,verified);
|
|
if (repair && !check_only && (!has_activation || !known) && !fresh) {
|
|
// Recover only an independently recorded, published build. For an older
|
|
// updater the compaction marker may lag activation, so only accept it
|
|
// at a signed channel tip. Verify the store before replacing activation.
|
|
std::string recorded;
|
|
{ std::ifstream f(g_work / "active-build.txt"); std::getline(f,recorded); }
|
|
if (recorded.empty()) { std::ifstream f(g_work / "compacted.txt"); std::getline(f,recorded); }
|
|
bool is_child = false, has_next = false, has_content = false;
|
|
for (const auto& step : steps) {
|
|
if (step.kind != "CONTENT" && step.kind != "STORE") continue;
|
|
has_content = true;
|
|
if (step.child == recorded) is_child = true;
|
|
if (step.parent == recorded) has_next = true;
|
|
}
|
|
bool looks_like_build = key.size() == 32 && key.find_first_not_of("0123456789abcdefABCDEF") == std::string::npos;
|
|
bool foreign_config = looks_like_build && fs::exists(g_root / "Data" / "config" / key.substr(0,2) / key.substr(2,2) / key);
|
|
auto stock = recorded_base_key(base_activation(base));
|
|
if (!has_content && !stock.empty() && !foreign_config && recorded == stock) key = stock;
|
|
else if (has_content || !has_activation || key.empty()) {
|
|
if (is_child && !has_next && !foreign_config) key = recorded;
|
|
else throw Fail("cannot identify the installed build for repair; existing store preserved");
|
|
}
|
|
}
|
|
std::vector<const Step*> todo; std::string k = key; std::set<std::string> fdone = done;
|
|
std::map<std::string, const Step*> store; // a STORE step replaces the CONTENT step with the same parent
|
|
for (auto& s : steps) if (s.kind == "STORE") store[s.parent] = &s;
|
|
for (auto& s : steps) {
|
|
if ((s.kind == "CONTENT" || s.kind == "STORE") && s.parent == k) { const Step* p = store.count(k) ? store[k] : &s; todo.push_back(p); k = p->child; }
|
|
else if (s.kind == "FILES" && !fdone.count(s.id)) { todo.push_back(&s); fdone.insert(s.id); }
|
|
}
|
|
auto content = [](const Step& s) { return s.kind == "CONTENT" || s.kind == "STORE"; };
|
|
known = std::any_of(steps.begin(), steps.end(), [&](const Step& s) { return content(s) && (s.child == key || s.parent == key); });
|
|
if (!known && std::any_of(steps.begin(), steps.end(), content))
|
|
say("Note: this client's build %s is not on the %s channel; content updates skipped", key.substr(0, 8).c_str(), cfg["channel"].c_str());
|
|
say("Client build %s, %zu update(s) available", key.substr(0, 8).c_str(), todo.size());
|
|
const bool skipped_running_client = !check_only && game_running();
|
|
if (skipped_running_client) {
|
|
// Several clients at once: leave updates and their notification cache pending.
|
|
say("A client is already running: file checks and %zu update(s) will wait until all clients are closed", todo.size());
|
|
}
|
|
complete_update_pass(check_only, skipped_running_client, [&] {
|
|
bool completed_without_exception = true;
|
|
auto wanted = current_files::file_outputs(steps,fdone);
|
|
auto damaged = mismatches(wanted,verified,repair);
|
|
check_put_history(steps,done,current_files::file_outputs(steps,done),damaged);
|
|
if (repair && !fresh) {
|
|
auto installed = current_files::content_outputs(steps,key);
|
|
repair_stock(base,key,installed,steps,verified);
|
|
auto activation = installed.extract(".build.info");
|
|
if (activation.empty() && build_key() != key)
|
|
throw Fail("cannot establish signed activation for this store layout");
|
|
restore_outputs(mismatches(installed,verified,true),verified);
|
|
if (!activation.empty()) {
|
|
Outputs marker; marker.insert(std::move(activation));
|
|
auto damaged_marker = mismatches(marker,verified,true);
|
|
if (!damaged_marker.empty()) {
|
|
verify_store(steps,key);
|
|
restore_outputs(damaged_marker,verified);
|
|
}
|
|
}
|
|
}
|
|
for (auto* s : todo) {
|
|
if (s->kind == "STORE") apply_store(*s);
|
|
else if (s->kind == "CONTENT") apply_content(*s);
|
|
if (content(*s)) save_active_build(s->child);
|
|
}
|
|
if (repair && !fresh) {
|
|
auto current = current_files::content_outputs(steps,k);
|
|
Outputs overrides = current;
|
|
overrides.insert(wanted.begin(),wanted.end());
|
|
install(true,cfg,overrides,verified,base);
|
|
verify_store(steps,k);
|
|
record_base(base,k,verified);
|
|
}
|
|
restore_outputs(damaged,verified);
|
|
if (fdone != done) {
|
|
std::ofstream ledger(g_work / "applied.txt",std::ios::app);
|
|
for (auto* s : todo) if (s->kind == "FILES") ledger << s->id << "\n";
|
|
ledger.close(); if (!ledger) throw Fail("cannot save applied FILES history");
|
|
}
|
|
verified.save();
|
|
if (known) save_active_build(k);
|
|
say("Client is up to date (build %s, %zu FILES targets checked)",build_key().substr(0,8).c_str(),wanted.size());
|
|
// Work-dir cleanup (owner 2026-11-29: OCTO grew to 77 GB, 7.4 GB of backup/ + 1.5 GB of blobs/): blobs are only
|
|
// reused to resume a failed pass, and backup/ is never read back; keep only this pass's file backups.
|
|
if (completed_without_exception && !game_running()) {
|
|
std::error_code ec; fs::remove_all(g_work / "blobs", ec);
|
|
std::set<std::string> keep; for (auto* s : todo) if (s->kind == "FILES") keep.insert(s->id);
|
|
for (const auto& [path,file] : damaged) keep.insert(file.step);
|
|
std::vector<fs::path> old;
|
|
for (auto& e : fs::directory_iterator(g_work / "backup", ec)) if (!keep.count(e.path().filename().string())) old.push_back(e.path());
|
|
for (auto& p : old) fs::remove_all(p, ec);
|
|
}
|
|
// Compaction is best-effort maintenance after all selected updates.
|
|
bool stored = std::any_of(todo.begin(), todo.end(), [](const Step* s) { return s->kind == "STORE" || s->kind == "CONTENT"; });
|
|
fs::path mark = g_work / "compacted.txt"; std::string bk = build_key(), last;
|
|
{ std::ifstream m(mark); std::getline(m, last); }
|
|
if (!game_running() && (stored || last != bk)) {
|
|
try { compact_store(); std::ofstream(mark, std::ios::trunc) << bk << "\n"; }
|
|
catch (const std::exception& e) { completed_without_exception = false; say("Store compaction skipped: %s", e.what()); }
|
|
}
|
|
return completed_without_exception;
|
|
}, [&] {
|
|
// Commit the verified pair after a complete pass. The installed
|
|
// notifier still compares the legacy signature file on each login.
|
|
save_list_cache(list.cache_body(), list.body);
|
|
save_list_cache(list.cache_signature(), list.signature);
|
|
save_list_cache(g_work / "manifest.txt.sig", compact ? legacy_marker : list.signature);
|
|
if (!octo_updater::ensure_repair_shortcut(g_root)) say("Could not create the Repair client files shortcut in the client folder");
|
|
});
|
|
} catch (const std::exception& e) {
|
|
say("UPDATE FAILED: %s", e.what()); rc = 1;
|
|
if (dialog) MessageBoxA(nullptr, (std::string("The update did not complete:\n\n") + e.what() + "\n\nDetails: _patch\\updater.log").c_str(), "OctoWoW updater", MB_ICONWARNING);
|
|
}
|
|
if (g_self_replaced && !check_only) { // the old code would otherwise do the launch steps (#65: locale pin came with an update)
|
|
std::wstring cmd = L"\"" + g_self.wstring() + L"\""; for (int i = 1; i < argc; ++i) cmd += std::wstring(L" \"") + argv[i] + L"\"";
|
|
STARTUPINFOW si{}; si.cb = sizeof si; PROCESS_INFORMATION pi{};
|
|
if (CreateProcessW(g_self.c_str(), cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, g_self.parent_path().c_str(), &si, &pi)) {
|
|
say("Updater updated itself: continuing with the new version"); CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
|
|
if (g_log) std::fclose(g_log); return rc;
|
|
}
|
|
}
|
|
if (!check_only) try { ensure_client_config(); } catch (const std::exception& e) { say("Client settings not written: %s", e.what()); }
|
|
if (!check_only && launch) launch_game(options.game_args, dialog); // a failed update leaves the previous build intact and playable
|
|
if (g_log) std::fclose(g_log);
|
|
return rc;
|
|
}
|