Files

222 lines
18 KiB
C++

#pragma once
#include "gateway/chat.hpp"
#include "gateway/legacy_stream.hpp"
#include "gateway/club_identity.hpp"
#include <algorithm>
#include <chrono>
#include <deque>
#include <map>
#include <optional>
// The original 70334 club RPC contract, backed only by received Source guild
// records. No provider character, database access or synthetic membership.
namespace gateway::club_wire {
constexpr uint32_t Request=0x440124, Response=0x4702b0, Notification=0x4702b1;
// Client api/client/v1/club_membership_listener: OriginalHash 0x2b34597b;
// methods 1/2 are OnClubAdded/OnClubRemoved, separate from stream ClubListener.
constexpr uint32_t Membership=0x94b94786, Club=0xe273de0e, Listener=0x80909d73, MembershipListener=0x2b34597b;
inline void vi(Bytes& out,uint64_t n){do{auto b=uint8_t(n&127);n>>=7;out.push_back(b|(n?128:0));}while(n);}
inline Bytes v(unsigned f,uint64_t n){Bytes b;vi(b,uint64_t(f)<<3);vi(b,n);return b;}
inline Bytes l(unsigned f,std::span<const uint8_t> x){Bytes b;vi(b,(uint64_t(f)<<3)|2);vi(b,x.size());append(b,x);return b;}
inline Bytes l(unsigned f,std::string_view x){return l(f,std::span(reinterpret_cast<const uint8_t*>(x.data()),x.size()));}
inline Bytes join(std::initializer_list<Bytes> parts){Bytes b;for(auto& p:parts)append(b,p);return b;}
inline uint64_t read_vi(Reader& r){uint64_t n=0;for(unsigned s=0;s<70;s+=7){auto b=r.le(1);if(s==63 && b>1)throw Error("club varint overflow");n|=(b&127)<<s;if(!(b&128))return n;}throw Error("club varint bound");}
struct Field {unsigned number,wire;uint64_t value=0;Bytes bytes;};
inline std::vector<Field> fields(std::span<const uint8_t> data){
if(data.size()>65535)throw Error("club protobuf bound");
Reader r(data);std::vector<Field> out;
while(r.left()) {if(out.size()>=1024)throw Error("club field bound");auto key=read_vi(r);Field f{unsigned(key>>3),unsigned(key&7),0,{}};if(!f.number)throw Error("club field zero");
if(f.wire==0)f.value=read_vi(r);else if(f.wire==1)f.value=r.le(8);else if(f.wire==5)f.value=r.le(4);else if(f.wire==2){auto n=read_vi(r);if(n>r.left())throw Error("club field length");f.bytes=r.take(n);}else throw Error("club wire type");out.push_back(std::move(f));}return out;
}
inline uint64_t number(const std::vector<Field>& f,unsigned key,uint64_t fallback=0){for(auto i=f.rbegin();i!=f.rend();++i)if(i->number==key){if(i->wire!=0)throw Error("club number type");return i->value;}return fallback;}
inline Bytes data(const std::vector<Field>& f,unsigned key){for(auto i=f.rbegin();i!=f.rend();++i)if(i->number==key){if(i->wire!=2)throw Error("club data type");return i->bytes;}return {};}
struct Call {uint64_t type=0,object=0;uint32_t token=0;Bytes body;uint32_t service()const{return type>>32;}uint32_t method()const{return uint32_t(type)&0x3fffffff;}};
inline Call parse(std::span<const uint8_t> bytes){Reader r(bytes);Call c;c.type=r.le(8);c.object=r.le(8);c.token=r.le(4);auto n=r.le(4);if(n>65535)throw Error("club RPC bound");c.body=r.take(n);r.end();fields(c.body);return c;}
inline LegacyPacket response(const Call& c,uint32_t status,const Bytes& payload={}){Bytes b;le(b,status,4);le(b,c.type,8);le(b,1,8);le(b,c.token,4);le(b,payload.size(),4);append(b,payload);return {Response,std::move(b)};}
inline LegacyPacket notification(uint32_t method,uint32_t token,const Bytes& payload,uint32_t listener=Listener){Bytes b;le(b,(uint64_t(listener)<<32)|(0xc0000000u|method),8);le(b,1,8);le(b,token,4);le(b,payload.size(),4);append(b,payload);return {Notification,std::move(b)};}
// Character-name friends use the Source friends path. Platform-service reads
// expose empty internal state only; no account, tag or invitation is produced.
// Read continuations are explicit zero, matching the original service writers.
inline std::optional<LegacyPacket> empty_social_response(const Call& c){
uint32_t status=0xbc7;Bytes payload;const auto m=c.method();
if(c.service()==0x5869be8c){ // friends.v2
if(m>=1 && m<=7){status=0;if(m>=3 && m<=5)payload=v(2,0);}
}else if(c.service()==0x8e8f5fb0){ // block_list.v1: original generic stub
}else if(c.service()==0x138d200c){ // presence.v2, ephemeral internal state
if(m>=3 && m<=6)status=0;
}else if(c.service()==0xfee1aa14){ // whisper.v2
if(m==1||m==2||m==3||m==5||m==6||m==7){status=0;if(m==3)payload=v(2,0);}
}else return std::nullopt;
return response(c,status,payload);
}
inline Bytes type(){Bytes b{13};le(b,0x576f57,4);append(b,l(2,"guild"));return b;}
inline Bytes member_id(uint64_t low,uint16_t realm,uint32_t account=0){return join({v(2,guild_club_member_id(low,realm)),v(3,account)});}
struct Snapshot {
GuildInfo info{};GuildRoster roster;uint64_t self=0,created_us=0;uint16_t realm=0;
// Unknown peer accounts retain the reference CharacterCache zero fallback.
// The authenticated self can carry the private local Source-name-derived
// key shared with the native startup context; never a persona or tag.
std::map<uint64_t,uint32_t> accounts;
uint32_t account(uint64_t low)const{auto i=accounts.find(low);return i==accounts.end()?0:i->second;}
Bytes id(uint64_t low)const{return member_id(low,realm,account(low));}
const GuildRosterMember* find(uint64_t low)const{auto i=std::find_if(roster.members.begin(),roster.members.end(),[&](auto& m){return m.guid==low;});return i==roster.members.end()?nullptr:&*i;}
const GuildRosterMember& leader()const{auto i=std::find_if(roster.members.begin(),roster.members.end(),[](auto& m){return m.rank==0;});if(i==roster.members.end())throw Error("club lacks Source leader");return *i;}
unsigned role(const GuildRosterMember& m)const{if(m.rank>=roster.source_rank_rights.size())throw Error("club source rank bound");return m.rank==0?1:(roster.source_rank_rights[m.rank]&12)?3:4;}
Bytes member(const GuildRosterMember& m,bool note=true)const{return join({l(1,id(m.guid)),l(3,v_role(m)),v(6,2),v(8,0),note?l(9,m.note):Bytes{},v(50,m.online?1:0)});}
Bytes v_role(const GuildRosterMember& m)const{Bytes b;vi(b,role(m));return b;}
Bytes description()const{return join({v(1,info.id),l(2,type()),l(3,info.name),v(6,3),v(7,0),v(8,roster.members.size()),l(9,l(1,id(leader().guid))),v(10,created_us),l(11,""),l(12,"")});}
Bytes membership_description()const{return join({l(1,id(self)),l(2,description())});}
Bytes membership()const{return l(1,join({l(1,membership_description()),l(4,join({v(1,0),v(2,0)}))}));}
Bytes club()const{const auto low=leader().guid;return join({v(1,info.id),l(2,type()),l(4,info.name),v(8,3),v(9,0),v(10,roster.members.size()),l(14,l(1,join({v(2,low),v(3,account(low))})))});}
Bytes subscribe()const{auto me=find(self);if(!me)throw Error("club self absent");return join({l(1,id(self)),v(3,info.id),l(4,club()),l(11,member(*me,false))});}
Bytes subscriber()const{return join({v(3,info.id),l(4,join({l(1,id(self)),v(2,1)}))});}
Bytes members()const{Bytes b;for(auto& m:roster.members)append(b,l(1,member(m)));return b;}
Bytes stream(unsigned sid)const{bool officer=sid==2;return join({v(1,info.id),v(2,sid),l(3,join({l(1,"global_strings_tag"),l(2,l(4,officer?"COMMUNITIES_GUILD_OFFICER_CHANNEL_NAME":"COMMUNITIES_GUILD_GENERAL_CHANNEL_NAME"))})),l(4,officer?"Officer":"Guild"),l(6,l(1,officer?Bytes{1,2,3}:Bytes{1,2,3,4})),v(7,0)});}
Bytes streams()const{return join({l(1,stream(1)),l(1,stream(2)),l(2,join({v(1,info.id),v(2,1)})),l(2,join({v(1,info.id),v(2,2)}))});}
};
inline uint64_t creation_time(std::span<const uint8_t> bytes,const std::string& name){Reader r(bytes);if(r.cstring(127)!=name)throw Error("club creation guild mismatch");auto day=r.le(4),month=r.le(4),year=r.le(4);r.le(4);r.le(4);r.end();using namespace std::chrono;year_month_day date{std::chrono::year(int(year)),std::chrono::month(unsigned(month)),std::chrono::day(unsigned(day))};if(year<1970||year>9999||!date.ok())throw Error("club creation date bound");return uint64_t(duration_cast<microseconds>(sys_days(date).time_since_epoch()).count());}
}
struct NativeClubService {
std::deque<gateway::club_wire::Call> waiting;
std::deque<gateway::LegacyPacket> output;
std::optional<gateway::club_wire::Snapshot> snapshot;
std::optional<gateway::Bytes> creation;
struct ChatPending {gateway::club_wire::Call call;uint32_t stream;gateway::Bytes text;std::chrono::steady_clock::time_point sent;};
std::deque<ChatPending> chat_pending;
std::deque<gateway::LegacyPacket> chat_source;
uint64_t chat_epoch=0;
// #43: listener150 (stream message added) for a stream the client has not loaded asserts
// AuroraClubListener.cpp(426) ASSERTSAFE(stream); notify only after the client fetched streams (105).
bool queried=false,drain=false,subscribed=false,streams_known=false;
uint32_t notification_token=0;
// Membership subscription belongs to the connection, not its current guild.
bool membership_subscribed=false;
uint32_t announced_guild=0;
gateway::Bytes announced_member;
void reset(){waiting.clear();output.clear();snapshot.reset();creation.reset();queried=false;drain=false;subscribed=false;streams_known=false;chat_pending.clear();chat_source.clear();chat_epoch=0;membership_subscribed=false;announced_guild=0;announced_member.clear();}
// A Source-confirmed guild leave keeps the character's connection alive.
// Answer admitted calls under the ordinary guildless policy on this connection.
void leave_guild() {
using namespace gateway::club_wire;
auto pending_calls = std::move(waiting);
auto pending_messages = std::move(chat_pending);
auto queued_output = std::move(output);
const bool listening = membership_subscribed;
const auto old_guild = announced_guild;
const auto old_member = std::move(announced_member);
reset();
membership_subscribed = listening;
output = std::move(queued_output);
// Guild field changes do not distinguish kick/leave/disband: reason NONE.
if (listening && old_guild)
output.push_back(notification(2,notification_token++,join({
l(1,old_member),l(3,old_member),v(4,old_guild),v(5,0)}),MembershipListener));
for (const auto& call : pending_calls) complete(call, true, 0);
for (const auto& message : pending_messages) complete(message.call, true, 0);
}
bool pending()const{return drain||!output.empty();}
// Source acceptance is the real own SMSG_MESSAGECHAT echo, not successful
// queueing. The original service response owns the sender's cache entry;
// listener150 carries actual received messages from other guild members.
void receive_chat(std::span<const uint8_t> body){
using namespace gateway;using namespace club_wire;
if(!snapshot)return;
Reader r(body);const auto type=r.le(1),language=r.le(4);
if((type!=3&&type!=4)||language==0xffffffffu)return;
const auto sender=r.le(8),length=r.le(4);
if(!length||length>4096)throw Error("club Source chat length");
auto text=r.take(length);const auto tag=r.le(1);r.end();
if(text.back()!=0||std::find(text.begin(),text.end()-1,0)!=text.end()-1||tag>3)throw Error("club Source chat framing");
text.pop_back();const auto& s=*snapshot;if(!s.find(sender))return;
const uint32_t stream=type==3?1:2;
const auto time=uint64_t(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
chat_epoch=std::max(time,chat_epoch+1);
const auto message=join({l(3,join({v(1,chat_epoch),v(2,0)})),l(4,l(1,s.id(sender))),l(6,join({l(5,text),v(8,chat_epoch)}))});
// Octo wraps each staff echo in |c1Xrrggbb...|r. Compare the submitted
// text inside that single envelope, keeping the full echo in the message.
std::span<const uint8_t> submitted=text;
const std::string_view rendered(reinterpret_cast<const char*>(text.data()),text.size());
if(tag==3 && rendered.size()>=12 && rendered.starts_with("|c1") &&
rendered[3]>='0' && rendered[3]<='3' && rendered.ends_with("|r") &&
rendered.substr(4,6).find_first_not_of("0123456789abcdefABCDEF")==std::string_view::npos)
submitted=submitted.subspan(10,submitted.size()-12);
auto pending=std::find_if(chat_pending.begin(),chat_pending.end(),[&](const ChatPending& p){return sender==s.self&&p.stream==stream&&std::equal(p.text.begin(),p.text.end(),submitted.begin(),submitted.end());});
if(pending!=chat_pending.end()){
output.push_back(response(pending->call,0,l(1,message)));chat_pending.erase(pending);
}else if(subscribed&&streams_known){
output.push_back(notification(150,notification_token++,join({l(1,s.id(sender)),v(3,s.info.id),v(4,stream),l(5,message)})));
}
}
void complete(const gateway::club_wire::Call& c,bool in_world,uint32_t guild){
using namespace gateway;using namespace club_wire;auto reply=[&](uint32_t status,const Bytes& body=Bytes{}){output.push_back(response(c,status,body));};
if(!in_world){reply(1);return;}
const auto method=c.method();const auto f=fields(c.body);
if(c.service()==Membership){
if(method==2){membership_subscribed=false;announced_guild=0;announced_member.clear();reply(0);return;}
if(method!=1&&method!=3){reply(13);return;}
if(method==1)membership_subscribed=true;
reply(0,guild?snapshot->membership():Bytes{});
// The response itself establishes this baseline; do not also send OnClubAdded.
if(membership_subscribed){announced_guild=guild;announced_member=guild?snapshot->id(snapshot->self):Bytes{};}
return;
}
if(method==6){const auto t=data(f,2);if(t!=type()){reply(13);return;}reply(0,l(1,type()));return;}
if(!guild){reply(0x2af9);return;}
const auto& s=*snapshot;
if(number(f,2)!=guild){reply(0x2af9);return;}
auto agent=data(f,1);if(!agent.empty() && number(fields(agent),2)!=guild_club_member_id(s.self,s.realm)){reply(0x2afa);return;}
if(method==1){subscribed=true;output.push_back(notification(1,notification_token++,s.subscribe()));output.push_back(notification(33,notification_token++,s.subscriber()));reply(0);}
else if(method==2){subscribed=false;streams_known=false;reply(0);}
else if(method==34)reply(0,s.members());
else if(method==33){const auto identity=fields(data(f,3));auto uid=number(identity,2);const auto* m=s.find(uid&0x0000ffffffffffffULL);if(!m||uid!=guild_club_member_id(m->guid,s.realm))reply(0x2afc);else reply(0,l(1,s.member(*m)));}
else if(method==150){
const auto stream=number(f,3);const auto text=data(fields(data(f,4)),2);
const auto* self=s.find(s.self);
if((stream!=1&&stream!=2)||!self||self->rank>=s.roster.source_rank_rights.size()){reply(0x2b61);return;}
const auto right=stream==1?2u:8u;
if(!(s.roster.source_rank_rights[self->rank]&right)||text.empty()||text.size()>255||std::find(text.begin(),text.end(),0)!=text.end()||chat_pending.size()>=16){reply(0x2b61);return;}
Bytes source;le(source,stream==1?3:4,4);le(source,0,4);append(source,text);le(source,0,1);
chat_pending.push_back({c,uint32_t(stream),text,std::chrono::steady_clock::now()});
chat_source.push_back({0x95,std::move(source)});
// Deliberately no response before the authoritative Source echo.
}
else if(method==105){streams_known=true;reply(0,s.streams());}
else if(method==100||method==101||method==107||method==155){auto stream=number(f,3);reply(streams_known&&(stream==1||stream==2)?0:0x2af9);}
else reply(13); // No invented success for unimplemented mutations.
}
void request(std::span<const uint8_t> bytes,bool in_world,uint32_t guild,std::deque<gateway::LegacyPacket>& source){
using namespace gateway;using namespace club_wire;auto c=parse(bytes);if(c.service()!=Club && c.service()!=Membership)throw Error("unhandled service");
drain=true;
if(!in_world||!guild||snapshot||(c.service()==Club&&c.method()==6)||(c.service()==Membership&&c.method()==2)){complete(c,in_world,guild);return;}
if(waiting.size()>=32){output.push_back(response(c,1));return;}
waiting.push_back(std::move(c));
if(!queried){if(source.size()>4092)throw Error("club source queue bound");Bytes b;le(b,guild,4);source.push_back({0x54,std::move(b)});source.push_back({0x89,{}});source.push_back({0x87,{}});queried=true;}
}
void refresh(uint32_t guild,uint64_t self,uint16_t realm,const std::optional<gateway::GuildInfo>& info,const std::optional<gateway::GuildRoster>& roster,uint32_t own_account=0,bool allow_membership_add=true){
if(!guild||!info||info->id!=guild||!roster||!creation)return;
gateway::club_wire::Snapshot next{*info,*roster,self,0,realm,{}};
if(own_account)next.accounts[self]=own_account;
if(!next.find(self))return;
try{next.leader();next.created_us=gateway::club_wire::creation_time(*creation,info->name);}catch(const gateway::Error&){return;}
snapshot=std::move(next);
while(!waiting.empty()){auto c=std::move(waiting.front());waiting.pop_front();complete(c,true,guild);}
if(allow_membership_add && membership_subscribed && announced_guild!=guild){
using namespace gateway::club_wire;
announced_guild=guild;announced_member=snapshot->id(self);
output.push_back(notification(1,notification_token++,join({
l(1,announced_member),l(3,snapshot->membership_description())}),MembershipListener));
}
}
void take(std::vector<gateway::LegacyPacket>& packets,std::deque<gateway::LegacyPacket>* source=nullptr){
using namespace gateway::club_wire;
const auto now=std::chrono::steady_clock::now();
while(!chat_pending.empty()&&now-chat_pending.front().sent>std::chrono::seconds(15)){
output.push_back(response(chat_pending.front().call,0x2b61));chat_pending.pop_front();
}
if(source){
if(source->size()+chat_source.size()>4096)throw gateway::Error("club chat Source queue bound");
while(!chat_source.empty()){source->push_back(std::move(chat_source.front()));chat_source.pop_front();}
}
drain=false;while(!output.empty()){packets.push_back(std::move(output.front()));output.pop_front();}
}
};