Files
WoW-Hybrid-gateway/native/diagnostics_journal.hpp

339 lines
24 KiB
C++

#pragma once
// W36 first slice: typed, bounded, PE-local journal. There is deliberately no
// arbitrary packet/body, player-name, chat, account or authentication API.
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <ctime>
#include <functional>
#include <cstdio>
#include <cstring>
#include <deque>
#include <filesystem>
#include <fstream>
#include <map>
#include <mutex>
#include <span>
#include <string>
#include <thread>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#endif
namespace gw_diagnostics {
enum class Stream:unsigned {Known,Item,Creature,GameObject,Quest,Unhandled,Error,ClientDropped,Count};
inline constexpr std::array<const char*,8> Names={"known_spells","query_item","query_creature","query_gameobject","query_quest","packets_unhandled","packets_error","client_dropped"};
struct Options {
std::filesystem::path directory;
uint64_t stream_bytes=64ULL*1024*1024,session_bytes=256ULL*1024*1024;
uint64_t retained_bytes=256ULL*1024*1024;
size_t queue_bytes=1024*1024,queue_events=256,dedup_keys=4096,retained_sessions=8;
std::string server_kind,stack_commit;
#ifdef GW_DIAGNOSTICS_TEST_HOOKS
std::function<void()> before_worker_start,before_retention_delete;
#endif
};
struct Status {bool enabled=false;uint32_t error=0,capped=0;uint64_t dropped=0;std::array<uint64_t,Names.size()> bytes{},events{};};
class Journal {
struct Event {Stream stream;uint32_t key=0,opcode=0;bool found=true;std::vector<uint8_t> body;std::vector<uint32_t> ids;size_t size()const{return 64+body.size()+ids.size()*4;}};
struct Seen {uint64_t count=0,fingerprint=0;};
Options options_;std::atomic<bool> enabled_{true};std::atomic<uint32_t> error_{0},capped_{0};std::atomic<uint64_t>dropped_{0};
std::array<std::atomic<uint64_t>,Names.size()> bytes_{},events_{};
std::mutex mutex_,io_mutex_;std::condition_variable wake_;std::deque<Event> queue_;size_t queued_=0;bool stopping_=false;std::atomic<uint16_t>realm_{0};std::atomic<uint64_t>control_{0};
using Counters=std::array<std::map<uint64_t,uint64_t>,3>;
Counters counters_;bool flush_requested_=false,end_pending_=false;
std::thread worker_;std::filesystem::path session_;std::chrono::steady_clock::time_point started_=std::chrono::steady_clock::now();
static bool ordinary(const std::filesystem::path&p){
std::error_code e;const auto s=std::filesystem::symlink_status(p,e);
if(e||std::filesystem::is_symlink(s))return false;
#ifdef _WIN32
const auto a=GetFileAttributesW(p.c_str());if(a==INVALID_FILE_ATTRIBUTES||(a&FILE_ATTRIBUTE_REPARSE_POINT))return false;
#endif
return true;
}
static uint64_t hash(std::span<const uint8_t>b){uint64_t h=1469598103934665603ULL;for(auto c:b){h^=c;h*=1099511628211ULL;}return h;}
static std::string hex(std::span<const uint8_t>b){static const char digits[]="0123456789abcdef";std::string s;s.reserve(b.size()*2);for(auto c:b){s+=digits[c>>4];s+=digits[c&15];}return s;}
static bool commit_valid(const std::string&s){return s.size()>=7&&s.size()<=40&&std::all_of(s.begin(),s.end(),[](char c){return(c>='0'&&c<='9')||(c>='a'&&c<='f');});}
static std::string session_name(){
const auto now=std::chrono::system_clock::now();const auto t=std::chrono::system_clock::to_time_t(now);std::tm tm{};
#ifdef _WIN32
gmtime_s(&tm,&t);const auto pid=GetCurrentProcessId();
#else
gmtime_r(&t,&tm);const auto pid=uint32_t(std::hash<std::thread::id>{}(std::this_thread::get_id()));
#endif
char text[64];std::snprintf(text,sizeof(text),"%04d%02d%02dT%02d%02d%02dZ-%u",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec,unsigned(pid));return text;
}
void fail(uint32_t e)noexcept{error_.store(e?e:1);enabled_.store(false);try{std::lock_guard<std::mutex>g(mutex_);dropped_+=queue_.size();queue_.clear();queued_=0;++control_;}catch(...){}wake_.notify_all();}
static bool allowed_name(const std::string&name){
if(name=="manifest.json"||name=="complete"||name=="packet-counters-end")return true;
for(const char*n:Names)if(name==std::string(n)+".jsonl")return true;
return false;
}
struct Retained {
std::filesystem::path path;uint64_t bytes=0;bool safe=true,complete=false;
std::map<std::string,std::pair<uint64_t,std::filesystem::file_time_type>> files;
};
static bool scan_owned(const std::filesystem::path&path,Retained&out){
if(!ordinary(path)||!std::filesystem::is_directory(path))return false;
const auto manifest=path/"manifest.json";
// Check BEFORE opening: never follow a linked/device/FIFO manifest.
if(!ordinary(manifest)||!std::filesystem::is_regular_file(manifest))return false;
std::ifstream input(manifest,std::ios::binary);char prefix[49]{};input.read(prefix,48);
if(std::string(prefix,size_t(input.gcount())).find("{\"kind\":\"wowhybrid-diagnostics-session-v1\"")!=0)return false;
out.path=path;
// Account all known owned bytes even if an unrelated file prevents
// deletion. No unknown filename can hide this session's JSONL bytes.
std::vector<std::string> names={"manifest.json","complete"};
for(const char*n:Names)names.push_back(std::string(n)+".jsonl");
for(const auto&name:names){
const auto file=path/name;std::error_code error;const auto status=std::filesystem::symlink_status(file,error);
if(error||!std::filesystem::exists(status))continue;
if(!ordinary(file)||!std::filesystem::is_regular_file(status)){out.safe=false;continue;}
const auto size=std::filesystem::file_size(file);
if(size>UINT64_MAX-out.bytes)return false;
out.bytes+=size;out.files.emplace(name,std::make_pair(size,std::filesystem::last_write_time(file)));
}
size_t entries=0;
for(const auto&file:std::filesystem::directory_iterator(path)){
if(++entries>16){out.safe=false;break;}
const auto name=file.path().filename().string();
if(!allowed_name(name)||!out.files.contains(name))out.safe=false;
}
out.complete=out.files.contains("complete");return true;
}
static bool previous_process_finished(const std::filesystem::path&path){
#ifdef _WIN32
// Process-lifetime production journals have no DLL-detach destructor.
// A later launch may reclaim only an owned session whose PID is
// positively gone; PID reuse/access denial conservatively retains it.
const auto name=path.filename().string();const auto dash=name.rfind('-');
if(dash==std::string::npos||dash+1==name.size())return false;
uint64_t pid=0;for(size_t i=dash+1;i<name.size();++i){if(name[i]<'0'||name[i]>'9')return false;pid=pid*10+unsigned(name[i]-'0');if(pid>UINT32_MAX)return false;}
if(!pid||pid==GetCurrentProcessId())return false;
HANDLE process=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,DWORD(pid));
if(!process)return GetLastError()==ERROR_INVALID_PARAMETER;
DWORD code=STILL_ACTIVE;const bool finished=GetExitCodeProcess(process,&code)&&code!=STILL_ACTIVE;CloseHandle(process);return finished;
#else
(void)path;return false;
#endif
}
// Wine gives every client process the same Windows PID (32), so an unfinished session can never be proven
// finished by PID and the journal stopped after 8 sessions. An unfinished session nobody wrote for 12 hours is
// reclaimable too; a concurrently running instance keeps its fresh session.
static bool stale(const Retained&d){
if(d.files.empty())return false;
auto newest=d.files.begin()->second.second;
for(const auto&[_,identity]:d.files)newest=std::max(newest,identity.second);
return std::filesystem::file_time_type::clock::now()-newest>std::chrono::hours(12);
}
bool retention(){
if(!std::filesystem::exists(options_.directory))std::filesystem::create_directories(options_.directory);
if(!ordinary(options_.directory)||!std::filesystem::is_directory(options_.directory))return false;
std::vector<Retained>old;uint64_t total=0;size_t scanned=0;
for(const auto& d:std::filesystem::directory_iterator(options_.directory)){
if(++scanned>256)return false;
Retained value;if(!scan_owned(d.path(),value))continue;
if(value.bytes>UINT64_MAX-total)return false;
total+=value.bytes;old.push_back(std::move(value));
}
std::sort(old.begin(),old.end(),[](const auto&a,const auto&b){return a.path.filename()<b.path.filename();});
size_t remaining=old.size();
for(const auto& d:old){
if(total<=options_.retained_bytes&&remaining<options_.retained_sessions)break;
if(!d.safe||(!d.complete&&!previous_process_finished(d.path)&&!stale(d)))continue;
#ifdef GW_DIAGNOSTICS_TEST_HOOKS
if(options_.before_retention_delete)options_.before_retention_delete();
#endif
Retained current;
if(!scan_owned(d.path,current)||!current.safe||current.files!=d.files)return false;
// Delete ONLY the validated explicit filenames, never a fresh
// directory enumeration. Keep the ownership manifest until last.
for(const auto&[name,identity]:d.files){
if(name=="manifest.json")continue;
const auto file=d.path/name;
if(!ordinary(file)||!std::filesystem::is_regular_file(file)||
std::filesystem::file_size(file)!=identity.first||std::filesystem::last_write_time(file)!=identity.second)return false;
if(!std::filesystem::remove(file))return false;
}
Retained final;
if(!scan_owned(d.path,final)||!final.safe||final.files.size()!=1||!final.files.contains("manifest.json")||final.files.at("manifest.json")!=d.files.at("manifest.json"))return false;
if(!std::filesystem::remove(d.path/"manifest.json")||!std::filesystem::remove(d.path))return false;
total-=d.bytes;--remaining;
}
return total<=options_.retained_bytes&&remaining<options_.retained_sessions;
}
bool open(){
if(options_.directory.empty()||!retention())return false;
session_=options_.directory/session_name();if(!std::filesystem::create_directory(session_))return false;
std::ofstream manifest(session_/"manifest.json",std::ios::binary);manifest<<"{\"kind\":\"wowhybrid-diagnostics-session-v1\",\"slice\":\"known-definition-and-packet-counters\",\"native_readiness_available\":false,\"command_binding_available\":false}\n";manifest.flush();if(!manifest)return false;
const auto kind=options_.server_kind=="local"||options_.server_kind=="octo"?'"'+options_.server_kind+'"':"null";
const auto commit=commit_valid(options_.stack_commit)?'"'+options_.stack_commit+'"':"null";
uint64_t header_bytes=0;
for(size_t i=0;i<Names.size();++i){
const auto line="{\"schema\":1,\"stream\":\""+std::string(Names[i])+"\",\"client_build\":\"1.60.1.70334\",\"stack_commit\":"+commit+",\"realm_id\":"+std::to_string(realm_.load())+",\"server_kind\":"+kind+",\"native_readiness_available\":false}\n";
header_bytes+=line.size();if(line.size()>options_.stream_bytes||header_bytes>options_.session_bytes)return false;
std::ofstream f(session_/(std::string(Names[i])+".jsonl"),std::ios::binary);f.write(line.data(),std::streamsize(line.size()));f.flush();if(!f)return false;bytes_[i]=line.size();
}
return true;
}
int append(size_t stream,const std::string&line,uint64_t control){
std::lock_guard<std::mutex>io(io_mutex_);
if(!enabled_.load()||control!=control_.load())return 0;
uint64_t total=0;for(const auto& b:bytes_)total+=b.load();
if(bytes_[stream].load()+line.size()>options_.stream_bytes){capped_.fetch_or(1u<<stream);++dropped_;return 0;}
if(total+line.size()>options_.session_bytes){fail(3);return -1;}
std::ofstream f(session_/(std::string(Names[stream])+".jsonl"),std::ios::binary|std::ios::app);f.write(line.data(),std::streamsize(line.size()));f.flush();if(!f){fail(2);return -1;}
bytes_[stream]+=line.size();++events_[stream];return 1;
}
void run()noexcept{
try{
#ifdef GW_DIAGNOSTICS_TEST_HOOKS
if(options_.before_worker_start)options_.before_worker_start();
#endif
bool opened=false;
while(!opened){
uint64_t epoch;
{std::unique_lock<std::mutex>g(mutex_);wake_.wait(g,[&]{return stopping_||enabled_.load()||error_.load();});if(stopping_||error_.load())return;epoch=control_.load();}
bool failed=false;
{std::lock_guard<std::mutex>io(io_mutex_);if(!enabled_.load()||control_.load()!=epoch)continue;opened=open();failed=!opened;}
if(failed){fail(1);return;}
}
std::array<std::map<uint32_t,Seen>,5>seen;
Counters totals;uint64_t transport_ends=0;
for(;;){
std::deque<Event>batch;Counters counters;uint64_t control;bool stop,end;
{std::unique_lock<std::mutex>g(mutex_);wake_.wait_for(g,std::chrono::seconds(1),[&]{return stopping_||!enabled_.load()||flush_requested_;});stop=stopping_;control=control_;end=end_pending_;end_pending_=false;flush_requested_=false;if(enabled_.load()){batch.swap(queue_);counters.swap(counters_);queued_=0;}else{queue_.clear();queued_=0;}}
for(const auto&e:batch){
const auto stream=unsigned(e.stream);auto&table=seen[stream];auto it=table.find(e.key);
if(it==table.end()){if(table.size()>=options_.dedup_keys){++dropped_;continue;}it=table.emplace(e.key,Seen{}).first;}
auto&value=it->second;uint64_t fingerprint=hash(e.body);for(auto id:e.ids){fingerprint^=id;fingerprint*=1099511628211ULL;}fingerprint^=e.found;
const bool payload=value.count==0||value.fingerprint!=fingerprint;const auto count=value.count+1;
const auto ms=std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-started_).count();
std::string line="{\"t\":"+std::to_string(double(ms)/1000.0)+(e.stream==Stream::Known?",\"guid_low\":":",\"id\":")+std::to_string(e.key)+",\"count\":"+std::to_string(count);
if(payload&&e.stream==Stream::Known){line+=",\"source_opcode\":298,\"ids\":[";for(size_t i=0;i<e.ids.size();++i){if(i)line+=',';line+=std::to_string(e.ids[i]);}line+="],\"name_rows\":null,\"spellbook_rows\":null,\"is_spell_known\":null,\"native_observation\":\"unavailable\",\"evidence\":\"parsed-source-initial-list\"";}
else if(payload){line+=",\"source_opcode\":"+std::to_string(e.opcode)+",\"found\":"+(e.found?"true":"false");if(e.found)line+=",\"body_hex\":\""+hex(e.body)+'"';}
line+="}\n";const int written=append(stream,line,control);if(written<0)return;if(written){value.count=count;value.fingerprint=fingerprint;}
}
// Numeric metadata only; a burst occupies one bounded map entry
// per (opcode,size), rather than overflowing the payload queue.
for(size_t i=0;i<counters.size();++i)for(const auto&[key,delta]:counters[i]){
auto& table=totals[i];auto it=table.find(key);
if(it==table.end()){
if(table.size()>=options_.dedup_keys){dropped_+=delta;continue;}
it=table.emplace(key,0).first;
}
const auto count=it->second+std::min(delta,UINT64_MAX-it->second);
const auto ms=std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-started_).count();
const auto line="{\"t\":"+std::to_string(double(ms)/1000.0)+",\"opcode\":"+std::to_string(key>>32)+",\"size\":"+std::to_string(uint32_t(key))+",\"count\":"+std::to_string(count)+"}\n";
const int written=append(i+5,line,control);if(written<0)return;
if(written)it->second=count;
}
if(end){
std::lock_guard<std::mutex>io(io_mutex_);
if(enabled_.load()&&control==control_.load()){
// Rewritten bounded marker, after the requested counter batch.
std::ofstream f(session_/"packet-counters-end",std::ios::binary);
f<<"{\"scope\":\"process-journal\",\"transport_ends\":"<<++transport_ends<<",\"journal_dropped\":"<<dropped_.load()<<",\"capped_streams\":"<<capped_.load()<<"}\n";f.flush();
if(!f){fail(2);return;}
}
}
if(stop)break;
if(!enabled_.load()){std::unique_lock<std::mutex>g(mutex_);wake_.wait(g,[&]{return stopping_||enabled_.load();});if(stopping_)break;}
}
{std::lock_guard<std::mutex>io(io_mutex_);if(enabled_.load()){std::ofstream complete(session_/"complete",std::ios::binary);complete<<"complete\n";}}
}catch(...){fail(4);}
}
bool enqueue(Event event,uint64_t epoch)noexcept{
if(!enabled_.load()||error_.load())return false;
try{std::lock_guard<std::mutex>g(mutex_);const auto size=event.size();if(!enabled_.load()||error_.load()||control_.load()!=epoch||!realm_.load()||stopping_||queue_.size()>=options_.queue_events||size>options_.queue_bytes-std::min(queued_,options_.queue_bytes)){++dropped_;return false;}queued_+=size;queue_.push_back(std::move(event));return true;}catch(...){++dropped_;return false;}
}
public:
explicit Journal(Options options):options_(std::move(options)){}
~Journal(){try{{std::lock_guard<std::mutex>g(mutex_);stopping_=true;}wake_.notify_all();if(worker_.joinable())worker_.join();}catch(...){}}
Journal(const Journal&)=delete;Journal&operator=(const Journal&)=delete;
void begin(uint16_t realm)noexcept{
if(!realm||error_.load()||!enabled_.load())return;
try{std::lock_guard<std::mutex>g(mutex_);if(!enabled_.load()||error_.load())return;if(realm_.load()){if(realm_!=realm){error_=5;enabled_=false;queue_.clear();queued_=0;++control_;wake_.notify_all();}return;}realm_=realm;worker_=std::thread([this]{run();});}catch(...){error_=4;enabled_=false;}
}
void enabled(bool value)noexcept{try{std::lock_guard<std::mutex>io(io_mutex_);std::lock_guard<std::mutex>g(mutex_);if(error_.load())return;enabled_=value;++control_;if(!value){dropped_+=queue_.size();queue_.clear();queued_=0;for(auto&table:counters_){for(auto&row:table)dropped_+=row.second;table.clear();}end_pending_=false;flush_requested_=false;}wake_.notify_all();}catch(...){}}
Status status()const noexcept{Status s;s.enabled=enabled_.load();s.error=error_.load();s.capped=capped_.load();s.dropped=dropped_.load();for(size_t i=0;i<Names.size();++i){s.bytes[i]=bytes_[i].load();s.events[i]=events_[i].load();}return s;}
// There is intentionally no body/string/span parameter at this boundary.
void packet(Stream stream,uint32_t opcode,uint32_t size)noexcept{
if(stream<Stream::Unhandled||stream>Stream::ClientDropped||!enabled_.load()||error_.load())return;
try{std::lock_guard<std::mutex>g(mutex_);if(!enabled_.load()||error_.load()||!realm_.load()||stopping_)return;
auto&table=counters_[unsigned(stream)-unsigned(Stream::Unhandled)];
const auto key=(uint64_t(opcode)<<32)|size;auto it=table.find(key);
if(it==table.end()){if(table.size()>=options_.dedup_keys){++dropped_;return;}it=table.emplace(key,0).first;}
if(it->second<UINT64_MAX)++it->second;
}catch(...){++dropped_;}
}
void session_end()noexcept{
try{std::lock_guard<std::mutex>g(mutex_);if(!enabled_.load()||error_.load()||!realm_.load()||stopping_)return;
end_pending_=true;flush_requested_=true;wake_.notify_all();
}catch(...){}
}
template<class Range>void known(uint64_t guid,const Range&ids)noexcept{
try{const auto epoch=control_.load();if(!enabled_.load()||error_.load()||!guid||!uint32_t(guid))return;Event e{};e.stream=Stream::Known;e.key=uint32_t(guid);for(auto id:ids){if(!id||uint64_t(id)>0x7fffffffu||e.ids.size()>=4096){++dropped_;return;}e.ids.push_back(uint32_t(id));}if(!std::is_sorted(e.ids.begin(),e.ids.end())||std::adjacent_find(e.ids.begin(),e.ids.end())!=e.ids.end()){++dropped_;return;}enqueue(std::move(e),epoch);}catch(...){++dropped_;}
}
// Call ONLY after the existing full definition parser succeeded. The closed
// opcode allowlist cannot store player-name/chat/mail/auth/integrity bodies.
bool definition(uint32_t opcode,uint32_t id,bool found,std::span<const uint8_t>body)noexcept{
Stream stream;switch(opcode){case 0x58:stream=Stream::Item;break;case 0x61:stream=Stream::Creature;break;case 0x5f:stream=Stream::GameObject;break;case 0x5d:stream=Stream::Quest;break;default:return false;}
if(!id||id>0x7fffffffu||body.size()>65535)return false;
try{const auto epoch=control_.load();if(!enabled_.load()||error_.load())return false;Event e{};e.stream=stream;e.key=id;e.opcode=opcode;e.found=found;if(found)e.body.assign(body.begin(),body.end());return enqueue(std::move(e),epoch);}catch(...){++dropped_;return false;}
}
};
inline Options defaults(){Options o;
#ifdef _WIN32
std::vector<wchar_t>path(32768);const auto n=GetModuleFileNameW(nullptr,path.data(),DWORD(path.size()));if(n&&n<path.size())o.directory=std::filesystem::path(std::wstring(path.data(),n)).parent_path()/L"Diagnostics";
#endif
#ifdef GW_DIAGNOSTICS_SERVER_KIND
o.server_kind=GW_DIAGNOSTICS_SERVER_KIND;
#endif
#ifdef GW_DIAGNOSTICS_STACK_COMMIT
o.stack_commit=GW_DIAGNOSTICS_STACK_COMMIT;
#endif
#ifdef _WIN32
// Use the immutable already-loaded Wire selector, without loading a DLL or I/O.
if(auto wire=GetModuleHandleW(L"GWNativeWire.dll")){
using Kind=LONG(WINAPI*)();
const auto proc=GetProcAddress(wire,"gw_source_profile_kind");
Kind kind=nullptr;static_assert(sizeof(kind)==sizeof(proc));std::memcpy(&kind,&proc,sizeof(kind));
if(kind){const auto value=kind();if(value==2)o.server_kind="octo";else if(value==4||value==5)o.server_kind="local";}
}
#endif
return o;
}
// Production is process-lifetime and pins its containing PE module. Never
// join a worker from a static destructor/DllMain under the Windows loader lock.
inline void module_anchor()noexcept{}
inline bool pin_production_module()noexcept{
#ifdef _WIN32
HMODULE module=nullptr;return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_PIN,reinterpret_cast<LPCWSTR>(&module_anchor),&module)!=0;
#else
return true;
#endif
}
template<class Factory>inline Journal* process_instance(Factory&&factory)noexcept{
try{if(!pin_production_module())return nullptr;return factory();}catch(...){return nullptr;}
}
class JournalHandle {
Journal* value_;
public:
explicit JournalHandle(Journal*value=nullptr)noexcept:value_(value){}
void begin(uint16_t realm)const noexcept{if(value_)value_->begin(realm);}
void enabled(bool value)const noexcept{if(value_)value_->enabled(value);}
Status status()const noexcept{if(value_)return value_->status();Status s;s.error=6;return s;}
template<class Range>void known(uint64_t guid,const Range&ids)const noexcept{if(value_)value_->known(guid,ids);}
void packet(Stream stream,uint32_t opcode,uint32_t size)const noexcept{if(value_)value_->packet(stream,opcode,size);}
void session_end()const noexcept{if(value_)value_->session_end();}
bool definition(uint32_t opcode,uint32_t id,bool found,std::span<const uint8_t>body)const noexcept{return value_&&value_->definition(opcode,id,found,body);}
};
inline JournalHandle journal()noexcept{
static Journal*const instance=process_instance([]{return new Journal(defaults());});return JournalHandle(instance);
}
}