Files

466 lines
30 KiB
C++

#include "source_creation_options.h"
#include "diagnostics_journal.hpp"
#include "source_auth_detail_contract.h"
// The installed Wine Unix-call ABI performs the Windows/Unix context switch.
// No engine functions or sockets are cast, no code/credential buffers exported.
#include "wine_wire_abi.h"
#include "serializer.h"
#include "gateway/protocol.hpp"
#include "gateway/character_creation_lifecycle.hpp"
#include "gateway/turtle_login_profile.hpp"
#include <memory>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <cstddef>
#include <cstring>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <filesystem>
static_assert(sizeof(void*)==8 && sizeof(gw_wire_call)==640);
static_assert(GW_WIRE_ROSTER_DIAGNOSTICS==39 && GW_WIRE_CREATE_CHARACTER==40 && GW_WIRE_CREATE_RESULT==41);
static_assert(GW_WIRE_TRANSPORT_OPEN_IPV4_BYTES==44 && GW_WIRE_INITIAL_SPELL_IDS==45 && GW_WIRE_DIAGNOSTIC_CLIENT_DROP==46);
static_assert(offsetof(gw_wire_call,auth)==32 && offsetof(gw_wire_call,addon_path)==112);
extern "C" int gw_native_authenticate_memory_ipv4_detail(const gw_native_auth_memory_ipv4_config*,gw_native_login**,uint32_t*);
namespace {
using Login=std::unique_ptr<gw_native_login,decltype(&gw_native_login_close)>;
using Transport=std::unique_ptr<gw_native_transport,decltype(&gw_native_transport_close)>;
struct Registry {
std::mutex mutex;
uint64_t next=1;
std::unordered_map<uint64_t,Login> logins;
std::unordered_map<uint64_t,Transport> transports;
std::unordered_map<uint64_t,gateway::character_creation::Lifecycle> creations;
std::unordered_set<uint64_t> create_trace_generations;
} registry;
// A transport handle is monotonic within this owned process, so it is a
// session generation without exposing a pointer, account or packet content.
enum class CreateTraceReason : unsigned {
Entry=0,TransportUnavailable=1,Busy=2,Malformed=3,Unsupported=4,
Capacity=5,SendFailed=6,Submitted=7,Exception=8,RosterNotReady=9,
FeatureUnrepresented=10,RaceClassUnavailable=11,AppearanceUnsupported=12
};
CreateTraceReason create_unsupported_reason(const char* message){
if(!std::strcmp(message,"authenticated preworld roster not ready for creation"))return CreateTraceReason::RosterNotReady;
if(!std::strcmp(message,"native creation feature unrepresented"))return CreateTraceReason::FeatureUnrepresented;
if(!std::strcmp(message,"source creation race/class unavailable"))return CreateTraceReason::RaceClassUnavailable;
if(std::strstr(message,"appearance"))return CreateTraceReason::AppearanceUnsupported;
return CreateTraceReason::Unsupported;
}
struct CreateTraceScope {
bool enabled;
uint64_t generation;
CreateTraceReason reason=CreateTraceReason::Exception;
CreateTraceScope(bool enabled,uint64_t generation):enabled(enabled),generation(generation){emit(0,CreateTraceReason::Entry);}
~CreateTraceScope(){emit(1,reason);}
void emit(unsigned stage,CreateTraceReason why)const{
if(!enabled)return;
auto now=std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
std::fprintf(stderr,"GW create trace event=40 stage=%u reason=%u generation=%llu epoch_ms=%lld\n",
stage,unsigned(why),static_cast<unsigned long long>(generation),static_cast<long long>(now));
}
};
struct SourceCodec {
#ifdef _WIN32
HMODULE module=nullptr;
#else
void* module=nullptr;
#endif
decltype(&gw_codec_serialize) serialize=nullptr;
SourceCodec(){
#if defined(_WIN32) && defined(GW_WINDOWS_LINKED_CODEC)
if(gw_codec_abi()!=GW_CODEC_ABI)throw gateway::Error("source codec ABI mismatch");
serialize=&gw_codec_serialize;
#elif defined(_WIN32)
HMODULE owner=nullptr;
if(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&registry),&owner))throw gateway::Error("owned codec location unavailable");
std::wstring name(32768,L'\0');const auto length=GetModuleFileNameW(owner,name.data(),DWORD(name.size()));
if(!length || length>=name.size())throw gateway::Error("owned codec location unavailable");
name.resize(length);const auto path=std::filesystem::canonical(name).parent_path()/L"forever_codec.dll";
module=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
if(!module)throw gateway::Error("source codec unavailable");
auto abi_symbol=GetProcAddress(module,"gw_codec_abi");auto serialize_symbol=GetProcAddress(module,"gw_codec_serialize");
decltype(&gw_codec_abi) abi=nullptr;
static_assert(sizeof(abi)==sizeof(abi_symbol) && sizeof(serialize)==sizeof(serialize_symbol));
std::memcpy(&abi,&abi_symbol,sizeof(abi));std::memcpy(&serialize,&serialize_symbol,sizeof(serialize));
if(!abi||!serialize||abi()!=GW_CODEC_ABI){FreeLibrary(module);module=nullptr;throw gateway::Error("source codec ABI mismatch");}
#else
Dl_info info{};
if(!dladdr(&registry,&info)||!info.dli_fname)throw gateway::Error("owned codec location unavailable");
auto path=std::filesystem::canonical(info.dli_fname).parent_path()/"forever-schema/libforever_codec.so";
module=dlopen(path.c_str(),RTLD_NOW|RTLD_LOCAL);
if(!module)throw gateway::Error("source codec unavailable");
auto abi=reinterpret_cast<decltype(&gw_codec_abi)>(dlsym(module,"gw_codec_abi"));
serialize=reinterpret_cast<decltype(serialize)>(dlsym(module,"gw_codec_serialize"));
if(!abi||!serialize||abi()!=GW_CODEC_ABI){dlclose(module);module=nullptr;throw gateway::Error("source codec ABI mismatch");}
#endif
}
~SourceCodec(){
#ifndef _WIN32
if(module)dlclose(module);
#else
// Static destruction can run under DllMain's loader lock. The owned
// codec stays resident until process shutdown; never FreeLibrary here.
// ABI-mismatch cleanup above runs during dispatch, outside loader lock.
module=nullptr;
#endif
}
};
template<class Map> auto lookup(Map& map,uint64_t key){auto it=map.find(key);return it==map.end()?nullptr:it->second.get();}
#ifndef _WIN32
// The dispatch mutex serializes these calls. The trace contains no call data.
const char* observed_action(uint32_t opcode){
switch(opcode){
case 0x3e0176:return "cast";
case 0x3f0074:return "logout";
case 0x3f0029:return "gossip";
default:return nullptr;
}
}
long long action_time_ns(){
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
unsigned begin_action_observation(const gw_wire_call& call,bool has_transport){
static const bool enabled=[]{
const char* value=std::getenv("GW_GAMEPLAY_ACTION_TRACE");
return value && std::strcmp(value,"1")==0;
}();
static unsigned recorded=0;
if(!enabled || call.index || recorded>=96)return 0;
const char* action=observed_action(call.opcode);
if(!action)return 0;
const unsigned id=++recorded;
std::fprintf(stderr,"GWActionDispatch time_ns=%lld seq=%u action=%s phase=enter transport=%u output_capacity=%u\n",
action_time_ns(),id,action,unsigned(has_transport),unsigned(call.capacity!=0));
return id;
}
void finish_action_observation(unsigned id,int result){
if(id)std::fprintf(stderr,"GWActionDispatch time_ns=%lld seq=%u phase=return result=%d\n",
action_time_ns(),id,result);
}
#endif
bool creation_native_reply(gw_wire_call& c,const gateway::LegacyPacket& packet){
c.required=uint32_t(packet.body.size());
if(c.required>c.capacity){c.result=-3;return false;}
if(c.required)std::memcpy(c.output,packet.body.data(),c.required);
c.packet={packet.opcode,c.required};c.value=GW_CREATE_NATIVE_REPLY;c.result=0;return true;
}
void creation_local_reject(gw_wire_call& c,uint32_t diagnostic){
c.reserved=diagnostic;creation_native_reply(c,gateway::character_creation::local_compatibility_rejection());
}
}
extern "C" int32_t gw_wire_unix_dispatch(void* pointer){
if(!pointer)return int32_t(0xc000000d);
auto& c=*static_cast<gw_wire_call*>(pointer);
if(c.abi!=GW_WINE_WIRE_ABI || c.size!=sizeof(c))return int32_t(0xc000000d);
c.result=-1;c.required=0;c.consumed=0;c.value=0;c.packet={};
try{
std::lock_guard lock(registry.mutex);
auto login=lookup(registry.logins,c.login);
auto transport=lookup(registry.transports,c.transport);
switch(c.operation){
case GW_WIRE_WORLD_REQUEST:if(transport)c.result=gw_native_transport_world_request(transport,&c.opcode,c.output,c.capacity,&c.required);break;
case GW_WIRE_MOTION_STATE:if(transport)c.result=gw_native_transport_motion_state(transport,c.output,c.capacity,&c.required);break;
case GW_WIRE_INVENTORY_STATE:if(transport)c.result=gw_native_transport_inventory_state(transport,c.output,c.capacity,&c.required);break;
case GW_WIRE_AURA_STATE:if(transport)c.result=gw_native_transport_aura_state(transport,c.output,c.capacity,&c.required);break;
case GW_WIRE_ENTITY_STATE:if(transport)c.result=gw_native_transport_entity_state(transport,c.output,c.capacity,&c.required);break;
case GW_WIRE_DIAGNOSTIC_CLIENT_DROP:
if(transport&&gw_native_transport_authenticated(transport)&&!c.input&&!c.input_bytes&&!c.output&&!c.capacity&&!c.index){
gw_diagnostics::journal().packet(gw_diagnostics::Stream::ClientDropped,c.opcode,c.build);c.result=0;
}
break;
case GW_WIRE_INITIAL_SPELL_IDS:
if(transport && !c.input && !c.input_bytes)
c.result=gw_native_transport_initial_spell_ids(transport,c.output,c.capacity,&c.required);
break;
case GW_WIRE_SAY:if(transport)c.result=gw_native_transport_say(transport,c.input,c.input_bytes,c.output,c.capacity,&c.required);break;
case GW_WIRE_PRIVATE_GAMEPLAY_CAPTURE:if(transport)c.result=gw_native_transport_private_capture_body(transport,c.index,c.opcode,c.build,c.input,c.input_bytes,c.output,c.capacity,&c.required);break;
case GW_WIRE_GAMEPLAY:{
#ifndef _WIN32
const auto observation=begin_action_observation(c,transport!=nullptr);
#endif
if(transport){
if(!c.index){
c.result=gw_native_transport_gameplay(transport,c.opcode,c.input,c.input_bytes,c.output,c.capacity,&c.required);
// A local gameplay reply can be ready without a Source packet to trigger the drain. #93: also
// when the request produced Source packets (bag sort: swaps + BagCleanupFinished); Source replies
// drain ahead of the queue and never repoll it, so the host drains after sending.
if(!c.result && (gw_native_transport_world_call_state(transport,c.realm_id)&64u))
c.value=GW_WIRE_LOCAL_PRESENTATION_READY;
}
else if(c.index==1 && c.opcode==0x440025 && !c.input_bytes && !c.capacity)
c.result=gw_native_transport_gameplay_completed(transport,c.opcode);
}
#ifndef _WIN32
finish_action_observation(observation,c.result);
#endif
break;
}
case GW_WIRE_PING:c.value=GW_NATIVE_ABI;c.result=0;break;
case GW_WIRE_AUTHENTICATE:
case GW_WIRE_AUTHENTICATE_MEMORY:
case GW_WIRE_AUTHENTICATE_MEMORY_IPV4:
case GW_WIRE_AUTHENTICATE_MEMORY_IPV4_HASH:{
c.login=0;
if(registry.logins.size()>=8 || !registry.next){c.result=-5;break;}
gw_native_login* raw=nullptr;
if(c.operation==GW_WIRE_AUTHENTICATE_MEMORY_IPV4_HASH){
if(c.auth.abi || c.auth.auth_port || c.auth.username || c.auth.password_path || c.auth.version_hash_path ||
!c.input || c.input_bytes!=sizeof(gw_native_auth_memory_ipv4_hash_config))break;
gw_native_auth_memory_ipv4_hash_config memory{};
std::memcpy(&memory,c.input,sizeof(memory));
if(memory.abi!=GW_NATIVE_IPV4_HASH_ABI || memory.size!=sizeof(memory) ||
!memory.version_hash || memory.version_hash_bytes!=20)break;
uint32_t detail=0;
c.result=gw_native_authenticate_memory_ipv4_hash_detail(&memory,&raw,
c.reserved==GW_AUTH_DETAIL_REQUEST_V1?&detail:nullptr);
if(c.reserved==GW_AUTH_DETAIL_REQUEST_V1 && c.result==-2 && detail)
c.value=GW_AUTH_DETAIL_RESPONSE_V1|detail;
}else if(c.operation==GW_WIRE_AUTHENTICATE_MEMORY_IPV4){
if(c.auth.abi || c.auth.auth_port || c.auth.username || c.auth.password_path || c.auth.version_hash_path ||
!c.input || c.input_bytes!=sizeof(gw_native_auth_memory_ipv4_config))break;
// Copy only the borrowed POD, avoiding assumptions about its
// alignment in the wire buffer. Pointed inputs stay borrowed.
gw_native_auth_memory_ipv4_config memory{};
std::memcpy(&memory,c.input,sizeof(memory));
uint32_t detail=0;
c.result=gw_native_authenticate_memory_ipv4_detail(&memory,&raw,c.reserved==GW_AUTH_DETAIL_REQUEST_V1?&detail:nullptr);
if(c.reserved==GW_AUTH_DETAIL_REQUEST_V1 && c.result==-2 && detail)c.value=GW_AUTH_DETAIL_RESPONSE_V1|detail;
}else if(c.operation==GW_WIRE_AUTHENTICATE_MEMORY){
// Same real proof-verified login and ownership path. Credentials
// are borrowed only while the owning Windows worker dispatches.
if(c.auth.password_path)break;
const gw_native_auth_memory_config memory{c.auth.abi,c.auth.auth_port,c.auth.username,
c.input,c.input_bytes,c.auth.version_hash_path};
c.result=gw_native_authenticate_memory(&memory,&raw);
}else c.result=gw_native_authenticate(&c.auth,&raw);
Login owned(raw,gw_native_login_close);
if(!c.result){auto id=registry.next++;registry.logins.emplace(id,std::move(owned));c.login=id;}
break;
}
case GW_WIRE_DISCOVER:if(login)c.result=gw_native_discover(login);break;
case GW_WIRE_CONFIRM_REALM_LIST:if(login)c.result=gw_native_confirm_realm_list(login);break;
case GW_WIRE_REALM_COUNT:if(login){c.value=gw_native_realm_count(login);c.result=0;}break;
case GW_WIRE_REALM_AT:c.realm={};if(login)c.result=gw_native_realm_at(login,c.index,&c.realm);break;
case GW_WIRE_LOGIN_CLOSE:if(login){registry.logins.erase(c.login);c.login=0;c.result=0;}break;
case GW_WIRE_TRANSPORT_OPEN:
case GW_WIRE_TRANSPORT_OPEN_IPV4:
case GW_WIRE_TRANSPORT_OPEN_IPV4_BYTES:{
c.transport=0;
if(!login)break;
if(registry.transports.size()>=16 || !registry.next){c.result=-5;break;}
gw_native_transport* raw=nullptr;
if(c.operation==GW_WIRE_TRANSPORT_OPEN_IPV4_BYTES){
if(c.addon_path || c.input_bytes>9999 || (c.input_bytes && !c.input))break;
c.result=gw_native_transport_open_ipv4_bytes(login,c.index,c.input,c.input_bytes,c.build,&raw);
}else c.result=c.operation==GW_WIRE_TRANSPORT_OPEN_IPV4?
gw_native_transport_open_ipv4(login,c.index,c.addon_path,c.build,&raw):
gw_native_transport_open(login,c.index,c.addon_path,c.build,&raw);
Transport owned(raw,gw_native_transport_close);
if(!c.result){auto id=registry.next++;registry.transports.emplace(id,std::move(owned));c.transport=id;}
break;
}
case GW_WIRE_PORT:if(transport){c.value=gw_native_transport_port(transport);c.result=0;}break;
case GW_WIRE_CHALLENGE:if(transport)c.result=gw_native_transport_challenge(transport,c.opcode,c.input,c.input_bytes);break;
case GW_WIRE_AUTH_REQUEST:if(transport)c.result=gw_native_transport_auth_request(transport,c.output,c.capacity,&c.required);break;
case GW_WIRE_FEED:if(transport)c.result=gw_native_transport_feed(transport,c.input,c.input_bytes,&c.consumed);break;
case GW_WIRE_PACKET:if(transport){
c.result=gw_native_transport_packet(transport,&c.packet,c.output,c.capacity);c.required=c.packet.payload_bytes;
if(!c.result)registry.creations[c.transport].observe_source(c.packet.opcode,std::span(c.output,c.packet.payload_bytes));
}break;
case GW_WIRE_SEND:if(transport)c.result=gw_native_transport_send(transport,c.opcode,c.input,c.input_bytes,c.output,c.capacity,&c.required);break;
case GW_WIRE_ACTIVE_MOVER:if(transport)c.result=gw_native_transport_active_mover(transport,c.input,c.input_bytes,c.output,c.capacity,&c.required);break;
case GW_WIRE_MOVEMENT:if(transport)c.result=gw_native_transport_movement(transport,c.opcode,c.input,c.input_bytes,c.output,c.capacity,&c.required);break;
case GW_WIRE_BEGIN_WORLD:if(transport){
auto& creation=registry.creations[c.transport];if(creation.busy())break;
c.result=gw_native_transport_begin_world(transport,c.realm_id,c.input,c.input_bytes,c.output,c.capacity,&c.required);
if(!c.result)creation.enter_world();
}break;
case GW_WIRE_WORLD_PACKET:if(transport){
/* This operation owns reserved. Volatile preserves the last
* completed stage if the synchronous backend call faults. */
auto* phase=static_cast<volatile uint32_t*>(&c.reserved);
*phase=GW_WORLD_CALL_PHASE_MAGIC|1u;
if(!c.input||c.input_bytes!=8)break;
gateway::Reader r(std::span(c.input,c.input_bytes));auto clock=r.le(8);
*phase=GW_WORLD_CALL_PHASE_MAGIC|2u;
/* Publish the bounded pre-call flags before translation so a
* transport fault may retain them; clear on normal success. */
c.value=gw_native_transport_world_call_state(transport,c.realm_id);
*phase=GW_WORLD_CALL_PHASE_MAGIC|3u;
if(c.index==1){
*phase=GW_WORLD_CALL_PHASE_MAGIC|4u;
c.result=gw_native_transport_world_packet(transport,c.realm_id,c.virtual_address,clock,nullptr,c.output,c.capacity,&c.required);
}else if(!c.index){
static SourceCodec codec;
*phase=GW_WORLD_CALL_PHASE_MAGIC|4u;
c.result=gw_native_transport_world_packet(transport,c.realm_id,c.virtual_address,clock,codec.serialize,c.output,c.capacity,&c.required);
}
/* Success-only metadata in the existing value word. This is the
* translator's selected-player state, not an opcode guess; older
* callers ignore it, and no payload or structure changes. */
if(!c.result){c.value=gw_native_transport_world_self_created(transport,c.realm_id)?0x53454c46u:0u;c.reserved=0;}
}break;
case GW_WIRE_AUTHENTICATED:if(transport){c.value=gw_native_transport_authenticated(transport);c.result=0;}break;
case GW_WIRE_TRANSPORT_CLOSE:if(transport){registry.creations.erase(c.transport);registry.transports.erase(c.transport);c.transport=0;c.result=0;}break;
case GW_WIRE_CHARACTER_COUNT:if(transport){c.value=gw_native_transport_character_count(transport);c.result=0;}break;
case GW_WIRE_CHARACTER_AT:c.character={};if(transport)c.result=gw_native_transport_character_at(transport,c.index,&c.character);break;
case GW_WIRE_ROSTER_DIAGNOSTICS:if(transport){
c.required=sizeof(gw_native_roster_diagnostics);
if(!c.output || c.capacity<c.required){c.result=-3;break;}
gw_native_roster_diagnostics report{};
c.result=gw_native_transport_roster_diagnostics(transport,&report);
if(!c.result)std::memcpy(c.output,&report,sizeof(report));
}break;
case GW_WIRE_ENCODE_ROSTER:if(transport){
c.result=gw_native_transport_encode_roster(transport,c.realm_id,c.virtual_address,c.super_district,c.output,c.capacity,&c.required);
if(!c.result)registry.creations[c.transport].bind_roster_context(c.realm_id,c.virtual_address,c.super_district);
}break;
case GW_WIRE_COUNTS:c.value=uint32_t(registry.logins.size());c.consumed=uint32_t(registry.transports.size());c.result=0;break;
case GW_WIRE_ACCOUNT_NAME:
if(transport && !c.input_bytes)c.result=gw_native_transport_account_name(transport,c.output,c.capacity,&c.required);
break;
case GW_WIRE_AUTH_INITIALIZATION:if(transport){
if(c.input_bytes!=8||!c.input)break;
gateway::Reader time(std::span(c.input,c.input_bytes));auto clock=time.le(8);time.end();
uint32_t required=0;c.result=gw_native_transport_auth_metadata(transport,c.virtual_address,clock,nullptr,0,&required);
if(c.result!=-3)break;
gateway::Bytes input(required);c.result=gw_native_transport_auth_metadata(transport,c.virtual_address,clock,input.data(),uint32_t(input.size()),&required);
if(c.result)break;
static SourceCodec codec;
auto result=codec.serialize(GW_CODEC_NATIVE_AUTH_SUCCESS,input.data(),uint32_t(input.size()),0,c.output,c.capacity,&c.required);
c.result=result==GW_CODEC_OK?0:result==GW_CODEC_CAPACITY?-3:result==GW_CODEC_ARGUMENT?-1:-2;
if(!c.result){
// Return exactly the metadata serialized into VirtualRealms, through
// existing response fields carried by both native and Backend IPC.
gateway::Reader metadata(input);c.value=uint32_t(metadata.le(4));metadata.le(8);
const auto length=metadata.le(2);const auto name=metadata.take(length);metadata.end();
if(name.empty()||name.size()>=sizeof(c.realm.name))throw gateway::Error("realm presentation size");
std::memset(c.realm.name,0,sizeof(c.realm.name));
std::memcpy(c.realm.name,name.data(),name.size());
}
break;
}break;
case GW_WIRE_CLIENT_INITIALIZATION:if(transport&&gw_native_transport_authenticated(transport)){
if(!c.input||c.input_bytes!=8)break;
gateway::Bytes input;gateway::le(input,c.virtual_address,4);gateway::le(input,c.index,4);gateway::append(input,std::span(c.input,c.input_bytes));
if(c.index==0){
// #80: all 20 account-data times (global ones from the local store, others 0).
for(uint32_t type=0;type<20;++type)
gateway::le(input,uint64_t(std::max<int64_t>(0,gw_native_transport_global_account_time(transport,type))),8);
}
static SourceCodec codec;
auto result=codec.serialize(GW_CODEC_NATIVE_CLIENT_INITIALIZATION,input.data(),uint32_t(input.size()),0,c.output,c.capacity,&c.required);
c.result=result==GW_CODEC_OK?0:result==GW_CODEC_CAPACITY?-3:result==GW_CODEC_ARGUMENT?-1:-2;
}break;
case GW_WIRE_DB_REPLY_MISSING:if(transport&&gw_native_transport_authenticated(transport)){
if(!c.input||c.input_bytes!=12)break;
static SourceCodec codec;
auto result=codec.serialize(GW_CODEC_NATIVE_DB_REPLY_MISSING,c.input,c.input_bytes,0,c.output,c.capacity,&c.required);
c.result=result==GW_CODEC_OK?0:result==GW_CODEC_CAPACITY?-3:result==GW_CODEC_ARGUMENT?-1:-2;
}break;
case GW_WIRE_HOTFIX_REPLY:if(transport&&gw_native_transport_authenticated(transport)){
if(!c.input||c.input_bytes<12||c.input_bytes>12+4096*4)break;
static SourceCodec codec;
auto result=codec.serialize(GW_CODEC_NATIVE_HOTFIX_REPLY,c.input,c.input_bytes,0,c.output,c.capacity,&c.required);
c.result=result==GW_CODEC_OK?0:result==GW_CODEC_CAPACITY?-3:result==GW_CODEC_ARGUMENT?-1:-2;
}break;
case GW_WIRE_CREATE_CHARACTER_CHALLENGES:
case GW_WIRE_CREATE_CHARACTER:{
const gw_source_creation_options options{c.operation==GW_WIRE_CREATE_CHARACTER_CHALLENGES ? c.reserved : 0u};
CreateTraceScope trace(registry.create_trace_generations.insert(c.transport).second,c.transport);
c.reserved=GW_CREATE_REJECT_NONE;
if(!transport||!gw_native_transport_authenticated(transport)||c.capacity>65535||(!c.output&&c.capacity)){
trace.reason=CreateTraceReason::TransportUnavailable;break;
}
if(!gw_source_creation_options_valid(options) ||
(c.operation==GW_WIRE_CREATE_CHARACTER_CHALLENGES && c.opcode!=0x420070)){
creation_local_reject(c,GW_CREATE_REJECT_MALFORMED);break;
}
auto& creation=registry.creations[c.transport];
if(creation.busy()){c.result=0;c.value=GW_CREATE_NONE;c.reserved=GW_CREATE_REJECT_BUSY;trace.reason=CreateTraceReason::Busy;break;}
const bool rename=c.opcode==gateway::character_creation::NativeRenameOpcode;
if(!c.input||!c.input_bytes||c.input_bytes>4096){
if(rename){c.result=0;c.value=GW_CREATE_NONE;c.reserved=GW_CREATE_REJECT_MALFORMED;}
else creation_local_reject(c,GW_CREATE_REJECT_MALFORMED);
trace.reason=CreateTraceReason::Malformed;break;
}
auto body=std::span(c.input,c.input_bytes);
if(rename || c.opcode==gateway::character_creation::NativeDeleteOpcode){
// Both operations must name a character from the bound Source roster.
gateway::LegacyPacket source;
try{source=rename?creation.prepare_rename(body):creation.prepare_delete(body);}
catch(const gateway::Error& error){
if(rename){c.result=0;c.value=GW_CREATE_NONE;c.reserved=GW_CREATE_REJECT_MALFORMED;}
else{
std::fprintf(stderr,"GW delete refused: %s\n",error.what());
gateway::Bytes failed;gateway::le(failed,68,4);
creation_native_reply(c,gateway::LegacyPacket{gateway::character_creation::NativeDeleteResultOpcode,std::move(failed)});
}
trace.reason=CreateTraceReason::Malformed;break;
}
auto needed=gateway::frame(source.opcode,source.body,true).size();
if(needed>c.capacity){c.required=uint32_t(needed);c.result=-3;trace.reason=CreateTraceReason::Capacity;break;}
gateway::Reader reader(source.body);
const auto counter=reader.le(8);
c.result=gw_native_transport_send(transport,source.opcode,source.body.data(),uint32_t(source.body.size()),c.output,c.capacity,&c.required);
if(!c.result){
if(rename)creation.rename_submitted(counter);
else creation.delete_submitted(counter);
c.packet={source.opcode,uint32_t(source.body.size())};c.value=GW_CREATE_SOURCE_FRAME;
trace.reason=CreateTraceReason::Submitted;
}else trace.reason=CreateTraceReason::SendFailed;
break;
}
try{(void)gateway::character_creation::parse_request(c.opcode,body);}
catch(const gateway::Error&){creation_local_reject(c,GW_CREATE_REJECT_MALFORMED);trace.reason=CreateTraceReason::Malformed;break;}
std::optional<gateway::character_creation::Translation> plan;
try{plan=creation.prepare_request(c.opcode,body,gateway::TurtleSourceRosterRaceClasses);}
catch(const gateway::character_creation::Unsupported& error){creation_local_reject(c,GW_CREATE_REJECT_UNSUPPORTED);trace.reason=create_unsupported_reason(error.what());std::fprintf(stderr,"GW create unsupported: %s\n",error.what());break;}
if(options.challenge_mask && !gw_source_creation_apply(plan->packet.body.data(),plan->packet.body.size(),options)){
creation_local_reject(c,GW_CREATE_REJECT_MALFORMED);break;
}
auto needed=gateway::frame(plan->packet.opcode,plan->packet.body,true).size();
if(needed>c.capacity){c.required=uint32_t(needed);c.result=-3;trace.reason=CreateTraceReason::Capacity;break;}
c.result=gw_native_transport_send(transport,plan->packet.opcode,plan->packet.body.data(),uint32_t(plan->packet.body.size()),c.output,c.capacity,&c.required);
if(!c.result){
creation.request_submitted(std::move(plan->request));c.packet={plan->packet.opcode,uint32_t(plan->packet.body.size())};c.value=GW_CREATE_SOURCE_FRAME;
trace.reason=CreateTraceReason::Submitted;
}else trace.reason=CreateTraceReason::SendFailed;
}break;
case GW_WIRE_CREATE_RESULT:{
c.reserved=GW_CREATE_REJECT_NONE;
if(!transport||!gw_native_transport_authenticated(transport)||c.input||c.input_bytes||c.capacity>65535||(!c.output&&c.capacity))break;
auto found=registry.creations.find(c.transport);if(found==registry.creations.end()){c.result=0;break;}
auto& creation=found->second;
if(auto reply=creation.reply()){
if(creation_native_reply(c,*reply))creation.reply_taken();
}else if(creation.need_roster_request()){
auto needed=gateway::frame(0x37,{},true).size();
if(needed>c.capacity){c.required=uint32_t(needed);c.result=-3;break;}
c.result=gw_native_transport_send(transport,0x37,nullptr,0,c.output,c.capacity,&c.required);
if(!c.result){creation.roster_request_submitted();c.packet={0x37,0};c.value=GW_CREATE_SOURCE_FRAME;}
}else c.result=0;
}break;
case GW_WIRE_GLUE_FEATURES:if(transport)c.result=gw_native_transport_encode_glue_features(transport,c.index,c.output,c.capacity,&c.required);break;
case GW_WIRE_RESTRICTIONS:if(transport)c.result=gw_native_transport_encode_restrictions(transport,c.realm_id,c.virtual_address,c.super_district,c.output,c.capacity,&c.required);break;
}
}catch(...){c.result=-2;}
return 0;
}