Files
WoW-Hybrid-gateway/native/windows_backend_ipc_client.cpp
praxisandClaude Fable 5.2 8e02dccb86 In-client stack: transport, session lifecycle and engine bridge
175 files, from working commit b1a079a.

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

224 lines
8.0 KiB
C++

// Optional existing Wire frontend: owned worker IPC, never an engine hook.
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "windows_backend_ipc.hpp"
#include <array>
#include <string>
#include <windows.h>
#include <winternl.h>
namespace {
using namespace gateway::backend_ipc;
constexpr NTSTATUS Invalid = NTSTATUS(0xc000000d),
Failed = NTSTATUS(0xc0000001);
SRWLOCK mutex = SRWLOCK_INIT;
LONG64 generation_counter = 0;
struct Lock {
Lock() { AcquireSRWLockExclusive(&mutex); }
~Lock() { ReleaseSRWLockExclusive(&mutex); }
};
struct Handle {
HANDLE value = nullptr;
Handle() = default;
explicit Handle(HANDLE handle) : value(handle) {}
Handle(const Handle &) = delete;
Handle &operator=(const Handle &) = delete;
~Handle() { reset(); }
void reset(HANDLE handle = nullptr) noexcept {
if (value && value != INVALID_HANDLE_VALUE)
CloseHandle(value);
value = handle;
}
HANDLE release() noexcept {
auto result = value;
value = nullptr;
return result;
}
};
struct Channel {
Handle process, input, output;
uint64_t generation = 0, sequence = 0;
void close() noexcept {
// EOF lets the existing host close its owned registry tokens. Never kill or
// replay a possibly completed dispatch after reply/transport loss.
input.reset();
output.reset();
if (process.value)
WaitForSingleObject(process.value, 5000);
process.reset();
generation = sequence = 0;
}
~Channel() { close(); }
} channel;
void require(bool value) {
if (!value)
throw gateway::Error("owned backend IPC system boundary");
}
void write(std::span<const uint8_t> bytes) {
size_t done = 0;
while (done < bytes.size()) {
DWORD sent = 0;
require(WriteFile(channel.input.value, bytes.data() + done,
DWORD(bytes.size() - done), &sent, nullptr) != 0 &&
sent != 0);
done += sent;
}
}
void read(uint8_t *bytes, size_t count, ULONGLONG deadline) {
size_t done = 0;
while (done < count) {
DWORD available = 0;
require(PeekNamedPipe(channel.output.value, nullptr, 0, nullptr, &available,
nullptr) != 0);
if (!available) {
if (WaitForSingleObject(channel.process.value, 0) != WAIT_TIMEOUT) {
SetLastError(ERROR_PROCESS_ABORTED);
require(false);
}
if (GetTickCount64() >= deadline) {
SetLastError(ERROR_TIMEOUT);
require(false);
}
Sleep(1);
continue;
}
DWORD received = 0;
require(ReadFile(channel.output.value, bytes + done,
DWORD((std::min)(count - done, size_t(available))),
&received, nullptr) != 0 &&
received != 0);
done += received;
}
}
NTSTATUS dispatch(gw_wire_call *call) {
if (!channel.process.value || !channel.generation) {
SetLastError(ERROR_INVALID_STATE);
return Failed;
}
if (channel.sequence == UINT64_MAX) {
SetLastError(ERROR_ARITHMETIC_OVERFLOW);
channel.close();
return Failed;
}
gateway::Bytes request;
WipeBytes clean_request{request};
const Context context{channel.generation, channel.sequence + 1};
try {
request = encode_request(*call, context);
} catch (const std::exception &) {
SetLastError(ERROR_INVALID_DATA);
call->result = -1;
return Invalid;
}
++channel.sequence;
try {
write(request);
std::array<uint8_t, HeaderBytes> header{};
const auto deadline = GetTickCount64() + 60000;
read(header.data(), header.size(), deadline);
const auto size = frame_size(header);
gateway::Bytes response(HeaderBytes + size);
WipeBytes clean_response{response};
std::copy(header.begin(), header.end(), response.begin());
read(response.data() + HeaderBytes, size, deadline);
return NTSTATUS(apply_response(response, *call, context));
} catch (const std::exception &) {
DWORD error = GetLastError();
channel.close();
call->result = -1;
call->required = call->consumed = call->value = 0;
call->packet = {};
SetLastError(error ? error : ERROR_INVALID_DATA);
return Failed;
}
}
} // namespace
extern "C" NTSTATUS WINAPI
gw_windows_backend_ipc_initialize(const WCHAR *backend) {
Lock lock;
if (channel.process.value)
return NTSTATUS(0x80000011);
try {
const std::wstring path(backend);
auto split = path.find_last_of(L"\\/");
if (split == std::wstring::npos || path.find(L'"') != std::wstring::npos) {
SetLastError(ERROR_INVALID_NAME);
return Invalid;
}
const auto directory = path.substr(0, split),
host = directory + L"\\windows-backend-host.exe";
require(GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES &&
GetFileAttributesW(host.c_str()) != INVALID_FILE_ATTRIBUTES);
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
HANDLE child_in_raw = nullptr, parent_in_raw = nullptr,
parent_out_raw = nullptr, child_out_raw = nullptr;
require(CreatePipe(&child_in_raw, &parent_in_raw, &security, 0) != 0);
Handle child_in(child_in_raw), parent_in(parent_in_raw);
require(CreatePipe(&parent_out_raw, &child_out_raw, &security, 0) != 0);
Handle parent_out(parent_out_raw), child_out(child_out_raw);
require(
SetHandleInformation(parent_in.value, HANDLE_FLAG_INHERIT, 0) != 0 &&
SetHandleInformation(parent_out.value, HANDLE_FLAG_INHERIT, 0) != 0);
Handle error(CreateFileW(L"NUL", GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, &security,
OPEN_EXISTING, 0, nullptr));
require(error.value != INVALID_HANDLE_VALUE);
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput = child_in.value;
startup.StartupInfo.hStdOutput = child_out.value;
startup.StartupInfo.hStdError = error.value;
SIZE_T attribute_bytes = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &attribute_bytes);
require(attribute_bytes != 0);
std::vector<uint8_t> attributes(attribute_bytes);
startup.lpAttributeList =
reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attributes.data());
require(InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0,
&attribute_bytes) != 0);
struct Attributes {
PPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} attribute_guard{startup.lpAttributeList};
const HANDLE handles[]{child_in.value, child_out.value, error.value};
require(UpdateProcThreadAttribute(startup.lpAttributeList, 0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
const_cast<HANDLE *>(handles),
sizeof(handles), nullptr, nullptr) != 0);
const uint64_t generation =
uint64_t(InterlockedIncrement64(&generation_counter));
require(generation != 0);
std::wstring command =
L"\"" + host + L"\" \"" + path + L"\" " + std::to_wstring(generation);
PROCESS_INFORMATION process{};
require(CreateProcessW(host.c_str(), command.data(), nullptr, nullptr, TRUE,
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT,
nullptr, directory.c_str(), &startup.StartupInfo,
&process) != 0);
CloseHandle(process.hThread);
channel.process.reset(process.hProcess);
channel.input.reset(parent_in.release());
channel.output.reset(parent_out.release());
channel.generation = generation;
channel.sequence = 0;
SetLastError(0);
return 0;
} catch (const std::exception &) {
DWORD error = GetLastError();
channel.close();
SetLastError(error ? error : ERROR_INVALID_DATA);
return Failed;
}
}
extern "C" NTSTATUS WINAPI gw_windows_backend_ipc_dispatch(gw_wire_call *call) {
Lock lock;
return dispatch(call);
}
extern "C" NTSTATUS WINAPI gw_windows_backend_ipc_shutdown() {
Lock lock;
channel.close();
return 0;
}