/
remoteuser.cpp
328 lines (280 loc) · 9.02 KB
/
remoteuser.cpp
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
/** @file remoteuser.cpp User that is communicating with the server over a network socket.
*
* @authors Copyright (c) 2013-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "remoteuser.h"
#include "serversystem.h"
#include "network/net_buf.h"
#include "network/net_msg.h"
#include "network/net_event.h"
#include "server/sv_def.h"
#include "serverapp.h"
#include "world/map.h"
#include <doomsday/network/Protocol>
#include <de/data/json.h>
#include <de/legacy/memory.h>
#include <de/Message>
#include <de/ByteRefArray>
#include <de/Garbage>
using namespace de;
enum RemoteUserState { Disconnected, Unjoined, Joined };
DE_PIMPL(RemoteUser)
, DE_OBSERVES(Socket, StateChange)
, DE_OBSERVES(Socket, Message)
{
Id id;
Socket * socket;
int protocolVersion;
Address address;
bool isFromLocal;
RemoteUserState state;
String name;
Impl(Public *i, Socket *sock)
: Base(i)
, socket(sock)
, state(Unjoined)
{
DE_ASSERT(socket != nullptr);
socket->audienceForStateChange() += this;
socket->audienceForMessage() += this;
address = socket->peerAddress();
isFromLocal = socket->isLocal();
LOG_NET_MSG("New remote user %s from socket %s (local:%b)") << id << address << isFromLocal;
}
~Impl() override
{
delete socket;
}
void socketStateChanged(Socket &, Socket::SocketState state) override
{
if (state == Socket::Disconnected) self().socketDisconnected();
}
void messagesIncoming(Socket &) override
{
self().handleIncomingPackets();
}
void notifyClientExit()
{
netevent_t netEvent;
netEvent.type = NE_CLIENT_EXIT;
netEvent.id = id;
N_NEPost(&netEvent);
}
void disconnect()
{
if (state == Disconnected) return;
LOG_NET_NOTE("Closing connection to remote user %s (from %s)") << id << address;
DE_ASSERT(socket->isOpen());
if (state == Joined)
{
// Send a msg notifying of disconnection.
Msg_Begin(PSV_SERVER_CLOSE);
Msg_End();
Net_SendBuffer(N_IdentifyPlayer(id), 0);
// This causes a network event.
notifyClientExit();
}
state = Disconnected;
if (socket && socket->isOpen())
{
socket->close();
}
}
/**
* Validate and process the command, which has been sent by a remote agent.
* If the command is invalid, the node is immediately closed.
*
* @return @c false to stop processing further incoming messages (for now).
*/
bool handleRequest(const Block &command)
{
LOG_AS("handleRequest");
const auto length = command.size();
// If the command is too long, it'll be considered invalid.
if (length >= 256)
{
disconnect();
return false;
}
// Status query?
if (command == "Info?")
{
const ServerInfo info = ServerApp::currentServerInfo();
const Block msg = "Info\n" + composeJSON(info.asRecord());
LOGDEV_NET_VERBOSE("Info reply:\n%s") << String::fromUtf8(msg);
self() << msg;
}
else if (command == "Ping?")
{
self() << Block("Pong");
}
else if (command == "MapOutline?")
{
network::MapOutlinePacket packet;
if (ServerApp::world().hasMap())
{
ServerApp::world().map().initMapOutlinePacket(packet);
}
Block serialized;
Writer(serialized).withHeader() << packet;
self() << Block("MapOutline\n" + serialized.compressed());
}
else if (command == "RemoteFeed")
{
// This connection will be only doing file system operations.
App_ServerSystem().convertToRemoteFeedUser(thisPublic);
return false;
}
else if (length >= 5 && command.beginsWith("Shell"))
{
if (length == 5)
{
// Password is not required for connections from the local computer.
if (strlen(netPassword) > 0 && !isFromLocal)
{
// Need to ask for a password, too.
self() << ByteRefArray("Psw?", 4);
return true;
}
}
else if (length > 5)
{
// A password was included.
Block supplied = command.mid(5);
Block pwd(netPassword, strlen(netPassword));
if (supplied != pwd.md5Hash())
{
// Wrong!
disconnect();
return false;
}
}
// This node will switch to shell mode: ownership of the socket is
// passed to a ShellUser.
App_ServerSystem().convertToShellUser(thisPublic);
return false;
}
else if (length >= 10 && command.beginsWith("Join ") && command[9] == ' ')
{
protocolVersion = String(command.mid(5, 4)).toInt(nullptr, 16);
// Read the client's name and convert the network node into an actual
// client. Here we also decide if the client's protocol is compatible
// with ours.
name = String::fromUtf8(command.mid(10));
if (App_ServerSystem().isUserAllowedToJoin(self()))
{
state = Joined;
// Successful! Send a reply.
self() << ByteRefArray("Enter", 5);
// Inform the higher levels of this occurence.
netevent_t netEvent;
netEvent.type = NE_CLIENT_ENTRY;
netEvent.id = id;
N_NEPost(&netEvent);
}
else
{
// Couldn't join the game, so close the connection.
disconnect();
return false;
}
}
else
{
// Too bad, scoundrel! Goodbye.
LOG_NET_WARNING("Received an invalid request from %s") << id;
disconnect();
return false;
}
// Everything was OK.
return true;
}
DE_PIMPL_AUDIENCE(Destroy)
};
DE_AUDIENCE_METHOD(RemoteUser, Destroy)
RemoteUser::RemoteUser(Socket *socket) : d(new Impl(this, socket))
{}
RemoteUser::~RemoteUser()
{
DE_NOTIFY(Destroy, i) { i->aboutToDestroyRemoteUser(*this); }
d->disconnect();
}
Id RemoteUser::id() const
{
return d->id;
}
String RemoteUser::name() const
{
return d->name;
}
Socket *RemoteUser::takeSocket()
{
Socket *sock = d->socket;
sock->audienceForMessage() -= d;
sock->audienceForStateChange() -= d;
d->socket = nullptr;
d->state = Disconnected; // not signaled
return sock;
}
void RemoteUser::send(const IByteArray &data)
{
if (d->state != Disconnected && d->socket->isOpen())
{
d->socket->send(data);
}
}
void RemoteUser::handleIncomingPackets()
{
LOG_AS("RemoteUser");
for (;;)
{
std::unique_ptr<Message> packet(d->socket->receive());
if (!packet) break;
switch (d->state)
{
case Unjoined:
// Let's see if it is a command we recognize.
if (!d->handleRequest(*packet)) return;
break;
case Joined: {
/// @todo The incoming packets should go through a de::Protocol and
/// be handled immediately.
// Post the data into the queue.
netmessage_t *msg = (netmessage_t *) M_Calloc(sizeof(netmessage_t));
msg->sender = d->id;
msg->data = new byte[packet->size()];
memcpy(msg->data, packet->data(), packet->size());
msg->size = packet->size();
msg->handle = msg->data; // needs delete[]
// The message queue will handle the message from now on.
N_PostMessage(msg);
break; }
default:
// Ignore the message.
break;
}
}
}
void RemoteUser::socketDisconnected()
{
d->state = Disconnected;
d->notifyClientExit();
trash(this);
}
bool RemoteUser::isJoined() const
{
return d->state == Joined;
}