Files
WoW-Hybrid-gateway/native/session.cpp
T
praxisandClaude Opus 5.5 4488241bec
Launcher frontends / frontend (ubuntu-22.04) (push) Canceled after 0s
Launcher frontends / frontend (windows-2022) (push) Canceled after 0s
Sync with working repository at cd3c245
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 05:51:18 +02:00

1033 lines
68 KiB
C++

#include "diagnostics_journal.hpp"
#include "accepted_feature_defaults.h"
#include <chrono>
#include "private_gameplay_capture.hpp"
#include "object_update_layout_guard.hpp"
#include "session.h"
#include "wine_wire_abi.h"
#include "gateway/legacy_client.hpp"
#include "gateway/object_updates.hpp"
#include "gateway/world.hpp"
#include "gateway/roster_translation.hpp"
#include "gateway/turtle_login_profile.hpp"
#include "gateway/character_initialization.hpp"
#include "gateway/chat.hpp"
#include "gateway/random_roll.hpp"
#include "gateway/forever_opcode_profile.hpp"
#include <set>
#include "gateway/talents.hpp"
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <optional>
#include <openssl/crypto.h>
#include "world_translation.hpp"
#include "initial_spell_ids.hpp"
struct gw_native_session {
std::unique_ptr<gateway::LegacySession> backend;
std::optional<gateway::LegacyPacket> pending;
bool world_begun=false;
int stream_error=0;
std::optional<uint32_t> ping_sequence;
uint32_t pings_sent=0,pongs_received=0;
};
struct gw_native_login {
std::unique_ptr<gateway::LegacyLogin> backend;
std::vector<gateway::LegacyRealm> realms;
bool discovered=false;
bool explicit_numeric_profile=false;
};
// Read-only character-selection queries belong to the fresh authenticated
// roster, never to a fabricated world/player. Generation changes revoke them.
struct NativeRosterGuildQueries {
uint64_t generation=0;
std::optional<gateway::RosterRealm> context;
std::set<uint32_t> pending;
void refreshed(){++generation;context.reset();pending.clear();}
void bind(gateway::RosterRealm next){
if(!generation || !next.virtual_address || next.realm_id>8191){context.reset();pending.clear();return;}
if(context && (context->realm_id!=next.realm_id || context->virtual_address!=next.virtual_address))pending.clear();
context=next;
}
uint32_t query(const std::vector<gateway::Character>& roster,std::span<const uint8_t> body)const{
using namespace gateway;
if(!generation || !context || roster.empty() || roster.size()>10)throw Error("guild query lacks fresh owned roster");
Reader r(body);auto guild=unpack_guid(r,16),player=unpack_guid(r,16);r.end();
for(const auto& c:roster){
if(!c.guild || !c.guid)continue;
auto expected=forever_guild_guid(c.guild,context->realm_id),member=forever_player_guid(c.guid,context->realm_id);
if(std::equal(guild.begin(),guild.end(),expected.begin()) &&
(player==Bytes(16) || std::equal(player.begin(),player.end(),member.begin())))return c.guild;
}
throw Error("guild query outside owned roster guild/member/realm");
}
gateway::Bytes reply(const std::vector<gateway::Character>& roster,const gateway::GuildInfo& guild,uint32_t realm,uint32_t address){
using namespace gateway;
Bytes result;bool known=generation && context && context->realm_id==realm && context->virtual_address==address &&
pending.contains(guild.id) && std::any_of(roster.begin(),roster.end(),[&](const auto& c){return c.guild==guild.id;});
le(result,known?1:0,4);
if(known){auto body=forever_guild_info(guild,*context);le(result,forever_opcodes::SMSG_QUERY_GUILD_INFO_RESPONSE,4);le(result,body.size(),4);append(result,body);pending.erase(guild.id);}
return result;
}
};
struct gw_native_transport {
gateway::LegacyRealm realm;
bool unmetered_auth=false;
std::vector<gateway::Character> roster;
bool roster_seen=false;
mutable NativeRosterGuildQueries roster_guild;
std::unique_ptr<gateway::WorldAuthentication> authentication;
gateway::Bytes request;
std::optional<gateway::LegacyPacket> pending;
int error=0;
std::unique_ptr<NativeWorldTranslation> world;
std::optional<gateway::LegacyPacket> world_packet;
std::optional<gateway::Bytes> world_encoded;
std::deque<gateway::LegacyPacket> service_presentations;
PrivateGameplayCapture private_capture;
bool private_in_recorded=false;
bool world_error_recorded=false;
~gw_native_transport(){if(!request.empty())OPENSSL_cleanse(request.data(),request.size());}
};
namespace {
bool bounded(const char* s,size_t limit){return s && strnlen(s,limit+1)<=limit && *s;}
}
extern "C" int gw_native_authenticate(const gw_native_auth_config* c,gw_native_login** out){
if(out)*out=nullptr;
if(!c || !out || c->abi!=GW_NATIVE_ABI || !c->auth_port || !bounded(c->username,32) ||
!bounded(c->password_path,1024) || !bounded(c->version_hash_path,1024))return -1;
try{
auto login=std::make_unique<gw_native_login>();
login->backend=std::make_unique<gateway::LegacyLogin>(c->auth_port,c->username,c->password_path,c->version_hash_path);
*out=login.release();return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_discover(gw_native_login* login){
if(!login || !login->backend)return -1;
if(login->discovered)return 0;
try{login->realms=login->backend->realms();login->discovered=true;return 0;}catch(...){return -2;}
}
extern "C" int gw_native_authenticate_memory(const gw_native_auth_memory_config* c,gw_native_login** out){
if(out)*out=nullptr;
if(!c || !out || c->abi!=GW_NATIVE_ABI || !c->auth_port || !bounded(c->username,32) ||
!c->password || !c->password_bytes || c->password_bytes>64 || !bounded(c->version_hash_path,1024))return -1;
for(uint32_t i=0;i<c->password_bytes;++i)if(c->password[i]<32 || c->password[i]>126)return -1;
try{
auto login=std::make_unique<gw_native_login>();
login->backend=std::make_unique<gateway::LegacyLogin>(c->auth_port,c->username,std::span<const uint8_t>(c->password,c->password_bytes),c->version_hash_path);
*out=login.release();return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_authenticate_memory_ipv4_detail(const gw_native_auth_memory_ipv4_config* c,gw_native_login** out,uint32_t* detail){
if(detail)*detail=0;
if(out)*out=nullptr;
if(!c || !out || c->abi!=GW_NATIVE_IPV4_ABI || c->size!=sizeof(*c) || c->reserved ||
!c->auth_port || !bounded(c->auth_ipv4,15) || !bounded(c->username,32) ||
!c->password || !c->password_bytes || c->password_bytes>64 || !bounded(c->version_hash_path,1024))return -1;
for(uint32_t i=0;i<c->password_bytes;++i)if(c->password[i]<32 || c->password[i]>126)return -1;
// Validate the endpoint before opening a file/socket or doing SRP work.
std::optional<gateway::NumericIPv4Endpoint> endpoint;
try{endpoint.emplace(c->auth_ipv4,c->auth_port);}catch(...){return -1;}
try{
auto login=std::make_unique<gw_native_login>();
if(detail)login->backend=std::make_unique<gateway::LegacyLogin>(*endpoint,c->username,
std::span<const uint8_t>(c->password,c->password_bytes),c->version_hash_path,true);
else login->backend=std::make_unique<gateway::LegacyLogin>(*endpoint,c->username,
std::span<const uint8_t>(c->password,c->password_bytes),c->version_hash_path);
login->explicit_numeric_profile=true;*out=login.release();return 0;
}catch(const gateway::SourceAuthRejected& e){if(detail && (e.phase==1 || e.phase==2) && e.code)*detail=(uint32_t(e.phase)<<8)|e.code;return -2;}
catch(...){return -2;}
}
extern "C" int gw_native_authenticate_memory_ipv4(const gw_native_auth_memory_ipv4_config* c,gw_native_login** out){return gw_native_authenticate_memory_ipv4_detail(c,out,nullptr);}
extern "C" int gw_native_authenticate_memory_ipv4_hash_detail(const gw_native_auth_memory_ipv4_hash_config* c,gw_native_login** out,uint32_t* detail){
if(detail)*detail=0;
if(out)*out=nullptr;
if(!c || !out || c->abi!=GW_NATIVE_IPV4_HASH_ABI || c->size!=sizeof(*c) || c->reserved ||
!c->auth_port || !bounded(c->auth_ipv4,15) || !bounded(c->username,32) ||
!c->password || !c->password_bytes || c->password_bytes>64 ||
!c->version_hash || c->version_hash_bytes!=20)return -1;
for(uint32_t i=0;i<c->password_bytes;++i)if(c->password[i]<32 || c->password[i]>126)return -1;
std::optional<gateway::NumericIPv4Endpoint> endpoint;
try{endpoint.emplace(c->auth_ipv4,c->auth_port);}catch(...){return -1;}
try{
auto login=std::make_unique<gw_native_login>();
login->backend=std::make_unique<gateway::LegacyLogin>(*endpoint,c->username,
std::span<const uint8_t>(c->password,c->password_bytes),
std::span<const uint8_t>(c->version_hash,c->version_hash_bytes),detail!=nullptr);
login->explicit_numeric_profile=true;*out=login.release();return 0;
}catch(const gateway::SourceAuthRejected& e){if(detail && (e.phase==1 || e.phase==2) && e.code)*detail=(uint32_t(e.phase)<<8)|e.code;return -2;}
catch(...){return -2;}
}
extern "C" int gw_native_authenticate_memory_ipv4_hash(const gw_native_auth_memory_ipv4_hash_config* c,gw_native_login** out){return gw_native_authenticate_memory_ipv4_hash_detail(c,out,nullptr);}
extern "C" uint32_t gw_native_realm_count(const gw_native_login* login){return login && login->discovered?uint32_t(login->realms.size()):0;}
extern "C" int gw_native_realm_at(const gw_native_login* login,uint32_t index,gw_native_realm* out){
if(!login || !out || !login->discovered || index>=login->realms.size())return -1;
const auto& r=login->realms[index];*out={};out->type=r.type;out->flags=r.flags;out->characters=r.characters;
out->category=r.category;out->wire_id=r.wire_id;out->population=r.population;
std::copy(r.name.begin(),r.name.end(),out->name);std::copy(r.address.begin(),r.address.end(),out->address);return 0;
}
extern "C" int gw_native_select(gw_native_login* login,uint32_t index,const char* addons,uint32_t build,gw_native_session** out){
if(out)*out=nullptr;
if(!login || !login->backend || !out || !login->discovered || index>=login->realms.size() ||
!bounded(addons,1024) || build!=5875)return -1;
try{gateway::local_realm_endpoint(login->realms[index]);}catch(...){return -1;}
try{
auto session=std::make_unique<gw_native_session>();
session->backend=std::make_unique<gateway::LegacySession>(*login->backend,index,addons,build);
*out=session.release();return 0;
}catch(...){return -2;}
}
extern "C" void gw_native_login_close(gw_native_login* login){delete login;}
extern "C" int gw_native_open(const gw_native_config* c,gw_native_session** out){
if(out)*out=nullptr;
if(!c || !out || c->abi!=GW_NATIVE_ABI || !c->auth_port || !c->world_port || c->world_build!=5875 || !bounded(c->username,32) || !bounded(c->password_path,1024) || !bounded(c->version_hash_path,1024) || !bounded(c->addon_path,1024))return -1;
try{
auto s=std::make_unique<gw_native_session>();
s->backend=std::make_unique<gateway::LegacySession>(c->auth_port,c->world_port,c->username,c->password_path,c->version_hash_path,c->addon_path,c->world_build);
*out=s.release();return 0;
}catch(...){return -2;}
}
extern "C" uint32_t gw_native_character_count(const gw_native_session* s){return s && s->backend?uint32_t(s->backend->roster().size()):0;}
extern "C" int gw_native_character_at(const gw_native_session* s,uint32_t index,gw_native_character* out){
if(!s || !s->backend || !out || index>=s->backend->roster().size())return -1;
const auto& c=s->backend->roster()[index];*out={};out->guid=c.guid;out->level=c.level;out->race=c.race;out->class_id=c.cls;
std::copy_n(c.name.data(),std::min(c.name.size(),sizeof(out->name)-1),out->name);return 0;
}
extern "C" int gw_native_enter(gw_native_session* s,uint64_t guid,gw_native_world* out){
if(!s || !s->backend || !out)return -1;
*out={};
auto begun=gw_native_begin_world(s,guid);if(begun)return begun;
try{
bool world=false,self=false;
for(unsigned n=0;n<256;++n){
auto p=s->backend->receive();++out->packets;
if(p.opcode==0x2E6){s->stream_error=-4;return -4;} // Unsupported integrity challenge: never synthesize a response.
if(p.opcode==0x236){auto w=gateway::turtle_login_world(p.body);out->map=w.map;out->x=w.position[0];out->y=w.position[1];out->z=w.position[2];out->orientation=w.position[3];world=true;}
if(p.opcode==0xA9 || p.opcode==0x1F6)for(const auto& o:gateway::turtle_object_updates(p.opcode,p.body)){
if(o.kind==2 || o.kind==3){++out->objects;if(o.guid==guid)self=true;}
}
if(world && self)return 0;
}
return -3;
}catch(...){return -2;}
}
extern "C" int gw_native_encode_roster(const gw_native_session* s,uint32_t realm,uint32_t address,uint32_t district,uint8_t* destination,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!s || !s->backend || !required || (!destination && capacity) || realm>8191 || capacity>1048576)return -1;
try{
auto body=gateway::forever_roster(s->backend->roster(),{realm,address,district},true);
*required=uint32_t(body.size());
if(body.size()>capacity)return -3;
if(!body.empty())std::memcpy(destination,body.data(),body.size());
return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_begin_world(gw_native_session* s,uint64_t guid){
if(!s || !s->backend)return -1;
if(s->stream_error)return s->stream_error;
if(s->world_begun || std::none_of(s->backend->roster().begin(),s->backend->roster().end(),[&](const auto& c){return c.guid==guid;}))return -1;
try{s->backend->login(guid);s->world_begun=true;return 0;}catch(...){s->stream_error=-2;return -2;}
}
extern "C" int gw_native_encode_glue_features(const gw_native_session* s,uint32_t limit,uint8_t* destination,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!s || !s->backend || !required || !limit || limit>10 || (!destination && capacity) || capacity>1048576)return -1;
try{
auto body=gateway::forever_glue_features(limit);*required=uint32_t(body.size());
if(body.size()>capacity)return -3;
std::memcpy(destination,body.data(),body.size());return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_receive(gw_native_session* s,gw_native_packet* out,uint8_t* payload,uint32_t capacity){
if(out)*out={};
if(!s || !s->backend || !out || (!payload && capacity) || capacity>65533)return -1;
if(s->stream_error)return s->stream_error;
if(!s->world_begun)return -1;
try{
if(!s->pending)s->pending=s->backend->receive();
if(s->pending->opcode==0x2E6){s->pending.reset();s->stream_error=-4;return -4;}
out->opcode=s->pending->opcode;out->payload_bytes=uint32_t(s->pending->body.size());
if(out->payload_bytes>capacity)return -3;
if(out->payload_bytes)std::memcpy(payload,s->pending->body.data(),out->payload_bytes);
s->pending.reset();return 0;
}catch(...){s->pending.reset();s->stream_error=-2;return -2;}
}
extern "C" int gw_native_send(gw_native_session* s,uint32_t opcode,const uint8_t* payload,uint32_t size){
if(!s || !s->backend || (!payload && size) || size>10236 || opcode>10240 ||
opcode==0x1ED || opcode==0x2E7 || opcode==0x3D)return -1;
if(s->stream_error)return s->stream_error;
if(!s->world_begun)return -1;
try{
gateway::Bytes body;if(size)body.assign(payload,payload+size);
s->backend->send(opcode,body);return 0;
}catch(...){s->stream_error=-2;return -2;}
}
extern "C" int gw_native_ping(gw_native_session* s,uint32_t sequence,uint32_t latency){
if(!s || !s->backend)return -1;
if(s->stream_error)return s->stream_error;
if(s->ping_sequence || s->pending)return -1;
try{
gateway::Bytes body;gateway::le(body,sequence,4);gateway::le(body,latency,4);
s->backend->send(0x1dc,body);s->ping_sequence=sequence;++s->pings_sent;return 0;
}catch(...){s->stream_error=-2;return -2;}
}
extern "C" int gw_native_service(gw_native_session* s,uint32_t timeout_ms){
if(!s || !s->backend || timeout_ms>1000)return -1;
if(s->stream_error)return s->stream_error;
try{
if(!s->pending)s->pending=s->backend->receive_for(timeout_ms);
if(!s->pending)return 0;
if(s->pending->opcode==0x2e6){s->pending.reset();s->stream_error=-4;return -4;}
if(s->pending->opcode!=0x1dd)return 2;
if(!s->ping_sequence || s->pending->body.size()!=4){s->stream_error=-2;return -2;}
gateway::Reader reader(s->pending->body);
if(reader.le(4)!=*s->ping_sequence){s->stream_error=-2;return -2;}
s->pending.reset();s->ping_sequence.reset();++s->pongs_received;return 1;
}catch(...){s->stream_error=-2;return -2;}
}
extern "C" int gw_native_lifecycle_at(const gw_native_session* s,gw_native_lifecycle* out){
if(out)*out={};
if(!s || !s->backend || !out)return -1;
*out={GW_NATIVE_ABI,sizeof(*out),1,1,uint32_t(s->world_begun),s->stream_error,
uint32_t(s->ping_sequence.has_value()),s->pings_sent,s->pongs_received,uint32_t(s->pending.has_value())};
return 0;
}
extern "C" void gw_native_close(gw_native_session* s){delete s;}
extern "C" int gw_native_transport_open(gw_native_login* login,uint32_t index,const char* addons,uint32_t build,gw_native_transport** out){
if(out)*out=nullptr;
if(!login || !login->backend || !login->discovered || !out || index>=login->realms.size() || !bounded(addons,1024) || build!=5875)return -1;
try{gateway::local_realm_endpoint(login->realms[index]);}catch(...){return -1;}
try{auto t=std::make_unique<gw_native_transport>();t->realm=login->realms[index];t->authentication=login->backend->prepare_transport(index,addons,build);*out=t.release();return 0;}catch(...){return -2;}
}
extern "C" int gw_native_transport_open_ipv4(gw_native_login* login,uint32_t index,const char* addons,uint32_t build,gw_native_transport** out){
if(out)*out=nullptr;
if(!login || !login->backend || !login->explicit_numeric_profile || !login->discovered ||
!out || index>=login->realms.size() || !bounded(addons,1024) || build!=5875)return -1;
try{gateway::numeric_realm_endpoint(login->realms[index]);}catch(...){return -1;}
try{auto t=std::make_unique<gw_native_transport>();t->realm=login->realms[index];
t->authentication=login->backend->prepare_transport(index,addons,build);*out=t.release();return 0;}catch(...){return -2;}
}
extern "C" int gw_native_transport_open_ipv4_bytes(gw_native_login* login,uint32_t index,const uint8_t* addons,uint32_t addon_len,uint32_t build,gw_native_transport** out){
if(out)*out=nullptr;
if(!login || !login->backend || !login->explicit_numeric_profile || !login->discovered ||
!out || index>=login->realms.size() || (!addons && addon_len) || addon_len>=10000 || build!=5875)return -1;
try{gateway::numeric_realm_endpoint(login->realms[index]);}catch(...){return -1;}
try{auto t=std::make_unique<gw_native_transport>();t->realm=login->realms[index];
t->authentication=login->backend->prepare_transport_bytes(index,std::span<const uint8_t>(addons,addon_len),build);
*out=t.release();return 0;}catch(...){return -2;}
}
static bool private_gameplay_scope(const gw_native_transport* t){
return t&&t->authentication&&t->authentication->accepted()&&!t->error&&t->world&&
(t->world->self_created || t->world->transfer_owned())&&t->world->location&&t->world->selected.guid&&!t->world->logout_complete;
}
static void capture_club_membership_reply(gw_native_transport* t) noexcept {
if (!private_gameplay_scope(t) || !t->world_encoded ||
!t->private_capture.needs_club_membership_reply()) return;
try {
using namespace gateway::club_wire;
std::span<const uint8_t> remaining(*t->world_encoded);
if (remaining.size() < 4) return;
gateway::Reader prefix(remaining.first(4));
const auto count = prefix.le(4);
if (count > 4096) return;
remaining = remaining.subspan(4);
std::optional<uint64_t> returned;
uint32_t reply_bytes = 0;
for (uint64_t i = 0; i < count; ++i) {
if (remaining.size() < 8) return;
gateway::Reader header(remaining.first(8));
const auto opcode = header.le(4);
const auto length = header.le(4);
remaining = remaining.subspan(8);
if (length > remaining.size()) return;
const auto body = remaining.first(length);
remaining = remaining.subspan(length);
if (opcode != Response || returned) continue;
gateway::Reader rpc(body);
const auto status = rpc.le(4);
const auto type = rpc.le(8);
if (status || uint32_t(type >> 32) != Membership ||
(uint32_t(type) & 0x3fffffffu) != 1) continue;
rpc.le(8);
rpc.le(4);
const auto payload_size = rpc.le(4);
if (payload_size > 65535 || payload_size != rpc.left()) continue;
const auto payload = rpc.take(payload_size);
rpc.end();
if (payload.empty()) continue;
const auto membership = data(fields(payload), 1);
const auto description = data(fields(membership), 1);
const auto member = fields(data(fields(description), 1));
const bool has_id = std::any_of(member.begin(), member.end(),
[](const auto& f) { return f.number == 2 && f.wire == 0; });
if (!has_id) continue;
returned = number(member, 2);
reply_bytes = uint32_t(body.size());
}
if (!remaining.empty()) return;
if (returned) t->private_capture.club_membership_reply(true,
t->world->selected.guid, t->world->realm, *returned, reply_bytes);
} catch (...) {
// Optional numeric observation must never change the game service.
}
}
static void capture_source_input(gw_native_transport* t){
if(t&&t->world_packet&&!t->private_in_recorded&&private_gameplay_scope(t)){
t->private_capture.source_in(true,t->world->selected.guid,t->world_packet->opcode,t->world_packet->body);t->private_in_recorded=true;
}
}
extern "C" int gw_native_transport_private_capture(gw_native_transport* t,uint32_t kind,uint32_t opcode,uint32_t bytes,uint8_t* output,uint32_t capacity,uint32_t* required){
return gw_native_transport_private_capture_body(t,kind,opcode,bytes,nullptr,0,output,capacity,required);
}
extern "C" int gw_native_transport_private_capture_body(gw_native_transport* t,uint32_t kind,uint32_t opcode,uint32_t bytes,const uint8_t* body,uint32_t body_bytes,uint8_t* output,uint32_t capacity,uint32_t* required){
if(!t || (!body && body_bytes) || body_bytes>GW_WIRE_PRIVATE_INVITE_BODY_MAX)return -1;
if(!t->private_capture.notice(kind,private_gameplay_scope(t),t->world?t->world->selected.guid:0,opcode,bytes,std::span(body,body_bytes)))return -1;
if(required)*required=32;
if(output&&capacity>=32){gateway::Bytes state;for(auto v:{1u,32u,t->private_capture.configured(),t->private_capture.error()})gateway::le(state,v,4);gateway::le(state,t->private_capture.count(),8);gateway::le(state,t->private_capture.bytes(),8);std::memcpy(output,state.data(),32);}
return 0; // Optional capture failure must never change gameplay transport.
}
extern "C" uint16_t gw_native_transport_port(const gw_native_transport* t){return t && t->authentication?t->authentication->port():0;}
extern "C" int gw_native_transport_authenticated(const gw_native_transport* t){return t && t->authentication && !t->error && t->authentication->accepted();}
extern "C" int gw_native_transport_challenge(gw_native_transport* t,uint32_t opcode,const uint8_t* bytes,uint32_t size){
if(!t || !t->authentication || (!bytes && size) || size>65533)return -1;
if(t->error)return t->error;
try{gateway::Bytes body;if(size)body.assign(bytes,bytes+size);t->request=t->authentication->begin({opcode,std::move(body)});return 0;}catch(...){return t->error=-2;}
}
extern "C" int gw_native_transport_auth_request(gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !required || (!bytes && capacity) || capacity>65535)return -1;
if(t->error)return t->error;
if(t->request.empty())return -1;
*required=uint32_t(t->request.size());if(*required>capacity)return -3;
std::memcpy(bytes,t->request.data(),t->request.size());OPENSSL_cleanse(t->request.data(),t->request.size());t->request.clear();return 0;
}
extern "C" int gw_native_transport_feed(gw_native_transport* t,const uint8_t* bytes,uint32_t size,uint32_t* consumed){
if(consumed)*consumed=0;
if(!t || !t->authentication || !consumed || (!bytes && size) || size>65535)return -1;
if(t->error)return t->error;
if(!t->request.empty())return -1;
if(t->pending)return 0;
try{
auto& wire=t->authentication->stream();*consumed=uint32_t(wire.feed(std::span(bytes,size)));
if(!t->authentication->accepted())
std::fprintf(stderr,"GW world pre-auth feed bytes=%u consumed=%u ready=%d ms=%lld\n",unsigned(size),unsigned(*consumed),int(wire.ready()),(long long)std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
if(wire.ready()){
auto packet=wire.take();
if(!t->authentication->accepted())
std::fprintf(stderr,"GW world pre-auth opcode=0x%x bytes=%zu result=%d\n",unsigned(packet.opcode),
packet.body.size(),packet.body.empty()?-1:int(packet.body[0]));
if(packet.opcode==0x2e6)return t->error=-4;
if(packet.opcode==0x1ee){t->authentication->accept(packet);t->unmetered_auth=std::all_of(packet.body.begin()+1,packet.body.end(),[](uint8_t b){return b==0;});}
else if(!t->authentication->accepted() && packet.opcode!=0x2ef && packet.opcode!=0xfd && packet.opcode!=0x127 && packet.opcode!=0x96 && packet.opcode!=0x14e)throw gateway::Error("packet before world authentication");
if(packet.opcode==0x3b){t->roster=gateway::characters(packet.body);t->roster_seen=true;t->roster_guild.refreshed();}
t->pending=std::move(packet);
}
return 0;
}catch(const std::exception& error){std::fprintf(stderr,"GW world feed failed: %s\n",error.what());return t->error=-2;}
catch(...){return t->error=-2;}
}
extern "C" int gw_native_transport_packet(gw_native_transport* t,gw_native_packet* out,uint8_t* bytes,uint32_t capacity){
if(out)*out={};
if(!t || !out || (!bytes && capacity) || capacity>65533)return -1;
if(t->error)return t->error;
if(!t->pending)return 1;
out->opcode=t->pending->opcode;out->payload_bytes=uint32_t(t->pending->body.size());
if(out->payload_bytes>capacity)return -3;
if(t->world_packet || t->world_encoded)return -1;
if(out->payload_bytes)std::memcpy(bytes,t->pending->body.data(),out->payload_bytes);
if(t->world && !t->world->logout_complete){
t->world_packet=std::move(t->pending);t->private_in_recorded=false;t->world_error_recorded=false;capture_source_input(t);
}
else if(t->pending->opcode==0x55 && gw_native_transport_authenticated(t)){
t->world_packet=std::move(t->pending); // Narrow pre-world guild result only.
}
t->pending.reset();return 0;
}
extern "C" int gw_native_transport_send(gw_native_transport* t,uint32_t opcode,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->authentication || !required || (!body && size) || (!bytes && capacity) || size>10236 || capacity>65535 || opcode>10240 || opcode==0x1ed || opcode==0x2e7 || opcode==0x3d)return -1;
if(t->error)return t->error;
if(!t->request.empty() || !t->authentication->accepted())return -1;
*required=size+6;if(*required>capacity)return -3;
try{t->private_capture.discard_send();auto packet=t->authentication->stream().encode(opcode,std::span(body,size));t->private_capture.stage_source_out(private_gameplay_scope(t),t->world?t->world->selected.guid:0,opcode,std::span(body,size));std::memcpy(bytes,packet.data(),packet.size());return 0;}catch(...){t->private_capture.discard_send();return t->error=-2;}
}
extern "C" int gw_native_transport_say(gw_native_transport* t,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t) || !t->world || (!t->world->self_created || t->world->far_transfer) || !body || !required || size>261 || (!bytes&&capacity) || capacity>65535)return -1;
try{
auto legacy=gateway::turtle_say(std::span(body,size));
gateway::Reader reader(legacy);reader.le(4);reader.le(4);auto text=reader.cstring(255);reader.end();
std::optional<gateway::LegacyPacket> control;
if(t->world->talent_control(text,control)){
// Zero outbound bytes is a locally consumed control. The Windows
// host drains the existing presentation queue without send_wire(0).
if(!control)return 0;
auto result=gw_native_transport_send(t,control->opcode,control->body.data(),uint32_t(control->body.size()),bytes,capacity,required);
if(!result)t->world->talent_control_sent(*control);
return result;
}
return gw_native_transport_send(t,0x95,legacy.data(),uint32_t(legacy.size()),bytes,capacity,required);
}catch(...){return -2;}
}
static bool preworld_guild_scope(const gw_native_transport* t){
return gw_native_transport_authenticated(t) && t->roster_seen && (!t->world || t->world->logout_complete);
}
static int preworld_guild_gameplay(gw_native_transport* t,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(!preworld_guild_scope(t) || !required || (!body&&size) || size>36 || (!bytes&&capacity) || capacity>65535)return -1;
try{
auto guild=t->roster_guild.query(t->roster,std::span(body,size));
if(t->roster_guild.pending.contains(guild))return 0;
if(t->roster_guild.pending.size()>=10)return -1;
gateway::Bytes query;gateway::le(query,guild,4);
auto result=gw_native_transport_send(t,0x54,query.data(),uint32_t(query.size()),bytes,capacity,required);
if(!result)t->roster_guild.pending.insert(guild);
return result;
}catch(...){return -2;}
}
static int preworld_guild_result(gw_native_transport* t,uint32_t realm,uint32_t address,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(!gw_native_transport_authenticated(t) || (t->world && !t->world->logout_complete) || !required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND ||
(!t->world_encoded && (!t->world_packet || t->world_packet->opcode!=0x55)))return -1;
try{
if(!t->world_encoded){
auto guild=gateway::turtle_guild_info(t->world_packet->body);
t->world_encoded=t->roster_seen?t->roster_guild.reply(t->roster,guild,realm,address):gateway::Bytes(4,0);
}
*required=uint32_t(t->world_encoded->size());if(*required>capacity)return -3;
if(*required)std::memcpy(bytes,t->world_encoded->data(),*required);
t->world_encoded.reset();t->world_packet.reset();return 0;
}catch(...){return t->error=-6;}
}
extern "C" int gw_native_transport_gameplay(gw_native_transport* t,uint32_t opcode,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(opcode==gateway::club_wire::Request){
if(!t || !required || !gw_native_transport_authenticated(t) || (!body&&size) || size>65559)return -1;
try{
const auto call=gateway::club_wire::parse(std::span(body,size));
t->private_capture.club_chat_request(private_gameplay_scope(t),t->world?t->world->selected.guid:0,std::span(body,size));
static thread_local unsigned club_requests_reported=0;
if(t->private_capture.enabled() && club_requests_reported++<64)
std::fprintf(stderr,"GWClub request service=%08x method=%08x token=%u in_world=%u guild=%u ready=%u waiting=%zu\n",call.service(),uint32_t(call.type),call.token,
unsigned(t->world && t->world->self_created && !t->world->logout_complete),t->world?t->world->guild_id:0,
unsigned(t->world && t->world->clubs.snapshot.has_value()),t->world?t->world->clubs.waiting.size():0);
if(auto empty=gateway::club_wire::empty_social_response(call)){
if(t->world && !t->world->logout_complete){
if(t->world->clubs.output.size()>=64)return -1;
t->world->clubs.output.push_back(std::move(*empty));t->world->clubs.drain=true;
}else{
if(t->service_presentations.size()>=32)return -1;
t->service_presentations.push_back(std::move(*empty));
}
return 0;
}
if(call.service()!=gateway::club_wire::Membership && call.service()!=gateway::club_wire::Club)return -1;
if(t->world && !t->world->logout_complete)
t->world->clubs.request(std::span(body,size),t->world->self_created,t->world->guild_id,t->world->requests);
else {
if(t->service_presentations.size()>=32)return -1;
t->service_presentations.push_back(gateway::club_wire::response(call,1));
}
return 0;
}catch(const gateway::Error&){return -1;}
}
if(opcode==0x4400b6 && t && (!t->world || t->world->logout_complete))
return preworld_guild_gameplay(t,body,size,bytes,capacity,required);
if(!t || !t->world || !required || (!body&&size) || size>4096)return -1;
try{
if(gw_native_far_control_kind(opcode)==GW_NATIVE_FAR_SUSPEND){
if(!gw_native_transport_authenticated(t) || !t->world->transfer_owned())return -1;
t->world->suspend_transfer_response(std::span(body,size));return 0;
}
if(t->world->far_transfer && gw_native_far_control_kind(opcode)!=GW_NATIVE_FAR_WORLDPORT)return -1;
if(opcode==0x3e0148){
if(!gw_native_transport_authenticated(t) || !t->request.empty() || !t->world->self_created ||
!t->world->location || t->world->logout_complete || t->world->pending_teleport ||
(!bytes&&capacity) || capacity>65535)return -1;
if(auto input=t->world->entities.companion_name_query(std::span(body,size),t->world->realm,t->world->location->map))
t->world->queue_social(GW_CODEC_COMPANION_NAME,*input);
return 0; // Source61 already proves the current passive companion name.
}
if(NativeSocialTranslation::handles_client(opcode) || opcode==gateway::NativeContactNameQuery){
if(!gw_native_transport_authenticated(t) || !t->request.empty() || !t->world->self_created ||
!t->world->location || t->world->logout_complete || t->world->pending_teleport ||
(!bytes&&capacity) || capacity>65535)return -1;
gateway::RosterRealm context;context.realm_id=t->world->realm;context.virtual_address=t->world->virtual_realm_address;
t->world->contact_names.sync(t->world->social,t->world->selected.guid,t->world->realm);
std::optional<NativeContactNames::Prepared> names;
std::optional<NativeSocialTranslation::Prepared> contacts;
std::vector<gateway::LegacyPacket> packets;
if(opcode==gateway::NativeContactNameQuery){names=t->world->contact_names.client(std::span(body,size),t->world->social,context);packets=names->source;}
else{contacts=t->world->social.client(opcode,std::span(body,size),context);packets=contacts->source;}
for(const auto& p:packets)*required+=uint32_t(p.body.size()+6);
if(*required>capacity)return -3; // Full fanout before stream/cipher advance or sent bookkeeping.
if(names&&!t->world->contact_names.current(*names))return -1;
gateway::Bytes wire;t->private_capture.discard_send();
for(const auto& p:packets){gateway::append(wire,t->authentication->stream().encode(p.opcode,p.body));
t->private_capture.stage_source_out(private_gameplay_scope(t),t->world->selected.guid,p.opcode,p.body);}
if(!wire.empty())std::memcpy(bytes,wire.data(),wire.size());
if(names){t->world->contact_names.sent(*names);if(!names->native.empty())t->world->queue_social(GW_CODEC_CONTACT_NAMES,gateway::contact_names_input(names->native));if(names->held)++t->world->social_holds;}
if(contacts){for(const auto& p:contacts->native)t->world->queue_social(GW_CODEC_SOCIAL_PACKET,gateway::social_projection_input(p));if(contacts->held)++t->world->social_holds;}
return 0;
}
if(NativeQuestTranslation::handles_client(opcode)){
if(!gw_native_transport_authenticated(t) || !t->request.empty() || !t->world->self_created ||
!t->world->location || t->world->logout_complete || t->world->pending_teleport ||
(!bytes&&capacity) || capacity>65535)return -1;
const auto prepared=t->world->quests.client(opcode,std::span(body,size),t->world->quest_bindings());
for(const auto& packet:prepared.packets)*required+=uint32_t(packet.body.size()+6);
if(*required>capacity)return -3; // Whole fanout before any real Source header/cipher advances.
const auto status_bindings=t->world->quest_bindings();
std::vector<QuestStatusRefresh::Request> status_sent;
for(const auto& packet:prepared.packets)if(packet.opcode==0x182){
gateway::Reader id(packet.body);auto guid=id.le(8);id.end();auto found=status_bindings.find(guid);
if(found==status_bindings.end() || !found->second.generation)return -1;
status_sent.push_back({guid,found->second.generation,false});
}
if(!t->world->quest_status_refresh.can_send(status_sent.size()))return -1;
gateway::Bytes wire;t->private_capture.discard_send();
for(const auto& packet:prepared.packets){
gateway::append(wire,t->authentication->stream().encode(packet.opcode,packet.body));
t->private_capture.stage_source_out(private_gameplay_scope(t),t->world->selected.guid,packet.opcode,packet.body);
}
if(!wire.empty())std::memcpy(bytes,wire.data(),wire.size());
for(auto status:status_sent)t->world->quest_status_refresh.sent(status);
t->world->quests.sent(prepared); // Metadata only, after actual serialization.
if(opcode==0x4400de){
const auto* pilot=std::getenv("GW_QUEST_POI_60141_PROTOTYPE");
bool admitted=false;
const bool dataset_enabled=gw_accepted_feature_enabled("GW_QUEST_POI_DATASET");
if(dataset_enabled)admitted=t->world->queue_quest_poi(std::span(body,size),true);
else if(pilot && std::strcmp(pilot,"1")==0)
admitted=t->world->queue_quest_poi_60141(std::span(body,size),true);
// Reuse the already opt-in private capture, bounded metadata only.
// Native request bodies were omitted, hiding which quest IDs the
// live client actually requested after quest-log changes.
static thread_local unsigned poi_requests_reported=0;
if(t->private_capture.enabled() && poi_requests_reported<32){
++poi_requests_reported;gateway::Reader query(std::span(body,size));
const auto count=query.le(4);std::string ids;
for(size_t i=0;i<count && i<20;++i){if(i)ids+=",";ids+=std::to_string(query.le(4));}
const auto active=t->world->entities.self_quest_log.active_quests();
std::fprintf(stderr,"GWQuestPOI request dataset=%d admitted=%d count=%llu first20=%s active=%zu pending=%zu waiting=%zu local=%d self=%d logout=%d location=%d teleport=%d initialized=%d\n",
dataset_enabled,admitted,static_cast<unsigned long long>(count),ids.c_str(),active.size(),
t->world->quest_poi_pending.size(),t->world->quest_poi_waiting_definitions.size(),
t->world->local_gameobject_authority,t->world->self_created,t->world->logout_complete,
bool(t->world->location),bool(t->world->pending_teleport),t->world->entities.self_quest_log.initialized());
}
}
return 0;
}
if(opcode==0x3e008a){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
const auto request=t->world->area_trigger_request(std::span(body,size));
if(!request)return 0; // Observed outside report has no SourceB4 equivalent.
return gw_native_transport_send(t,request->opcode,request->body.data(),uint32_t(request->body.size()),bytes,capacity,required);
}
if(opcode==0x3e0057 && t->world->bank_duplicate_query(opcode,std::span(body,size))){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
return 0; // One pending genuine response fulfills identical UI queries.
}
if(opcode==0x3e0028 && t->world->bank_window){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
if(!t->world->close_bank(std::span(body,size)))return -2;
return 0;
}
if(opcode==0x3e00ce || opcode==0x3e00cf){
if(!gw_native_transport_authenticated(t) || !t->world->self_created || (!bytes&&capacity) || capacity>65535)return -1;
auto packets=opcode==0x3e00cf?t->world->loot.master_items(std::span(body,size),t->world->entities,t->world->selected.guid,t->world->realm):t->world->loot.items(std::span(body,size),t->world->entities);
for(const auto& p:packets)*required+=uint32_t(p.body.size()+6);
if(*required>capacity)return -3; // Whole-batch validation/capacity before header-cipher advance.
uint32_t at=0;
for(const auto& p:packets){uint32_t written=0;
auto result=gw_native_transport_send(t,p.opcode,p.body.data(),uint32_t(p.body.size()),bytes+at,capacity-at,&written);
if(result)return result;
at+=written;
}
return 0;
}
if(opcode==0x440080){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
auto request=gateway::source_random_roll_request(std::span(body,size));
return gw_native_transport_send(t,0x1fb,request.data(),uint32_t(request.size()),bytes,capacity,required);
}
if(opcode==0x2d002b){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
auto message=gateway::forever_self_addon_request(std::span(body,size),t->world->selected,t->world->realm);
if(message.prefix!="GWTURTLE"){
auto request=gateway::turtle_server_addon_request(message);
auto tab=message.prefix=="TW_GUILDBANK"?t->world->guild_bank.tab_query(message.text):std::nullopt;
auto result=gw_native_transport_send(t,0x95,request.data(),uint32_t(request.size()),bytes,capacity,required);
if(!result && tab)t->world->guild_bank.begin_tab(*tab);
return result;
}
if(message.text.starts_with("guild1 ")){
auto intent=t->world->guild_control_prepare(message.text);
if(!intent)return 0;
const auto& control=intent->source;
auto result=gw_native_transport_send(t,control.opcode,control.body.data(),uint32_t(control.body.size()),bytes,capacity,required);
if(!result)t->world->guild_control_sent(*intent);
return result;
}
auto text=gateway::turtle_talent_addon_control(std::span(body,size),t->world->selected,t->world->realm);
std::optional<gateway::LegacyPacket> control;
if(!t->world->talent_control(text,control))return -2;
if(!control)return 0;
auto result=gw_native_transport_send(t,control->opcode,control->body.data(),uint32_t(control->body.size()),bytes,capacity,required);
if(!result)t->world->talent_control_sent(*control);
return result;
}
if((t->world->standing_cast || t->world->stance_cast || (opcode==0x3e0176 && t->world->source_stand_pending)) &&
(!gw_native_transport_authenticated(t) || !t->request.empty() || (!bytes&&capacity) || capacity>65535))return -1;
if(t->world->cancel_standing_cast(opcode,std::span(body,size))||t->world->cancel_stance_cast(opcode,std::span(body,size)))return 0;
auto packet=t->world->gameplay(opcode,std::span(body,size));
if(t->world->defer_standing_cast(opcode,std::span(body,size),packet))return 0;
if(auto held=t->world->prepare_stance_cast(opcode,std::span(body,size),packet)){
const auto stance=t->world->stance_switch_packet(*held);
const auto result=gw_native_transport_send(t,stance.opcode,stance.body.data(),uint32_t(stance.body.size()),bytes,capacity,required);
if(!result)t->world->stance_switch_sent(std::move(*held));
return result;
}
auto result=gw_native_transport_send(t,packet.opcode,packet.body.data(),uint32_t(packet.body.size()),bytes,capacity,required);
if(!result && opcode==0x3f0029){t->world->merchant.reset();t->world->vendor_inventory.reset();t->world->trainer.reset();}
if(!result)t->world->gameplay_sent(opcode,std::span(body,size));
return result;
}catch(const std::exception& error){
t->private_capture.guild_rank_rejected(private_gameplay_scope(t),t->world?t->world->selected.guid:0,opcode,std::span(body,size),error.what());
return -2;
}catch(...){return -2;}
}
extern "C" int gw_native_transport_gameplay_completed(gw_native_transport* t,uint32_t opcode){
if(!gw_native_transport_authenticated(t) || !t->world || opcode!=0x440025)return -1;
try{return t->world->worldport_send_completed()?0:-1;}catch(...){return -2;}
}
extern "C" int gw_native_transport_active_mover(gw_native_transport* t,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t||!t->world||(!t->world->self_created||t->world->far_transfer)||!body||!required||(!bytes&&capacity)||capacity>65535)return -1;
if(t->error)return t->error;
try{
auto legacy=gateway::turtle_active_mover(std::span(body,size),t->world->selected.guid,t->world->realm);
auto result=gw_native_transport_send(t,0x26a,legacy.data(),uint32_t(legacy.size()),bytes,capacity,required);
if(!result)t->world->mover_confirmed=true;
return result;
}catch(...){return -2;}
}
extern "C" int gw_native_transport_movement(gw_native_transport* t,uint32_t opcode,const uint8_t* body,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t||!t->world||(!t->world->self_created||t->world->far_transfer)||!body||!required||(!bytes&&capacity)||capacity>65535||size>65533)return -1;
if(t->error)return t->error;
if(!t->authentication || !t->authentication->accepted() || !t->request.empty())return -1;
try{
std::vector<gateway::LegacyPacket> packets;
try{
// Validation is a pure projection: no cipher/control state has
// advanced and no source bytes exist yet. Reject this request
// locally; keep the authenticated connection and full diagnostics.
packets=t->world->player_movement(opcode,std::span(body,size),t->roster);
}catch(const gateway::Error&){return -1;}
for(const auto& packet:packets)*required+=uint32_t(packet.body.size()+6);
if(*required>capacity)return -3; // No cipher/control state advances on sizing retries.
gateway::Bytes wire;
try{
t->private_capture.discard_send();
for(const auto& packet:packets){gateway::append(wire,t->authentication->stream().encode(packet.opcode,packet.body));t->private_capture.stage_source_out(private_gameplay_scope(t),t->world?t->world->selected.guid:0,packet.opcode,packet.body);}
}catch(...){return t->error=-2;}
std::memcpy(bytes,wire.data(),wire.size());
// Consume the server's sequence only after the genuine engine ACK was
// validated and serialized. Sizing/failed calls leave it retryable.
t->world->movement_sent(opcode,std::span(body,size),packets);
return 0;
}catch(...){return -2;}
}
extern "C" void gw_native_transport_close(gw_native_transport* t){if(t&&t->world)gw_diagnostics::journal().session_end();delete t;}
extern "C" int gw_native_transport_begin_world(gw_native_transport* t,uint32_t realm,const uint8_t* input,uint32_t size,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t)||!t->roster_seen||(t->world && !t->world->logout_complete)||!required||!input||size>128||realm>8191||(!bytes&&capacity)||capacity>65535)return -1;
try{
const auto presented=gateway::forever_preview_roster(t->roster);
// Resolve only an explicitly presented owned identity BEFORE creating
// world state or encoding anything with the authenticated cipher.
auto guid=gateway::selected_turtle_guid(std::span(input,size),uint16_t(realm),presented);
auto found=std::find_if(presented.begin(),presented.end(),[&](const auto& c){return c.guid==guid;});
// Preview aliases and other roster classes are NOT gameplay support.
// Gate on the untouched SOURCE race/class before state/cipher changes.
if(found==presented.end() || !gateway::turtle_native_presentation_pair(found->race,found->cls))return -1;
// Identity follows the verified Source authentication, not the realm's
// transport address. Wire publishes this same normalized private key.
const auto source_account=t->authentication->internal_source_account();
if(!source_account)return -1;
*required=14;if(capacity<*required)return -3;
auto world=std::make_unique<NativeWorldTranslation>();world->selected=*found;world->realm=uint16_t(realm);
world->internal_source_account=source_account;
// The pinned local GO snapshot belongs to the owned Source server.
// Loopback and its proved VM bridge alias reach that same deployment;
// every other advertised endpoint retains metadata authority holds.
world->local_gameobject_authority=t->realm.address=="127.0.0.1:8090" ||
t->realm.address=="192.168.122.1:8090";
if(t->world)world->contact_names.hold_retired(t->world->contact_names.retired_queries());
if(t->world)world->loot.serial=t->world->loot.serial; // Distinct loot presentations across authenticated re-entry.
gateway::Bytes body;gateway::le(body,guid,8);auto wire=t->authentication->stream().encode(0x3d,body);
std::memcpy(bytes,wire.data(),wire.size());t->world=std::move(world);return 0;
}catch(...){return -1;}
}
extern "C" uint32_t gw_native_transport_world_call_state(const gw_native_transport* t,uint32_t realm){
uint32_t flags=0x80000000u;
if(!t)return flags;
if(gw_native_transport_authenticated(t))flags|=1u;
if(t->world){
flags|=2u;
if(t->world->logout_complete)flags|=4u;
if(t->world->realm==realm)flags|=8u;
if(t->world->local_presentation_pending())flags|=64u;
}
if(!t->service_presentations.empty())flags|=64u;
if(t->world_packet)flags|=16u;
if(t->world_encoded)flags|=32u;
return flags;
}
extern "C" int gw_native_transport_world_self_created(const gw_native_transport* t,uint32_t realm){
return t && t->world && t->world->realm==realm && t->world->self_created && !t->world->logout_complete;
}
extern "C" int gw_native_transport_world_packet(gw_native_transport* t,uint32_t realm,uint32_t address,uint64_t clock,decltype(&gw_codec_serialize) codec,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(t && !t->service_presentations.empty()){
if(!gw_native_transport_authenticated(t)||!required||(!bytes&&capacity)||capacity>GW_CODEC_BOUND)return -1;
gateway::Bytes bundle;gateway::le(bundle,t->service_presentations.size(),4);
for(const auto& packet:t->service_presentations){gateway::le(bundle,packet.opcode,4);gateway::le(bundle,packet.body.size(),4);gateway::append(bundle,packet.body);}
*required=uint32_t(bundle.size());if(capacity<*required)return -3;
std::memcpy(bytes,bundle.data(),bundle.size());t->service_presentations.clear();return 0;
}
if(t && (!t->world || t->world->logout_complete))return preworld_guild_result(t,realm,address,bytes,capacity,required);
if(!gw_native_transport_authenticated(t)||!t->world||t->world->realm!=realm||(!t->world_packet&&!t->world_encoded&&!t->world->local_presentation_pending())||!required||!codec||!address||clock>0x7fffffffffffffffULL||(!bytes&&capacity)||capacity>GW_CODEC_BOUND)return -1;
try{
if(!t->world_encoded){
t->world_encoded=t->world_packet?t->world->translate(*t->world_packet,address,clock,codec):t->world->local_presentation(address,codec);
// Translation materializes LogoutComplete before the caller may
// retry its output buffer. Revoke the old roster at that same
// boundary: retry copies use the preworld path once logout is set.
// Never invalidate a genuinely newer roster during a copy retry.
if(t->world->logout_complete){t->roster_seen=false;t->roster_guild.refreshed();}
static thread_local unsigned club_replies_reported=0;
if(t->private_capture.enabled() && club_replies_reported<64){
try{
gateway::Reader bundle(*t->world_encoded);const auto count=bundle.le(4);
for(size_t i=0;i<count;++i){const auto opcode=bundle.le(4),length=bundle.le(4);const auto body=bundle.take(length);
if(opcode!=gateway::club_wire::Response && opcode!=gateway::club_wire::Notification)continue;
gateway::Reader rpc(body);const auto status=opcode==gateway::club_wire::Response?rpc.le(4):0;const auto type=rpc.le(8);rpc.le(8);const auto token=rpc.le(4),size=rpc.le(4);
++club_replies_reported;std::fprintf(stderr,"GWClub reply opcode=%08x service=%08x method=%08x token=%u status=%u bytes=%u\n",unsigned(opcode),unsigned(type>>32),unsigned(type),unsigned(token),unsigned(status),unsigned(size));
}
}catch(const gateway::Error&){} // Private diagnostics never alter service state.
}
static thread_local unsigned poi_bundles_reported=0;
if(t->private_capture.enabled() && poi_bundles_reported<32){
try{
gateway::Reader bundle(*t->world_encoded);const auto packets=bundle.le(4);
for(size_t i=0;i<packets;++i){
const auto opcode=bundle.le(4),length=bundle.le(4);const auto payload=bundle.take(length);
if(opcode!=0x67001d)continue;
++poi_bundles_reported;gateway::Reader poi(payload);const auto records=poi.le(4),data_count=poi.le(4);
std::fprintf(stderr,"GWQuestPOI bundle path=%s records=%llu data_count=%llu bytes=%llu\n",
t->world_packet?"source":"local",static_cast<unsigned long long>(records),
static_cast<unsigned long long>(data_count),static_cast<unsigned long long>(length));
}
}catch(const gateway::Error&){} // Optional capture cannot affect gameplay.
}
}
capture_source_input(t);
*required=uint32_t(t->world_encoded->size());if(*required>capacity)return -3;
if(*required)std::memcpy(bytes,t->world_encoded->data(),*required);
// Observe copied game output, never sizing or short-buffer retries.
capture_club_membership_reply(t);
t->world_encoded.reset();t->world_packet.reset();return 0;
}catch(const std::exception& error){
if(t->world_packet&&!t->world_error_recorded){gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,t->world_packet->opcode,uint32_t(t->world_packet->body.size()));t->world_error_recorded=true;}
// Local object updates only: disclose no credentials, auth/session
// buffers, chat or raw packet data. Preserve the first exact parsing
// failure instead of making every reconnect look like a login error.
if(t->realm.address=="127.0.0.1:8090" && t->world_packet &&
(t->world_packet->opcode==0xa9 || t->world_packet->opcode==0x1f6)){
char reason[161]{};const char* text=error.what();
for(size_t i=0;i<160 && text[i];++i)reason[i]=text[i]>=32 && text[i]<=126?text[i]:'?';
std::fprintf(stderr,"GW local object-update rejected opcode=%u bytes=%zu reason=%s\n",
t->world_packet->opcode,t->world_packet->body.size(),reason);
if(std::strcmp(reason,"unsupported legacy creature GUID profile")==0){
try{
unsigned reported=0;
for(const auto& row:gateway::turtle_object_updates(t->world_packet->opcode,t->world_packet->body)){
if((row.kind!=2 && row.kind!=3) || row.type!=3)continue;
auto entry=row.fields.find(3);if(entry==row.fields.end())continue;
if((row.guid>>48)!=0xf130 || ((row.guid>>24)&0xffffff)!=entry->second || !(row.guid&0xffffff)){
std::fprintf(stderr,"GW local creature identity guid=%016llx encoded_entry=%u object_entry=%u\n",
static_cast<unsigned long long>(row.guid),unsigned((row.guid>>24)&0xffffff),entry->second);
if(++reported==16)break;
}
}
}catch(...){/* Diagnostics must never replace the original failure. */}
}
}
return t->error=-6;
}catch(...){if(t->world_packet&&!t->world_error_recorded){gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,t->world_packet->opcode,uint32_t(t->world_packet->body.size()));t->world_error_recorded=true;}return t->error=-6;}
}
extern "C" int gw_native_transport_world_request(gw_native_transport* t,uint32_t* opcode,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(opcode)*opcode=0;
if(!t || !t->world || !opcode || !required || (!bytes&&capacity) || capacity>65535 ||
t->world_packet || t->world_encoded || !gw_native_transport_authenticated(t))return -1;
try{
if(auto packet=t->world->stance_cast_request()){
*opcode=packet->opcode;
const auto result=gw_native_transport_send(t,packet->opcode,packet->body.data(),uint32_t(packet->body.size()),bytes,capacity,required);
if(!result)t->world->stance_ability_sent();
return result;
}
if(auto packet=t->world->standing_cast_request()){
if(auto held=t->world->prepare_stance_cast(0x3e0176,t->world->standing_cast->original,*packet)){
const auto stance=t->world->stance_switch_packet(*held);*opcode=stance.opcode;
const auto result=gw_native_transport_send(t,stance.opcode,stance.body.data(),uint32_t(stance.body.size()),bytes,capacity,required);
if(!result)t->world->stance_switch_sent(std::move(*held));
return result;
}
*opcode=packet->opcode;
auto result=gw_native_transport_send(t,packet->opcode,packet->body.data(),uint32_t(packet->body.size()),bytes,capacity,required);
if(!result)t->world->standing_cast_sent();
return result;
}
}catch(...){return -2;}
if(t->world->requests.empty() && t->world->entities.requests.empty() && t->world->inventory.requests.empty() && t->world->loot.requests.empty()){
if(auto status=t->world->quest_status_refresh.next(t->world->quest_bindings())){
gateway::Bytes body;gateway::le(body,status->guid,8);*opcode=0x182;
auto result=gw_native_transport_send(t,*opcode,body.data(),uint32_t(body.size()),bytes,capacity,required);
if(!result)t->world->quest_status_refresh.sent_pending(*status);
return result;
}
// Names are real Source dependencies of confirmed contacts, including
// offline additions. The original client need not emit a name query.
// Existing gameplay/definition queues retain priority; never block
// World readiness or mark a query pending before actual serialization.
if(!t->world->self_created||t->world->logout_complete||!t->world->location)return 1;
try{
gateway::RosterRealm realm;realm.realm_id=t->world->realm;realm.virtual_address=t->world->virtual_realm_address;
t->world->contact_names.sync(t->world->social,t->world->selected.guid,t->world->realm);
auto plan=t->world->contact_names.dependency(realm);
if(!plan||!t->world->contact_names.current(*plan))return 1;
const auto& packet=plan->source.front();*opcode=packet.opcode;
auto result=gw_native_transport_send(t,packet.opcode,packet.body.data(),uint32_t(packet.body.size()),bytes,capacity,required);
if(!result)t->world->contact_names.sent(*plan);
return result;
}catch(...){return -2;}
}
if(!t->world->self_created)return t->world->transfer_owned()?1:-1;
auto& queue=!t->world->requests.empty()?t->world->requests:!t->world->entities.requests.empty()?t->world->entities.requests:
!t->world->loot.requests.empty()?t->world->loot.requests:t->world->inventory.requests;
const auto& packet=queue.front();*opcode=packet.opcode;
auto result=gw_native_transport_send(t,packet.opcode,packet.body.data(),uint32_t(packet.body.size()),bytes,capacity,required);
if(!result)queue.pop_front();
return result;
}
extern "C" int gw_native_transport_entity_state(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->world || !required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND || !gw_native_transport_authenticated(t))return -1;
try{
auto state=t->world->entities.snapshot();*required=uint32_t(state.size());if(*required>capacity)return -3;
std::memcpy(bytes,state.data(),state.size());return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_transport_initial_spell_ids(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t)return -1;
return gateway::native::copy_initial_spell_ids(gw_native_transport_authenticated(t),t->roster_seen,
t->roster,t->world.get(),bytes,capacity,required);
}
extern "C" int gw_native_transport_aura_state(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->world || !required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND || !gw_native_transport_authenticated(t))return -1;
try{auto state=t->world->auras.snapshot(t->world->selected.guid);*required=uint32_t(state.size());if(*required>capacity)return -3;
std::memcpy(bytes,state.data(),state.size());return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_transport_inventory_state(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->world || !required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND || !gw_native_transport_authenticated(t))return -1;
try{auto state=t->world->inventory.snapshot();*required=uint32_t(state.size());if(*required>capacity)return -3;
std::memcpy(bytes,state.data(),state.size());return 0;
}catch(...){return -2;}
}
extern "C" int gw_native_transport_motion_state(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->world || !required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND || !gw_native_transport_authenticated(t))return -1;
try{
auto state=t->world->entities.motion_snapshot();*required=uint32_t(state.size());if(*required>capacity)return -3;
std::memcpy(bytes,state.data(),state.size());return 0;
}catch(...){return -2;}
}
extern "C" uint32_t gw_native_transport_character_count(const gw_native_transport* t){
return t && !t->error && t->roster_seen?uint32_t(t->roster.size()):0;
}
extern "C" int gw_native_transport_roster_diagnostics(const gw_native_transport* t,gw_native_roster_diagnostics* out){
if(out)*out={};
if(!out || !t || !gw_native_transport_authenticated(t) || !t->roster_seen)return -1;
out->abi=GW_NATIVE_ROSTER_DIAGNOSTICS_ABI;out->size=sizeof(*out);out->count=uint32_t(t->roster.size());
if(t->roster.size()>10)out->overall_reason=GW_NATIVE_ROSTER_COUNT_BOUND;
for(size_t i=0;i<std::min<size_t>(t->roster.size(),10);++i){
const auto& c=t->roster[i];auto reason=uint32_t(gateway::forever_roster_row_reason(c));
bool common=c.gender<=1 && !c.name.empty() && c.name.size()<=63 && c.guid &&
std::count_if(t->roster.begin(),t->roster.end(),[&](const auto& other){return other.guid==c.guid;})==1;
for(unsigned slot=0;slot<19;++slot)if(c.visuals[slot].type>28)common=false;
// ABI2 names the explicit destination visual projection separately.
// Strict compatibility reasons remain unchanged; a preview is neither
// playable eligibility nor proof that the engine rendered a model.
const auto preview=common?gateway::forever_roster_preview_race(c):std::nullopt;
out->rows[i]={c.race,c.cls,c.gender,c.level,reason,preview?uint32_t(*preview):0};
if(!out->overall_reason && reason)out->overall_reason=reason;
}
return 0;
}
extern "C" int gw_native_transport_character_at(const gw_native_transport* t,uint32_t index,gw_native_character* out){
if(out)*out={};
if(!t || t->error || !t->roster_seen || !out || index>=t->roster.size())return -1;
const auto& c=t->roster[index];out->guid=c.guid;out->level=c.level;out->race=c.race;out->class_id=c.cls;
std::copy_n(c.name.data(),std::min(c.name.size(),sizeof(out->name)-1),out->name);return 0;
}
extern "C" int gw_native_transport_encode_roster(const gw_native_transport* t,uint32_t realm,uint32_t address,uint32_t district,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || t->error || !t->roster_seen || !required || (!bytes && capacity) || realm>8191 || capacity>1048576)return -1;
try{
// This transport is already authenticated to one selected Turtle realm.
// Regionwide results trigger a modern Battle.net realm-join dependency.
auto body=gateway::forever_roster_preview(t->roster,{realm,address,district},false);*required=uint32_t(body.size());
if(body.size()>capacity)return -3;
if(!body.empty())std::memcpy(bytes,body.data(),body.size());
t->roster_guild.bind({realm,address,district});
return 0;
}catch(...){return -2;}
}
namespace {
int initialization_copy(const gateway::Bytes& body,uint8_t* bytes,uint32_t capacity,uint32_t* required){
*required=uint32_t(body.size());if(body.size()>capacity)return -3;
if(!body.empty())std::memcpy(bytes,body.data(),body.size());
return 0;
}
}
extern "C" int gw_native_transport_auth_metadata(const gw_native_transport* t,uint32_t address,uint64_t clock,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t)||!required||(!bytes&&capacity)||capacity>1048576||!address||clock>0x7fffffffffffffffULL)return -1;
if(!t->unmetered_auth)return -5;
try{
if(t->realm.name.empty()||t->realm.name.size()>127)throw gateway::Error("unsupported realm presentation");
gateway::Bytes body;gateway::le(body,address,4);gateway::le(body,clock,8);gateway::le(body,t->realm.name.size(),2);
body.insert(body.end(),t->realm.name.begin(),t->realm.name.end());return initialization_copy(body,bytes,capacity,required);
}catch(...){return -2;}
}
extern "C" int gw_native_transport_encode_glue_features(const gw_native_transport* t,uint32_t limit,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t)||!required||(!bytes&&capacity)||capacity>1048576)return -1;
try{return initialization_copy(gateway::forever_glue_features(limit),bytes,capacity,required);}catch(...){return -2;}
}
extern "C" int gw_native_transport_encode_restrictions(const gw_native_transport* t,uint32_t realm,uint32_t address,uint32_t district,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t)||!t->roster_seen||!required||(!bytes&&capacity)||capacity>1048576||realm>8191)return -1;
try{return initialization_copy(gateway::forever_restrictions(gateway::forever_preview_roster(t->roster),{realm,address,district}),bytes,capacity,required);}catch(...){return -2;}
}