-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
467 lines (441 loc) · 14.3 KB
/
server.cpp
File metadata and controls
467 lines (441 loc) · 14.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
Game server for Alien Front Online.
Copyright (C) 2025 Flyinghead
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 3 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 <https://www.gnu.org/licenses/>.
*/
#include "log.h"
#include "http.h"
#include "game.h"
#include "tomcrypt.h"
#include "db.h"
#include <dcserver/status.hpp>
#include <unordered_map>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
static std::unordered_map<std::string, std::string> Config;
static void replyNotFound(const Request& request, Reply& reply) {
WARN_LOG("CGI not found: %s [%s]", request.uri.c_str(), request.content.c_str());
reply = Reply::stockReply(Reply::not_found);
}
static std::vector<uint8_t> hexStringToBytes(const std::string &s)
{
std::vector<uint8_t> v;
v.reserve(s.length() / 2);
for (std::size_t pos = 0; pos < s.length() - 1; pos += 2)
{
int n;
if (sscanf(&s[pos], "%02x", &n) != 1) {
ERROR_LOG("Invalid hex string %s", s.c_str());
v.clear();
break;
}
v.push_back(n);
}
return v;
}
static const unsigned char NaomiKey[] = { 0x01, 0xD3, 0xB4, 0x90, 0xAB, 0x32, 0x2D, 0xC7 };
static const unsigned char DreamcastKey[] = { 0xd4, 0x61, 0xdb, 0x19, 0x4a, 0x30, 0x17, 0xbc };
static std::string decrypt(const std::string& hex, const unsigned char *key)
{
std::vector<uint8_t> ciphered = hexStringToBytes(hex);
symmetric_key skey;
rc5_setup(key, sizeof(DreamcastKey), 0, &skey);
std::vector<uint8_t> plain;
plain.resize(ciphered.size());
for (size_t i = 0; i < ciphered.size(); i += 8)
rc5_ecb_decrypt(ciphered.data() + i, plain.data() + i, &skey);
rc5_done(&skey);
return std::string((char *)&plain[0], (char *)&plain[plain.size()]);
}
static std::string descramble(const std::string& cs)
{
std::vector<uint8_t> data = hexStringToBytes(cs);
std::string ps;
ps.reserve(data.size());
for (uint8_t c : data)
ps.push_back((char)~((c >> 5) | (c << 3)));
return ps;
}
static std::vector<std::string> splitParams(const std::string& s)
{
std::vector<std::string> params;
size_t start = 0;
for (;;)
{
size_t end = s.find('&', start);
if (end == s.npos) {
params.push_back(s.substr(start));
break;
}
else {
params.push_back(s.substr(start, end - start));
start = end + 1;
}
}
return params;
}
static void handleHighScoreRequest(const Request& request, Reply& reply)
{
DEBUG_LOG("ranking.cgi: [%s]", request.content.c_str());
if (request.content.substr(0, 10) == "request=1 ")
{
// Naomi: Register new high score
std::string s = request.content.substr(10);
std::string plain = decrypt(s, NaomiKey);
DEBUG_LOG("New Naomi high score: %s", plain.c_str());
std::vector<std::string> params = splitParams(plain);
if (params.size() >= 6)
{
try {
registerNewScore(atol(params[5].c_str()), params[0], params[1], params[2], params[3]);
reply = Reply::stockReply(Reply::ok);
} catch (const std::runtime_error& e) {
ERROR_LOG("Naomi high score registration failed: %s", e.what());
reply = Reply::stockReply(Reply::internal_server_error);
}
}
return;
}
if (request.content == "request=2")
{
// Naomi: Return top 10 players
// TODO DC: unknown usage. No content in request.
try {
std::string scores = getTop10Scores();
std::for_each(scores.begin(), scores.end(), [](char &c) { c = std::toupper((unsigned char)c); });
reply.setContent("***" + scores + "&&&");
} catch (const std::runtime_error& e) {
ERROR_LOG("Naomi high score fetch failed: %s", e.what());
reply = Reply::stockReply(Reply::internal_server_error);
}
return;
}
if (request.content.substr(0, 10) == "request=3 ")
{
// DC: Register new high score (if any) and fetch the top 10
// example: &000000000000&0.0.0.0&0&1 (no high score)
// or FLY2&000000000000&192.168.167.2&210000&3 (FLY2, player ID 000000000000 score 210000, from IP 192.168.167.2)
std::string s = request.content.substr(10);
std::string plain = decrypt(s, DreamcastKey);
DEBUG_LOG("New DC high score: %s", plain.c_str());
std::vector<std::string> params = splitParams(plain);
if (params.size() >= 4)
{
try {
registerNewDcScore(atol(params[3].c_str()), params[0]);
} catch (const std::runtime_error& e) {
ERROR_LOG("DC high score registration failed: %s", e.what());
}
}
try {
reply.setContent("***" + getTop10Scores() + "&&&");
} catch (const std::runtime_error& e) {
ERROR_LOG("DC high score fetch failed: %s", e.what());
reply = Reply::stockReply(Reply::internal_server_error);
}
return;
}
replyNotFound(request, reply);
}
class ServerImpl : public Server
{
public:
ServerImpl(asio::io_context& io_context, const std::string& serverIp,
uint16_t portMin = 9400, uint16_t portMax = 9419)
: io_context(io_context), serverIp(serverIp),
signals(io_context), httpServer(io_context, "0.0.0.0", 8080),
statusTimer(io_context)
{
signals.add(SIGINT);
signals.add(SIGTERM);
#if defined(SIGQUIT)
signals.add(SIGQUIT);
#endif
signals.async_wait(
[this](std::error_code /*ec*/, int /*signo*/)
{
this->io_context.stop();
});
for (uint16_t port = portMin; port <= portMax; port++)
ports.push_back(port);
// alienfnt: Server2/NaomiNetwork/CGI/Watch
// Server2/NaomiNetwork/CGI/SampleCGI4
// Server2/NaomiNetwork/CGI/RankingSys/ranking.cgi
httpServer.addCgiHandler("Server2/NaomiNetwork/CGI/RankingSys/ranking.cgi", handleHighScoreRequest);
httpServer.addCgiHandler("Server2/NaomiNetwork/CGI/Watch",
[this](const Request& request, Reply& reply)
{
DEBUG_LOG("/NaomiNetwork/CGI/Watch: [%s]", request.content.c_str());
// Data1=s:s:i:s:s:s:s:c:c:c:c 04 00 81 00 48 00 00 00 02 00 10 00 0f 00 f4 01 01 fe fd fc
// close to Data1 param of AFODC: unknown
// Data2=c 00
// Data3=c*8:c:c:c:c:s:s fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
std::vector<std::string> params = splitParams(request.content);
for (const std::string& param : params)
{
size_t pos = param.find('=');
if (pos == param.npos)
continue;
std::string plain = descramble(param.substr(pos + 1));
fprintf(stderr, "%s=", param.substr(0, pos).c_str());
pos = plain.find('\0');
if (pos == plain.npos)
fprintf(stderr, "null char not found\n");
else
{
fprintf(stderr, "%s ", plain.substr(0, pos).c_str());
pos++;
dumpData((uint8_t *)&plain[pos], plain.length() - pos);
}
}
std::string replyContent;
for (const auto& game : games)
replyContent += game->getHttpDesc(false) + " GAMEDONE\n";
reply.setContent(replyContent + "END\n");
});
httpServer.addCgiHandler("Server2/NaomiNetwork/CGI/SampleCGI4",
[this](const Request& request, Reply& reply)
{
DEBUG_LOG("/NaomiNetwork/CGI/SampleCGI4: [%s]", request.content.c_str());
reply.setContent("END\n");
});
// afo: AFODC/RankingSys/ranking.cgi
// AFODC/CGI/AFODCCGI
httpServer.addCgiHandler("AFODC/RankingSys/ranking.cgi", handleHighScoreRequest);
httpServer.addCgiHandler("AFODC/CGI/AFODCCGI",
[this](const Request& request, Reply& reply)
{
this->handleHttpRequest(request, reply);
});
onStatusTimer({});
}
void deleteGame(Game::Ptr game) override
{
for (size_t i = 0; i < games.size(); i++)
if (game == games[i])
{
ports.push_back(game->getIpPort());
games.erase(games.begin() + i);
return;
}
ERROR_LOG("Server::deleteGame game %s [port %d] not found", game->getName().c_str(), game->getIpPort());
}
private:
static std::vector<std::string> splitParams(const std::string& str)
{
std::vector<std::string> params;
for (size_t pos = 0; pos < str.length();)
{
size_t end = str.find(' ', pos);
if (end == std::string::npos)
end = str.length();
if (end - pos >= 2)
params.push_back(str.substr(pos, end - pos));
pos = end + 1;
}
return params;
}
void handleHttpRequest(const Request& request, Reply& reply)
{
DEBUG_LOG("AFODCCGI: [%s]", request.content.c_str());
int reqType = -1;
int gamePort = -1;
std::string playerName;
std::string replyContent;
std::vector<std::string> params = splitParams(request.content);
for (auto& param : params)
{
if (param.substr(0, 4) == "PID=")
{
// Player ID (6 bytes). Also sent as param #2 when registering a new high score. TODO how do you get one?
//std::string value = descramble(param.substr(4));
//if (value.substr(0, 4) == "c*18")
// DEBUG_LOG("PID=%s", value.substr(5).c_str());
}
else if (param.substr(0, 8) == "Request=")
{
std::string value = descramble(param.substr(8));
if (value[0] == 'c' && value[1] == '\0') {
reqType = value[2];
DEBUG_LOG("Request=%d", reqType);
}
else {
WARN_LOG("*** Unrecognized request: %s", value.c_str());
}
}
else if (param.substr(0, 6) == "Data2=")
{
std::string value = descramble(param.substr(6));
if (value.substr(0, 7) == "i:s:c:c")
gamePort = (value[12] & 0xff) + (value[13] & 0xff) * 0x100;
}
else if (param.substr(0, 6) == "Data3=" && reqType == 2)
{
std::string value = descramble(param.substr(6));
if (value.substr(0, 17) == "c*8:c:c:c:c:s:c:c" && value[17] == '\0')
{
playerName = &value[18];
DEBUG_LOG("Player: %s (%x %x %x %x %x %x %x)", playerName.c_str(),
value[26] & 0xff, value[27] & 0xff, value[28] & 0xff, value[29] & 0xff,
(value[30] & 0xff) + (value[31] & 0xff) * 256, value[32] & 0xff, value[33] & 0xff);
}
}
else if (param.substr(0, 6) == "Data4=" && reqType == 2)
{
std::string value = descramble(param.substr(6));
if (value.substr(0, 16) == "c*16:i:i:c*8:c*8" && value[16] == '\0')
{
std::string gameName = &value[17];
unsigned gameType, maps;
memcpy(&gameType, &value[33], 4);
memcpy(&maps, &value[37], 4);
std::array<Game::SlotType, 8> slots;
memcpy(slots.data(), &value[41], sizeof(slots));
std::array<uint8_t, 8> sides;
memcpy(sides.data(), &value[49], sizeof(sides));
Game::Ptr game = Game::create(*this, io_context, serverIp, ports.back());
ports.pop_back();
game->setName(gameName);
game->setType((Game::GameType)gameType);
game->setMaps(maps);
game->setSlots(slots);
games.push_back(game);
game->start();
replyContent += game->getHttpDesc(false);
DEBUG_LOG("Create game: %s", replyContent.c_str());
replyContent += "\nCREATED\nGAMEDONE\n";
break;
}
}
}
if (reqType == -1) {
replyNotFound(request, reply);
return;
}
if (reqType == 0)
{
for (const auto& game : games)
replyContent += game->getHttpDesc(false) + " GAMEDONE\n";
// replyContent += "Address=146.185.135.179 Port=9407 Response=20 GameName=War is Hell GameType=3 Maps=63 "
// "Slots=2 0 255 255 0 0 255 255 Sides=0 0 0 0 1 1 1 1 GAMEDONE\n"
// "Address=146.185.135.179 Port=9408 Response=20 GameName=Alien Fest GameType=1 Maps=63 "
// "Slots=2 0 255 255 2 0 255 255 Sides=0 0 0 0 1 1 1 1 GAMEDONE\n";
}
else if (reqType == 1)
{
for (const auto& game : games)
if (game->getIpPort() == gamePort) {
replyContent += game->getHttpDesc(true) + "\nGAMEDONE\n";
break;
}
}
reply.setContent(replyContent + "END\n");
}
void onStatusTimer(const std::error_code& ec)
{
if (ec)
return;
int gameCount = games.size();
int playerCount = 0;
for (auto game : games)
{
for (int i = 0; i < 8; i++) {
if (game->getPlayer(i) != nullptr)
++playerCount;
}
}
statusUpdate("afo", playerCount, gameCount);
try {
statusCommit("afo");
} catch (const std::exception& e) {
ERROR_LOG("statusCommit failed: %s", e.what());
}
statusTimer.expires_at(asio::chrono::steady_clock::now() + asio::chrono::seconds(statusGetInterval()));
statusTimer.async_wait(std::bind(&ServerImpl::onStatusTimer, this, asio::placeholders::error));
}
private:
asio::io_context& io_context;
std::string serverIp;
/// The signal_set is used to register for process termination notifications.
asio::signal_set signals;
HttpServer httpServer;
asio::steady_timer statusTimer;
std::vector<Game::Ptr> games;
std::vector<uint16_t> ports;
};
static void loadConfig(const std::string& path)
{
std::filebuf fb;
if (!fb.open(path, std::ios::in)) {
ERROR_LOG("config file %s not found", path.c_str());
return;
}
std::istream istream(&fb);
std::string line;
while (std::getline(istream, line))
{
if (line.empty() || line[0] == '#')
continue;
auto pos = line.find_first_of("=:");
if (pos != std::string::npos)
Config[line.substr(0, pos)] = line.substr(pos + 1);
else
ERROR_LOG("config file syntax error: %s", line.c_str());
}
}
std::string getConfig(const std::string& name, const std::string& default_value = "")
{
auto it = Config.find(name);
if (it == Config.end())
return default_value;
else
return it->second;
}
int main(int argc, char *argv[])
{
setvbuf(stdout, nullptr, _IOLBF, BUFSIZ);
if (argc > 2) {
fprintf(stderr, "Usage: %s [<config file path>]\n", argv[0]);
return 1;
}
loadConfig(argc < 2 ? "afo.cfg" : argv[1]);
try {
setDatabasePath(getConfig("DatabasePath", LOCALSTATEDIR "/lib/afo/afo.db"));
} catch (const std::exception& e) {
fprintf(stderr, "Database error: %s\n", e.what());
return 1;
}
std::string serverIp = getConfig("ServerIP", "127.0.0.1");
std::string serverPorts = getConfig("ServerPorts", "9400-9419");
size_t pos = serverPorts.find('-');
uint16_t portMin = 9400;
uint16_t portMax = 9419;
if (pos != std::string::npos)
{
portMin = atoi(serverPorts.substr(0, pos).c_str());
portMax = atoi(serverPorts.substr(pos + 1).c_str());
}
NOTICE_LOG("Alien Front Online server started");
NOTICE_LOG("Server IP %s TCP ports %d-%d UDP ports %d-%d", serverIp.c_str(), portMin, portMax, portMin + 1, portMax + 1);
try {
asio::io_context io_context;
ServerImpl server(io_context, serverIp, portMin, portMax);
io_context.run();
}
catch (const std::exception& e) {
ERROR_LOG("Fatal exception: %s", e.what());
}
NOTICE_LOG("Alien Front Online server stopped");
}