Files

1550 lines
103 KiB
C++

#include <cstdarg>
#include "diagnostics_journal.hpp"
#include "account_data_store.hpp"
#include "realm_query.hpp"
#include "extended_action_bars.hpp"
#include "sdhd_preference.hpp"
#include "gateway/auction_aux.hpp"
#include "query_failure_numeric.hpp"
#include "accepted_feature_defaults.h"
#include <chrono>
#include "login_timing.h"
#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/mount_special_packet.hpp"
#include "gateway/mount_special_sound_map.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 "radio_player.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;
}
};
static uint64_t login_timing_now(){return uint64_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());}
static void login_timing_note(const char* phase,uint32_t opcode,uint32_t bytes,uint64_t start){
const auto now=login_timing_now();
std::fprintf(stderr,"GW_LOGIN_TIMING side=backend phase=%s opcode=0x%x bytes=%u ms=%llu elapsed_ms=%llu clock=steady\n",
phase,opcode,bytes,(unsigned long long)now,(unsigned long long)(now>=start?now-start:0));
}
struct gw_native_transport {
gw_login_timing login_timing{};
gateway::LegacyRealm realm;
mutable gateway::realm_query::Context realm_query;
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;
gateway::account_data::CharacterOwner account_data_owner;
struct MountSpecialSoundPresentation {
gateway::LegacyPacket packet;
uint64_t source_owner=0;
uint16_t realm=0;
uint32_t map=0,display=0;
};
std::deque<MountSpecialSoundPresentation> mount_sound_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;}
bool mount_sound_current(const gw_native_transport* t,const gw_native_transport::MountSpecialSoundPresentation& sound,uint32_t realm){
if(!t || !t->world || !gw_native_transport_authenticated(t) || !t->world->self_created ||
t->world->logout_complete || t->world->far_transfer || t->world->pending_teleport ||
!t->world->location || t->world->realm!=realm || sound.realm!=realm ||
sound.source_owner!=t->world->selected.guid || sound.map!=t->world->location->map)
return false;
auto unit=t->world->auras.units.find(sound.source_owner);
return unit!=t->world->auras.units.end() && unit->second.mount_display==sound.display;
}
}
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_confirm_realm_list(gw_native_login* login){
if(!login || !login->backend || !login->discovered)return -1;
try{
if(login->backend->confirm_realm_list())return 0;
}catch(...){
// A closed socket or an invalid reply also invalidates the choices.
}
login->discovered=false;
login->realms.clear();
login->backend.reset();
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.is_self_player_create(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{
const bool sd_enabled=gateway::sdhd_preference::load(s->backend->internal_source_account()).value_or(false);
auto body=gateway::forever_account_roster(s->backend->roster(),{realm,address,district},true,sd_enabled);
*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;
}
// Incoming server packets are recorded from the world location on, so the own Player create (which sets
// self_created) is in the capture too (#116: skin/face bytes of the viewer's own character).
static bool private_source_in_scope(const gw_native_transport* t){
return private_gameplay_scope(t)||(t&&t->authentication&&t->authentication->accepted()&&!t->error&&t->world&&
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.enabled() ||
t->world->club_membership_reply_recorded) 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->world->club_membership_reply_recorded = 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_source_in_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>(kind==4?GW_WIRE_PRIVATE_HOTFIX_BODY_MAX:GW_WIRE_PRIVATE_INVITE_BODY_MAX))return -1;
if(!t->private_capture.notice(kind,kind==4?gw_native_transport_authenticated(t)!=0: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" int64_t gw_native_transport_global_layout_time(const gw_native_transport* t){
if(!gw_native_transport_authenticated(t))return 0;
try{
return gateway::account_data::stored_time(t->authentication->internal_source_account(),
gateway::account_data::GlobalEditMode,{});
}catch(...){return 0;}
}
// #80: every global account-data type's stored time (0 when absent or per-character).
extern "C" int64_t gw_native_transport_global_account_time(const gw_native_transport* t,uint32_t type){
if(!gw_native_transport_authenticated(t) || type>=gateway::account_data::Types || gateway::account_data::per_character(type))return 0;
try{return gateway::account_data::stored_time(t->authentication->internal_source_account(),type,{});}catch(...){return 0;}
}
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(const std::exception& error){if(auto* f=std::fopen("GWFeedErrors.txt","a")){std::fprintf(f,"request 0x%x failed: %s\n",opcode,error.what());std::fclose(f);}return t->error=-2;}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(gw_login_timing_take(&t->login_timing,GW_LOGIN_FIRST_SOURCE,login_timing_now()))
login_timing_note("first-source-packet",packet.opcode,uint32_t(packet.body.size()),t->login_timing.started_ms);
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());
// stderr does not leave Proton: keep the reason beside the client (GWFeedErrors.txt, append-only diagnostic).
if(auto* f=std::fopen("GWFeedErrors.txt","a")){std::fprintf(f,"world feed failed: %s\n",error.what());std::fclose(f);}
return t->error=-2;}
catch(...){if(auto* f=std::fopen("GWFeedErrors.txt","a")){std::fputs("world feed failed: unknown\n",f);std::fclose(f);}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(const std::exception& error){t->private_capture.discard_send();if(auto* f=std::fopen("GWFeedErrors.txt","a")){std::fprintf(f,"send 0x%x failed: %s\n",opcode,error.what());std::fclose(f);}return t->error=-2;}catch(...){t->private_capture.discard_send();return t->error=-2;}
}
// Several Source packets in one outbound write (cast + its facing update, #87); same checks as gw_native_transport_send.
static int send_packets(gw_native_transport* t,const std::vector<gateway::LegacyPacket>& packets,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!t || !t->authentication || !required || (!bytes && capacity) || capacity>65535 || packets.empty())return -1;
if(t->error)return t->error;
if(!t->request.empty() || !t->authentication->accepted())return -1;
for(const auto& p:packets){if(p.body.size()>10236 || p.opcode>10240)return -1;*required+=uint32_t(p.body.size()+6);}
if(*required>capacity)return -3;
try{
t->private_capture.discard_send();gateway::Bytes wire;
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?t->world->selected.guid:0,p.opcode,p.body);}
std::memcpy(bytes,wire.data(),wire.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),t->world->selected.race);
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;}
}
// A rejected client request ends the session; leave its reason (no packet data) in the startup log.
// Player builds have no GW_NATIVE_STARTUP_LOG: request rejections and sort plans then go to a bounded
// Logs/GatewayRequests.log in the client folder (#93: bag sort failed on OCTO without any trace).
static FILE* gw_request_log_open(){
const char* path=std::getenv("GW_NATIVE_STARTUP_LOG");
if(path && *path)return std::fopen(path,"a");
FILE* file=std::fopen("Logs/GatewayRequests.log","a");if(!file)return nullptr;
if(std::fseek(file,0,SEEK_END)==0 && std::ftell(file)>(4L<<20)){std::fclose(file);file=std::fopen("Logs/GatewayRequests.log","w");}
return file;
}
static void gw_inv_log(const char* fmt,...){ // appended to GW_NATIVE_STARTUP_LOG (bank-sort error hunt)
FILE* file=gw_request_log_open();if(!file)return;
va_list args;va_start(args,fmt);std::vfprintf(file,fmt,args);va_end(args);std::fclose(file);
}
static void note_request_rejected(uint32_t opcode,uint32_t size,const char* what){
char reason[161]{};for(size_t i=0;i<160 && what && what[i];++i)reason[i]=what[i]>=32 && what[i]<=126?what[i]:'?';
if(FILE* file=gw_request_log_open()){std::fprintf(file,"GW %s rejected opcode=%x bytes=%u reason=%s\n",(opcode>>31)?"source packet":"request",opcode&0x7fffffffu,size,reason);std::fclose(file);}
}
static int gameplay_request(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::realm_query::Request){
if(!t || !required || !gw_native_transport_authenticated(t) || !body || size!=4)return -1;
try{
if(t->service_presentations.size()>=32)return -1;
t->service_presentations.push_back(t->realm_query.reply(std::span(body,size)));
return 0;
}catch(...){return -1;}
}
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==gateway::sdhd_preference::SetOpcode){
if(!required || !gw_native_transport_authenticated(t) || !body || size!=1)return -1;
try{
return gateway::sdhd_preference::set_from_client(t->authentication->internal_source_account(),std::span(body,size))?0:-1;
}catch(...){return -1;}
}
if(opcode==gateway::account_data::UpdateOpcode || opcode==gateway::account_data::RequestOpcode){
// Edit Mode layout account data (types 13/14) is answered locally; the
// source server has no account-data storage. Other types: existing drop.
if(!t || !required || !gw_native_transport_authenticated(t) || (!body&&size) || size>0x20100)return -1;
try{
if(t->service_presentations.size()>=32)return -1;
gateway::Guid128 player{};
// t->world (and its selected character) stays until the next character login replaces it:
// per-character saves sent during logout/quit belong to that character (7e7116).
const bool has_character=t->world && t->world->selected.guid;
if(has_character)player=gateway::forever_player_guid(t->world->selected.guid,t->world->realm);
auto reply=gateway::account_data::handle(t->authentication->internal_source_account(),
opcode,std::span(body,size),t->account_data_owner.current(has_character,player));
if(!reply)return -1;
if(gw_login_timing_take(&t->login_timing,GW_LOGIN_ACCOUNT_REPLY,login_timing_now()))
login_timing_note("account-reply-queued",reply->opcode,uint32_t(reply->body.size()),t->login_timing.started_ms);
t->service_presentations.push_back({reply->opcode,std::move(reply->body)});
return 0;
}catch(...){return -1;}
}
if(opcode==0x3f00ce && !gw_native_transport_authenticated(t))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 (opcode == gateway::extended_action_bars::SetActionButtonOpcode && size == 10 &&
gateway::extended_action_bars::extended(unsigned(body[8]) | (unsigned(body[9]) << 8))) {
// Gitea #15: slots beyond Turtle's 120 are stored locally and never forwarded.
if (!gw_native_transport_authenticated(t) || !t->world->self_created || t->world->logout_complete) return -1;
gateway::extended_action_bars::store_request(t->world->extended_action_bar_file(), std::span(body, size));
return 0;
}
if (opcode == gateway::equipment_sets::Save || opcode == gateway::equipment_sets::Delete ||
opcode == gateway::equipment_sets::Assign || opcode == gateway::equipment_sets::Use) {
if (!gw_native_transport_authenticated(t) || !t->world->self_created || !t->world->location ||
t->world->logout_complete || t->world->far_transfer || t->world->pending_teleport) return -1;
t->world->equipment_sets.handle(opcode, std::span(body, size), t->world->equipment_set_file(),
gateway::equipment_sets::accessible(t->world->inventory, opcode == gateway::equipment_sets::Use && t->world->equipment_bank_open()), gateway::equipment_sets::Clock::now());
return 0;
}
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==0x3f002a && gw_native_transport_authenticated(t)){
// CMSG_CLOSE_INTERACTION: no Source message exists; only the open stable reacts.
if(auto closed=t->world->close_interaction(std::span(body,size)))t->world->queue_social(GW_CODEC_PET_STABLE,*closed);
return 0;
}
if((opcode==0x3f006c || opcode==0x3f006d || opcode==0x3f006e) && gw_native_transport_authenticated(t)){
// Commodity quote / confirm / cancel: local answers first, then the single-AH-list guard.
try{
if(t->world->auction_commodity_local(opcode,std::span(body,size)))return 0;
if(t->world->defer_personal_list(opcode,std::span(body,size)))return 0;
}catch(const gateway::Error&){return -1;}
}
if((opcode==0x3f0066 || opcode==0x3f0067 || opcode==0x3f0068 || opcode==0x3f006b) && gw_native_transport_authenticated(t)){
// Later browse pages and bucket / item-ID clicks come from the complete published snapshot.
if(auto local=t->world->auction_local_request(opcode,std::span(body,size))){t->world->queue_social(local->first,local->second);return 0;}
// Bucket / item-ID lookups without a snapshot row become a real Source name search for that item.
if(opcode==0x3f0066 || opcode==0x3f0067 || opcode==0x3f0068 || opcode==0x3f006b){try{if(t->world->defer_personal_list(opcode,std::span(body,size)))return 0;}catch(const gateway::Error&){}}
}
if(opcode==0x3e0143){
// CMSG_QUERY_CREATURE: answered from the real Source template reply (entity translation).
if(!gw_native_transport_authenticated(t) || !t->world->self_created || t->world->logout_complete)return -1;
return t->world->entities.native_creature_query(std::span(body,size))?0:-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(!t->world->source_pet_name_query(std::span(body,size)))return 0;
// A Source hunter/warlock pet: fall through to the ordinary Source request (CMSG_PET_NAME_QUERY).
}
// 0x44010C carries TC TutorialSetFlag (1- or 5-byte bodies; live W36: action 0 + bits 0/29/30),
// not SendContactList (u32 Flags only). Those shapes go to the gameplay translator.
const bool tutorial=opcode==gateway::NativeContactListRequest && (size==1 || size==5);
if(!tutorial && (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{
if(opcode==gateway::NativeContactListRequest && size>=4){
// Numeric-only evidence for the 70334 SendContactList body (seen at 5 bytes;
// TC reads u32 Flags only): 0x7d0012 = Flags, 0x7d0013 = first trailing byte.
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0012u,uint32_t(body[0])|uint32_t(body[1])<<8|uint32_t(body[2])<<16|uint32_t(body[3])<<24);
if(size>4)gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0013u,uint32_t(body[4])|uint32_t(size-4)<<8);
}
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 status_bindings=t->world->quest_bindings();
const auto prepared=t->world->quests.client(opcode,std::span(body,size),status_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.
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==0x440096){
if(!gw_native_transport_authenticated(t))return -1;
if(t->world->summon_decline(opcode,std::span(body,size)))return 0;
}
if(t->world->party_response_idle(opcode,std::span(body,size))){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
return 0; // No invitation is open: a late answer changes nothing on the Source.
}
if(t->world->bank_idle_query(opcode,std::span(body,size))){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
return 0; // No bank open: nothing to report, and never a reason to end the session.
}
if(opcode==0x3f0059 && 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==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==0x3e021c || opcode==0x3e021d){
// Native SortBags / SortBankBags (empty bodies). Turtle has no sort opcode:
// the plan is a sequence of its own CMSG_SWAP_ITEM, then the native client is
// released with BagCleanupFinished (0x6a0007), as the Classic server does.
if(!gw_native_transport_authenticated(t) || !t->world->self_created ||
t->world->logout_complete || t->world->far_transfer ||
t->world->pending_teleport || size || (!bytes&&capacity) || capacity>65535)return -1;
const bool bank=opcode==0x3e021d;
std::vector<gateway::LegacyPacket> packets;
if(!bank || t->world->equipment_bank_open())packets=t->world->inventory.sort_plan(bank);
gw_inv_log("GW_INV sort bank=%d open=%d swaps=%zu\n",int(bank),int(t->world->equipment_bank_open()),packets.size());
for(const auto& p:packets)*required+=uint32_t(p.body.size()+6);
if(*required>capacity)return -3;
if(t->service_presentations.size()>=32)return -1;
uint32_t at=0;
for(const auto& p:packets){uint32_t written=0;
gw_inv_log("GW_INV sort-swap legacy=0x%x body=%02x%02x%02x%02x\n",unsigned(p.opcode),unsigned(p.body[0]),unsigned(p.body[1]),unsigned(p.body[2]),unsigned(p.body[3]));
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;
}
t->service_presentations.push_back({0x6a0007,{}});
return 0;
}
if(opcode==gateway::mount_special_packet::RequestOpcode){
if(!gw_native_transport_authenticated(t) || !t->world->self_created ||
t->world->logout_complete || t->world->far_transfer ||
t->world->pending_teleport || !t->world->location)return -1;
gateway::mount_special_packet::validate_request(std::span(body,size));
auto unit=t->world->auras.units.find(t->world->selected.guid);
if(unit==t->world->auras.units.end() || !unit->second.mount_display)return 0;
const auto display=unit->second.mount_display;
const auto kit=gateway::mount_special_sound::sound_for(display);
if(!kit)return 0; // The source model/sound or selected native audio is unproven.
if(t->mount_sound_presentations.size()>=16)return 0;
auto self=gateway::forever_player_guid(t->world->selected.guid,t->world->realm);
auto response=gateway::mount_special_packet::sound_response(kit,self);
t->mount_sound_presentations.push_back({
{gateway::mount_special_packet::SoundOpcode,std::move(response)},
t->world->selected.guid,t->world->realm,t->world->location->map,display});
return 0; // This is a client-local sound; no Source gameplay packet.
}
if(opcode==0x44007f){
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
t->world->party_stats_request(std::span(body,size));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==0x2d002a){
// Actual70334 CMSG_CHAT_ADDON_MESSAGE: peer party/raid/guild/officer addon traffic
// becomes the original Tortoise SendAddonMessage (CMSG_MESSAGECHAT, LANG_ADDON).
if(!gw_native_transport_authenticated(t) || !t->world->self_created)return -1;
auto request=gateway::turtle_peer_addon_request(gateway::forever_peer_addon_request(std::span(body,size)));
return gw_native_transport_send(t,0x95,request.data(),uint32_t(request.size()),bytes,capacity,required);
}
if(opcode==0x440146){
// WPP V1_60_1 CMSG_DO_COUNTDOWN. Turtle has no countdown packet: the raid hears it as the
// original BigWigs pull timer (Plugins/Pulltimer.lua), and this client shows its native timer
// at once. The raid echo of our own message is not presented a second time.
if(!gw_native_transport_authenticated(t) || !t->world->self_created || size!=4)return -1;
uint32_t seconds=uint32_t(body[0])|uint32_t(body[1])<<8|uint32_t(body[2])<<16|uint32_t(body[3])<<24;
if(seconds>3600 || t->service_presentations.size()>=32)return -1;
gateway::PeerAddonRequest pull{3,"BigWigs",seconds?"PulltimerSync "+std::to_string(seconds):"PulltimerStopSync"};
auto request=gateway::turtle_peer_addon_request(pull);
const auto result=gw_native_transport_send(t,0x95,request.data(),uint32_t(request.size()),bytes,capacity,required);
if(!result)t->service_presentations.push_back({0x47003e,gateway::forever_start_timer(seconds,seconds,nullptr)});
return result;
}
if(opcode==0x3e005c){
// CMSG_QUERY_COUNTDOWN_TIMER: running timers are already presented from the raid stream.
if(!gw_native_transport_authenticated(t) || size!=4)return -1;
return 0;
}
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==gateway::GraveRequestPrefix){
const auto request=gateway::turtle_grave_request(message,t->world->selected.race);
return gw_native_transport_send(t,0x95,request.data(),uint32_t(request.size()),bytes,capacity,required);
}
if(message.prefix=="GWInspectGear"){
auto& world=*t->world;
const auto target=world.inspect_control(message.text);
if(!target)return 0;
const auto inspect=world.gameplay(0x3f00ce,*target);
const auto result=gw_native_transport_send(t,inspect.opcode,inspect.body.data(),
uint32_t(inspect.body.size()),bytes,capacity,required);
if(!result)world.gameplay_sent(0x3f00ce,*target);
return result;
}
if(message.prefix=="OctoBG"){
// Queue-anywhere join for the Turtle minimap queue (OctoBattlegrounds). 70334 restricts
// C_PvP.JoinBattlefield to Blizzard UI code, so the add-on names the BattlemasterList ID
// ("J <id>") and this sends the client's own BattlemasterJoin through its normal translation
// (native 0x3f00c0 {count 1, roles, blacklist[2], queue 0x1f1<id>} -> Turtle 0x2ee, which names
// the list's battlemaster: the player itself for TW_BGQueue's self-addressed list).
auto& world=*t->world;
const auto& text=message.text;
if(text.size()!=3 || !text.starts_with("J ") || text[2]<'1' || text[2]>'9')return -2;
gateway::Bytes join;gateway::le(join,1,4);join.push_back(0);gateway::le(join,0,4);gateway::le(join,0,4);
gateway::le(join,0x1f10000000000000ULL|uint64_t(text[2]-'0'),8);
const auto packet=world.gameplay(0x3f00c0,join);
const auto result=gw_native_transport_send(t,packet.opcode,packet.body.data(),uint32_t(packet.body.size()),bytes,capacity,required);
if(!result)world.gameplay_sent(0x3f00c0,join);
return result;
}
if(message.prefix==gateway::AuxPrefix){
// Ported aux add-on: its 1.12 auction requests go to the Source as the exact Tortoise packets.
auto packet=t->world->aux_request(message.text);
if(!packet)return 0;
return gw_native_transport_send(t,packet->opcode,packet->body.data(),uint32_t(packet->body.size()),bytes,capacity,required);
}
if(message.prefix==gateway::RadioPrefix){
// OctoRadio (Gitea #5): Octo client radio stations played in this client; answer with the status.
t->world->addon_local(gateway::RadioPrefix,gateway::radio_control(message.text));
return 0;
}
if(message.prefix=="OctoBM"){
// Built-in boss mods name their spells; the subscription stays in this client.
try{t->world->boss_feed_control(message.text);}catch(const gateway::Error&){}
return 0;
}
if(message.prefix==gateway::InspectTransmogAnswerPrefix){
auto packet=t->world->inspect_transmog_answer(message.text);
if(!packet)return 0;
return gw_native_transport_send(t,0x95,packet->data(),uint32_t(packet->size()),bytes,capacity,required);
}
if(message.prefix==gateway::InspectTalentPrefix){
t->world->begin_inspect_talents(message.text);
return 0;
}
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("hardcore ")){
// #151 /h: Turtle hardcore chat (Tortoise checks the hardcore flag and answers with a notification).
gateway::Bytes chat;
try{chat=gateway::turtle_hardcore_request(std::string_view(message.text).substr(9),0);}catch(const gateway::Error&){return 0;}
return gw_native_transport_send(t,0x95,chat.data(),uint32_t(chat.size()),bytes,capacity,required);
}
if(message.text.starts_with("guildremove ")){
if(!t->world->guild_id)return 0;
gateway::LegacyPacket control;
try{control=gateway::source_guild_remove_by_name(std::string_view(message.text).substr(12));}catch(const gateway::Error&){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->requests.size()<4094)t->world->requests.push_back({0x89,{}});
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;
if((opcode==0x3e00d8 || opcode==0x3f00db) && t->world->mailbox_list.awaiting_list()){
if(!gw_native_transport_authenticated(t) || !t->request.empty() || (!bytes&&capacity) || capacity>65535)return -1;
if(t->world->coalesce_mailbox_list(std::span(body,size)))return 0;
}
if((opcode==0x3f0069 || opcode==0x3f006a) && gw_native_transport_authenticated(t)){
try{if(t->world->defer_personal_list(opcode,std::span(body,size)))return 0;}catch(const gateway::Error&){}
}
if(opcode==0x3e0144 && gw_native_transport_authenticated(t) &&
t->world->queue_undercity_template(std::span(body,size)))return 0;
auto packet=t->world->gameplay(opcode,std::span(body,size));
if(opcode==gateway::npc_text::Query){
gateway::Reader r(packet.body);
if(t->world->npc_text_queries.awaiting(uint32_t(r.le(4))))return 0;
}
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;
}
std::vector<gateway::LegacyPacket> facing;
if(opcode==0x3e0176){
// A facing update that fails validation must not cost the cast itself (fail open to the old behaviour).
try{facing=t->world->cast_move_update(opcode,std::span(body,size),t->roster);}catch(const gateway::Error&){facing.clear();}
}
if(!facing.empty()){
const auto request=gateway::forever_spell_request(std::span(body,size));
auto packets=facing;packets.push_back(packet);
auto result=send_packets(t,packets,bytes,capacity,required);
if(!result){t->world->movement_sent(0x420027,request.move_update,facing);t->world->gameplay_sent(opcode,std::span(body,size));}
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 NativeWorldTranslation::TradeOfferChanged&){
t->world->trade.notify_changed=true;
return 0; // Local native STATE_CHANGED; no source acceptance.
}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());
note_request_rejected(opcode,size,error.what());
return -2;
}catch(...){note_request_rejected(opcode,size,"non-standard exception");return -2;}
}
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){
const int result=gameplay_request(t,opcode,body,size,bytes,capacity,required);
// -3 asks for a larger output buffer; every other negative result is a refusal worth tracing.
static unsigned noted=0;
if(result<0 && result!=-3 && noted<64){++noted;char what[32];std::snprintf(what,sizeof what,"result %d",result);note_request_rejected(opcode,size,what);}
return result;
}
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{
gateway::Bytes legacy;
if(auto charm=t->world->possessed_source(std::span(body,size))){gateway::le(legacy,*charm,8);} // possess: Source moves the charmed unit
else 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(const std::exception& error){std::fprintf(stderr,"GW movement failed opcode=%x bytes=%u: %s\n",opcode,size,error.what());return -2;}
catch(...){std::fprintf(stderr,"GW movement failed opcode=%x bytes=%u: unknown\n",opcode,size);return -2;}
}
extern "C" void gw_native_transport_close(gw_native_transport* t){if(t&&t->world){gw_diagnostics::journal().session_end();gateway::RadioPlayer::instance().stop();}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){
const auto begin_ms=login_timing_now();
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;
gw_login_timing_begin(&t->login_timing,begin_ms);
login_timing_note("world-construction-begin",0x3d,8,t->login_timing.started_ms);
auto world=std::make_unique<NativeWorldTranslation>();world->selected=*found;world->realm=uint16_t(realm);
login_timing_note("world-construction-end",0x3d,8,t->login_timing.started_ms);
world->realm_name=t->realm.name;
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->mount_sound_presentations.clear();t->world=std::move(world);
login_timing_note("player-login-encoded",0x3d,uint32_t(wire.size()),t->login_timing.started_ms);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() || !t->mount_sound_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;
}
// Source cache replies enrich presentation. A malformed reply must not retire
// the authenticated world transport; a later valid reply can still fill it.
static thread_local unsigned object_updates_rejected_in_row=0; // see the world-packet catch (#55)
static bool recoverable_source_query_reply(uint32_t opcode){
switch(opcode){
case 0x51: // player name
case 0x55: // guild
case 0x58: // item
case 0x5d: // cache reply
case 0x5f: // game object
case 0x5b: // page text
case 0x61: // creature
return true;
default:return false;
}
}
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;
// A received Source packet drains first: a request poll is invalid while it is
// pending, so a queued presentation must not leave it behind (flag 64 repolls).
if(t && !t->service_presentations.empty() && !t->world_packet && !t->world_encoded){
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->mount_sound_presentations.empty() && !t->world_packet && !t->world_encoded){
if(!required || (!bytes&&capacity) || capacity>GW_CODEC_BOUND)return -1;
while(!t->mount_sound_presentations.empty() &&
!mount_sound_current(t,t->mount_sound_presentations.front(),realm))
t->mount_sound_presentations.pop_front();
if(!t->mount_sound_presentations.empty()){
const auto& sound=t->mount_sound_presentations.front().packet;
gateway::Bytes bundle;gateway::le(bundle,1,4);gateway::le(bundle,sound.opcode,4);
gateway::le(bundle,sound.body.size(),4);gateway::append(bundle,sound.body);
*required=uint32_t(bundle.size());if(capacity<*required)return -3;
std::memcpy(bytes,bundle.data(),bundle.size());t->mount_sound_presentations.pop_front();return 0;
}
// A dismount or map change can retire the sound between request and
// drain. Preserve the successful empty-bundle contract instead of
// turning that local presentation race into a world transport fault.
if(gw_native_transport_authenticated(t) && t->world &&
t->world->realm==realm && !t->world->logout_complete){
*required=4;if(capacity<*required)return -3;
std::memset(bytes,0,*required);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);
if(t->world_packet && (t->world_packet->opcode==0xa9 || t->world_packet->opcode==0x1f6))object_updates_rejected_in_row=0;
t->world_encoded.reset();t->world_packet.reset();return 0;
}catch(const std::bad_alloc&){return t->error=-6;
}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;}
if(t->world_packet){
gw_private_query_failure::record(t->world_packet->opcode,t->world_packet->body);
gw_private_query_failure::record_reason(t->world_packet->opcode,t->world_packet->body.size(),error.what());
note_request_rejected(0x80000000u|t->world_packet->opcode,uint32_t(t->world_packet->body.size()),error.what());
}
// 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. */}
}
}
// 2026-11-25 (#55 Mindvex): one object update the codec cannot convert (0xA9/0x1F6) closed the whole session,
// because the -6 below stays latched and the next packet read fails (Wire close error=15). Drop that update
// like a rejected cache reply; 32 rejected updates in a row still fail the session.
// 2026-11-25 23:49 (owner, Octo live): a rejected SMSG_TRADE_STATUS 0x120 closed the session the same way; trade
// window packets (0x120/0x121) each carry their whole state, so they are dropped the same way.
const bool object_update=t->world_packet && (t->world_packet->opcode==0xa9 || t->world_packet->opcode==0x1f6 ||
t->world_packet->opcode==0x120 || t->world_packet->opcode==0x121);
if(object_update && ++object_updates_rejected_in_row>32)return t->error=-6;
if(t->world_packet && !t->world_encoded && (object_update || recoverable_source_query_reply(t->world_packet->opcode))){
// The parser rejected this one cache reply before producing native
// output. Return a valid empty bundle and consume only this packet.
// Cache the empty bundle across a short-buffer retry; never parse
// the same rejected reply twice against mutable world state.
t->world_encoded.emplace(4,0);
*required=4;
if(capacity<*required)return -3;
std::memcpy(bytes,t->world_encoded->data(),*required);
t->world_encoded.reset();
t->world_packet.reset();
return 0;
}
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;
uint32_t declined=(!t?1u:0u)|(!opcode?2u:0u)|(!required?4u:0u)|
((!bytes&&capacity)?8u:0u)|(capacity>65535?16u:0u)|
(t&&!t->world?32u:0u)|(t&&t->world_packet?64u:0u)|
(t&&t->world_encoded?128u:0u);
if(!declined&&!gw_native_transport_authenticated(t))declined=256u;
if(declined){std::fprintf(stderr,"GW_WORLD_REQUEST_DECLINED mask=%u\n",declined);return -1;}
try{
if(auto list=t->world->next_mailbox_list()){
*opcode=list->source_opcode;
const int result=gw_native_transport_send(t,*opcode,list->source_body.data(),uint32_t(list->source_body.size()),bytes,capacity,required);
if(!result)t->world->gameplay_sent(0x3f00db,gateway::pack_guid(list->actor.native_guid));
return result;
}
auto& mailbox=t->world->mailbox_list;
if(mailbox.pending()){
if(auto request=mailbox.next_text(t->world->current_mailbox_actor())){
const auto [text,mail]=*request;
gateway::Bytes body;gateway::le(body,text,4);gateway::le(body,mail,4);gateway::le(body,0,4);
*opcode=0x243;
const int result=gw_native_transport_send(t,*opcode,body.data(),uint32_t(body.size()),bytes,capacity,required);
if(!result)mailbox.text_sent(text);
return result;
}
}
auto& sets = t->world->equipment_sets;
auto now = gateway::equipment_sets::Clock::now();
sets.expire(now);
if (sets.pending && sets.pending->next && !t->world->far_transfer && !t->world->pending_teleport &&
t->world->self_created && !t->world->logout_complete) {
if (sets.pending->next->from_bank && !t->world->equipment_bank_open()) {
sets.finish(1);
return 1;
}
const auto& packet = sets.pending->next->source;
*opcode = packet.opcode;
auto status = gw_native_transport_send(t, packet.opcode, packet.body.data(),
uint32_t(packet.body.size()), bytes, capacity, required);
if (!status) sets.sent(now);
return status;
}
if(auto packet=t->world->next_inspect_talents()){
*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->inspect_talents->sent=true;
return result;
}
if(auto packet=t->world->next_inspect_transmogs()){
*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->inspect_transmogs->sent=true;
return result;
}
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->next_quest_status_refresh()){
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){
if(packet.opcode==0x25a && &queue==&t->world->requests)t->world->auction_bid_dispatched(packet.body); // commodity buyout now in flight
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(!gw_native_transport_authenticated(t) || !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.
const bool sd_enabled=gateway::sdhd_preference::load(t->authentication->internal_source_account()).value_or(false);
auto body=gateway::forever_account_roster_preview(t->roster,{realm,address,district},false,sd_enabled);
*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_account_name(const gw_native_transport* t,uint8_t* bytes,uint32_t capacity,uint32_t* required){
if(required)*required=0;
if(!gw_native_transport_authenticated(t)||!required||(!bytes&&capacity)||capacity>33)return -1;
const auto name=t->authentication->account_name();
if(name.empty()||name.size()>32||name.find('\0')!=std::string_view::npos)return -1;
*required=uint32_t(name.size()+1);if(capacity<*required)return -3;
std::memcpy(bytes,name.data(),name.size());bytes[name.size()]=0;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());
// Validate and retain the identity used for this authenticated realm presentation.
t->realm_query.bind(address,t->realm.name);
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;}
}