Skip to content
Navigation Menu
{{ message }}
forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoteServer.cpp
More file actions
391 lines (308 loc) · 9.99 KB
/
Copy pathRemoteServer.cpp
File metadata and controls
391 lines (308 loc) · 9.99 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
/*
https://github.com/peterix/dfhack
Copyright (c) 2011 Petr Mrázek <peterix@gmail.com>
A thread-safe logging console with a line editor for windows.
Based on linenoise win32 port,
copyright 2010, Jon Griffiths <jon_p_griffiths at yahoo dot com>.
All rights reserved.
Based on linenoise, copyright 2010, Salvatore Sanfilippo <antirez at gmail dot com>.
The original linenoise can be found at: http://github.com/antirez/linenoise
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Redis nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdarg.h>
#include <errno.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
#include <stdint.h>
#include "RemoteServer.h"
#include "RemoteTools.h"
#include "PassiveSocket.h"
#include "PluginManager.h"
#include "MiscUtils.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <memory>
using namespace DFHack;
#include "tinythread.h"
using namespace tthread;
using dfproto::CoreTextNotification;
using dfproto::CoreTextFragment;
using google::protobuf::MessageLite;
bool readFullBuffer(CSimpleSocket *socket, void *buf, int size);
bool sendRemoteMessage(CSimpleSocket *socket, int16_t id,
const ::google::protobuf::MessageLite *msg, bool size_ready);
RPCService::RPCService()
{
owner = NULL;
holder = NULL;
}
RPCService::~RPCService()
{
if (holder)
holder->detach_connection(this);
for (size_t i = 0; i < functions.size(); i++)
delete functions[i];
}
ServerFunctionBase *RPCService::getFunction(const std::string &name)
{
assert(owner);
return lookup[name];
}
void RPCService::finalize(ServerConnection *owner, std::vector<ServerFunctionBase*> *ftable)
{
this->owner = owner;
for (size_t i = 0; i < functions.size(); i++)
{
auto fn = functions[i];
fn->id = (int16_t)ftable->size();
ftable->push_back(fn);
lookup[fn->name] = fn;
}
}
ServerConnection::ServerConnection(CActiveSocket *socket)
: socket(socket), stream(this)
{
in_error = false;
core_service = new CoreService();
core_service->finalize(this, &functions);
thread = new tthread::thread(threadFn, (void*)this);
}
ServerConnection::~ServerConnection()
{
in_error = true;
socket->Close();
delete socket;
for (auto it = plugin_services.begin(); it != plugin_services.end(); ++it)
delete it->second;
delete core_service;
}
ServerFunctionBase *ServerConnection::findFunction(color_ostream &out, const std::string &plugin, const std::string &name)
{
RPCService *svc;
if (plugin.empty())
svc = core_service;
else
{
svc = plugin_services[plugin];
if (!svc)
{
Plugin *plug = Core::getInstance().plug_mgr->getPluginByName(plugin);
if (!plug)
{
out.printerr("No such plugin: %s\n", plugin.c_str());
return NULL;
}
svc = plug->rpc_connect(out);
if (!svc)
{
out.printerr("Plugin %s doesn't export any RPC methods.\n", plugin.c_str());
return NULL;
}
svc->finalize(this, &functions);
plugin_services[plugin] = svc;
}
}
return svc->getFunction(name);
}
void ServerConnection::connection_ostream::flush_proxy()
{
if (owner->in_error)
{
buffer.clear();
return;
}
if (buffer.empty())
return;
CoreTextNotification msg;
for (auto it = buffer.begin(); it != buffer.end(); ++it)
{
auto frag = msg.add_fragments();
frag->set_text(it->second);
if (it->first >= 0)
frag->set_color(CoreTextFragment::Color(it->first));
}
buffer.clear();
if (!sendRemoteMessage(owner->socket, RPC_REPLY_TEXT, &msg, false))
{
owner->in_error = true;
Core::printerr("Error writing text into client socket.\n");
}
}
void ServerConnection::threadFn(void *arg)
{
ServerConnection *me = (ServerConnection*)arg;
me->threadFn();
delete me;
}
void ServerConnection::threadFn()
{
color_ostream_proxy out(Core::getInstance().getConsole());
/* Handshake */
{
RPCHandshakeHeader header;
if (!readFullBuffer(socket, &header, sizeof(header)))
{
out << "In RPC server: could not read handshake header." << endl;
return;
}
if (memcmp(header.magic, RPCHandshakeHeader::REQUEST_MAGIC, sizeof(header.magic)) ||
header.version < 1 || header.version > 255)
{
out << "In RPC server: invalid handshake header." << endl;
return;
}
memcpy(header.magic, RPCHandshakeHeader::RESPONSE_MAGIC, sizeof(header.magic));
header.version = 1;
if (socket->Send((uint8*)&header, sizeof(header)) != sizeof(header))
{
out << "In RPC server: could not send handshake response." << endl;
return;
}
}
/* Processing */
std::cerr << "Client connection established." << endl;
while (!in_error) {
// Read the message
RPCMessageHeader header;
if (!readFullBuffer(socket, &header, sizeof(header)))
{
out.printerr("In RPC server: I/O error in receive header.\n");
break;
}
if ((DFHack::DFHackReplyCode)header.id == RPC_REQUEST_QUIT)
break;
if (header.size < 0 || header.size > RPCMessageHeader::MAX_MESSAGE_SIZE)
{
out.printerr("In RPC server: invalid received size %d.\n", header.size);
break;
}
std::auto_ptr<uint8_t> buf(new uint8_t[header.size]);
if (!readFullBuffer(socket, buf.get(), header.size))
{
out.printerr("In RPC server: I/O error in receive %d bytes of data.\n", header.size);
break;
}
//out.print("Handling %d:%d\n", header.id, header.size);
// Find and call the function
int in_size = header.size;
ServerFunctionBase *fn = vector_get(functions, header.id);
MessageLite *reply = NULL;
command_result res = CR_FAILURE;
if (!fn)
{
stream.printerr("RPC call of invalid id %d\n", header.id);
}
else
{
if (!fn->in()->ParseFromArray(buf.get(), header.size))
{
stream.printerr("In call to %s: could not decode input args.\n", fn->name);
}
else
{
buf.reset();
reply = fn->out();
if (fn->flags & SF_DONT_SUSPEND)
{
res = fn->execute(stream);
}
else
{
CoreSuspender suspend;
res = fn->execute(stream);
}
}
}
// Flush all text output
if (in_error)
break;
//out.print("Answer %d:%d\n", res, reply);
// Send reply
int out_size = (reply ? reply->ByteSize() : 0);
if (out_size > RPCMessageHeader::MAX_MESSAGE_SIZE)
{
stream.printerr("In call to %s: reply too large: %d.\n",
(fn ? fn->name : "UNKNOWN"), out_size);
res = CR_LINK_FAILURE;
}
stream.flush();
if (res == CR_OK && reply)
{
if (!sendRemoteMessage(socket, RPC_REPLY_RESULT, reply, true))
{
out.printerr("In RPC server: I/O error in send result.\n");
break;
}
}
else
{
header.id = RPC_REPLY_FAIL;
header.size = res;
if (socket->Send((uint8_t*)&header, sizeof(header)) != sizeof(header))
{
out.printerr("In RPC server: I/O error in send failure code.\n");
break;
}
}
// Cleanup
if (fn)
{
fn->reset((fn->flags & SF_CALLED_ONCE) ||
(out_size > 128*1024 || in_size > 32*1024));
}
}
std::cerr << "Shutting down client connection." << endl;
}
ServerMain::ServerMain()
{
socket = new CPassiveSocket();
thread = NULL;
}
ServerMain::~ServerMain()
{
socket->Close();
delete socket;
}
bool ServerMain::listen(int port)
{
if (thread)
return true;
socket->Initialize();
if (!socket->Listen((const uint8 *)"127.0.0.1", port))
return false;
thread = new tthread::thread(threadFn, this);
return true;
}
void ServerMain::threadFn(void *arg)
{
ServerMain *me = (ServerMain*)arg;
CActiveSocket *client;
while ((client = me->socket->Accept()) != NULL)
{
new ServerConnection(client);
}
}
You can’t perform that action at this time.
