Files

288 lines
11 KiB
C++

#pragma once
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <optional>
#include <span>
#include <string>
#include <utility>
#include <fcntl.h>
#include <zlib.h>
#ifdef _WIN32
#include <io.h>
#include <sys/stat.h>
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "gateway/protocol.hpp"
namespace gateway::account_data {
constexpr uint32_t UpdateOpcode = 0x4400c4;
constexpr uint32_t RequestOpcode = 0x4400c3;
constexpr uint32_t DataOpcode = 0x4701b4;
constexpr uint32_t CompleteOpcode = 0x4701b5;
constexpr uint32_t Types = 20;
constexpr uint32_t GlobalEditMode = 13, CharacterEditMode = 14;
constexpr uint32_t MaxSize = 0xffff;
constexpr size_t MaxCompressed = 0x20000;
// TrinityCore AccountDataType masks (WorldSession.h): GLOBAL_CACHE_MASK 0x000BA515, PER_CHARACTER 0x00045AEA.
// #80 (report 2244b2): every type is stored client-locally, not only Edit Mode layouts, so keybinds, CVars,
// macros and chat settings survive a restart (the source server has no account-data storage).
constexpr uint32_t PerCharacterMask = 0x00045AEAu;
inline bool per_character(uint32_t type) { return type < Types && ((PerCharacterMask >> type) & 1u); }
inline bool provided(uint32_t type) { return type < Types; }
struct Entry { int64_t time = 0; uint32_t size = 0; Bytes compressed; };
struct Update { Bytes guid; int64_t time = 0; uint32_t size = 0; uint32_t type = 0; Bytes compressed; };
struct Request { Bytes guid; uint32_t type = 0; };
struct Reply { uint32_t opcode = 0; Bytes body; };
inline Update parse_update(std::span<const uint8_t> body) {
Reader r(body);
Update u;
u.time = int64_t(r.le(8));
u.size = uint32_t(r.le(4));
u.guid = unpack_guid(r, 16);
u.type = uint32_t(r.le(4));
auto length = r.le(4);
if (u.type >= Types || u.size > MaxSize || length > MaxCompressed)
throw Error("invalid account data update");
u.compressed = r.take(size_t(length));
r.end();
return u;
}
inline Request parse_request(std::span<const uint8_t> body) {
Reader r(body);
Request q{unpack_guid(r, 16), uint32_t(r.le(4))};
r.end();
if (q.type >= Types) throw Error("invalid account data request");
return q;
}
inline Bytes complete(std::span<const uint8_t> guid, uint32_t type, int32_t result) {
Bytes out = pack_guid(guid);
le(out, type, 4);
le(out, uint32_t(result), 4);
return out;
}
inline Bytes data(const Entry& e, std::span<const uint8_t> guid, uint32_t type) {
Bytes out;
le(out, uint64_t(e.time), 8);
le(out, e.size, 4);
append(out, pack_guid(guid));
le(out, type, 4);
// The stock handler reserves compressBound(0) zero bytes for an absent or erased layout.
if (!e.size) {
const size_t empty_size = compressBound(0);
le(out, empty_size, 4);
out.resize(out.size() + empty_size, 0);
} else {
le(out, e.compressed.size(), 4);
append(out, e.compressed);
}
return out;
}
inline bool valid_payload(const Entry& e) {
if (e.time < 0 || !e.size || e.size > MaxSize || e.compressed.empty() || e.compressed.size() > MaxCompressed)
return false;
// One spare byte permits the inflater to consume its end marker at the declared bound.
Bytes plain(size_t(e.size) + 1);
z_stream z{};
z.next_in = const_cast<Bytef*>(e.compressed.data());
z.avail_in = static_cast<uInt>(e.compressed.size());
z.next_out = plain.data();
z.avail_out = static_cast<uInt>(plain.size());
if (inflateInit(&z) != Z_OK) return false;
const int status = inflate(&z, Z_FINISH);
const bool valid = status == Z_STREAM_END && z.avail_in == 0 && z.total_out == e.size;
return inflateEnd(&z) == Z_OK && valid;
}
inline std::filesystem::path storage_directory() {
#ifdef _WIN32
std::wstring buffer(32768, L'\0');
const auto n = GetModuleFileNameW(nullptr, buffer.data(), DWORD(buffer.size()));
if (!n || n >= buffer.size()) return {};
buffer.resize(n);
return std::filesystem::path(buffer).parent_path() / L"WTF" / L"GatewayAccountData";
#else
return std::filesystem::path("WTF") / "GatewayAccountData";
#endif
}
inline bool valid_character(std::span<const uint8_t> guid) {
return guid.size() == 16 && std::any_of(guid.begin(), guid.end(), [](auto b) { return b != 0; });
}
inline std::filesystem::path account_directory(uint32_t account, const std::filesystem::path& root) {
if (root.empty() || !account) return {};
char dir[9];
std::snprintf(dir, sizeof(dir), "%08x", static_cast<unsigned>(account));
return root / dir;
}
inline std::filesystem::path file(uint32_t account, uint32_t type, std::span<const uint8_t> guid,
const std::filesystem::path& root = storage_directory()) {
auto directory = account_directory(account, root);
if (directory.empty() || !provided(type) || (per_character(type) && !valid_character(guid)))
return {};
std::string name = "t" + std::to_string(type);
if (per_character(type)) {
constexpr char digits[] = "0123456789abcdef";
name += '-';
for (auto b : guid) {
name += digits[b >> 4];
name += digits[b & 15];
}
}
return directory / (name + ".bin");
}
inline std::optional<Entry> load(uint32_t account, uint32_t type, std::span<const uint8_t> guid,
const std::filesystem::path& root = storage_directory()) {
auto path = file(account, type, guid, root);
if (path.empty()) return std::nullopt;
std::ifstream in(path, std::ios::binary);
uint8_t header[16];
if (!in.read(reinterpret_cast<char*>(header), sizeof(header))) return std::nullopt;
Reader r{std::span<const uint8_t>(header)};
Entry e;
e.time = int64_t(r.le(8));
e.size = uint32_t(r.le(4));
auto length = r.le(4);
if (!e.size || e.size > MaxSize || !length || length > MaxCompressed) return std::nullopt;
e.compressed.resize(size_t(length));
if (!in.read(reinterpret_cast<char*>(e.compressed.data()), std::streamsize(length)) ||
in.peek() != std::char_traits<char>::eof() || in.bad() || !valid_payload(e))
return std::nullopt;
return e;
}
// Exclusive creation gives each writer ownership of a single temporary in the destination directory.
inline bool replace_file(const std::filesystem::path& path, const Bytes& content) {
static std::atomic<uint64_t> sequence{};
#ifdef _WIN32
const auto pid = GetCurrentProcessId();
#else
const auto pid = getpid();
#endif
for (unsigned attempt = 0; attempt < 128; ++attempt) {
auto temp = path;
temp += ".tmp-" + std::to_string(pid) + "-" + std::to_string(sequence.fetch_add(1));
#ifdef _WIN32
int fd = _wopen(temp.c_str(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY | _O_NOINHERIT,
_S_IREAD | _S_IWRITE);
#else
int fd = open(temp.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0600);
#endif
if (fd < 0) {
if (errno == EEXIST) continue;
return false;
}
#ifdef _WIN32
auto written = _write(fd, content.data(), static_cast<unsigned>(content.size()));
bool ok = written >= 0 && size_t(written) == content.size() && _commit(fd) == 0;
if (_close(fd) != 0) ok = false;
if (ok) ok = MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
#else
auto written = write(fd, content.data(), content.size());
bool ok = written >= 0 && size_t(written) == content.size() && fsync(fd) == 0;
if (close(fd) != 0) ok = false;
if (ok) ok = std::rename(temp.c_str(), path.c_str()) == 0;
#endif
if (!ok) {
std::error_code ignored;
std::filesystem::remove(temp, ignored);
}
return ok;
}
return false;
}
inline bool save(uint32_t account, uint32_t type, std::span<const uint8_t> guid, const Entry& e,
const std::filesystem::path& root = storage_directory()) {
auto path = file(account, type, guid, root);
if (path.empty() || e.compressed.size() > MaxCompressed) return false;
std::error_code ec;
if (!e.size) {
// The reference treats Size == 0 as erase, before attempting to inflate any bytes.
// Unlink only a file. A directory in its place signals a store error.
#ifdef _WIN32
if (DeleteFileW(path.c_str())) return true;
auto error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND;
#else
return unlink(path.c_str()) == 0 || errno == ENOENT;
#endif
}
if (!valid_payload(e)) return false;
std::filesystem::create_directories(path.parent_path(), ec);
if (ec) return false;
Bytes content;
content.reserve(16 + e.compressed.size());
le(content, uint64_t(e.time), 8);
le(content, e.size, 4);
le(content, e.compressed.size(), 4);
append(content, e.compressed);
return replace_file(path, content);
}
inline bool owns(uint32_t type, std::span<const uint8_t> guid, std::span<const uint8_t> selected) {
return provided(type) && (!per_character(type) ||
(valid_character(selected) && std::ranges::equal(guid, selected)));
}
// The client writes its per-character data (config, bindings, macros, chat: types 1,3,5,7,...) while it
// logs out or quits, after the world session has ended (report 7e7116: tracked quests, nameplate options
// reverted on restart). The character that was last in world keeps owning its per-character data until
// another character enters; only that exact guid is accepted.
struct CharacterOwner {
Guid128 last{};
std::span<const uint8_t> current(bool in_world, std::span<const uint8_t> selected) {
if (in_world && valid_character(selected)) std::ranges::copy(selected, last.begin());
return valid_character(last) ? std::span<const uint8_t>(last) : std::span<const uint8_t>{};
}
};
inline std::optional<Reply> handle(uint32_t account, uint32_t opcode, std::span<const uint8_t> body,
std::span<const uint8_t> selected = {},
const std::filesystem::path& root = storage_directory()) {
if (!account) return std::nullopt;
if (opcode == UpdateOpcode) {
auto u = parse_update(body);
if (!owns(u.type, u.guid, selected)) return std::nullopt;
const bool ok = save(account, u.type, u.guid, {u.time, u.size, std::move(u.compressed)}, root);
return Reply{CompleteOpcode, complete(u.guid, u.type, ok ? 0 : 1)};
}
if (opcode == RequestOpcode) {
auto q = parse_request(body);
if (!owns(q.type, q.guid, selected)) return std::nullopt;
auto e = load(account, q.type, q.guid, root);
const Guid128 empty{};
auto player = valid_character(selected) ? selected : std::span<const uint8_t>(empty);
return Reply{DataOpcode, data(e ? *e : Entry{}, player, q.type)};
}
return std::nullopt;
}
inline int64_t stored_time(uint32_t account, uint32_t type, std::span<const uint8_t> guid,
const std::filesystem::path& root = storage_directory()) {
auto e = load(account, type, guid, root);
return e ? e->time : 0;
}
} // namespace gateway::account_data