VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
ConVars.cpp
Go to the documentation of this file.
1
8#include <engine2/igameeventsystem.h>
9#include <format>
10#include <icvar.h>
11#include <networkbasetypes.pb.h>
12#include <networksystem/inetworkmessages.h>
13#include <recipientfilter.h>
14#include <string>
15#include <string_view>
16#include <tier0/convar.h>
17
18// ICvar provides no callback context. Each plugin DLL owns one ConVars instance and callback.
20
21static std::string_view Text(const char* value)
22{
23 return value ? std::string_view(value) : std::string_view{};
24}
25
26static void GlobalConVarChangeCallback(ConVarRefAbstract* ref, CSplitScreenSlot /*slot*/, const char* newValue,
27 const char* oldValue, ConVarUserInfoSet_t* /*userInfo*/)
28{
29 if (!ref || !g_changeCallback)
30 {
31 return;
32 }
33
34 g_changeCallback->Changed.Raise(
35 VoltMod::ConVarChange{.Name = Text(ref->GetName()), .OldValue = Text(oldValue), .NewValue = Text(newValue)});
36}
37
38namespace VoltMod
39{
40
42 : Changed({.OnFirst = [this] { return RouteChanges(); }, .OnLast = [this] { StopRoutingChanges(); }}),
43 _interfaces(interfaces)
44{}
45
47{
48 // Guard against subscriptions that outlive the service.
49 StopRoutingChanges();
50}
51
53{
54 if (!_interfaces.CVar)
55 {
56 return std::unexpected(Error::NotReady("ICvar not available"));
57 }
58 return {};
59}
60
61void ConVars::ExecuteServerCommand(std::string_view command)
62{
63 auto* engine = _interfaces.Engine;
64 if (!engine)
65 {
66 return;
67 }
68
69 // A newline cannot be quoted away - it ends the line and whatever follows runs as its
70 // own command - so an injected one is refused rather than escaped.
71 if (command.find_first_of("\r\n") != std::string_view::npos)
72 {
73 Log::Warn("ConVars: refused a server command with an embedded newline.");
74 return;
75 }
76
77 // ServerCommand adds no separator between buffered commands.
78 std::string line(command);
79 if (line.empty() || line.back() != '\n')
80 {
81 line.push_back('\n');
82 }
83
84 engine->ServerCommand(line.c_str());
85}
86
87Status ConVars::ExecuteFile(std::string_view path)
88{
89 auto text = ReadAllText(path);
90 if (!text)
91 {
92 return std::unexpected(text.error());
93 }
94
95 std::string_view rest = *text;
96 while (!rest.empty())
97 {
98 const auto end = rest.find('\n');
99 const std::string_view raw = rest.substr(0, end);
100 rest = end == std::string_view::npos ? std::string_view{} : rest.substr(end + 1);
101
102 const std::string line = Strings::Trim(raw.substr(0, raw.find("//")));
103 if (!line.empty())
104 {
106 }
107 }
108 return {};
109}
110
111void ConVars::SetByConsole(std::string_view name, std::string_view value)
112{
113 ExecuteServerCommand(std::format("{} {}", name, Strings::QuoteConsoleArg(value)));
114}
115
116NetMessageInfo_t* ConVars::SetConVarMessage()
117{
118 if (_setConVarMsg)
119 {
120 return _setConVarMsg;
121 }
122
123 auto* messages = _interfaces.NetworkMessages;
124 if (!messages)
125 {
126 return nullptr;
127 }
128
129 _setConVarMsg = messages->FindNetworkMessagePartial("SetConVar");
130 if (!_setConVarMsg)
131 {
132 Log::Warn("ConVars: CNETMsg_SetConVar not found; per-client convar overrides are unavailable.");
133 }
134
135 return _setConVarMsg;
136}
137
138bool ConVars::SendToClient(int slot, std::string_view name, std::string_view value)
139{
140 if (!_interfaces.GameEventSystem || !IsValidSlot(slot) || name.empty())
141 {
142 return false;
143 }
144
145 auto* msgType = SetConVarMessage();
146 if (!msgType)
147 {
148 return false;
149 }
150
151 CNetMessage* msg = msgType->AllocateMessage();
152 if (!msg)
153 {
154 return false;
155 }
156
157 auto* setConVar = msg->ToPB<CNETMsg_SetConVar>();
158 if (setConVar)
159 {
160 auto* cvar = setConVar->mutable_convars()->add_cvars();
161 cvar->set_name(std::string(name));
162 cvar->set_value(std::string(value));
163
164 CReliableSingleUserRecipientFilter filter(slot);
165 _interfaces.GameEventSystem->PostEventAbstract(-1, false, &filter, msgType, msg, 0);
166 }
167
168 delete msg;
169 return setConVar != nullptr;
170}
171
172bool ConVars::RouteChanges()
173{
174 if (_routingChanges)
175 {
176 return true;
177 }
178
179 auto* cvar = _interfaces.CVar;
180 if (!cvar)
181 {
182 Log::Warn("ConVars: ICvar is not resolved; convar change handlers will not fire.");
183 return false;
184 }
185
186 cvar->InstallGlobalChangeCallback(&GlobalConVarChangeCallback);
187 g_changeCallback = this;
188 _routingChanges = true;
189 return true;
190}
191
192void ConVars::StopRoutingChanges()
193{
194 if (!_routingChanges)
195 {
196 return;
197 }
198
199 if (auto* cvar = _interfaces.CVar)
200 {
201 cvar->RemoveGlobalChangeCallback(&GlobalConVarChangeCallback);
202 }
203
204 g_changeCallback = nullptr;
205 _routingChanges = false;
206}
207
208} // namespace VoltMod
static std::string_view Text(const char *value)
Definition ConVars.cpp:21
static void GlobalConVarChangeCallback(ConVarRefAbstract *ref, CSplitScreenSlot, const char *newValue, const char *oldValue, ConVarUserInfoSet_t *)
Definition ConVars.cpp:26
static VoltMod::ConVars * g_changeCallback
Definition ConVars.cpp:19
void SetByConsole(std::string_view name, std::string_view value)
Assign a convar over the console, quoting the value.
Definition ConVars.cpp:111
Status ExecuteFile(std::string_view path)
Definition ConVars.cpp:87
ConVars(Interfaces &interfaces)
Definition ConVars.cpp:41
Event< const ConVarChange & > Changed
Definition ConVar.hpp:145
void ExecuteServerCommand(std::string_view command)
Definition ConVars.cpp:61
Status Available() const
Definition ConVars.cpp:52
static std::string Trim(std::string_view str)
Definition Strings.cpp:107
static std::string QuoteConsoleArg(std::string_view value)
Definition Strings.cpp:216
void Warn(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:88
std::expected< void, Error > Status
Definition Result.hpp:67
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13
Result< std::string > ReadAllText(std::string_view path)
Read path (resolved via ResolvePath) into a string.
Definition File.cpp:12
static Error NotReady(std::string detail)
Definition Result.hpp:50
Centralized holder for all SDK interface pointers.
INetworkMessages * NetworkMessages