891 lines
69 KiB
C++
891 lines
69 KiB
C++
#include "gateway/forever.hpp"
|
|
#include "gateway/legacy_client.hpp"
|
|
#include "gateway/roster_translation.hpp"
|
|
#include "gateway/world.hpp"
|
|
#include "gateway/chat.hpp"
|
|
#include "gateway/queries.hpp"
|
|
#include "gateway/object_updates.hpp"
|
|
#include "gateway/splines.hpp"
|
|
#include "gateway/gameplay.hpp"
|
|
#include "gateway/npc_text.hpp"
|
|
#include "gateway/reputation.hpp"
|
|
#include "gateway/talents.hpp"
|
|
#include <cstdlib>
|
|
#include <sys/wait.h>
|
|
#include <arpa/inet.h>
|
|
#include <sys/socket.h>
|
|
#include <poll.h>
|
|
#include <unistd.h>
|
|
#include <openssl/evp.h>
|
|
#include <openssl/crypto.h>
|
|
#include <mysql/mysql.h>
|
|
#include <boost/property_tree/json_parser.hpp>
|
|
#include <boost/property_tree/ptree.hpp>
|
|
#include <zlib.h>
|
|
#include <cerrno>
|
|
#include <chrono>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <sstream>
|
|
#include <csignal>
|
|
#include <set>
|
|
#include <fcntl.h>
|
|
using namespace gateway;
|
|
namespace {
|
|
Bytes read_exact(int fd,size_t n) {
|
|
if(n>16777216) throw Error("relay read limit");
|
|
Bytes b(n); size_t at=0;
|
|
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(15);
|
|
while(at<n) {
|
|
auto ms=std::chrono::duration_cast<std::chrono::milliseconds>(deadline-std::chrono::steady_clock::now()).count();
|
|
if(ms<=0) throw Error("relay read timeout");
|
|
pollfd p{fd,POLLIN,0}; auto status=poll(&p,1,int(ms));
|
|
if(status<0 && errno==EINTR) continue;
|
|
if(status<=0) throw Error("relay read timeout");
|
|
auto got=recv(fd,b.data()+at,n-at,0);
|
|
if(got<=0) throw Error("relay peer closed");
|
|
at+=size_t(got);
|
|
}
|
|
return b;
|
|
}
|
|
void write_all(int fd,const Bytes& b) {
|
|
size_t at=0;
|
|
while(at<b.size()) { auto n=send(fd,b.data()+at,b.size()-at,MSG_NOSIGNAL);
|
|
if(n<0 && errno==EINTR) continue;
|
|
if(n<=0) throw Error("relay write failed");
|
|
at+=size_t(n); }
|
|
}
|
|
Bytes read_frame(int fd,size_t limit) { auto b=read_exact(fd,16); Reader r(b); auto n=r.le(4);
|
|
if(n<4 || n>limit) throw Error("relay frame length: "+std::to_string(n));
|
|
append(b,read_exact(fd,n)); return b; }
|
|
struct Fd { int value=-1; ~Fd(){if(value>=0)close(value);} };
|
|
void capture_glue_features(const Bytes& body){
|
|
// Explicit local diagnostic opt-in. Public capability fields only; never
|
|
// capture auth responses, tickets, account buffers or arbitrary opcodes.
|
|
const char* enabled=std::getenv("GW_CAPTURE_GLUE_FEATURES");
|
|
if(!enabled || std::string_view(enabled)!="1" || body.size()!=94)return;
|
|
Fd output;output.value=open("runtime/reference-glue-features.bin",O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOFOLLOW,0600);
|
|
if(output.value<0)return; // Existing evidence is preserved, including links.
|
|
size_t at=0;
|
|
while(at<body.size()){
|
|
auto n=::write(output.value,body.data()+at,body.size()-at);
|
|
if(n<0 && errno==EINTR)continue;
|
|
if(n<=0){std::cerr<<"Public glue-feature capture incomplete\n";return;}
|
|
at+=size_t(n);
|
|
}
|
|
std::cerr<<"Captured public Forever glue-feature packet bytes="<<body.size()<<'\n';
|
|
}
|
|
Bytes hash512(const Bytes& b) { Bytes out(64); unsigned len=0;
|
|
if(EVP_Digest(b.data(),b.size(),out.data(),&len,EVP_sha512(),nullptr)!=1 || len!=64) throw Error("SHA512 failed");
|
|
return out; }
|
|
Bytes hmac512(const Bytes& key,Bytes data) {
|
|
// EVP's one-shot keyed digest avoids deprecated HMAC APIs.
|
|
Bytes out(64); size_t n=out.size();
|
|
if(!EVP_Q_mac(nullptr,"HMAC",nullptr,"SHA512",nullptr,key.data(),key.size(),data.data(),data.size(),out.data(),out.size(),&n) || n!=64)
|
|
throw Error("HMAC512 failed");
|
|
return out;
|
|
}
|
|
Bytes derive(const Bytes& data,const Bytes& local,const Bytes& server,Bytes& retained_session) {
|
|
auto session_seed=unhex("e81e8b5927621eaa861518eac0bf668c6dbf8393bcaa80525b1edc23a012b750");
|
|
Bytes input=server; append(input,local); append(input,session_seed); auto h=hmac512(hash512(data),input);
|
|
Bytes first(h.begin(),h.begin()+32),second(h.begin()+32,h.end());
|
|
auto o1=hash512(first),o2=hash512(second); Bytes generated=o1; append(generated,Bytes(64)); append(generated,o2);
|
|
auto digest=hash512(generated); Bytes session(digest.begin(),digest.begin()+40);
|
|
auto encrypt_seed=unhex("71c9ed5aa70e4dff4c36a65a3e468a4a5da148c830474adef60d6cbe6fe45573");
|
|
input=local; append(input,server); append(input,encrypt_seed); auto key=hmac512(session,input); key.resize(32);
|
|
retained_session=session; OPENSSL_cleanse(session.data(),session.size()); return key;
|
|
}
|
|
struct Provider {
|
|
MYSQL* db=nullptr; uint32_t allowed=0;
|
|
Provider(const std::string& path,uint32_t account):allowed(account) {
|
|
std::ifstream f(path); std::string line; if(!std::getline(f,line)) throw Error("missing private provider config");
|
|
std::vector<std::string> fields; std::stringstream split(line);
|
|
while(std::getline(split,line,';')) fields.push_back(line);
|
|
if(fields.size()!=5 || fields[0]!="127.0.0.1" || fields[4]!="forever_auth") throw Error("provider must be local forever_auth");
|
|
db=mysql_init(nullptr); unsigned timeout=3; mysql_options(db,MYSQL_OPT_CONNECT_TIMEOUT,&timeout);
|
|
if(!mysql_real_connect(db,fields[0].c_str(),fields[2].c_str(),fields[3].c_str(),fields[4].c_str(),unsigned(std::stoul(fields[1])),nullptr,0)) {
|
|
mysql_close(db); db=nullptr; throw Error("local provider DB connection failed"); }
|
|
}
|
|
uint32_t bnet_identity() {
|
|
std::string query="SELECT battlenet_account FROM account WHERE id="+std::to_string(allowed);
|
|
if(mysql_query(db,query.c_str()))throw Error("frontend identity lookup failed");
|
|
std::unique_ptr<MYSQL_RES,decltype(&mysql_free_result)> result(mysql_store_result(db),mysql_free_result);
|
|
if(!result || mysql_num_rows(result.get())!=1)throw Error("frontend account missing");
|
|
auto row=mysql_fetch_row(result.get());if(!row[0])throw Error("frontend Battle.net binding missing");
|
|
auto id=std::stoul(row[0]);if(!id || id>UINT32_MAX)throw Error("frontend Battle.net ID bound");return uint32_t(id);
|
|
}
|
|
~Provider(){if(db)mysql_close(db);}
|
|
RosterRealm realm_metadata() {
|
|
if(mysql_query(db,"SELECT Region,Battlegroup FROM realmlist WHERE id=70 AND gamebuild=70334"))throw Error("local realm lookup failed");
|
|
std::unique_ptr<MYSQL_RES,decltype(&mysql_free_result)> result(mysql_store_result(db),mysql_free_result);
|
|
if(!result || mysql_num_rows(result.get())!=1)throw Error("local 70334 realm missing");
|
|
auto row=mysql_fetch_row(result.get());if(!row[0] || !row[1])throw Error("local realm metadata missing");
|
|
auto region=std::stoul(row[0]),site=std::stoul(row[1]);if(region>255 || site>255)throw Error("local realm components out of bounds");
|
|
RosterRealm realm;realm.virtual_address=uint32_t((region<<24)|(site<<16)|70);return realm;
|
|
}
|
|
Bytes key(const std::string& account) {
|
|
// Only the explicitly allowed disposable account is ever queried. No general SQL input.
|
|
if(account!=std::to_string(allowed)+"#1") throw Error("frontend account is not the bound local test account");
|
|
std::string query="SELECT session_key_bnet FROM account WHERE id="+std::to_string(allowed)+" AND client_build=70334";
|
|
if(mysql_query(db,query.c_str())) throw Error("provider session lookup failed");
|
|
std::unique_ptr<MYSQL_RES,decltype(&mysql_free_result)> result(mysql_store_result(db),mysql_free_result);
|
|
if(!result || mysql_num_rows(result.get())!=1) throw Error("provider session missing");
|
|
auto row=mysql_fetch_row(result.get()); auto lengths=mysql_fetch_lengths(result.get());
|
|
if(!row[0] || lengths[0]!=64) throw Error("provider session key has invalid width");
|
|
return Bytes(reinterpret_cast<uint8_t*>(row[0]),reinterpret_cast<uint8_t*>(row[0])+64);
|
|
}
|
|
};
|
|
struct Instance {
|
|
Fd listener,client;
|
|
ForeverChannel incoming{Direction::client_to_server,1048576},outgoing{Direction::server_to_client,16777216};
|
|
uint64_t key=0;
|
|
Bytes connect_to(uint32_t account,uint32_t realm_address) {
|
|
listener.value=socket(AF_INET,SOCK_STREAM,0);int reuse=1;
|
|
setsockopt(listener.value,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
|
|
sockaddr_in address{};address.sin_family=AF_INET;address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);address.sin_port=htons(19086);
|
|
if(listener.value<0 || bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) || listen(listener.value,1)) throw Error("instance loopback bind failed");
|
|
auto random=random_bytes(4);Reader reader(random);key=(reader.le(4)&0x7FFFFFFF)<<33;key|=(uint64_t(1)<<32)|account;
|
|
Bytes b;le(b,1,4);le(b,17,4);le(b,1,1);le(b,key,8);le(b,realm_address,4);le(b,0,4);
|
|
append(b,Bytes{1,127,0,0,1});le(b,19086,2);append(b,Bytes{0,0,0,8,0});le(b,0,8);return b;
|
|
}
|
|
void authenticate(const Bytes& session,uint32_t realm_address) {
|
|
pollfd ready{listener.value,POLLIN,0}; if(poll(&ready,1,15000)<=0) throw Error("actual client did not open instance connection");
|
|
client.value=accept(listener.value,nullptr,nullptr);if(client.value<0)throw Error("instance accept failed");
|
|
close(listener.value);listener.value=-1;
|
|
Fd provider;provider.value=socket(AF_INET,SOCK_STREAM,0);
|
|
sockaddr_in address{};address.sin_family=AF_INET;address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);address.sin_port=htons(8085);
|
|
if(provider.value<0 || connect(provider.value,reinterpret_cast<sockaddr*>(&address),sizeof(address))) throw Error("instance auth provider unavailable");
|
|
constexpr std::string_view server_banner="WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT - V2\n";
|
|
constexpr std::string_view client_banner="WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER - V2\n";
|
|
auto banner=read_exact(provider.value,server_banner.size());
|
|
if(std::string(banner.begin(),banner.end())!=server_banner)throw Error("instance provider banner mismatch");
|
|
write_all(client.value,banner);banner=read_exact(client.value,client_banner.size());
|
|
if(std::string(banner.begin(),banner.end())!=client_banner)throw Error("instance client banner mismatch");
|
|
write_all(provider.value,banner);
|
|
ForeverChannel from_provider(Direction::server_to_client),to_provider(Direction::client_to_server);
|
|
auto challenge=from_provider.decode(read_frame(provider.value,65535));
|
|
if(challenge.opcode!=0x4E0000 || challenge.body.size()!=65)throw Error("instance auth challenge mismatch");
|
|
Bytes server(challenge.body.begin()+32,challenge.body.begin()+64);
|
|
write_all(client.value,outgoing.encode(challenge.opcode,challenge.body));
|
|
auto auth=incoming.decode(read_frame(client.value,1048576));
|
|
if(auth.opcode!=0x460003)throw Error("instance continued auth opcode mismatch");
|
|
Reader r(auth.body);r.le(8);auto local=r.take(32);auto digest=r.take(24);auto supplied_key=r.le(8);
|
|
auto native=r.le(4),key3=r.le(4);r.end();
|
|
if(supplied_key!=key || native!=realm_address || key3 || session.size()!=40)throw Error("instance account/realm binding mismatch");
|
|
Bytes proof;le(proof,key,8);append(proof,local);append(proof,server);
|
|
append(proof,unhex("565c619c483a521f615d0549b29a39bf4b97b01bf96cded6801dab2602a99b9d"));
|
|
auto expected=hmac512(session,proof);
|
|
if(CRYPTO_memcmp(expected.data(),digest.data(),digest.size()))throw Error("instance continued session proof failed");
|
|
write_all(provider.value,to_provider.encode(auth.opcode,auth.body));
|
|
auto enable=from_provider.decode(read_frame(provider.value,65535));
|
|
if(enable.opcode!=0x4E0004 || enable.body.size()!=69)throw Error("instance provider refused continued auth");
|
|
write_all(client.value,outgoing.encode(enable.opcode,enable.body));
|
|
auto ack=incoming.decode(read_frame(client.value,1048576));
|
|
if(ack.opcode!=0x460005 || !ack.body.empty())throw Error("instance encryption acknowledgement mismatch");
|
|
Bytes seed=local;append(seed,server);append(seed,unhex("71c9ed5aa70e4dff4c36a65a3e468a4a5da148c830474adef60d6cbe6fe45573"));
|
|
auto encryption=hmac512(session,seed);encryption.resize(32);
|
|
incoming.enter_encrypted_mode(encryption);outgoing.enter_encrypted_mode(encryption);OPENSSL_cleanse(encryption.data(),encryption.size());
|
|
// Provider validated continued auth and signed the transition. Gameplay is supplied solely by Turtle.
|
|
write_all(client.value,outgoing.encode(0x4E0006,{}));
|
|
write_all(client.value,outgoing.encode(0x600000,Bytes(4)));
|
|
std::cerr<<"Real Forever continued instance authentication verified and encryption enabled\n";
|
|
}
|
|
};
|
|
Bytes create_self(const char* executable,const Bytes& input,const char* mode=nullptr) {
|
|
int pair[2]; if(socketpair(AF_UNIX,SOCK_STREAM,0,pair)) throw Error("create codec socketpair failed");
|
|
Fd parent,child; parent.value=pair[0];child.value=pair[1];
|
|
auto pid=fork(); if(pid<0) throw Error("create codec fork failed");
|
|
if(pid==0) {
|
|
close(parent.value);dup2(child.value,STDIN_FILENO);dup2(child.value,STDOUT_FILENO);close(child.value);
|
|
execl(executable,executable,mode,static_cast<char*>(nullptr));_exit(127);
|
|
}
|
|
close(child.value);child.value=-1;
|
|
try {
|
|
write_all(parent.value,input);shutdown(parent.value,SHUT_WR);
|
|
Bytes output;
|
|
while(true) {
|
|
pollfd fd{parent.value,POLLIN,0}; if(poll(&fd,1,15000)<=0) throw Error("create codec deadline");
|
|
uint8_t b[8192]; auto n=recv(parent.value,b,sizeof(b),0);
|
|
if(n==0) break;
|
|
if(n<0 || output.size()+size_t(n)>1048576) throw Error("create codec output bound");
|
|
output.insert(output.end(),b,b+n);
|
|
}
|
|
int status; if(waitpid(pid,&status,0)!=pid || !WIFEXITED(status) || WEXITSTATUS(status) || output.empty())
|
|
throw Error("create codec failed");
|
|
return output;
|
|
} catch(...) { kill(pid,SIGTERM);waitpid(pid,nullptr,0);throw; }
|
|
}
|
|
struct Inflate {
|
|
z_stream z{};
|
|
Inflate(){if(inflateInit2(&z,-15)!=Z_OK)throw Error("inflate init failed");}
|
|
~Inflate(){inflateEnd(&z);}
|
|
ForeverPacket unwrap(ForeverPacket p) {
|
|
if(p.opcode!=0x4E000E) return p;
|
|
Reader r(p.body); auto size=r.le(4); auto original_adler=r.le(4),compressed_adler=r.le(4); auto compressed=r.take(r.left());
|
|
if(size<4 || size>16777216 || adler32(0x9827D8F1,compressed.data(),compressed.size())!=compressed_adler) throw Error("invalid compression metadata: uncompressed="+std::to_string(size)+" compressed="+std::to_string(compressed.size()));
|
|
Bytes output(size); z.next_in=compressed.data(); z.avail_in=compressed.size(); z.next_out=output.data(); z.avail_out=output.size();
|
|
auto status=inflate(&z,Z_SYNC_FLUSH);
|
|
if((status!=Z_OK && status!=Z_BUF_ERROR) || z.avail_in || z.avail_out || adler32(0x9827D8F1,output.data(),output.size())!=original_adler)
|
|
throw Error("invalid compressed packet");
|
|
Reader decoded(output); auto opcode=uint32_t(decoded.le(4)); return {opcode,decoded.take(decoded.left())};
|
|
}
|
|
};
|
|
void relay(int client,Provider& provider,char** backend) {
|
|
Fd upstream; upstream.value=socket(AF_INET,SOCK_STREAM,0);
|
|
sockaddr_in addr{}; addr.sin_family=AF_INET; addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK); addr.sin_port=htons(8085);
|
|
if(upstream.value<0 || connect(upstream.value,reinterpret_cast<sockaddr*>(&addr),sizeof(addr))) throw Error("local authentication provider unavailable");
|
|
timeval timeout{5,0}; setsockopt(client,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout)); setsockopt(upstream.value,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));
|
|
constexpr std::string_view server_banner="WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT - V2\n";
|
|
constexpr std::string_view client_banner="WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER - V2\n";
|
|
auto banner=read_exact(upstream.value,server_banner.size());
|
|
if(std::string(banner.begin(),banner.end())!=server_banner) throw Error("invalid provider banner");
|
|
write_all(client,banner);
|
|
banner=read_exact(client,client_banner.size());
|
|
if(std::string(banner.begin(),banner.end())!=client_banner) throw Error("invalid client banner");
|
|
write_all(upstream.value,banner);
|
|
ForeverChannel from_client(Direction::client_to_server,1048576),to_provider(Direction::client_to_server,1048576),from_provider(Direction::server_to_client,16777216),to_client(Direction::server_to_client,16777216);
|
|
std::unique_ptr<LegacySession> turtle; bool world_requested=false,self_sent=false,played_trigger=false; uint64_t selected_guid=0; uint32_t world_map=0;
|
|
std::optional<NearTeleport> pending_teleport;
|
|
std::map<uint64_t,Guid128> known_world_objects;
|
|
std::map<uint32_t,uint8_t> known_creature_classes;
|
|
std::map<uint64_t,uint8_t> unit_power_types;
|
|
std::set<uint32_t> known_spells;
|
|
uint32_t free_talent_points=0;
|
|
uint32_t backend_level=0,talent_state_sequence=0;
|
|
std::set<uint32_t> pending_creature_queries;
|
|
std::set<uint16_t> audited_movement_opcodes;
|
|
std::set<uint64_t> audited_spline_guids;
|
|
std::set<std::string> unsupported_splines;
|
|
const bool general_population=std::getenv("GATEWAY_POPULATION_EXPERIMENT")!=nullptr;
|
|
std::map<uint32_t,CreatureTemplateReply> creature_templates;
|
|
struct PendingNpcs {Bytes header,wire;std::vector<std::pair<LegacyObjectUpdate,uint64_t>> actors;};
|
|
std::vector<PendingNpcs> pending_npcs;
|
|
std::map<uint64_t,uint64_t> npc_generations;uint64_t npc_generation=0;
|
|
Fd population_audit;size_t audit_bytes=0;bool audit_capped=false;
|
|
auto audit_start=std::chrono::steady_clock::now();
|
|
if(std::getenv("GATEWAY_POPULATION_AUDIT")) {
|
|
auto path="runtime/population-"+std::to_string(getpid())+"-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())+".jsonl";
|
|
population_audit.value=open(path.c_str(),O_WRONLY|O_CREAT|O_EXCL,0600);
|
|
if(population_audit.value<0)throw Error("population audit output unavailable");
|
|
std::cerr<<"Private population audit: "<<path<<'\n';
|
|
}
|
|
auto audit=[&](boost::property_tree::ptree event) {
|
|
if(population_audit.value<0 || audit_capped)return;
|
|
event.put("elapsed_ms",std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-audit_start).count());
|
|
std::ostringstream json;boost::property_tree::write_json(json,event,false);auto text=json.str()+"\n";size_t at=0;
|
|
if(audit_bytes+text.size()>16777216){text="{\"event\":\"capture_capped\"}\n";audit_capped=true;}
|
|
while(at<text.size()) {auto n=write(population_audit.value,text.data()+at,text.size()-at);if(n<0 && errno==EINTR)continue;if(n<=0)throw Error("population audit write failed");at+=size_t(n);}
|
|
audit_bytes+=text.size();
|
|
};
|
|
auto audit_sent=[&](uint64_t guid,Guid128 modern,std::string profile) {
|
|
boost::property_tree::ptree event;event.put("event","sent");event.put("guid",guid);event.put("profile",profile);
|
|
std::string hex;constexpr char digits[]="0123456789abcdef";for(auto byte:modern){hex+=digits[byte>>4];hex+=digits[byte&15];}
|
|
event.put("modern_guid",hex);audit(event);
|
|
};
|
|
auto last_turtle_ping=std::chrono::steady_clock::now()-std::chrono::seconds(30);
|
|
bool experimental_world=std::getenv("GATEWAY_WORLD_EXPERIMENT")!=nullptr;
|
|
Instance instance;
|
|
Inflate inflater; Bytes session_key,server_challenge,encrypt_key;
|
|
struct Wipe { Bytes& key;~Wipe(){if(!key.empty())OPENSSL_cleanse(key.data(),key.size());} } wipe{session_key}; bool encrypted=false,authenticated=false; RosterRealm realm;
|
|
if(experimental_world) realm=provider.realm_metadata();
|
|
auto world_send=[&](uint32_t opcode,const Bytes& body) {
|
|
if(instance.client.value>=0) write_all(instance.client.value,instance.outgoing.encode(opcode,body));
|
|
else write_all(client,to_client.encode(opcode,body));
|
|
};
|
|
FactionMappings faction_mappings;std::map<uint32_t,int32_t> reputation_standings;
|
|
if(auto file=std::getenv("GATEWAY_FACTION_MAP"))faction_mappings=load_faction_mappings(file);
|
|
std::optional<GossipMenu> active_gossip;
|
|
npc_text::Queries npc_text_queries;
|
|
std::optional<uint64_t> merchant_context;
|
|
std::optional<std::pair<uint64_t,uint32_t>> talent_reset_offer;
|
|
auto talent_system_message=[&](const std::string& text){
|
|
Bytes body{10};le(body,0,4);le(body,0,8);le(body,text.size()+1,4);cstring(body,text);le(body,0,1);
|
|
world_send(0x4C0001,forever_chat(body,turtle->roster(),realm,provider.allowed));
|
|
};
|
|
auto talent_state=[&](){
|
|
if(!self_sent || !std::getenv("GATEWAY_TALENT_EXPERIMENT"))return;
|
|
auto character=std::find_if(turtle->roster().begin(),turtle->roster().end(),[&](const auto& c){return c.guid==selected_guid;});if(character==turtle->roster().end())throw Error("talent state lost character binding");
|
|
auto seq=std::to_string(++talent_state_sequence);std::string prefix="GWTURTLE1 ";
|
|
talent_system_message(prefix+"BEGIN "+seq+" "+std::to_string(selected_guid)+" "+std::to_string(character->cls)+" "+std::to_string(backend_level)+" "+std::to_string(free_talent_points)+" "+std::to_string(known_spells.size()));
|
|
std::string chunk;unsigned count=0;for(auto spell:known_spells){if(count++)chunk+=',';chunk+=std::to_string(spell);if(count==20){talent_system_message(prefix+"SPELLS "+seq+" "+chunk);chunk.clear();count=0;}}
|
|
if(count)talent_system_message(prefix+"SPELLS "+seq+" "+chunk);
|
|
talent_system_message(prefix+"END "+seq);
|
|
};
|
|
auto frontend_say=[&](const Bytes& body){
|
|
auto legacy=turtle_say(body);Reader r(legacy);r.le(4);r.le(4);auto text=r.cstring(255);r.end();
|
|
if(self_sent && std::getenv("GATEWAY_TALENT_EXPERIMENT"))try{
|
|
if(auto command=turtle_talent_control(text)){
|
|
if(command->reset_guid){
|
|
if(!talent_reset_offer || talent_reset_offer->first!=command->reset_guid || !known_world_objects.contains(command->reset_guid))throw Error("unbound Turtle talent reset offer");
|
|
Bytes request;le(request,command->reset_guid,8);turtle->send(0x2AA,request);talent_reset_offer.reset();
|
|
boost::property_tree::ptree event;event.put("event","turtle_ui_reset");event.put("trainer",command->reset_guid);audit(event);
|
|
}
|
|
if(command->talent){Bytes request;le(request,command->talent,4);le(request,command->rank-1,4);turtle->send(0x251,request);
|
|
boost::property_tree::ptree event;event.put("event","turtle_ui_purchase");event.put("talent",command->talent);event.put("rank",command->rank);audit(event);}
|
|
talent_state();return;
|
|
}
|
|
}catch(const Error&){talent_system_message("GWTURTLE1 ERROR invalid-request");return;}
|
|
turtle->send(0x95,legacy);std::cerr<<"Forwarded actual Forever say to Turtle\n";
|
|
};
|
|
auto gameplay_request=[&](uint32_t opcode,const Bytes& body) {
|
|
if(self_sent && turtle && opcode==0x3E02C0 && std::getenv("GATEWAY_TALENT_EXPERIMENT")) {
|
|
boost::property_tree::ptree event;event.put("event","talent_commit");
|
|
std::string hex;constexpr char digits[]="0123456789abcdef";for(auto byte:body){hex+=digits[byte>>4];hex+=digits[byte&15];}event.put("body",hex);audit(event);
|
|
try {
|
|
Bytes input;le(input,selected_guid&0x7FFFFFFF,4);le(input,free_talent_points,4);le(input,known_spells.size(),4);for(auto spell:known_spells)le(input,spell,4);append(input,body);
|
|
auto output=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--talent-commit");Reader decoded(output);auto count=decoded.le(4);if(!count || count>54 || decoded.left()!=count*8)throw Error("talent codec output bound");
|
|
for(unsigned i=0;i<count;++i){auto request=decoded.take(8);turtle->send(0x251,request);Reader r(request);std::cerr<<"Forwarded actual trait purchase to Turtle talent="<<r.le(4)<<" rank="<<r.le(4)+1<<'\n';}
|
|
} catch(const Error& e){std::cerr<<"Rejected Turtle-incompatible talent commit: "<<e.what()<<'\n';Bytes failed;le(failed,selected_guid&0x7FFFFFFF,4);le(failed,0,4);le(failed,0x10,1);world_send(0x470075,failed);}
|
|
return true;
|
|
}
|
|
if(!self_sent || !turtle || (opcode!=npc_text::Query && opcode!=0x3F0038 && opcode!=0x3F0029 && opcode!=0x3F002B && opcode!=0x3E011E && opcode!=0x3E011F && opcode!=0x3F00CD))return false;
|
|
try {
|
|
Reader r(body);
|
|
if(opcode==npc_text::Query){
|
|
auto request=npc_text_queries.request(body,active_gossip ? &*active_gossip : nullptr,known_world_objects);
|
|
const uint32_t id=r.le(4);
|
|
if(!npc_text_queries.awaiting(id)){
|
|
turtle->send(0x17f,request);
|
|
npc_text_queries.sent(id);
|
|
}
|
|
return true;
|
|
}
|
|
if(opcode==0x3E011F){r.end();turtle->send(0x142,{});return true;}
|
|
if(opcode==0x3F002B) {
|
|
if(!active_gossip || !active_gossip->broadcast_text)throw Error("no displayed Turtle gossip menu");
|
|
auto selected=turtle_gossip_selection(r,*active_gossip,known_world_objects);
|
|
turtle->send(0x17C,selected);std::cerr<<"Forwarded actual Forever gossip selection to Turtle\n";return true;
|
|
}
|
|
|
|
auto guid=bound_legacy_guid(r,known_world_objects,opcode==0x3F00CD);r.end();
|
|
if(opcode==0x3F0029)merchant_context.reset();
|
|
if(opcode!=0x3F00CD && opcode!=0x3E011E && (guid>>48)!=0xF130)throw Error("NPC interaction target category");
|
|
uint16_t legacy=opcode==0x3E011E?0x141:opcode==0x3F0038?0x19E:(opcode==0x3F0029?0x17B:0x13D);
|
|
Bytes input;le(input,guid,8);turtle->send(legacy,input);
|
|
if(opcode==0x3F0029 || opcode==0x3F0038)active_gossip.reset();
|
|
std::cerr<<"Forwarded actual Forever gameplay request 0x"<<std::hex<<opcode<<" -> Turtle 0x"<<legacy<<std::dec<<" guid="<<guid<<'\n';
|
|
} catch(const Error& e) {std::cerr<<"Rejected gameplay request: "<<e.what()<<'\n';}
|
|
return true;
|
|
};
|
|
auto flush_npcs=[&]() {
|
|
for(auto it=pending_npcs.begin();it!=pending_npcs.end();) {
|
|
if(std::any_of(it->actors.begin(),it->actors.end(),[&](const auto& actor) {
|
|
return !creature_templates.contains(actor.first.fields.at(3));
|
|
})) {++it;continue;}
|
|
Bytes input=it->header;std::map<uint32_t,uint8_t> types;std::vector<const LegacyObjectUpdate*> alive;
|
|
for(const auto& [update,generation]:it->actors) {
|
|
auto entry=update.fields.at(3);const auto& metadata=creature_templates.at(entry);
|
|
if(npc_generations.contains(update.guid) && npc_generations.at(update.guid)==generation && metadata.found) {
|
|
types[entry]=metadata.type;alive.push_back(&update);
|
|
}
|
|
}
|
|
le(input,types.size(),4);for(auto [entry,type]:types){le(input,entry,4);le(input,type,1);}
|
|
le(input,alive.size(),4);for(auto update:alive)le(input,update->guid,8);append(input,it->wire);
|
|
auto payload=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--npcs-types");
|
|
Reader summary(payload);summary.le(2);auto count=summary.le(4);
|
|
if(count!=alive.size())throw Error("NPC serializer/tracker population mismatch");
|
|
if(count) {
|
|
world_send(0x5E0000,payload);
|
|
for(auto update:alive) {
|
|
auto entry=update->fields.at(3);auto id=forever_creature_guid(update->guid,entry,realm.realm_id,world_map);
|
|
known_world_objects[update->guid]=id;audit_sent(update->guid,id,"creature");
|
|
}
|
|
std::cerr<<"Translated Turtle general-population NPC creates: "<<count<<'\n';
|
|
}
|
|
it=pending_npcs.erase(it);
|
|
}
|
|
};
|
|
auto teleport_ack=[&](const Bytes& body) {
|
|
if(!pending_teleport) {std::cerr<<"Ignored unsolicited teleport acknowledgment\n";return;}
|
|
auto reply=turtle_near_teleport_ack(body,*pending_teleport,realm.realm_id);
|
|
turtle->send(0xC7,reply);pending_teleport.reset();std::cerr<<"Forwarded actual Forever teleport acknowledgment to Turtle\n";
|
|
};
|
|
auto creature_query=[&](const Bytes& body) {
|
|
for(auto entry:forever_creature_queries(body)) {
|
|
if(!known_creature_classes.contains(entry)) {std::cerr<<"Ignored creature query outside translated NPC profile entry="<<entry<<'\n';continue;}
|
|
if(creature_templates.contains(entry)) {world_send(0x4B0006,forever_creature_template(creature_templates.at(entry),known_creature_classes.at(entry)));continue;}
|
|
if(pending_creature_queries.insert(entry).second) {
|
|
turtle->send(0x60,turtle_creature_query(entry));
|
|
std::cerr<<"Forwarded actual Forever creature query to Turtle entry="<<entry<<'\n';
|
|
}
|
|
}
|
|
};
|
|
while(true) {
|
|
pollfd fds[4]{{upstream.value,POLLIN,0},{client,POLLIN,0},{turtle?turtle->descriptor():-1,POLLIN,0},{instance.client.value,POLLIN,0}};
|
|
int n=poll(fds,4,60000); if(n<0 && errno==EINTR)continue; if(n<=0)throw Error("relay idle timeout");
|
|
if(fds[0].revents) {
|
|
auto packet=from_provider.decode(read_frame(upstream.value,16777216)); packet=inflater.unwrap(std::move(packet));
|
|
std::cerr<<"Provider opcode 0x"<<std::hex<<packet.opcode<<std::dec<<" bytes="<<packet.body.size()<<'\n';
|
|
if(packet.opcode==0x4E0000) { if(packet.body.size()!=65)throw Error("invalid Forever auth challenge"); server_challenge=Bytes(packet.body.begin()+32,packet.body.begin()+64); }
|
|
if(experimental_world && packet.opcode==0x4702B0) {
|
|
Reader metadata(packet.body); std::cerr<<"Battle.net response status="<<metadata.le(4)<<'\n';
|
|
}
|
|
if(packet.opcode==0x470001 && encrypted) {
|
|
Reader response(packet.body);if(response.le(4)!=0)throw Error("Forever provider rejected authentication");authenticated=true;
|
|
}
|
|
if(packet.opcode==0x470064 && encrypted && authenticated)capture_glue_features(packet.body);
|
|
if(packet.opcode==0x470018) {
|
|
if(!encrypted || !authenticated) throw Error("unauthenticated provider roster");
|
|
if(world_requested) throw Error("roster requested during Turtle world session");
|
|
turtle=std::make_unique<LegacySession>(3724,8090,backend[3],backend[4],backend[5],backend[6],5875);
|
|
const auto& roster=turtle->roster();
|
|
auto translated=forever_roster(roster,realm,!experimental_world);
|
|
// Preserve frontend race/class entitlement metadata, never provider character data.
|
|
if(experimental_world) {
|
|
Reader entitlement(packet.body); entitlement.take(2);
|
|
if(entitlement.le(4) || entitlement.le(4)) throw Error("test frontend account must have zero provider characters");
|
|
entitlement.le(4); auto counts=entitlement.take(16); entitlement.take(4);
|
|
std::copy(counts.begin(),counts.end(),translated.begin()+14);
|
|
append(translated,entitlement.take(entitlement.left()));
|
|
}
|
|
packet.body=std::move(translated); write_all(client,to_client.encode(packet.opcode,packet.body));
|
|
write_all(client,to_client.encode(0x470019,forever_restrictions(roster,realm)));
|
|
std::cerr<<"Translated real Turtle roster: "<<roster.size()<<" characters\n"; continue;
|
|
}
|
|
if(packet.opcode==0x470019 || packet.opcode==0x47001A) { packet.body=Bytes{0,0,0,0}; }
|
|
write_all(client,to_client.encode(packet.opcode,packet.body));
|
|
}
|
|
if(fds[1].revents) {
|
|
auto packet=from_client.decode(read_frame(client,1048576));
|
|
std::cerr<<"Client opcode 0x"<<std::hex<<packet.opcode<<std::dec<<" bytes="<<packet.body.size()<<'\n';
|
|
if(packet.opcode==0x460006 && turtle && packet.body.size()==8 &&
|
|
std::chrono::steady_clock::now()-last_turtle_ping>=std::chrono::seconds(28)) {
|
|
turtle->send(0x1DC,packet.body);last_turtle_ping=std::chrono::steady_clock::now();
|
|
std::cerr<<"Forwarded local session keepalive to Turtle\n";
|
|
}
|
|
if(gameplay_request(packet.opcode,packet.body))continue;
|
|
if(packet.opcode==0x420016 && self_sent)teleport_ack(packet.body);
|
|
if(packet.opcode==0x3E0143 && self_sent) {creature_query(packet.body);continue;}
|
|
if(packet.opcode==0x2D0023 && self_sent) {
|
|
frontend_say(packet.body);continue;
|
|
}
|
|
if(packet.opcode==0x460001) {
|
|
Reader r(packet.body); r.le(8); r.le(4); r.le(4); auto realm_id=r.le(4);
|
|
if(realm_id!=70 || server_challenge.size()!=32) throw Error("only the local 70334 test realm is supported");
|
|
auto local=r.take(32); r.take(24); r.le(1); auto length=r.le(4); auto json=r.take(length); r.end();
|
|
std::stringstream text(std::string(json.begin(),json.end())); boost::property_tree::ptree ticket; boost::property_tree::read_json(text,ticket);
|
|
auto account=ticket.get<std::string>("gameAccount",ticket.get<std::string>("gameaccount",""));
|
|
auto data=provider.key(account); encrypt_key=derive(data,local,server_challenge,session_key); OPENSSL_cleanse(data.data(),data.size());
|
|
}
|
|
if(experimental_world && packet.opcode==0x440124) {
|
|
std::string payload(packet.body.begin(),packet.body.end());
|
|
for(const std::string command:{"Command_RealmListRequest_v1","Command_RealmJoinRequest_v1","Command_LastCharPlayedRequest_v1"})
|
|
if(payload.find(command)!=std::string::npos) std::cerr<<"Local Battle.net command "<<command<<'\n';
|
|
}
|
|
if(experimental_world && packet.opcode==0x440015) {
|
|
std::cerr<<"Character selection payload:";
|
|
for(auto v:packet.body) std::cerr<<' '<<std::hex<<unsigned(v);
|
|
std::cerr<<std::dec<<'\n';
|
|
}
|
|
if(experimental_world && packet.opcode==0x440129 && packet.body.size()==36) {
|
|
Reader r(packet.body); auto token=r.le(4); r.take(32); r.end();
|
|
Bytes response; le(response,token,4); le(response,0x80,1);
|
|
std::string ticket="WorldserverRealmListTicket"; le(response,ticket.size(),4);
|
|
response.insert(response.end(),ticket.begin(),ticket.end());
|
|
write_all(client,to_client.encode(0x4702B3,response));
|
|
std::cerr<<"Experimental local realm-ticket response sent\n"; continue;
|
|
}
|
|
if(packet.opcode==0x440016) {
|
|
if(!authenticated || !turtle) throw Error("character login before Turtle authentication");
|
|
auto guid=selected_turtle_guid(packet.body,realm.realm_id,turtle->roster());
|
|
if(experimental_world) {
|
|
selected_guid=guid;
|
|
if(std::getenv("GATEWAY_INSTANCE_EXPERIMENT")) {
|
|
write_all(client,to_client.encode(0x4E0008,instance.connect_to(provider.allowed,realm.virtual_address)));
|
|
instance.authenticate(session_key,realm.virtual_address);
|
|
}
|
|
turtle->login(guid); world_requested=true;
|
|
std::cerr<<"Selected Turtle character login forwarded: guid="<<guid<<'\n';
|
|
} else {
|
|
Bytes failure{1}; write_all(client,to_client.encode(0x4701B1,failure));
|
|
std::cerr<<"World translation experimental; set GATEWAY_WORLD_EXPERIMENT to test\n";
|
|
}
|
|
continue;
|
|
}
|
|
write_all(upstream.value,to_provider.encode(packet.opcode,packet.body));
|
|
if(packet.opcode==0x460005) {
|
|
if(encrypted || encrypt_key.size()!=32) throw Error("invalid Forever encryption transition");
|
|
from_client.enter_encrypted_mode(encrypt_key); to_provider.enter_encrypted_mode(encrypt_key);
|
|
from_provider.enter_encrypted_mode(encrypt_key); to_client.enter_encrypted_mode(encrypt_key);
|
|
OPENSSL_cleanse(encrypt_key.data(),encrypt_key.size()); encrypted=true;
|
|
std::cerr<<"Forever encrypted relay active\n";
|
|
}
|
|
}
|
|
if(fds[2].revents) {
|
|
auto packet=turtle->receive();
|
|
if((self_sent && (packet.opcode==0x19F || packet.opcode==0x17D || packet.opcode==0x17E || (packet.opcode>=0x143 && packet.opcode<=0x14A))) || (selected_guid && (packet.opcode==0x122 || packet.opcode==0x123 || packet.opcode==0x124))) {
|
|
boost::property_tree::ptree event;event.put("event","gameplay_packet");event.put("opcode",packet.opcode);
|
|
constexpr char digits[]="0123456789abcdef";std::string hex;for(auto byte:packet.body){hex+=digits[byte>>4];hex+=digits[byte&15];}event.put("body",hex);audit(event);
|
|
}
|
|
if(packet.opcode==0x2FB || packet.opcode==0xDD) {
|
|
boost::property_tree::ptree event;event.put("event","movement");event.put("opcode",packet.opcode);
|
|
constexpr char digits[]="0123456789abcdef";std::string hex;for(auto byte:packet.body){hex+=digits[byte>>4];hex+=digits[byte&15];}event.put("body",hex);audit(event);
|
|
}
|
|
std::cerr<<"Turtle opcode 0x"<<std::hex<<packet.opcode<<std::dec<<" bytes="<<packet.body.size()<<'\n';
|
|
if((packet.opcode==0x2FB || packet.opcode==0xDD) && self_sent &&
|
|
(std::getenv("GATEWAY_MOVEMENT_AUDIT") || std::getenv("GATEWAY_SPLINE_EXPERIMENT"))) {
|
|
auto records=packet.opcode==0x2FB?turtle_compressed_moves(packet.body):std::vector<LegacyMovementRecord>{{0xDD,packet.body}};
|
|
for(const auto& record:records) {
|
|
if(std::getenv("GATEWAY_MOVEMENT_AUDIT") && audited_movement_opcodes.insert(record.opcode).second)
|
|
std::cerr<<"Audited actual Turtle movement opcode 0x"<<std::hex<<record.opcode<<std::dec<<" bytes="<<record.body.size()<<'\n';
|
|
if(record.opcode==0xDD && std::getenv("GATEWAY_SPLINE_EXPERIMENT")) {
|
|
try {
|
|
auto spline=turtle_monster_spline(record.body);auto known=known_world_objects.find(spline.guid);
|
|
if(known==known_world_objects.end())continue; // Never move a not-yet-created or removed actor.
|
|
auto translated=forever_monster_spline(spline,known->second);world_send(0x600002,translated);
|
|
boost::property_tree::ptree event;event.put("event","monster_sent");event.put("guid",spline.guid);event.put("id",spline.id);event.put("duration",spline.duration);event.put("points",spline.points.size());
|
|
const auto& destination=spline.points.empty()?spline.start:spline.points.back();
|
|
for(unsigned i=0;i<3;++i){event.put("start."+std::to_string(i),spline.start[i]);event.put("destination."+std::to_string(i),destination[i]);}audit(event);
|
|
if(audited_spline_guids.insert(spline.guid).second)std::cerr<<"Translated actual Turtle monster spline guid="<<spline.guid<<" duration="<<spline.duration<<" points="<<spline.points.size()<<'\n';
|
|
} catch(const Error& e) {
|
|
if(unsupported_splines.insert(e.what()).second)std::cerr<<"NPC spline translation unsupported: "<<e.what()<<'\n';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if(packet.opcode==0x61 && self_sent) {
|
|
auto reply=turtle_creature_template(packet.body);
|
|
if(pending_creature_queries.erase(reply.entry)) {
|
|
creature_templates[reply.entry]=reply;
|
|
world_send(0x4B0006,forever_creature_template(reply,known_creature_classes.at(reply.entry)));
|
|
boost::property_tree::ptree event;event.put("event","template");event.put("entry",reply.entry);event.put("type",reply.type);event.put("name",reply.names[0]);event.put("found",reply.found);audit(event);
|
|
std::cerr<<"Translated Turtle creature template entry="<<reply.entry<<" found="<<reply.found<<'\n';
|
|
if(general_population)flush_npcs();
|
|
}
|
|
}
|
|
if(packet.opcode==0x122 && selected_guid && !faction_mappings.empty()) {
|
|
auto states=turtle_initial_reputation(packet.body);for(const auto& s:states)reputation_standings[s.index]=s.standing;
|
|
world_send(0x4701CF,forever_initial_reputation(states,faction_mappings));
|
|
unsigned unsupported=0;for(const auto& s:states)if((s.flags&1) && !faction_mappings.contains(s.index))++unsupported;
|
|
std::cerr<<"Translated actual Turtle initial reputation rows="<<states.size()<<" mapped="<<faction_mappings.size()<<" visible_unmapped="<<unsupported<<'\n';
|
|
}
|
|
if(packet.opcode==0x124 && selected_guid && !faction_mappings.empty())world_send(0x4701D7,forever_reputation_standing(packet.body,faction_mappings,reputation_standings));
|
|
if(packet.opcode==0x123 && selected_guid && !faction_mappings.empty()) {
|
|
try{world_send(0x4701D5,forever_reputation_visible(packet.body,faction_mappings));}catch(const Error& e){std::cerr<<"Reputation visibility not translated: "<<e.what()<<'\n';}
|
|
}
|
|
if(self_sent && (packet.opcode==0x143 || packet.opcode==0x144 || packet.opcode==0x14A)) {
|
|
try {if(packet.opcode==0x14A){auto damage=turtle_melee_damage(packet.body);world_send(0x4D002C,forever_melee_damage(damage,known_world_objects));std::cerr<<"Translated actual Turtle melee damage="<<damage.damage<<" victim="<<damage.victim<<'\n';}
|
|
else {world_send(packet.opcode==0x143?0x4D0017:0x4D0018,forever_attack_event(packet.opcode,packet.body,known_world_objects));std::cerr<<"Translated actual Turtle attack event 0x"<<std::hex<<packet.opcode<<std::dec<<'\n';}
|
|
}catch(const Error& e){std::cerr<<"Combat event not translated: "<<e.what()<<'\n';}
|
|
}
|
|
if(self_sent && (packet.opcode==0x145 || packet.opcode==0x146 || packet.opcode==0x148 || packet.opcode==0x149)) {
|
|
world_send(0x4D0026,forever_attack_error(uint16_t(packet.opcode),packet.body));
|
|
std::cerr<<"Translated actual Turtle attack error opcode="<<packet.opcode<<'\n';
|
|
}
|
|
if(packet.opcode==0x2AA && self_sent && std::getenv("GATEWAY_TALENT_EXPERIMENT")) {
|
|
Reader r(packet.body);auto guid=r.le(8);auto cost=uint32_t(r.le(4));r.end();
|
|
if(!guid){talent_reset_offer.reset();talent_system_message("GWTURTLE1 RESET 0 0");}
|
|
else if(known_world_objects.contains(guid) && (guid>>48)==0xF130){
|
|
talent_reset_offer=std::pair{guid,cost};talent_system_message("GWTURTLE1 RESET "+std::to_string(guid)+" "+std::to_string(cost));
|
|
boost::property_tree::ptree event;event.put("event","turtle_reset_offer");event.put("trainer",guid);event.put("cost",cost);audit(event);
|
|
}
|
|
}
|
|
if(packet.opcode==0x17D && self_sent) {
|
|
auto menu=turtle_gossip_menu(packet.body);auto target=known_world_objects.find(menu.guid);
|
|
if(target==known_world_objects.end())throw Error("gossip response target binding lost");
|
|
npc_text_queries.new_menu();
|
|
active_gossip=menu;
|
|
if (auto query=npc_text_queries.greeting_request(*active_gossip)) {
|
|
turtle->send(0x17f,*query);
|
|
} else {
|
|
active_gossip->broadcast_text=0;
|
|
world_send(0x670018,forever_gossip_menu(*active_gossip,target->second));
|
|
}
|
|
std::cerr<<"Translated Turtle gossip menu options="<<menu.options.size()<<" quests="<<menu.quests.size()<<'\n';
|
|
}
|
|
if(packet.opcode==0x180 && self_sent){
|
|
if (auto reply=npc_text_queries.response(packet.body,active_gossip ? &*active_gossip : nullptr)) {
|
|
if (!active_gossip->broadcast_text) {
|
|
npc_text_queries.resolve(*active_gossip,*reply);
|
|
world_send(0x670018,forever_gossip_menu(*active_gossip,known_world_objects.at(active_gossip->guid)));
|
|
} else {
|
|
world_send(npc_text::Response,*reply);
|
|
}
|
|
}
|
|
}
|
|
if(packet.opcode==0x17E && self_sent) {Reader r(packet.body);r.end();active_gossip.reset();world_send(0x670017,Bytes{0});}
|
|
if(packet.opcode==0x19F && self_sent) {
|
|
auto inventory=turtle_vendor_inventory(packet.body);auto target=known_world_objects.find(inventory.guid);
|
|
if(target==known_world_objects.end())throw Error("vendor response target binding lost");
|
|
// Actual70334 GetMerchantNumItems context check at RVA2DBB4D3 expects type5.
|
|
if(merchant_context!=inventory.guid){merchant_context=inventory.guid;world_send(0x47031B,forever_interaction_open(target->second,5));}
|
|
world_send(0x47005C,forever_vendor_inventory(inventory,target->second));
|
|
std::cerr<<"Translated actual Turtle vendor inventory guid="<<inventory.guid<<" items="<<inventory.items.size()<<'\n';
|
|
}
|
|
if(packet.opcode==0xAA && self_sent) {
|
|
Reader removal(packet.body);auto legacy=removal.le(8);removal.end();auto found=known_world_objects.find(legacy);
|
|
boost::property_tree::ptree event;event.put("event","destroy");event.put("guid",legacy);audit(event);
|
|
npc_generations.erase(legacy);
|
|
unit_power_types.erase(legacy);
|
|
if(found!=known_world_objects.end()) {
|
|
std::array<Guid128,1> destroyed{found->second};world_send(0x5E0000,forever_object_removal(uint16_t(world_map),destroyed,{}));
|
|
if(active_gossip && active_gossip->guid==legacy)active_gossip.reset();
|
|
known_world_objects.erase(found);std::cerr<<"Translated Turtle "<<((legacy>>48)==0xF110?"game-object":"NPC")<<" destruction guid="<<legacy<<'\n';
|
|
}
|
|
}
|
|
if(packet.opcode==0xC7 && self_sent) {
|
|
if(pending_teleport)throw Error("overlapping Turtle teleport unsupported");
|
|
pending_teleport=turtle_near_teleport(packet.body,selected_guid);
|
|
write_all(client,to_client.encode(0x600034,forever_near_teleport(*pending_teleport,realm.realm_id)));
|
|
std::cerr<<"Translated authoritative Turtle near teleport sequence="<<pending_teleport->sequence<<" x="<<pending_teleport->position[0]<<" y="<<pending_teleport->position[1]<<" z="<<pending_teleport->position[2]<<'\n';
|
|
}
|
|
if(packet.opcode==0x96) {
|
|
try {write_all(client,to_client.encode(0x4C0001,forever_chat(packet.body,turtle->roster(),realm,provider.allowed)));std::cerr<<"Translated Turtle chat reply\n";}
|
|
catch(const Error& e) {std::cerr<<"Chat reply unsupported: "<<e.what()<<'\n';}
|
|
}
|
|
if(packet.opcode==0x1DD) {
|
|
if(packet.body.size()!=4)throw Error("invalid Turtle keepalive response");
|
|
std::cerr<<"Turtle keepalive acknowledged\n";continue;
|
|
}
|
|
if(packet.opcode==0x209) {
|
|
if(packet.body!=Bytes(128))throw Error("nonempty legacy account cache requires semantic mapping");
|
|
Bytes times=pack_guid(forever_player_guid(selected_guid,realm.realm_id));
|
|
le(times,uint64_t(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()),8);
|
|
append(times,Bytes(20*8));world_send(0x4701B6,times);
|
|
std::string timezone="Etc/UTC";Bytes zones{0x0E,0x1C,0x38};
|
|
for(unsigned i=0;i<3;++i)zones.insert(zones.end(),timezone.begin(),timezone.end());
|
|
world_send(0x470124,zones);
|
|
if(std::getenv("GATEWAY_CREATE_CODEC"))world_send(0x470063,create_self(std::getenv("GATEWAY_CREATE_CODEC"),{},"--features"));
|
|
}
|
|
if(packet.opcode==0x1CD) {
|
|
if(packet.body.size()!=8)throw Error("invalid Turtle played-time response");
|
|
auto response=packet.body;response.push_back(played_trigger?0x80:0);world_send(0x470181,response);
|
|
}
|
|
if(packet.opcode==0x12A) {
|
|
auto spells=forever_initial_spells(packet.body);world_send(0x690019,spells.known);world_send(0x69001A,spells.history);
|
|
world_send(0x69001B,Bytes(4));world_send(0x69001C,Bytes(4));
|
|
Reader initial(spells.known);initial.le(1);auto count=initial.le(4);initial.le(4);known_spells.clear();for(unsigned i=0;i<count;++i)known_spells.insert(uint32_t(initial.le(4)));initial.end();
|
|
boost::property_tree::ptree event;event.put("event","initial_spells");for(auto spell:known_spells){boost::property_tree::ptree id;id.put("",spell);event.add_child("spells."+std::to_string(spell),id);}audit(event);
|
|
}
|
|
if((packet.opcode==0x12B || packet.opcode==0x12C || packet.opcode==0x203) && selected_guid) {
|
|
Reader r(packet.body);uint32_t spell=0,old=0;
|
|
if(packet.opcode==0x12B){spell=uint32_t(r.le(4));r.end();known_spells.insert(spell);world_send(0x690040,forever_learned_spell(spell));}
|
|
else if(packet.opcode==0x203){old=uint32_t(r.le(2));r.end();known_spells.erase(old);world_send(0x690041,forever_removed_spell(old));}
|
|
else{old=uint32_t(r.le(2));spell=uint32_t(r.le(2));r.end();known_spells.erase(old);known_spells.insert(spell);world_send(0x69003F,forever_superceded_spell(old,spell));}
|
|
boost::property_tree::ptree event;event.put("event","spell_change");event.put("opcode",packet.opcode);event.put("spell",spell);event.put("old",old);audit(event);
|
|
if(self_sent && std::getenv("GATEWAY_TALENT_EXPERIMENT")){
|
|
Bytes input;le(input,realm.realm_id,2);le(input,world_map,4);le(input,selected_guid,8);le(input,free_talent_points,4);le(input,known_spells.size(),4);for(auto id:known_spells)le(input,id,4);
|
|
world_send(0x5E0000,create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--trait-values"));
|
|
}
|
|
}
|
|
if(packet.opcode==0x129) world_send(0x470083,forever_action_buttons(packet.body));
|
|
if(packet.opcode==0x155) world_send(0x470011,forever_bind_point(packet.body));
|
|
if(packet.opcode==0x2C2) world_send(0x4701F1,forever_initial_world_states(packet.body));
|
|
if(packet.opcode==0x42) world_send(0x4701B9,forever_login_time(packet.body));
|
|
if(packet.opcode==0xFD) {
|
|
if(packet.body.size()!=32)throw Error("invalid Turtle tutorial state");
|
|
world_send(0x470269,packet.body);
|
|
}
|
|
if(packet.opcode==0x236) {
|
|
active_gossip.reset();auto location=turtle_login_world(packet.body);world_map=location.map;
|
|
world_send(0x470046,Bytes(11)); // default normal-world info, no housing/restrictions
|
|
if(instance.client.value>=0) write_all(instance.client.value,instance.outgoing.encode(0x47002F,forever_login_world(location)));
|
|
else write_all(client,to_client.encode(0x47002F,forever_login_world(location)));
|
|
std::cerr<<"Translated Turtle LOGIN_VERIFY_WORLD map="<<location.map<<" position="
|
|
<<location.position[0]<<','<<location.position[1]<<','<<location.position[2]<<'\n';
|
|
}
|
|
if(packet.opcode==0xA9 || packet.opcode==0x1F6) {
|
|
auto updates=turtle_object_updates(packet.opcode,packet.body);
|
|
for(const auto& update:updates) {
|
|
if(update.guid==selected_guid)if(auto points=update.fields.find(1102);points!=update.fields.end())free_talent_points=points->second;
|
|
if(update.guid==selected_guid)if(auto level=update.fields.find(34);level!=update.fields.end())backend_level=level->second;
|
|
// Pinned Turtle UNIT_FIELD_BYTES_0; keep resource context across delta-only updates.
|
|
if(auto traits=update.fields.find(36);traits!=update.fields.end() && (update.guid==selected_guid || (update.guid>>48)==0xF130)){
|
|
auto type=uint8_t(traits->second>>24);if(type<4)unit_power_types[update.guid]=type;else unit_power_types.erase(update.guid);
|
|
}
|
|
boost::property_tree::ptree event;event.put("event","legacy");event.put("kind",update.kind);event.put("guid",update.guid);event.put("type",update.type);event.put("update_flags",update.update_flags);
|
|
for(auto [index,value]:update.fields)event.put("fields."+std::to_string(index),value);
|
|
if(update.movement)for(unsigned i=0;i<4;++i)event.put("position."+std::to_string(i),update.movement->position[i]);
|
|
for(unsigned i=0;i<6;++i)event.put("speeds."+std::to_string(i),update.speeds[i]);
|
|
boost::property_tree::ptree removed;for(auto guid:update.removed){boost::property_tree::ptree value;value.put("",guid);removed.push_back({"",value});}event.add_child("removed",removed);audit(event);
|
|
}
|
|
std::vector<Guid128> out_of_range;
|
|
std::vector<uint64_t> removed_legacy;
|
|
for(const auto& update:updates)if(update.kind==4)for(auto legacy:update.removed) {
|
|
npc_generations.erase(legacy);
|
|
unit_power_types.erase(legacy);
|
|
auto found=known_world_objects.find(legacy);if(found==known_world_objects.end())continue;
|
|
if(active_gossip && active_gossip->guid==legacy)active_gossip.reset();
|
|
out_of_range.push_back(found->second);removed_legacy.push_back(legacy);known_world_objects.erase(found);
|
|
}
|
|
if(!out_of_range.empty()) {
|
|
world_send(0x5E0000,forever_object_removal(uint16_t(world_map),{},out_of_range));
|
|
std::cerr<<"Translated Turtle object out-of-range removals: "<<out_of_range.size()<<'\n';
|
|
for(auto legacy:removed_legacy)std::cerr<<"Translated Turtle out-of-range guid="<<legacy<<'\n';
|
|
}
|
|
if(!self_sent && std::getenv("GATEWAY_CREATE_CODEC")) {
|
|
for(const auto& update:updates) if(update.guid==selected_guid && update.type==4 && (update.update_flags&1)) {
|
|
auto it=std::find_if(turtle->roster().begin(),turtle->roster().end(),[&](auto& c){return c.guid==selected_guid;});
|
|
if(it==turtle->roster().end()) throw Error("self create lost roster binding");
|
|
Bytes input;le(input,selected_guid,8);le(input,realm.realm_id,2);le(input,realm.virtual_address,4);
|
|
le(input,world_map,4);le(input,it->zone,4);le(input,provider.allowed,4);le(input,provider.bnet_identity(),4);cstring(input,it->name);append(input,Bytes{it->race,it->cls,it->gender});
|
|
bool traits=std::getenv("GATEWAY_TALENT_EXPERIMENT")!=nullptr;
|
|
if(traits){le(input,known_spells.size(),4);for(auto spell:known_spells)le(input,spell,4);}
|
|
le(input,packet.opcode,4);append(input,packet.body);
|
|
auto payload=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,traits?"--self-talents":nullptr);
|
|
if(instance.client.value>=0) write_all(instance.client.value,instance.outgoing.encode(0x5E0000,payload));
|
|
else write_all(client,to_client.encode(0x5E0000,payload));
|
|
self_sent=true;known_world_objects[selected_guid]=forever_player_guid(selected_guid,realm.realm_id);audit_sent(selected_guid,forever_player_guid(selected_guid,realm.realm_id),"self");
|
|
auto mover=pack_guid(forever_player_guid(selected_guid,realm.realm_id));
|
|
if(instance.client.value>=0) write_all(instance.client.value,instance.outgoing.encode(0x600003,mover));
|
|
else write_all(client,to_client.encode(0x600003,mover));
|
|
std::cerr<<"Experimental modern self create sent: guid="<<selected_guid<<" bytes="<<payload.size()<<'\n';
|
|
}
|
|
}
|
|
if(self_sent && std::getenv("GATEWAY_CREATE_CODEC")) {
|
|
Bytes wire;unsigned count=0;for(const auto& u:updates)if(u.kind==0 && known_world_objects.contains(u.guid) && (u.guid==selected_guid || (u.guid>>48)==0xF130) && !u.fields.empty()) {
|
|
le(wire,0,1);Bytes raw;le(raw,u.guid,8);append(wire,pack_guid(raw));
|
|
unsigned n=u.fields.rbegin()->first/32+1;if(n>255)throw Error("unit value mask bound");le(wire,n,1);std::vector<uint32_t> mask(n);
|
|
for(const auto& [index,value]:u.fields)mask[index/32]|=1u<<(index%32);
|
|
for(auto m:mask){le(wire,m,4);}
|
|
for(const auto& [index,value]:u.fields){le(wire,value,4);}
|
|
++count;
|
|
}
|
|
if(count){Bytes input;le(input,realm.realm_id,2);le(input,world_map,4);le(input,selected_guid,8);
|
|
auto character=std::find_if(turtle->roster().begin(),turtle->roster().end(),[&](const auto& c){return c.guid==selected_guid;});if(character==turtle->roster().end())throw Error("unit power update lost character binding");
|
|
le(input,character->cls,1);if(unit_power_types.size()>4096)throw Error("unit power context bound");le(input,unit_power_types.size(),2);for(auto [id,type]:unit_power_types){le(input,id,8);le(input,type,1);}
|
|
le(input,0xA9,4);le(input,count,4);le(input,0,1);append(input,wire);
|
|
auto payload=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--unit-values-profile");Reader header(payload);header.le(2);auto translated=header.le(4);
|
|
if(translated){world_send(0x5E0000,payload);std::cerr<<"Translated actual Turtle unit value updates="<<translated<<'\n';}
|
|
}
|
|
// Native Unit::SetPower emits this notification as well as the UF delta.
|
|
// Update the actual displayed resource, keeping server-owned cached type context.
|
|
for(const auto& u:updates)if(u.kind==0 && known_world_objects.contains(u.guid)){
|
|
auto type=unit_power_types.find(u.guid);if(type==unit_power_types.end())continue;
|
|
auto field=u.fields.find(uint16_t(23+type->second));if(field==u.fields.end())continue;
|
|
world_send(0x47017E,forever_power_update(known_world_objects.at(u.guid),type->second,field->second));
|
|
std::cerr<<"Translated Turtle displayed power guid="<<u.guid<<" type="<<unsigned(type->second)<<" value="<<field->second<<'\n';
|
|
}
|
|
}
|
|
if(self_sent && std::any_of(updates.begin(),updates.end(),[&](const auto& u){return u.guid==selected_guid && (u.fields.contains(1102) || u.fields.contains(34));}))talent_state();
|
|
for(const auto& update:updates) if(self_sent && update.kind==1 && update.guid==selected_guid && update.movement) {
|
|
try { world_send(0x60000E,forever_ground_movement(*update.movement,realm.realm_id)); }
|
|
catch(const Error& e) {std::cerr<<"Server movement translation unsupported: "<<e.what()<<'\n';}
|
|
}
|
|
if(self_sent && std::getenv("GATEWAY_GO_EXPERIMENT") && std::getenv("GATEWAY_CREATE_CODEC") &&
|
|
std::any_of(updates.begin(),updates.end(),[](const auto& update){return update.type==5 && (update.kind==2 || update.kind==3);})) {
|
|
Bytes input;le(input,selected_guid,8);le(input,realm.realm_id,2);le(input,realm.virtual_address,4);le(input,world_map,4);
|
|
le(input,0,4);le(input,provider.allowed,4);le(input,provider.bnet_identity(),4);cstring(input,"Game-object profile");append(input,Bytes{1,1,0});le(input,packet.opcode,4);append(input,packet.body);
|
|
auto payload=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--gameobjects");
|
|
Reader summary(payload);summary.le(2);auto count=summary.le(4);
|
|
if(count) {
|
|
world_send(0x5E0000,payload);
|
|
for(const auto& update:updates)if(update.type==5 && (update.kind==2 || update.kind==3) && update.movement) {
|
|
auto type=update.fields.find(21),entry=update.fields.find(3); // Pinned Turtle GAMEOBJECT_TYPE_ID / OBJECT_FIELD_ENTRY.
|
|
if(type!=update.fields.end() && entry!=update.fields.end() && turtle_static_game_object_type(type->second)) {
|
|
auto id=forever_game_object_guid(update.guid,entry->second,realm.realm_id,world_map);known_world_objects[update.guid]=id;audit_sent(update.guid,id,"gameobject");
|
|
}
|
|
}
|
|
std::cerr<<"Experimental Turtle game-object creates sent: "<<count<<'\n';
|
|
}
|
|
}
|
|
if(self_sent && std::getenv("GATEWAY_NPC_EXPERIMENT") && std::getenv("GATEWAY_CREATE_CODEC")) {
|
|
Bytes input;le(input,selected_guid,8);le(input,realm.realm_id,2);le(input,realm.virtual_address,4);le(input,world_map,4);
|
|
le(input,0,4);le(input,provider.allowed,4);le(input,provider.bnet_identity(),4);cstring(input,"NPC profile");append(input,Bytes{1,1,0});
|
|
if(general_population) {
|
|
PendingNpcs batch;batch.header=input;le(batch.wire,packet.opcode,4);append(batch.wire,packet.body);
|
|
for(const auto& update:updates)if(update.type==3 && (update.kind==2 || update.kind==3) && update.movement && (update.guid>>48)==0xF130 && update.fields.contains(3) && update.fields.contains(36)) {
|
|
auto entry=update.fields.at(3);known_creature_classes[entry]=uint8_t(update.fields.at(36)>>8);
|
|
auto generation=++npc_generation;npc_generations[update.guid]=generation;batch.actors.push_back({update,generation});
|
|
if(!creature_templates.contains(entry) && pending_creature_queries.insert(entry).second)turtle->send(0x60,turtle_creature_query(entry));
|
|
}
|
|
if(!batch.actors.empty()) {
|
|
if(pending_npcs.size()>=4096)throw Error("pending NPC batch bound");
|
|
size_t bytes=batch.header.size()+batch.wire.size();
|
|
for(const auto& waiting:pending_npcs)bytes+=waiting.header.size()+waiting.wire.size();
|
|
if(bytes>16777216)throw Error("pending NPC bytes bound");
|
|
pending_npcs.push_back(std::move(batch));flush_npcs();
|
|
}
|
|
} else {
|
|
le(input,packet.opcode,4);append(input,packet.body);
|
|
auto payload=create_self(std::getenv("GATEWAY_CREATE_CODEC"),input,"--npcs");
|
|
Reader summary(payload);summary.le(2);auto count=summary.le(4);
|
|
if(count) {
|
|
world_send(0x5E0000,payload);
|
|
for(const auto& update:updates)if(update.type==3 && (update.kind==2 || update.kind==3) && update.movement) {
|
|
auto entry=update.fields.find(3),traits=update.fields.find(36); // Pinned Turtle OBJECT_FIELD_ENTRY / UNIT_FIELD_BYTES_0.
|
|
if(entry!=update.fields.end() && traits!=update.fields.end() && (entry->second==6 || entry->second==38 || entry->second==197)) {
|
|
known_creature_classes[entry->second]=uint8_t(traits->second>>8);
|
|
auto id=forever_creature_guid(update.guid,entry->second,realm.realm_id,world_map);known_world_objects[update.guid]=id;audit_sent(update.guid,id,"creature");
|
|
}
|
|
}
|
|
std::cerr<<"Experimental Turtle NPC creates sent: "<<count<<'\n';
|
|
}
|
|
}
|
|
}
|
|
for(const auto& update:updates) if(update.kind==2 || update.kind==3)
|
|
std::cerr<<"Decoded Turtle create guid="<<update.guid<<" type="<<unsigned(update.type)
|
|
<<" self="<<bool(update.update_flags&1)<<" fields="<<update.fields.size()<<'\n';
|
|
}
|
|
if(packet.opcode==0x2E6) throw Error("server integrity challenge unsupported");
|
|
}
|
|
if(fds[3].revents) {
|
|
auto packet=instance.incoming.decode(read_frame(instance.client.value,1048576));
|
|
std::cerr<<"Instance client opcode 0x"<<std::hex<<packet.opcode<<std::dec<<" bytes="<<packet.body.size()<<'\n';
|
|
if(gameplay_request(packet.opcode,packet.body))continue;
|
|
if(packet.opcode==0x420016 && self_sent)teleport_ack(packet.body);
|
|
if(packet.opcode==0x3E0143 && self_sent) {creature_query(packet.body);continue;}
|
|
if(packet.opcode==0x2D0023 && self_sent) {
|
|
frontend_say(packet.body);
|
|
}
|
|
if(packet.opcode==0x3E014E && world_requested && packet.body.size()==1) {
|
|
played_trigger=bool(packet.body[0]&0x80);turtle->send(0x1CC,{});
|
|
}
|
|
if(packet.opcode==0x42005B && self_sent) {
|
|
Reader mover_reader(packet.body);auto packed=unpack_guid(mover_reader,16);mover_reader.end();
|
|
auto expected=forever_player_guid(selected_guid,realm.realm_id);
|
|
if(!std::equal(packed.begin(),packed.end(),expected.begin()))throw Error("unbound active mover");
|
|
Bytes mover;le(mover,selected_guid,8);turtle->send(0x26A,mover);
|
|
}
|
|
if(self_sent) {
|
|
uint32_t legacy=0;
|
|
if(packet.opcode>=0x420000 && packet.opcode<=0x420005)legacy=0xB5+(packet.opcode-0x420000);
|
|
if(packet.opcode>=0x420008 && packet.opcode<=0x42000A)legacy=0xBC+(packet.opcode-0x420008);
|
|
if(packet.opcode==0x420006)legacy=0xBB;
|
|
if(packet.opcode==0x420017)legacy=0xC9;
|
|
if(packet.opcode==0x42000E)legacy=0xC2;
|
|
if(packet.opcode==0x42000F)legacy=0xC3;
|
|
if(packet.opcode==0x420027)legacy=0xDA;
|
|
if(packet.opcode==0x42002E)legacy=0xEE;
|
|
if(legacy) {
|
|
try {
|
|
auto basic=forever_basic_movement(packet.body,realm.realm_id,turtle->roster());
|
|
auto& movement=basic.state;
|
|
if(movement.guid!=selected_guid)throw Error("movement for unselected character");
|
|
turtle->send(legacy,turtle_basic_movement(basic));
|
|
std::cerr<<"Forwarded basic Forever movement to authoritative Turtle x="<<movement.position[0]<<" y="<<movement.position[1]<<" z="<<movement.position[2]<<" falling="<<basic.falling<<" fall_ms="<<basic.fall_time<<'\n';
|
|
} catch(const Error& error) {
|
|
std::cerr<<"Rejected movement without closing session: "<<error.what();
|
|
Reader diagnostic(packet.body);unpack_guid(diagnostic,16);
|
|
std::cerr<<" flags=0x"<<std::hex<<diagnostic.le(8)<<std::dec<<'\n';
|
|
}
|
|
}
|
|
}
|
|
if(packet.opcode==0x460006 && packet.body.size()==8) {
|
|
Bytes pong(packet.body.begin(),packet.body.begin()+4);write_all(instance.client.value,instance.outgoing.encode(0x4E0009,pong));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
int main(int argc,char** argv) {
|
|
if(argc!=8) { std::cerr<<"Usage: gateway-relay PROVIDER_CONFIG ALLOWED_ACCOUNT TURTLE_USER PASSWORD_FILE VERSION_FILE ADDON_FILE LISTEN_PORT\n"; return 2; }
|
|
std::signal(SIGPIPE,SIG_IGN);
|
|
try {
|
|
auto port=std::stoul(argv[7]); if(!port || port>65535)throw Error("invalid relay port");
|
|
Provider provider(argv[1],std::stoul(argv[2]));
|
|
auto roster=fetch_roster(3724,8090,argv[3],argv[4],argv[5],argv[6],5875);
|
|
// Validate mappings before exposing the frontend.
|
|
forever_roster(roster,{});
|
|
Fd listener; listener.value=socket(AF_INET,SOCK_STREAM,0); int reuse=1; setsockopt(listener.value,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
|
|
sockaddr_in address{}; address.sin_family=AF_INET; address.sin_addr.s_addr=htonl(INADDR_LOOPBACK); address.sin_port=htons(port);
|
|
if(listener.value<0 || bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) || listen(listener.value,4))throw Error("loopback relay bind failed");
|
|
std::cerr<<"Gateway listening on 127.0.0.1:"<<port<<" with real Turtle characters="<<roster.size()<<'\n';
|
|
while(true) { Fd client; client.value=accept(listener.value,nullptr,nullptr); if(client.value<0)throw Error("accept failed");
|
|
try { relay(client.value,provider,argv); } catch(const std::exception& e) { std::cerr<<"Session ended: "<<e.what()<<'\n'; }
|
|
}
|
|
} catch(const std::exception& e) { std::cerr<<"Relay failed: "<<e.what()<<'\n'; return 1; }
|
|
}
|