forked from codeurzebs/fivem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevConServer.cpp
More file actions
434 lines (330 loc) · 10.6 KB
/
Copy pathDevConServer.cpp
File metadata and controls
434 lines (330 loc) · 10.6 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#include "StdInc.h"
#if _WIN32
#include <CoreConsole.h>
#include <CfxState.h>
#include <HostSharedData.h>
#include <TcpServer.h>
#include <TcpServerManager.h>
#include <NetBuffer.h>
#include <mutex>
#include <shared_mutex>
#include <MultiplexTcpServer.h>
#include <HttpServerImpl.h>
#include <CL2LaunchMode.h>
#include <ResourceManager.h>
#include <Profiler.h>
#include <shellapi.h>
#pragma comment(lib, "shell32.lib")
#include <optional>
#include <json.hpp>
using json = nlohmann::json;
#include <strsafe.h>
static std::shared_mutex g_mutex;
static std::set<net::TcpServerStream*> g_streams;
struct ConsoleBuffer
{
char channels[512][48];
char buffers[512][1024];
int curBufferRead;
volatile int curBufferWrite;
ConsoleBuffer()
: curBufferRead(0), curBufferWrite(0)
{
}
};
static HANDLE g_stateSema = CreateSemaphore(nullptr, 0, 100000, L"CFX_Console_Produce");
static HANDLE g_stateMutex = CreateMutex(nullptr, FALSE, L"CFX_Console_Consume");
static void DevConPrintListener(ConsoleChannel channel, const char* message)
{
static HostSharedData<ConsoleBuffer> conData("ConsoleData");
WaitForSingleObject(g_stateMutex, INFINITE);
int curWrite = conData->curBufferWrite++;
StringCbCopyA(conData->buffers[curWrite], sizeof(conData->buffers[curWrite]), message);
StringCbCopyA(conData->channels[curWrite], sizeof(conData->channels[curWrite]), channel.data());
if (conData->curBufferWrite >= _countof(conData->channels))
{
conData->curBufferWrite = 0;
}
if (conData->curBufferWrite != conData->curBufferRead)
{
ReleaseSemaphore(g_stateSema, 1, nullptr);
}
ReleaseMutex(g_stateMutex);
}
inline uint16_t sSwapShortRead(uint16_t x)
{
return _byteswap_ushort(x);
}
inline uint32_t sSwapLongRead(uint32_t x)
{
return _byteswap_ulong(x);
}
inline uint64_t sSwapLongLongRead(uint64_t x)
{
return _byteswap_uint64(x);
}
static std::set<std::string> g_knownChannels = { "Any", "font-renderer" };
static void FlushKnownChannels(net::TcpServerStream* stream)
{
net::Buffer buf;
buf.Write(0x4E414843); // 'CHAN'
buf.Write<uint16_t>(sSwapShortRead(211)); // protocol
buf.Write<uint32_t>(sSwapLongRead(14 + (g_knownChannels.size() * 58)));
buf.Write<uint32_t>(sSwapLongRead(g_knownChannels.size()));
for (auto& channel : g_knownChannels)
{
buf.Write<uint32_t>(HashString(channel.c_str()));
buf.Write<uint32_t>(0);
buf.Write<uint32_t>(0);
buf.Write<uint32_t>(sSwapLongRead(2));
buf.Write<uint32_t>(sSwapLongRead(2));
buf.Write<uint32_t>(0);
char channelStr[30] = { 0 };
StringCbCopyA(channelStr, sizeof(channelStr), channel.c_str());
buf.Write(channelStr, sizeof(channelStr));
buf.Write<uint32_t>(sSwapLongRead(1));
}
stream->Write(buf.GetData());
}
static void FlushKnownCommands(net::TcpServerStream* stream)
{
static std::set<std::string> lastCmds;
std::set<std::string> cmds;
Instance<ConsoleCommandManager>::Get()->ForAllCommands([&](const std::string& cmd)
{
cmds.insert(cmd);
});
std::vector<std::string> cmdDiffs;
std::set_difference(cmds.begin(), cmds.end(), lastCmds.begin(), lastCmds.end(), std::back_inserter(cmdDiffs));
lastCmds.swap(cmds);
for (const std::string& cmd : cmdDiffs)
{
net::Buffer buf;
buf.Write(0x52415643); // 'CVAR'
buf.Write<uint16_t>(sSwapShortRead(211)); // protocol
buf.Write<uint32_t>(sSwapLongRead(93));
buf.Write<uint16_t>(0);
char cmdBuf[64];
strncpy(cmdBuf, cmd.c_str(), sizeof(cmdBuf));
cmdBuf[63] = '\0';
buf.Write(cmdBuf, sizeof(cmdBuf));
buf.Write<uint32_t>(0);
buf.Write<uint32_t>(sSwapLongRead(0)); // flags
buf.Write<uint32_t>(sSwapLongRead(0)); // min
buf.Write<uint32_t>(sSwapLongRead(0)); // max
buf.Write<uint8_t>(0x11);
stream->Write(buf.GetData());
}
}
static void HandleConsoleMessage(const std::string& channel, const std::string& buffer)
{
bool channelsChanged = false;
if (g_knownChannels.find(channel) == g_knownChannels.end())
{
channelsChanged = true;
g_knownChannels.insert(channel);
}
{
net::Buffer buf;
buf.Write(0x544E5250); // 'PRNT'
buf.Write<uint16_t>(sSwapShortRead(211)); // protocol
buf.Write<uint32_t>(sSwapLongRead(40 + 1 + buffer.length()));
buf.Write<uint16_t>(0);
buf.Write<uint32_t>(HashString(channel.c_str()));
char dummyBuffer[24] = { 0 };
buf.Write(dummyBuffer, 24);
buf.Write(buffer.data(), buffer.size() + 1);
{
std::shared_lock<std::shared_mutex> lock(g_mutex);
for (auto& stream : g_streams)
{
if (channelsChanged)
{
FlushKnownChannels(stream);
}
FlushKnownCommands(stream);
stream->Write(buf.GetData());
}
}
}
}
static InitFunction initFunction([]()
{
static HostSharedData<CfxState> hostData("CfxInitState");
static HostSharedData<ConsoleBuffer> conData("ConsoleData");
console::CoreAddPrintListener(DevConPrintListener);
if (!hostData->IsMasterProcess() && !hostData->IsGameProcess())
{
return;
}
std::thread([]()
{
SetThreadName(-1, "DevCon Thread");
while (true)
{
// wait for an incoming semaphore
WaitForSingleObject(g_stateSema, INFINITE);
// lock the mutex
WaitForSingleObject(g_stateMutex, INFINITE);
// try to catch up
int start = conData->curBufferRead;
int end = conData->curBufferWrite;
while (start != end)
{
std::string channel = conData->channels[start];
std::string buffer = conData->buffers[start];
HandleConsoleMessage(channel, buffer);
++start;
if (start >= _countof(conData->channels))
{
start = 0;
}
}
conData->curBufferRead = start;
// release the mutex
ReleaseMutex(g_stateMutex);
}
}).detach();
// Handle case where the client and server are on the same localhost.
#if defined(IS_FXSERVER)
static const int tcpServerPort = 29100;
#else
static const int tcpServerPort = IsCL2() ? 29300 : 29200;
#endif
static fwRefContainer<net::TcpServerManager> tcpStack = new net::TcpServerManager();
static fwRefContainer<net::TcpServer> tcpServer = tcpStack->CreateServer(
net::PeerAddress::FromString(
fmt::sprintf("%s:%d",
wcsstr(GetCommandLineW(), L"-devcon") != nullptr ? "0.0.0.0" : "127.0.0.1",
tcpServerPort
), tcpServerPort, net::PeerAddress::LookupType::NoResolution
).get());
if (!tcpServer.GetRef())
{
return;
}
static fwRefContainer<net::MultiplexTcpServer> multiServer = new net::MultiplexTcpServer();
multiServer->AttachToServer(tcpServer);
auto httpPatternMatcher = [](const std::vector<uint8_t>& bytes)
{
if (bytes.size() > 10)
{
auto firstR = std::find(bytes.begin(), bytes.end(), '\r');
if (firstR != bytes.end())
{
auto firstN = firstR + 1;
if (firstN != bytes.end())
{
if (*firstN == '\n')
{
std::string match(firstR - 8, firstR);
if (match.find("HTTP/") == 0)
{
return net::MultiplexPatternMatchResult::Match;
}
}
return net::MultiplexPatternMatchResult::NoMatch;
}
}
}
return net::MultiplexPatternMatchResult::InsufficientData;
};
struct Handler : public net::HttpHandler
{
std::function<bool(fwRefContainer<net::HttpRequest>, fwRefContainer<net::HttpResponse>)> handler;
virtual bool HandleRequest(fwRefContainer<net::HttpRequest> request, fwRefContainer<net::HttpResponse> response) override
{
return handler(request, response);
}
};
static std::optional<json> lastProfile;
fx::ResourceManager::OnInitializeInstance.Connect([](fx::ResourceManager* resman)
{
resman->GetComponent<fx::ProfilerComponent>()->OnRequestView.Connect([](const json& json)
{
lastProfile = json;
ShellExecuteW(nullptr, L"open", fmt::sprintf(L"%s?loadTimelineFromURL=http://localhost:%d/profileData.json", ToWide(fx::ProfilerComponent::GetDevToolsURL()), tcpServerPort).c_str(), NULL, NULL, SW_SHOW);
});
}, INT32_MAX);
static fwRefContainer<Handler> httpHandler = new Handler();
httpHandler->handler = [=](fwRefContainer<net::HttpRequest> request, fwRefContainer<net::HttpResponse> response)
{
if (request->GetPath() == "/profileData.json")
{
response->SetHeader("Access-Control-Allow-Origin", "*");
response->End(lastProfile->dump(-1, ' ', false, json::error_handler_t::replace));
return true;
}
response->SetStatusCode(404);
response->End(fmt::sprintf("Route %s not found.", std::string_view{ request->GetPath().c_str() }));
return true;
};
static fwRefContainer<net::HttpServer> httpServer = new net::HttpServerImpl();
httpServer->RegisterHandler(httpHandler);
httpServer->AttachToServer(multiServer->CreateServer(httpPatternMatcher));
static auto devconServer = multiServer->CreateServer([](const std::vector<uint8_t>& bytes)
{
if (bytes.size() >= 4)
{
return (*(uint32_t*)bytes.data() == 0x52435050 || *(uint32_t*)bytes.data() == 0x444E4D43)
? net::MultiplexPatternMatchResult::Match
: net::MultiplexPatternMatchResult::NoMatch;
}
return net::MultiplexPatternMatchResult::InsufficientData;
});
devconServer->SetConnectionCallback([](fwRefContainer<net::TcpServerStream> stream)
{
auto localStream = stream;
stream->SetReadCallback([=](const std::vector<uint8_t>& data)
{
if (*(uint32_t*)data.data() == 0x52435050)
{
// send an AINF
std::string commandLine = ToNarrow(GetCommandLine());
net::Buffer buf;
buf.Write(0x464E4941); // 'AINF'
buf.Write<uint16_t>(sSwapShortRead(211)); // protocol
buf.Write<uint32_t>(sSwapLongRead(commandLine.length() + 1 + 97));
buf.Write<uint16_t>(0);
//buf.Write<uint32_t>(HashString("Cfx"));
buf.Write<uint32_t>(0xEFF8A1A);
buf.Write<uint32_t>(0);
buf.Write<uint32_t>(0x321F0C00);
char gameName[32] = { 0 };
char appName[32] = { 0 };
strcpy(gameName, "CitizenFX");
strcpy(appName, "CitizenFX");
buf.Write(gameName, sizeof(gameName));
buf.Write(appName, sizeof(appName));
buf.Write<uint8_t>(0xFF);
buf.Write(sSwapLongRead(0x8));
buf.Write<uint32_t>(sSwapLongRead(commandLine.length() + 1));
buf.Write(commandLine.data(), commandLine.length() + 1);
localStream->Write(buf.GetData());
FlushKnownChannels(localStream.GetRef());
FlushKnownCommands(localStream.GetRef());
{
std::unique_lock<std::shared_mutex> lock(g_mutex);
g_streams.insert(localStream.GetRef());
}
}
else if (*(uint32_t*)data.data() == 0x444E4D43) // CMND
{
net::Buffer buf(data);
buf.Read<uint32_t>();
uint16_t protocol = sSwapShortRead(buf.Read<uint16_t>());
uint32_t length = sSwapLongRead(buf.Read<uint32_t>());
buf.Read<uint16_t>();
std::vector<uint8_t> d(buf.GetRemainingBytes());
buf.Read(d.data(), d.size() - 1);
Instance<console::Context>::Get()->AddToBuffer(std::string(d.begin(), d.end()) + "\n");
}
});
stream->SetCloseCallback([=]()
{
std::unique_lock<std::shared_mutex> lock(g_mutex);
g_streams.erase(localStream.GetRef());
});
});
});
#endif