VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
ClientConVars.cpp
Go to the documentation of this file.
2
11#include <cstdint>
12#include <engine2/igameeventsystem.h>
13#include <engine2/serversideclient.h>
14#include <netmessages.pb.h>
15#include <networksystem/inetchannel.h>
16#include <networksystem/inetworkmessages.h>
17#include <recipientfilter.h>
18#include <utility>
19
20namespace VoltMod
21{
22
23static_assert(std::to_underlying(ClientConVarStatus::Answered) == eQueryCvarValueStatus_ValueIntact);
24static_assert(std::to_underlying(ClientConVarStatus::NotFound) == eQueryCvarValueStatus_CvarNotFound);
25static_assert(std::to_underlying(ClientConVarStatus::NotAConVar) == eQueryCvarValueStatus_NotACvar);
26static_assert(std::to_underlying(ClientConVarStatus::Protected) == eQueryCvarValueStatus_CvarProtected);
27
28ClientConVars::ClientConVars(Interfaces& interfaces, const Bindings& bindings, SlotEvents& slots)
29 : _interfaces(interfaces), _bindings(bindings), _pending(std::make_unique<PendingConVarQueries>())
30{
31 // A slot transition invalidates requests for its previous occupant.
32 _slotListener = slots.Changed += [this](int slot) { _pending->Clear(slot); };
33
34 if (Status installed = Install(); !installed)
35 {
36 _failure = installed.error();
37 }
38}
39
41
43{
44 if (_hook)
45 {
46 return {};
47 }
48 return std::unexpected(_failure);
49}
50
51Status ClientConVars::Install()
52{
53 if (!_interfaces.Engine || !_interfaces.NetworkMessages || !_interfaces.GameEventSystem)
54 {
55 return std::unexpected(Error::NotReady("engine interfaces unavailable"));
56 }
57
58 NetMessageInfo_t* getCvarValue = _interfaces.NetworkMessages->FindNetworkMessagePartial("CSVCMsg_GetCvarValue");
59 if (!getCvarValue)
60 {
61 return std::unexpected(Error::Engine("the engine does not provide CSVCMsg_GetCvarValue"));
62 }
63
64 const auto onResponse = [this](CServerSideClientBase& client,
65 const CNetMessagePB<CCLCMsg_RespondCvarValue>& message) {
66 OnRespondCvarValue(client, message);
67 };
68 auto hook = HookTable("Client convar response", &CServerSideClientBase::ProcessRespondCvarValue,
69 _bindings.ClientTable, nullptr, onResponse);
70 if (!hook)
71 {
72 return std::unexpected(hook.error());
73 }
74
75 _hook = std::move(*hook);
76 _getCvarValue = getCvarValue;
77 Log::Info("Client convar queries enabled.");
78 return {};
79}
80
81bool ClientConVars::Query(int slot, std::string_view cvarName, QueryCallback callback)
82{
83 if (!_hook || !IsValidSlot(slot) || cvarName.empty() || !callback)
84 {
85 return false;
86 }
87
88 const double now = Time::MonotonicSeconds();
89 _pending->Prune(slot, now);
90
91 // Share one request among callbacks for the same convar.
92 if (PendingConVarQuery* inFlight = _pending->Find(slot, cvarName))
93 {
94 inFlight->Callback = std::move(callback);
95 return true;
96 }
97
98 if (_pending->Full(slot))
99 {
100 return false;
101 }
102
103 const int cookie = _pending->NextCookie(slot);
104 if (cookie < 0 || !Send(slot, cvarName, cookie))
105 {
106 return false;
107 }
108
109 _pending->Add(slot, cookie, std::string(cvarName), std::move(callback), now);
110 return true;
111}
112
113size_t ClientConVars::PendingCount(int slot) const
114{
115 return _pending->Count(slot);
116}
117
119{
120 _pending->ClearAll();
121}
122
123bool ClientConVars::Send(int slot, std::string_view cvarName, int cookie)
124{
125 // Bots and empty slots have no network channel.
126 if (!_interfaces.Engine->GetPlayerNetInfo(CPlayerSlot(slot)))
127 {
128 return false;
129 }
130
131 CNetMessage* message = _getCvarValue->AllocateMessage();
132 if (!message)
133 {
134 return false;
135 }
136
137 auto* request = message->ToPB<CSVCMsg_GetCvarValue>();
138 if (!request)
139 {
140 delete message;
141 return false;
142 }
143
144 request->set_cookie(cookie);
145 request->set_cvar_name(std::string(cvarName));
146
147 CReliableSingleUserRecipientFilter filter(slot);
148 _interfaces.GameEventSystem->PostEventAbstract(-1, false, &filter, _getCvarValue, request, 0);
149 delete message;
150 return true;
151}
152
153void ClientConVars::OnRespondCvarValue(const CServerSideClientBase& client, const CCLCMsg_RespondCvarValue& msg)
154{
155 const int slot = client.GetPlayerSlot().Get();
156
157 if (!IsValidSlot(slot) || !msg.has_cookie() || !msg.has_status_code() || !msg.has_name())
158 {
159 return;
160 }
161
162 // Validate every client-controlled field before dispatch.
163 const int status = msg.status_code();
164 if (!EQueryCvarValueStatus_IsValid(status))
165 {
166 return;
167 }
168
169 std::string_view value;
170 if (status == std::to_underlying(ClientConVarStatus::Answered))
171 {
172 if (!msg.has_value() || msg.value().find('\0') != std::string::npos)
173 {
174 return;
175 }
176 value = msg.value();
177 }
178
179 // Remove before callbacks may query the same convar again.
180 auto query = _pending->Take(slot, msg.cookie(), msg.name());
181 if (query && query->Callback)
182 {
183 query->Callback(slot, static_cast<ClientConVarStatus>(status), msg.name(), value);
184 }
185}
186
187} // namespace VoltMod
std::function< void(int slot, ClientConVarStatus status, std::string_view name, std::string_view value)> QueryCallback
bool Query(int slot, std::string_view cvarName, QueryCallback callback)
ClientConVars(Interfaces &interfaces, const Bindings &bindings, SlotEvents &slots)
size_t PendingCount(int slot) const
Bookkeeping for ClientConVars: per-slot, cookie-keyed queries awaiting an answer.
"The occupant of this slot changed" - raised by PlayerManager, consumed below it.
Event< int > Changed
static double MonotonicSeconds()
Definition Durations.hpp:29
void Info(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:79
Result< Subscription > HookTable(std::string_view name, Ret(Object::*method)(Args...), const ClassTable &table, Before &&before, After &&after=nullptr)
Hook an SDK-declared virtual on every object sharing a gamedata-found class table.
Definition Hook.hpp:200
std::expected< void, Error > Status
Definition Result.hpp:67
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13
ClientConVarStatus
How the client answered a convar query (CCLCMsg_RespondCvarValue::status_code).
@ NotFound
The client has no convar by that name.
@ Protected
The convar is marked protected; the client withholds its value.
@ Answered
The client reported the convar's current value.
@ NotAConVar
The name exists on the client but is a command, not a convar.
static Error Engine(std::string detail)
Definition Result.hpp:58
static Error NotReady(std::string detail)
Definition Result.hpp:50
Centralized holder for all SDK interface pointers.
IVEngineServer2 * Engine
IGameEventSystem * GameEventSystem
INetworkMessages * NetworkMessages
One outstanding client convar query, identified by the cookie sent to the client.