-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathNamedPipeServer.cpp
More file actions
372 lines (302 loc) · 13.3 KB
/
NamedPipeServer.cpp
File metadata and controls
372 lines (302 loc) · 13.3 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
#include "NamedPipeServer.h"
#include "TextMessage.h"
#include <sddl.h>
#include "Log.h"
#include "Engine.h"
#include <Tracy.hpp>
CNamedPipeServer::CNamedPipeServer(std::string fromPipeName, std::string toPipeName) {
this->setConnectedWrite(false);
this->setConnectedRead(false);
this->setPipeHandleWrite(INVALID_HANDLE_VALUE);
this->setPipeHandleRead(INVALID_HANDLE_VALUE);
this->setShuttingDown(false);
this->setFromPipeName(fromPipeName);
this->setToPipeName(toPipeName);
}
CNamedPipeServer::~CNamedPipeServer( void ) {
this->shutdown();
}
acre::Result CNamedPipeServer::initialize() {
ZoneScoped;
HANDLE writeHandle, readHandle;
SECURITY_DESCRIPTOR sd;
if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { LOG("InitializeSecurityDescriptor Error : %u", GetLastError()); }
if (!SetSecurityDescriptorDacl(&sd, TRUE, nullptr, FALSE)) { LOG("SetSecurityDescriptorDacl Error : %u", GetLastError()); }
if (!SetSecurityDescriptorControl(&sd, SE_DACL_PROTECTED, SE_DACL_PROTECTED)) { LOG("SetSecurityDescriptorControl Error : %u", GetLastError()); }
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), &sd, true };
// open our pipe handle, then kick up a thread to monitor it and add shit to our queue
// this end LISTENS and CREATES the pipe
LOG("Opening game pipe...");
bool tryAgain = true;
while (tryAgain) {
writeHandle = CreateNamedPipeA(
this->getFromPipeName().c_str(), // name of the pipe
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | // message-type pipe
PIPE_READMODE_MESSAGE, // send data as message
PIPE_UNLIMITED_INSTANCES,
4096, // no outbound buffer
4096, // no inbound buffer
0, // use default wait time
&sa
);
if (writeHandle == INVALID_HANDLE_VALUE) {
char errstr[1024];
_snprintf_s(errstr, sizeof(errstr), "Conflicting game write pipe detected, could not create pipe!\nERROR CODE: %d", GetLastError());
int ret = MessageBoxA(NULL, errstr, "ACRE Error", MB_RETRYCANCEL | MB_ICONEXCLAMATION);
if (ret != IDRETRY) {
tryAgain = false;
TerminateProcess(GetCurrentProcess(), 0);
}
} else {
tryAgain = false;
}
}
tryAgain = true;
while (tryAgain) {
readHandle = CreateNamedPipeA(
this->getToPipeName().c_str(), // name of the pipe
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | // message-type pipe
PIPE_NOWAIT | // Depricated but fuck it, it is simpler.
PIPE_READMODE_MESSAGE, // send data as message
PIPE_UNLIMITED_INSTANCES,
4096, // no outbound buffer
4096, // no inbound buffer
0, // use default wait time
&sa // use default security attributes
);
if (readHandle == INVALID_HANDLE_VALUE) {
char errstr[1024];
_snprintf_s(errstr, sizeof(errstr), "Conflicting game read pipe detected, could not create pipe!\nERROR CODE: %d", GetLastError());
int ret = MessageBoxA(NULL, errstr, "ACRE Error", MB_RETRYCANCEL | MB_ICONEXCLAMATION);
if (ret != IDRETRY) {
tryAgain = false;
TerminateProcess(GetCurrentProcess(), 0);
}
} else {
tryAgain = false;
}
}
this->setPipeHandleRead(readHandle);
this->setPipeHandleWrite(writeHandle);
LOG("Game pipe opening successful. [%d & %d]", this->getPipeHandleRead(), this->getPipeHandleWrite());
this->m_sendThread = std::thread(&CNamedPipeServer::sendLoop, this);
this->m_readThread = std::thread(&CNamedPipeServer::readLoop, this);
return acre::Result::ok;
}
acre::Result CNamedPipeServer::shutdown(void) {
ZoneScoped;
HANDLE hPipe;
this->setShuttingDown(true);
this->setConnectedWrite(false);
this->setConnectedRead(false);
//Wake the synchronous named pipe
//Called from the same process but from a different thread
hPipe = CreateFile(this->getToPipeName().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
}
// Read should initiate the full shutdown, so we wait for him to die first and we only wake him.
if (this->m_readThread.joinable()) {
this->m_readThread.join();
}
// Now we wake the write pipe just in case.
hPipe = CreateFile(this->getFromPipeName().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
}
if (this->m_sendThread.joinable()) {
this->m_sendThread.join();
}
this->setShuttingDown(false);
return acre::Result::ok;
}
const char *sendFrameName = "NamedPipeServer - sending";
acre::Result CNamedPipeServer::sendLoop() {
tracy::SetThreadName("NamedPipeServer::sendLoop");
while (!this->getShuttingDown()) {
do {
ConnectNamedPipe(this->m_PipeHandleWrite, NULL);
if (GetLastError() == ERROR_PIPE_CONNECTED) {
LOG("Client write connected");
CEngine::getInstance()->getSoundEngine()->onClientGameConnected();
this->setConnectedWrite(true);
break;
} else {
this->setConnectedWrite(false);
Sleep(1);
}
} while (!this->getConnectedWrite() && !this->getShuttingDown());
clock_t lastTick = clock() / CLOCKS_PER_SEC;
while (this->getConnectedWrite()) {
FrameMarkStart(sendFrameName);
if (this->getShuttingDown())
break;
clock_t tick = clock() / CLOCKS_PER_SEC;
if (tick - lastTick > (PIPE_TIMEOUT / 1000)) {
LOG("No send message for %d seconds, disconnecting", (PIPE_TIMEOUT / 1000));
this->setConnectedWrite(false);
break;
}
IMessage *msg = nullptr;
if (this->m_sendQueue.try_pop(msg)) {
if (msg != nullptr) {
ZoneScoped;
lastTick = clock() / CLOCKS_PER_SEC;
const DWORD size = (DWORD)strlen((char *)msg->getData()) + 1;
if (size > 3) {
DWORD cbWritten = 0;
// send it and free it
//LOCK(this);
this->lock();
const bool ret = WriteFile(
this->m_PipeHandleWrite, // pipe handle
msg->getData(), // message
size, // message length
&cbWritten, // bytes written
NULL); // not overlapped
this->unlock();
if (!ret) {
LOG("WriteFile failed, [%d]", GetLastError());
if (GetLastError() == ERROR_BROKEN_PIPE) {
this->setConnectedWrite(false);
}
}
}
delete msg;
}
FrameMarkEnd(sendFrameName);
}
Sleep(1);
}
LOG("Write loop disconnected");
FlushFileBuffers(this->m_PipeHandleWrite);
const bool ret = DisconnectNamedPipe(this->m_PipeHandleWrite);
Sleep(1);
}
TRACE("Sending thread terminating");
return acre::Result::ok;
}
const char *receiveFrameName = "NamedPipeServer - receiving";
acre::Result CNamedPipeServer::readLoop() {
tracy::SetThreadName("NamedPipeServer::readLoop");
DWORD cbRead;
char *mBuffer = (char *)LocalAlloc(LMEM_FIXED, BUFSIZE);
if (mBuffer == nullptr) {
LOG("LocalAlloc() failed: %d", GetLastError());
}
/*
this->validTSServers.insert(std::string("enter a ts3 server id here"));
*/
while (!this->getShuttingDown()) {
bool ret = false;
{
// ZoneScopedN("CNamedPipeServer::readLoop - connecting read pipe");
// this->checkServer();
ret = ConnectNamedPipe(this->m_PipeHandleRead, NULL);
if (GetLastError() == ERROR_PIPE_CONNECTED) {
LOG("Client read connected");
CEngine::getInstance()->getClient()->updateShouldSwitchChannel(false);
CEngine::getInstance()->getClient()->unMuteAll();
CEngine::getInstance()->getSoundEngine()->onClientGameConnected();
this->setConnectedRead(true);
} else {
this->setConnectedRead(false);
Sleep(1);
continue;
}
}
clock_t lastTick = clock() / CLOCKS_PER_SEC;
while (this->getConnectedRead()) {
FrameMarkStart(receiveFrameName);
//this->checkServer();
if (this->getShuttingDown()) {
break;
}
const clock_t tick = clock() / CLOCKS_PER_SEC;
//LOG("[%d] - [%d] = [%d] vs. [%d]", tick, lastTick, (tick - lastTick),(PIPE_TIMEOUT / 1000));
if (tick - lastTick > (PIPE_TIMEOUT / 1000)) {
LOG("No read message for %d seconds, disconnecting", (PIPE_TIMEOUT / 1000));
this->setConnectedWrite(false);
this->setConnectedRead(false);
break;
}
//Run channel switch to server channel
if (CEngine::getInstance()->getClient()->shouldSwitchChannel()) {
CEngine::getInstance()->getClient()->moveToServerChannel();
}
ret = false;
do {
ret = ReadFile(this->m_PipeHandleRead, mBuffer, BUFSIZE - 1, &cbRead, NULL); // -1 for null-byte below
if (!ret && GetLastError() != ERROR_MORE_DATA) {
break;
} else if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
this->setConnectedRead(false);
break;
}
ZoneScoped;
// handle the packet and run it
mBuffer[cbRead] = 0x00;
// LOG("READ: %s", (char *)mBuffer);
IMessage *const msg = new CTextMessage((char *) mBuffer, cbRead);
// TRACE("got and parsed message [%s]", msg->getData());
if (msg != nullptr && msg->getProcedureName()) {
// Do not free msg, this is deleted inside runProcedure()
CEngine::getInstance()->getRpcEngine()->runProcedure(this, msg);
lastTick = clock() / CLOCKS_PER_SEC;
// TRACE("tick [%d], [%s]",lastTick, msg->getData());
}
// wait 1ms for new msg so we dont hog cpu cycles
} while (!ret);
//ret = ConnectNamedPipe(this->getPipeHandle(), NULL);
FrameMarkEnd(receiveFrameName);
Sleep(1);
}
// Kill the write pipe along with ourselves, because we master shutdown/startup
this->setConnectedWrite(false);
this->setConnectedRead(false);
FlushFileBuffers(this->m_PipeHandleRead);
ret = DisconnectNamedPipe(this->m_PipeHandleRead);
//Run channel switch to original channel
CEngine::getInstance()->getClient()->moveToPreviousChannel();
CEngine::getInstance()->getSoundEngine()->onClientGameDisconnected();
LOG("Client disconnected");
CEngine::getInstance()->getClient()->unMuteAll();
// Clear the send queue since client disconnected
this->m_sendQueue.clear();
// send an event that we have disconnected
if (CEngine::getInstance()->getExternalServer()->getConnected()) {
CEngine::getInstance()->getExternalServer()->sendMessage(
CTextMessage::formatNewMessage("ext_reset",
"%d,",
CEngine::getInstance()->getSelf()->getId()
)
);
}
Sleep(1);
}
if (mBuffer)
LocalFree(mBuffer);
TRACE("Receiving thread terminating");
return acre::Result::ok;
}
acre::Result CNamedPipeServer::sendMessage( IMessage *message ) {
if (message) {
TRACE("sending [%s]", message->getData());
this->m_sendQueue.push(message);
return acre::Result::ok;
} else {
return acre::Result::error;
}
}
acre::Result CNamedPipeServer::checkServer( void ) {
std::string uniqueId = CEngine::getInstance()->getClient()->getUniqueId();
if (uniqueId != "" && this->validTSServers.find(uniqueId) == this->validTSServers.end()) {
MessageBoxA(NULL, "This server is NOT registered for ACRE2 testing! Please remove the plugin! Teamspeak will now close.", "ACRE Error", MB_OK | MB_ICONEXCLAMATION);
TerminateProcess(GetCurrentProcess(), 0);
}
return acre::Result::ok;
}