-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugins.cpp
More file actions
394 lines (354 loc) · 14.2 KB
/
Copy pathplugins.cpp
File metadata and controls
394 lines (354 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// plugins.cpp
#include "plugins.h"
#include "Interface/IPlugins.h"
#include <chrono>
#pragma comment(lib, "ws2_32.lib")
cl_enginefunc_t gEngfuncs;
cl_exportfuncs_t gExportfuncs;
metahook_api_t* g_pMetaHookAPI = NULL;
mh_interface_t* g_pInterface = NULL;
mh_enginesave_t* g_pMetaSave = NULL;
MessageQueue g_messageQueue;
cvar_t* cf_server_ip = NULL;
cvar_t* cf_server_port = NULL;
cvar_t* cf_allow_ip = NULL;
cvar_t* cf_listen_port = NULL;
cvar_t* cf_enabled = NULL;
cvar_t* cf_debug = NULL;
cvar_t* cf_listen_only = NULL;
cvar_t* cf_command_delay = NULL;
std::chrono::steady_clock::time_point g_lastCommandTime;
void (*g_pfnHUD_Init)(void) = NULL;
void (*g_pfnHUD_Frame)(double time) = NULL;
ThreadPoolHandle_t g_hThreadPool = nullptr;
ThreadWorkItemHandle_t g_hListenerWorkItem = nullptr;
std::atomic<bool> g_shutdownListener(false);
std::unique_ptr<WinsockRAII> g_winsock = nullptr;
SendQueue g_sendQueue;
ThreadWorkItemHandle_t g_hSenderWorkItem = nullptr;
std::atomic<bool> g_shutdownSender(false);
pfnUserMsgHook g_pfnTextMsg = NULL;
hook_t* g_hOutputDebugStringHook = nullptr;
bool g_bChatForwarderInitialized = false;
void (WINAPI* g_pfnOutputDebugStringA)(LPCSTR lpOutputString) = NULL;
void WINAPI NewOutputDebugStringA(LPCSTR lpOutputString) {
static thread_local bool g_inHook = false;
if (g_inHook || !lpOutputString || !lpOutputString[0]) {
if (g_pfnOutputDebugStringA) g_pfnOutputDebugStringA(lpOutputString);
return;
}
struct ReentryGuard {
bool& flag;
explicit ReentryGuard(bool& value) : flag(value) { flag = true; }
~ReentryGuard() { flag = false; }
} guard(g_inHook);
if (IsCvarValid(cf_enabled) && atoi(cf_enabled->string) != 0) {
static std::string g_sysLogBuffer;
static std::mutex g_logMutex;
std::lock_guard<std::mutex> lock(g_logMutex);
g_sysLogBuffer += lpOutputString;
size_t pos;
while ((pos = g_sysLogBuffer.find('\n')) != std::string::npos) {
std::string line = g_sysLogBuffer.substr(0, pos);
// Remove \r if present at the end
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
g_sysLogBuffer.erase(0, pos + 1);
std::string cleanMsg = CleanMessage(line.c_str());
if (!cleanMsg.empty()) {
QueueTask(MSG_TYPE_SYS, cleanMsg);
}
}
// Safety valve: if buffer grows too large without newline, flush it
if (g_sysLogBuffer.size() > 4096) {
std::string cleanMsg = CleanMessage(g_sysLogBuffer.c_str());
if (!cleanMsg.empty()) {
QueueTask(MSG_TYPE_SYS, cleanMsg);
}
g_sysLogBuffer.clear();
}
}
if (g_pfnOutputDebugStringA) g_pfnOutputDebugStringA(lpOutputString);
}
bool UDPListenerWorkCallback(void* ctx)
{
SOCKET listenSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (listenSocket == INVALID_SOCKET) {
return true;
}
struct SocketGuard {
SOCKET sock;
SocketGuard(SOCKET s) : sock(s) {}
~SocketGuard() {
if (sock != INVALID_SOCKET) {
closesocket(sock);
}
}
} socketGuard(listenSocket);
sockaddr_in serverAddr = {};
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
int listenPort = DEFAULT_LISTEN_PORT;
if (IsCvarValid(cf_listen_port)) {
int port = atoi(cf_listen_port->string);
if (port > 0 && port <= 65535) {
listenPort = port;
}
}
serverAddr.sin_port = htons(listenPort);
{
BOOL yes = TRUE;
setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const char*>(&yes), sizeof(yes));
}
if (bind(listenSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
return true;
}
int timeout_ms = SOCKET_TIMEOUT_MS;
setsockopt(listenSocket, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const char*>(&timeout_ms), sizeof(timeout_ms));
char buffer[256];
while (!g_shutdownListener.load(std::memory_order_relaxed))
{
if (IsCvarValid(cf_enabled) && atoi(cf_enabled->string) == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
sockaddr_in fromAddr = {};
int fromLen = sizeof(fromAddr);
int bytesRead = recvfrom(listenSocket, buffer, sizeof(buffer), 0, (sockaddr*)&fromAddr, &fromLen);
if (bytesRead > 0)
{
if (IsCvarValid(cf_allow_ip) && strcmp(cf_allow_ip->string, "*") != 0) {
sockaddr_in allowedAddr = {};
if (inet_pton(AF_INET, cf_allow_ip->string, &allowedAddr.sin_addr) != 1 ||
fromAddr.sin_addr.s_addr != allowedAddr.sin_addr.s_addr) {
continue;
}
}
std::string msg(buffer, bytesRead);
// Trim all trailing control characters and spaces
while (!msg.empty() && (unsigned char)msg.back() <= 32) {
msg.pop_back();
}
// Trim leading spaces
size_t first = msg.find_first_not_of(" \t\n\r");
if (first != std::string::npos && first > 0) {
msg = msg.substr(first);
}
if (!msg.empty()) {
g_messageQueue.push(std::move(msg));
}
}
else if (bytesRead == SOCKET_ERROR) {
int error = WSAGetLastError();
if (error != WSAETIMEDOUT && error != WSAEWOULDBLOCK) {
break;
}
}
}
return true;
}
bool SenderWorkCallback(void* ctx) {
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
return true;
}
struct SocketGuard {
SOCKET sock;
SocketGuard(SOCKET s) : sock(s) {}
~SocketGuard() {
if (sock != INVALID_SOCKET) {
closesocket(sock);
}
}
} socketGuard(sock);
// Static packet buffer: tag(1) + steamid64_LE(8) + text(up to CF_MAX_TEXT)
// Max size = CF_HEADER_SIZE + CF_MAX_TEXT = 1024 bytes
char pktbuf[CF_HEADER_SIZE + CF_MAX_TEXT];
while (!g_shutdownSender.load(std::memory_order_relaxed)) {
// Pause if plugin is disabled OR if listen-only mode is active
if (!IsCvarValid(cf_enabled) || atoi(cf_enabled->string) == 0 ||
(IsCvarValid(cf_listen_only) && atoi(cf_listen_only->string) != 0)) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
SendTask task;
// Batch processing: Drain the queue as fast as possible
// Wait 1ms for the first item, then process remaining items instantly
if (g_sendQueue.pop(task, 1)) {
do {
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(task.port);
// If the IP is invalid (e.g. cvar not yet set), skip this task
if (inet_pton(AF_INET, task.server_ip, &addr.sin_addr) != 1) {
continue;
}
// Assemble binary packet:
// [0] tag (1 byte, message type 0x12-0x16)
// [1..8] steamid64 (8 bytes, little-endian uint64)
// 0 = Steam unavailable / LAN game
// [9..] text (task.msglen bytes, not null-terminated)
const size_t pktlen = CF_HEADER_SIZE + task.msglen;
pktbuf[0] = static_cast<char>(task.tag);
// Write steamid64 LE (portable, no UB via type-punning)
uint64_t sid = task.steamid;
for (int i = 0; i < 8; ++i) {
pktbuf[1 + i] = static_cast<char>(sid & 0xFFu);
sid >>= 8;
}
memcpy(pktbuf + CF_HEADER_SIZE, task.text, task.msglen);
sendto(sock, pktbuf, static_cast<int>(pktlen), 0,
(const sockaddr*)&addr, sizeof(addr));
} while (g_sendQueue.pop(task, 0)); // Pop instantly until empty
}
}
return true;
}
void CleanupResources()
{
// 1. Signal all worker threads to stop
g_shutdownListener.store(true, std::memory_order_release);
g_shutdownSender.store(true, std::memory_order_release);
// 2. Wake up threads blocked on condition_variable so they exit immediately
// instead of waiting for the next pop/push timeout
g_sendQueue.shutdown();
g_messageQueue.shutdown();
// 3. Wait for listener thread to finish, then release its MetaHook work item
if (g_hListenerWorkItem) {
if (g_pMetaHookAPI && g_hThreadPool) {
g_pMetaHookAPI->WaitForWorkItemToComplete(g_hListenerWorkItem);
g_pMetaHookAPI->DeleteWorkItem(g_hListenerWorkItem);
}
g_hListenerWorkItem = nullptr;
}
// 4. Wait for sender thread to finish, then release its MetaHook work item
if (g_hSenderWorkItem) {
if (g_pMetaHookAPI && g_hThreadPool) {
g_pMetaHookAPI->WaitForWorkItemToComplete(g_hSenderWorkItem);
g_pMetaHookAPI->DeleteWorkItem(g_hSenderWorkItem);
}
g_hSenderWorkItem = nullptr;
}
// 5. Remove the IAT hook before the plugin can be unloaded.
if (g_hOutputDebugStringHook && g_pMetaHookAPI) {
g_pMetaHookAPI->UnHook(g_hOutputDebugStringHook);
g_hOutputDebugStringHook = nullptr;
g_pfnOutputDebugStringA = nullptr;
}
// 6. Release Winsock and allow clean reinitialization on the next HUD_Init.
g_winsock.reset();
g_sendQueue.reset();
g_messageQueue.reset();
g_bChatForwarderInitialized = false;
}
void ChatForwarder_Init(void)
{
// Engine type check as suggested
auto engineType = g_pMetaHookAPI->GetEngineType();
if (engineType == ENGINE_GOLDSRC_BLOB) {
// Blob engines can have limitations, check if we can get the client base.
if (g_pMetaHookAPI->GetClientBase() == 0) {
g_pMetaHookAPI->SysError("ChatForwarder: Blob client is not supported by this plugin.");
return;
}
}
// Initialize global resources once
if (!g_bChatForwarderInitialized)
{
// Optional: Check for debugger
if (g_pMetaHookAPI->IsDebuggerPresent()) {
gEngfuncs.Con_Printf("ChatForwarder: Debugger detected.\n");
}
g_winsock = std::unique_ptr<WinsockRAII>(new WinsockRAII());
if (!g_winsock->IsInitialized()) {
if (g_pMetaHookAPI) {
g_pMetaHookAPI->SysError("Failed to initialize Winsock");
}
return;
}
if (gEngfuncs.pfnRegisterVariable) {
cf_server_ip = gEngfuncs.pfnRegisterVariable("cf_server_ip", "127.0.0.1", FCVAR_ARCHIVE);
cf_server_port = gEngfuncs.pfnRegisterVariable("cf_server_port", "26000", FCVAR_ARCHIVE);
cf_allow_ip = gEngfuncs.pfnRegisterVariable("cf_allow_ip", "*", FCVAR_ARCHIVE);
cf_listen_port = gEngfuncs.pfnRegisterVariable("cf_listen_port", "26001", FCVAR_ARCHIVE);
cf_enabled = gEngfuncs.pfnRegisterVariable("cf_enabled", "1", FCVAR_ARCHIVE);
cf_debug = gEngfuncs.pfnRegisterVariable("cf_debug", "0", FCVAR_ARCHIVE);
cf_listen_only = gEngfuncs.pfnRegisterVariable("cf_listen_only", "0", FCVAR_ARCHIVE);
cf_command_delay = gEngfuncs.pfnRegisterVariable("cf_command_delay", "0", FCVAR_ARCHIVE);
}
// Hook OutputDebugStringA in engine to capture everything DebugView sees
// Only hook once!
g_hOutputDebugStringHook = g_pMetaHookAPI->IATHook(g_pMetaHookAPI->GetEngineModule(), "kernel32.dll", "OutputDebugStringA", NewOutputDebugStringA, (void**)&g_pfnOutputDebugStringA);
g_bChatForwarderInitialized = true;
}
// Ensure thread pool is valid
g_hThreadPool = g_pMetaHookAPI->GetGlobalThreadPool();
if (!g_hThreadPool) {
if (g_pMetaHookAPI) {
g_pMetaHookAPI->SysError("Failed to get MetaHook thread pool");
}
return;
}
// Start Sender thread only if NOT in listen-only mode.
// cf_listen_only=1 means: accept inbound commands, but send nothing outbound.
// Runtime blocking is also handled inside SenderWorkCallback.
if (!g_hSenderWorkItem && (!IsCvarValid(cf_listen_only) || atoi(cf_listen_only->string) == 0)) {
g_shutdownSender.store(false, std::memory_order_relaxed);
g_hSenderWorkItem = g_pMetaHookAPI->CreateWorkItem(g_hThreadPool, SenderWorkCallback, nullptr);
if (!g_hSenderWorkItem) {
if (g_pMetaHookAPI) {
g_pMetaHookAPI->SysError("Failed to create sender work item");
}
return;
}
g_pMetaHookAPI->QueueWorkItem(g_hThreadPool, g_hSenderWorkItem);
}
// Always start the Listener thread — it handles inbound console commands
// regardless of cf_listen_only mode.
if (!g_hListenerWorkItem) {
g_shutdownListener.store(false, std::memory_order_relaxed);
g_hListenerWorkItem = g_pMetaHookAPI->CreateWorkItem(g_hThreadPool, UDPListenerWorkCallback, nullptr);
if (!g_hListenerWorkItem) {
if (g_pMetaHookAPI) {
g_pMetaHookAPI->SysError("Failed to create listener work item");
}
return;
}
g_pMetaHookAPI->QueueWorkItem(g_hThreadPool, g_hListenerWorkItem);
}
}
void IPluginsV4::Init(metahook_api_t* pAPI, mh_interface_t* pInterface, mh_enginesave_t* pSave)
{
g_pInterface = pInterface;
g_pMetaHookAPI = pAPI;
g_pMetaSave = pSave;
}
void IPluginsV4::Shutdown(void)
{
CleanupResources();
}
void IPluginsV4::LoadEngine(cl_enginefunc_t* pEngfuncs)
{
memcpy(&gEngfuncs, pEngfuncs, sizeof(gEngfuncs));
}
void IPluginsV4::LoadClient(cl_exportfuncs_t* pExportFunc)
{
if (!pExportFunc) return;
memcpy(&gExportfuncs, pExportFunc, sizeof(gExportfuncs));
g_pfnHUD_Init = pExportFunc->HUD_Init;
pExportFunc->HUD_Init = HUD_Init;
g_pfnHUD_Frame = pExportFunc->HUD_Frame;
pExportFunc->HUD_Frame = HUD_Frame;
}
void IPluginsV4::ExitGame(int iResult)
{
CleanupResources();
}
const char* IPluginsV4::GetVersion(void)
{
return "1.4.5.1";
}
EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4);