Files
WoW-Hybrid-gateway/ops/casc_content_keys.cpp
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

258 lines
18 KiB
C++

// Read-only content identity for known files, including locally missing assets.
// CascFileFullInfo can fail on unavailable spans while CascFileContentKey still
// returns the content identity from the local root/encoding metadata. No online
// storage, downloads, writes, game engine calls or authentication data involved.
// FileID build profile: link ../tools/casc-tool/build/vendor/CascLib/libcasc.a.
// build/casc-tvfs-reference/libcasc.a remains valid for its TVFS/CKey framing
// proofs but may expose no FileDataID resolver; the capability guard rejects it.
#include <CascLib.h>
#include <array>
#include <charconv>
#include <cstdint>
#include <fstream>
#include <filesystem>
#include <iostream>
#include <set>
#include <sstream>
#include <algorithm>
#include <stdexcept>
#include <string>
#include <vector>
static std::string hex(const std::array<unsigned char, 16>& bytes) {
static constexpr char digits[] = "0123456789abcdef";
std::string result;
for (auto b : bytes) { result += digits[b >> 4]; result += digits[b & 15]; }
return result;
}
// Export public content in one local-storage lifetime. This avoids repeatedly
// loading the same multi-million-entry ROOT for each independent byte proof.
static int export_content(const char* local, const char* requests, const char* output, bool diagnostic=false) {
namespace fs = std::filesystem;
struct Request { std::string key; std::array<unsigned char,16> bytes{}; std::uint64_t size; };
if (fs::file_size(requests)>8192*48) throw std::runtime_error("Content request byte bound");
std::ifstream input(requests); if(!input) throw std::runtime_error("Cannot read content requests");
std::vector<Request> rows; std::set<std::string> seen; std::string line; std::uint64_t total=0;
while(std::getline(input,line)) {
Request r; std::string extra; std::istringstream fields(line);
if(rows.size()>=8192 || !(fields>>r.key>>r.size) || (fields>>extra) || r.key.size()!=32 ||
!r.size || r.size>67108864 || !seen.insert(r.key).second)
throw std::runtime_error("Invalid/duplicate content request");
for(size_t i=0;i<16;++i) {
auto digit=[](char c)->unsigned { if(c>='0'&&c<='9')return unsigned(c-'0');
if(c>='a'&&c<='f')return unsigned(c-'a'+10); throw std::runtime_error("Lowercase content key required"); };
r.bytes[i]=static_cast<unsigned char>((digit(r.key[2*i])<<4)|digit(r.key[2*i+1]));
}
total+=r.size; if(total>536870912)throw std::runtime_error("Content batch byte bound");
rows.push_back(r);
}
if(rows.empty())throw std::runtime_error("Empty content batch");
fs::path directory(output);
if(fs::is_symlink(directory)||!fs::is_directory(directory))throw std::runtime_error("Existing regular output directory required");
for(const auto&r:rows)if(fs::exists(directory/(r.key+".bin"))||fs::exists(directory/(r.key+".partial")))
throw std::runtime_error("Existing content output preserved");
CASC_OPEN_STORAGE_ARGS args{};args.Size=sizeof(args);args.szLocalPath=local;args.dwLocaleMask=CASC_LOCALE_ENUS;
HANDLE storage=nullptr;
if(!CascOpenStorageEx(nullptr,&args,false,&storage))throw std::runtime_error("Cannot open local CASC storage");
struct CloseStorage { HANDLE h; ~CloseStorage(){CascCloseStorage(h);} }close{storage};
std::array<char,65536> buffer{};unsigned failed=0;bool first=true;
if(diagnostic)std::cout<<"[\n";
for(const auto&r:rows) {
const char* stage="open";bool opened=false,sized=false,complete=false;DWORD error=0;ULONGLONG size=0;std::uint64_t written=0;
try {
HANDLE file=nullptr;
opened=CascOpenFile(storage,r.bytes.data(),CASC_LOCALE_ENUS,CASC_OPEN_BY_CKEY|CASC_STRICT_DATA_CHECK,&file);
if(!opened){error=GetCascError();throw std::runtime_error("Cannot open local content "+r.key+", SDK error="+std::to_string(error));}
struct CloseFile { HANDLE h; ~CloseFile(){CascCloseFile(h);} }close_file{file};
stage="size";sized=CascGetFileSize64(file,&size);
if(!sized){error=GetCascError();throw std::runtime_error("Local size API failed "+r.key+", SDK error="+std::to_string(error));}
if(size!=r.size)throw std::runtime_error("Local content size differs "+r.key+", expected="+std::to_string(r.size)+", observed="+std::to_string(size));
stage="output";auto partial=directory/(r.key+".partial");std::ofstream stream(partial,std::ios::binary);
if(!stream)throw std::runtime_error("Cannot create private content output");
std::uint64_t remaining=r.size;
while(remaining) {
stage="read";DWORD count=static_cast<DWORD>(std::min<std::uint64_t>(remaining,buffer.size())),received=0;
if(!CascReadFile(file,buffer.data(),count,&received)||received!=count){error=GetCascError();throw std::runtime_error("Strict content read incomplete "+r.key+", SDK error="+std::to_string(error));}
stage="output";stream.write(buffer.data(),received);if(!stream)throw std::runtime_error("Content output incomplete");remaining-=received;written+=received;
}
stream.close();if(!stream)throw std::runtime_error("Content close failed");
fs::rename(partial,directory/(r.key+".bin"));complete=true;stage="complete";
} catch(const std::exception&) {
if(!diagnostic)throw;
++failed;
}
if(diagnostic) {
if(!first)std::cout<<",\n";first=false;
std::cout<<"{\"content_key\":\""<<r.key<<"\",\"expected_size\":"<<r.size<<",\"opened\":"<<(opened?"true":"false")<<",\"size_API_succeeded\":"<<(sized?"true":"false")<<",\"observed_size\":";
if(sized)std::cout<<size;else std::cout<<"null";
std::cout<<",\"stage\":\""<<stage<<"\",\"SDK_error\":"<<error<<",\"bytes_written\":"<<written<<",\"strict_read_complete\":"<<(complete?"true":"false")<<",\"asset_absence_inferred\":false}";
}
}
if(diagnostic)std::cout<<"\n]\n";
else std::cout<<"Strict local content batch: "<<rows.size()<<" payloads, one storage open, "<<total<<" bytes\n";
return failed?1:0;
}
// Bounded named-context diagnostic for an exact preselected resource batch.
// It preserves the existing FileID/CKey modes and never changes ROOT selection.
// Query content identities in one local storage lifetime without exporting bytes.
// A failed local open does not prove the CKey is absent from remote/other stores.
static int content_metadata(const char* local, const char* requests) {
namespace fs = std::filesystem;
if(fs::file_size(requests)>1048576)throw std::runtime_error("Content metadata request byte bound");
std::ifstream in(requests); if(!in)throw std::runtime_error("Cannot read content metadata requests");
std::vector<std::array<unsigned char,16>> rows; std::set<std::string> seen; std::string key;
auto digit=[](char c)->unsigned { if(c>='0'&&c<='9')return unsigned(c-'0');
if(c>='a'&&c<='f')return unsigned(c-'a'+10); throw std::runtime_error("Lowercase content key required"); };
while(in>>key) {
if(rows.size()>=4096 || key.size()!=32 || !seen.insert(key).second)
throw std::runtime_error("Invalid/duplicate content metadata request");
std::array<unsigned char,16> bytes{};
for(size_t i=0;i<16;++i)bytes[i]=static_cast<unsigned char>((digit(key[2*i])<<4)|digit(key[2*i+1]));
rows.push_back(bytes);
}
if(rows.empty())throw std::runtime_error("Empty content metadata batch");
CASC_OPEN_STORAGE_ARGS args{};args.Size=sizeof(args);args.szLocalPath=local;args.dwLocaleMask=CASC_LOCALE_ENUS;
HANDLE storage=nullptr;if(!CascOpenStorageEx(nullptr,&args,false,&storage))throw std::runtime_error("Cannot open local CASC storage");
struct CloseStorage { HANDLE h; ~CloseStorage(){CascCloseStorage(h);} } close_storage{storage};
std::cout<<"[\n";bool first=true;
for(const auto& requested:rows) {
HANDLE file=nullptr;const bool opened=CascOpenFile(storage,requested.data(),CASC_LOCALE_ENUS,CASC_OPEN_BY_CKEY|CASC_STRICT_DATA_CHECK,&file);
const auto open_error=opened?0:GetCascError();
std::array<unsigned char,16> actual{};size_t needed=0;CASC_FILE_FULL_INFO info{};ULONGLONG size=0;
const bool ck=opened&&CascGetFileInfo(file,CascFileContentKey,actual.data(),actual.size(),&needed);
const bool full=opened&&CascGetFileInfo(file,CascFileFullInfo,&info,sizeof(info),&needed);
const bool sized=opened&&CascGetFileSize64(file,&size);
if(opened)CascCloseFile(file);
if(!first)std::cout<<",\n";first=false;
std::cout<<"{\"content_key\":\""<<hex(requested)<<"\",\"opened\":"<<(opened?"true":"false")
<<",\"open_error\":"<<open_error<<",\"returned_key_matches\":"<<(ck&&requested==actual?"true":"false")
<<",\"full_info_available\":"<<(full?"true":"false")<<",\"file_data_id\":";
if(full&&info.FileDataId!=CASC_INVALID_ID)std::cout<<info.FileDataId;else std::cout<<"null";
std::cout<<",\"content_size\":";if(sized)std::cout<<size;else std::cout<<"null";
std::cout<<",\"payload_exported\":false}";
}
std::cout<<"\n]\n";return 0;
}
static int named_paths(const char* local, const char* requests, const char* output) {
namespace fs = std::filesystem;
struct Request {std::string name, retained, file;};
if(fs::file_size(requests)>1048576)throw std::runtime_error("Named request byte bound");
std::ifstream in(requests);if(!in)throw std::runtime_error("Cannot read named requests");
std::vector<Request> rows;std::set<std::string> names, files;std::string line;
while(std::getline(in,line)) {
if(line.size()>2048 || rows.size()>=4096)throw std::runtime_error("Named request count/line bound");
std::istringstream fields(line);Request r;std::string extra;
if(!(fields>>r.name>>r.retained>>r.file) || (fields>>extra))throw std::runtime_error("Three named request fields required");
if(r.name.empty() || r.name.size()>1024 || r.name.front()=='/' || r.name.find("..")!=std::string::npos || r.name.find("//")!=std::string::npos || !std::all_of(r.name.begin(),r.name.end(),[](unsigned char c){return (c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='/'||c=='_'||c=='.'||c=='-';}) || !names.insert(r.name).second)throw std::runtime_error("Unsafe/duplicate named path");
if(r.retained!="-" && (r.retained.size()!=32 || !std::all_of(r.retained.begin(),r.retained.end(),[](unsigned char c){return(c>='0'&&c<='9')||(c>='a'&&c<='f');})))throw std::runtime_error("Invalid retained content key");
if(r.file!="-" && (r.file.size()>128 || r.file.find("..")!=std::string::npos || !std::all_of(r.file.begin(),r.file.end(),[](unsigned char c){return(c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='_'||c=='.'||c=='-';}) || !files.insert(r.file).second))throw std::runtime_error("Unsafe/duplicate named export file");
if(r.file!="-" && fs::exists(fs::path(output)/r.file))throw std::runtime_error("Preserve existing named export");
rows.push_back(std::move(r));
}
if(rows.empty())throw std::runtime_error("Empty named request batch");
CASC_OPEN_STORAGE_ARGS args{};args.Size=sizeof(args);args.szLocalPath=local;args.dwLocaleMask=CASC_LOCALE_ENUS;
HANDLE storage=nullptr;if(!CascOpenStorageEx(nullptr,&args,false,&storage))throw std::runtime_error("Cannot open local CASC storage");
struct CloseStorage{HANDLE h;~CloseStorage(){CascCloseStorage(h);}} close_storage{storage};
std::cout<<"[\n";bool first=true;
for(const auto& r:rows) {
HANDLE file=nullptr;const bool opened=CascOpenFile(storage,r.name.c_str(),CASC_LOCALE_ENUS,CASC_OPEN_BY_NAME|CASC_STRICT_DATA_CHECK,&file);auto open_error=opened?0:GetCascError();
std::array<unsigned char,16> ckey{},ekey{};size_t needed=0;CASC_FILE_FULL_INFO info{};ULONGLONG size=0;
const bool ck=opened&&CascGetFileInfo(file,CascFileContentKey,ckey.data(),ckey.size(),&needed);
const bool ek=opened&&CascGetFileInfo(file,CascFileEncodedKey,ekey.data(),ekey.size(),&needed);
const bool full=opened&&CascGetFileInfo(file,CascFileFullInfo,&info,sizeof(info),&needed);
const bool sized=opened&&CascGetFileSize64(file,&size);
const bool retained=ck&&r.retained!="-"&&hex(ckey)==r.retained;
bool read=false;unsigned int read_error=0;
if(opened && r.file!="-" && !retained) {
if(!ck || !sized || !size || size>67108864) {if(opened)CascCloseFile(file);throw std::runtime_error("Bounded named export identity/size required");}
std::vector<unsigned char> bytes(static_cast<size_t>(size));DWORD actual=0;
read=CascReadFile(file,bytes.data(),static_cast<DWORD>(bytes.size()),&actual)&&actual==size;
if(read) {fs::create_directories(output);std::ofstream out(fs::path(output)/r.file,std::ios::binary);out.write(reinterpret_cast<const char*>(bytes.data()),static_cast<std::streamsize>(bytes.size()));if(!out){CascCloseFile(file);throw std::runtime_error("Named export write failed");}}
else read_error=GetCascError();
}
if(opened)CascCloseFile(file);
if(!first)std::cout<<",\n";first=false;
std::cout<<"{\"name\":\""<<r.name<<"\",\"known\":"<<(opened?"true":"false")<<",\"open_error\":"<<open_error
<<",\"full_info_available\":"<<(full?"true":"false")<<",\"file_data_id\":";
if(full && info.FileDataId!=CASC_INVALID_ID)std::cout<<info.FileDataId;else std::cout<<"null";
std::cout<<",\"content_key\":"<<(ck?'"'+hex(ckey)+'"':"null")<<",\"encoded_key\":"<<(ek?'"'+hex(ekey)+'"':"null")<<",\"content_size\":";
if(sized)std::cout<<size;else std::cout<<"null";
std::cout<<",\"retained_CKey_match\":"<<(retained?"true":"false")<<",\"strict_payload_read\":"<<(read?"true":"false")<<",\"read_error\":"<<read_error<<",\"export_file\":";
if(read)std::cout<<'"'<<r.file<<'"';else std::cout<<"null";
std::cout<<'}';
}
std::cout<<"\n]\n";return 0;
}
int main(int argc, char** argv) {
try {
if(argc==4 && std::string(argv[1])=="--content-key-metadata")return content_metadata(argv[2],argv[3]);
if(argc==5 && std::string(argv[1])=="--named-paths")return named_paths(argv[2],argv[3],argv[4]);
if(argc==5 && std::string(argv[1])=="--diagnose-ckeys")return export_content(argv[2],argv[3],argv[4],true);
if(argc==5 && std::string(argv[1])=="--export-ckeys")return export_content(argv[2],argv[3],argv[4]);
if (argc != 3) throw std::runtime_error("usage: casc-content-keys LOCAL_STORAGE FILE_IDS.txt");
if (std::filesystem::file_size(argv[2]) > 4096 * 11) throw std::runtime_error("File-ID list byte bound");
std::ifstream input(argv[2]);
if (!input) throw std::runtime_error("Cannot read file-ID list");
std::set<std::uint32_t> unique;
std::vector<std::uint32_t> ids;
std::string line;
while (std::getline(input, line)) {
if (line.size() > 10 || ids.size() >= 4096) throw std::runtime_error("File-ID list bound");
std::uint32_t id = 0;
const auto parsed = std::from_chars(line.data(), line.data() + line.size(), id);
if (parsed.ec != std::errc{} || parsed.ptr != line.data() + line.size() || id == 0 || !unique.insert(id).second)
throw std::runtime_error("Invalid or duplicate file ID");
ids.push_back(id);
}
if (ids.empty()) throw std::runtime_error("Empty file-ID list");
CASC_OPEN_STORAGE_ARGS args{};
args.Size = sizeof(args);
args.szLocalPath = argv[1];
args.dwLocaleMask = CASC_LOCALE_ENUS;
HANDLE storage = nullptr;
if (!CascOpenStorageEx(nullptr, &args, false, &storage)) throw std::runtime_error("Cannot open local CASC storage");
struct CloseStorage { HANDLE h; ~CloseStorage() { CascCloseStorage(h); } } close_storage{storage};
// TVFS-only SDK profiles can open this storage but cannot resolve WoW
// FileDataIDs. Such a profile must never manufacture negative asset
// membership from its unsupported lookup API. Keep CKey/TVFS proof
// modes available; use the pinned WoW-root SDK for this FileID mode.
DWORD root_features = 0; size_t feature_bytes = 0;
if (!CascGetStorageInfo(storage, CascStorageFeatures, &root_features, sizeof(root_features), &feature_bytes)
|| !(root_features & CASC_FEATURE_FILE_DATA_IDS))
throw std::runtime_error("Unsupported SDK ROOT resolver: FileDataID lookup unavailable; no asset absence inferred");
std::cout << "[\n";
bool first = true;
for (auto id : ids) {
HANDLE file = nullptr;
const bool opened = CascOpenFile(storage, CASC_FILE_DATA_ID(id), CASC_LOCALE_ENUS, CASC_OPEN_BY_FILEID, &file);
const auto open_error = opened ? 0 : GetCascError();
std::array<unsigned char, 16> ckey{}, ekey{};
size_t needed = 0;
const bool ck = opened && CascGetFileInfo(file, CascFileContentKey, ckey.data(), ckey.size(), &needed);
const bool ek = opened && CascGetFileInfo(file, CascFileEncodedKey, ekey.data(), ekey.size(), &needed);
CASC_FILE_FULL_INFO info{};
const bool available = opened && CascGetFileInfo(file, CascFileFullInfo, &info, sizeof(info), &needed);
const auto info_error = available ? 0 : GetCascError();
if (opened) CascCloseFile(file);
if (!first) std::cout << ",\n";
first = false;
std::cout << "{\"file_data_id\":" << id << ",\"lookup_supported\":true,\"root_features\":" << root_features << ",\"known\":" << (opened ? "true" : "false")
<< ",\"open_error\":" << open_error
<< ",\"full_info_available\":" << (available ? "true" : "false")
<< ",\"full_info_error\":" << info_error
<< ",\"resolved_file_data_id\":" << (available ? std::to_string(info.FileDataId) : "null")
<< ",\"content_size\":" << (available ? std::to_string(info.ContentSize) : "null")
<< ",\"content_key\":" << (ck ? '"' + hex(ckey) + '"' : "null")
<< ",\"encoded_key\":" << (ek ? '"' + hex(ekey) + '"' : "null") << '}';
}
std::cout << "\n]\n";
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}