VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
WorkshopDownloads.cpp
Go to the documentation of this file.
2
9#include <engine2/ivengineserver2.h>
10#include <engine2/networkgameserverbase.h>
11#include <engine2/serversideclient.h>
12#include <networkbasetypes.pb.h>
13#include <networksystem/inetworkmessages.h>
14#include <playerslot.h>
15#include <string>
16#include <tier0/utlstring.h>
17#include <utility>
18
19namespace VoltMod
20{
21
22/** How soon a client must reconnect for its addon to count as downloaded. */
23static constexpr double DownloadTimeoutSeconds = 30.0;
24/** Offers of one addon before a declining client is dropped. */
25static constexpr int MaxDownloadAttempts = 3;
26/** A player back within this long is not asked to download again. */
27static constexpr double ForgetAfterSeconds = 12.0 * 60.0 * 60.0;
28
30 : _engine(engine.Engine), _bindings(bindings)
31{}
32
33bool WorkshopDownloads::Add(uint64_t addonId)
34{
35 if (addonId == 0)
36 {
37 return false;
38 }
39 if (Status hooked = Install(); !hooked)
40 {
41 Log::Warn("Addons: {} is not sent to clients: {}", addonId, hooked.error().Detail);
42 return false;
43 }
44 return _queue.Add(addonId);
45}
46
47void WorkshopDownloads::Remove(uint64_t addonId)
48{
49 _queue.Remove(addonId);
50 RemoveHooksIfUnused();
51}
52
54{
55 const bool nothingToCheck = _queue.Empty() || !IsValidSlot(slot) || !_engine;
56 if (nothingToCheck)
57 {
58 return true;
59 }
60 return !_queue.HasMissing(static_cast<int64_t>(_engine->GetClientXUID(CPlayerSlot(slot))));
61}
62
64{
65 if (!_queue.Empty())
66 {
67 _queue.ClientReconnected(steamId, Time::MonotonicSeconds(), DownloadTimeoutSeconds);
68 }
69}
70
72{
73 if (!_queue.Empty())
74 {
75 _queue.ClientLeft(steamId, Time::MonotonicSeconds(), ForgetAfterSeconds);
76 }
77}
78
80{
81 for (const Kick& kick : std::exchange(_kicks, {}))
82 {
83 // The slot may have changed hands since.
84 if (static_cast<int64_t>(_engine->GetClientXUID(CPlayerSlot(kick.Slot))) == kick.SteamId)
85 {
86 _engine->DisconnectClient(CPlayerSlot(kick.Slot), NETWORK_DISCONNECT_TIMEDOUT,
87 "Required workshop addon download was declined");
88 }
89 }
90}
91
92Status WorkshopDownloads::Install()
93{
94 if (_joinMessageHook)
95 {
96 return {};
97 }
98
99 // A listen server host needs no download step.
100 if (!_engine || !_engine->IsDedicatedServer())
101 {
102 return std::unexpected(Error::Unsupported("addon downloads need a dedicated server"));
103 }
104 const auto onJoinMessage = [this](CServerSideClientBase& client, const CNetMessage* message, NetChannelBufType_t) {
105 OnJoinMessage(message, client);
106 };
107 auto join = HookTable("Workshop addon download", &CServerSideClientBase::SendNetMessage, _bindings.ClientTable,
108 onJoinMessage);
109 if (!join)
110 {
111 return std::unexpected(Error::Unsupported(join.error().Detail));
112 }
113
114 const auto beforeReply = [this](CNetworkGameServerBase& server, CServerSideClient* client) {
115 AddToReply(server, *client);
116 };
117 const auto afterReply = [this](CNetworkGameServerBase& server, CServerSideClient*) { RestoreReply(server); };
118 auto reply = HookFunction("Workshop addon mount", _bindings.ReplyConnection, beforeReply, afterReply);
119 if (!reply)
120 {
121 return std::unexpected(Error::Unsupported(reply.error().Detail));
122 }
123
124 _joinMessageHook = std::move(*join);
125 _connectionReplyHook = std::move(*reply);
126 return {};
127}
128
129void WorkshopDownloads::RemoveHooksIfUnused()
130{
131 if (!_queue.Empty())
132 {
133 return;
134 }
135
136 _kicks.clear();
137 _joinMessageHook.Reset();
138 _connectionReplyHook.Reset();
139 _addedToReply.clear();
140 _queue.ClearProgress();
141}
142
143/** The server's addon list, or nullptr when the SDK layout misses the string GetAddonName returns. */
144static CUtlString* AddonList(CNetworkGameServerBase& server)
145{
146 CUtlString* list = &server.m_szAddonName;
147 // An empty list has no buffer to compare, and each side then returns its own "".
148 const char* stored = list->Get();
149 const char* reported = server.GetAddonName();
150 const bool same = stored == reported || (*stored == '\0' && *reported == '\0');
151 if (!same)
152 {
153 Log::Error("Addons: s2sdk's CNetworkGameServerBase::m_szAddonName is stale; not mounting addons.");
154 return nullptr;
155 }
156 return list;
157}
158
159void WorkshopDownloads::AddToReply(CNetworkGameServerBase& server, const CServerSideClientBase& client)
160{
161 const auto steamId = static_cast<int64_t>(client.GetClientSteamID().ConvertToUint64());
162 if (!SteamId::IsValid(steamId))
163 {
164 return;
165 }
166
167 const std::vector<uint64_t> mountList = _queue.ClientMountList(steamId);
168 if (mountList.empty())
169 {
170 return;
171 }
172
173 // The client mounts only what the connection reply names.
174 CUtlString* list = AddonList(server);
175 if (!list)
176 {
177 return;
178 }
179 std::string field = list->Get();
180 _addedToReply = AppendToAddonList(field, mountList);
181 if (_addedToReply.empty())
182 {
183 return;
184 }
185
186 list->Set(field.c_str());
187 Log::Info("Addons: telling {} to mount {}.", steamId, field);
188}
189
190void WorkshopDownloads::RestoreReply(CNetworkGameServerBase& server)
191{
192 if (_addedToReply.empty())
193 {
194 return;
195 }
196
197 // Only our entries; the map's stay.
198 CUtlString* list = AddonList(server);
199 if (!list)
200 {
201 _addedToReply.clear();
202 return;
203 }
204 std::string field = list->Get();
205 RemoveFromAddonList(field, _addedToReply);
206 list->Set(field.c_str());
207 _addedToReply.clear();
208}
209
210void WorkshopDownloads::OnJoinMessage(const CNetMessage* message, const CServerSideClientBase& client)
211{
212 NetMessageInfo_t* info = message ? message->GetNetMessage() : nullptr;
213 if (!info || info->GetMessageId() != net_SignonState)
214 {
215 return;
216 }
217
218 const auto steamId = static_cast<int64_t>(client.GetClientSteamID().ConvertToUint64());
219 if (!SteamId::IsValid(steamId))
220 {
221 return;
222 }
223
224 // Rewritten in place, before the engine serializes it.
225 auto* joinMessage = const_cast<CNetMessage*>(message)->ToPB<CNETMsg_SignonState>();
226 const bool reconnect = joinMessage->signon_state() == SIGNONSTATE_CHANGELEVEL;
227 const AddonDecision decision = _queue.DecideJoinMessage(steamId, reconnect, joinMessage->addons(),
229
230 switch (decision.Action)
231 {
233 return;
235 Log::Info("Addons: a reconnect message named {} addons; sending {} and holding the rest.",
236 decision.Remaining + 1, decision.Id);
237 [[fallthrough]];
239 joinMessage->set_addons(std::to_string(decision.Id));
240 return;
242 Log::Warn("Addons: {} did not take addon {} in {} attempts; dropping the client.", steamId, decision.Id,
244 if (const int slot = client.GetPlayerSlot().Get(); IsValidSlot(slot))
245 {
246 _kicks.push_back({.Slot = slot, .SteamId = steamId});
247 }
248 return;
250 joinMessage->set_addons(std::to_string(decision.Id));
251 joinMessage->set_signon_state(SIGNONSTATE_CHANGELEVEL);
252 Log::Info("Addons: sending addon {} to {} ({} left after it).", decision.Id, steamId, decision.Remaining);
253 return;
254 }
255}
256
257} // namespace VoltMod
static bool IsValid(int64_t steamId64)
Definition SteamId.cpp:76
static double MonotonicSeconds()
Definition Durations.hpp:29
void OnClientDisconnected(int64_t steamId)
WorkshopDownloads(const Bindings &bindings, const EngineInterfaces &engine)
void Remove(uint64_t addonId) override
bool IsReady(int slot) override
bool Add(uint64_t addonId) override
void OnClientConnected(int64_t steamId)
void Error(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:97
void Info(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:79
void Warn(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:88
static constexpr double ForgetAfterSeconds
static CUtlString * AddonList(CNetworkGameServerBase &server)
Result< Subscription > HookFunction(std::string_view name, const Fn< Ret(Object *, Args...)> &function, Before &&before, After &&after=nullptr)
Hook a signature-bound function at its entry.
Definition Hook.hpp:232
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
static constexpr double DownloadTimeoutSeconds
std::expected< void, Error > Status
Definition Result.hpp:67
@ Engine
The engine or SDK refused, returned nothing, or is not where it was expected.
Definition Result.hpp:29
std::vector< uint64_t > AppendToAddonList(std::string &field, const std::vector< uint64_t > &ids)
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13
void RemoveFromAddonList(std::string &field, const std::vector< uint64_t > &ids)
static constexpr int MaxDownloadAttempts
@ TrimToFirst
the message names several addons; keep only AddonDecision::Id
@ Kick
the client refused AddonDecision::Id too often
@ Unchanged
send the message as it is
@ Send
point the client at AddonDecision::Id and wait for its reconnect
@ KeepMounted
a map change names no addon; name AddonDecision::Id so the client keeps it
static Error Unsupported(std::string detail)
Definition Result.hpp:57