-
Notifications
You must be signed in to change notification settings - Fork 31
/
Main.cpp
493 lines (429 loc) · 14.6 KB
/
Main.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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2023 MaNGOS <https://getmangos.eu>
*
* 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,r
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/// \addtogroup realmd Realm Daemon
/// @{
/// \file
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "Realm/RealmList.h"
#include "Config/Config.h"
#include "GitRevision.h"
#include "Log.h"
#include "Auth/AuthSocket.h"
#include "SystemConfig.h"
#include "revision_data.h"
#include "Util.h"
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
# include <openssl/provider.h>
#endif
#include <ace/Get_Opt.h>
#include <ace/Dev_Poll_Reactor.h>
#include <ace/TP_Reactor.h>
#include <ace/ACE.h>
#include <ace/Acceptor.h>
#include <ace/SOCK_Acceptor.h>
#ifdef WIN32
#include "ServiceWin32.h"
char serviceName[] = "realmd";
char serviceLongName[] = "MaNGOS realmd service";
char serviceDescription[] = "Massive Network Game Object Server";
/*
* -1 - not in service mode
* 0 - stopped
* 1 - running
* 2 - paused
*/
int m_ServiceStatus = -1;
#else
#include "PosixDaemon.h"
#endif
bool StartDB();
void UnhookSignals();
void HookSignals();
bool stopEvent = false; ///< Setting it to true stops the server
DatabaseType LoginDatabase; ///< Accessor to the realm server database
/// Print out the usage string for this program on the console.
void usage(const char* prog)
{
sLog.outString("Usage: \n %s [<options>]\n"
" -v, --version print version and exist\n\r"
" -c config_file use config_file as configuration file\n\r"
#ifdef WIN32
" Running as service functions:\n\r"
" -s run run as service\n\r"
" -s install install service\n\r"
" -s uninstall uninstall service\n\r"
#else
" Running as daemon functions:\n\r"
" -s run run as daemon\n\r"
" -s stop stop daemon\n\r"
#endif
, prog);
}
/// Launch the realm server
extern int main(int argc, char** argv)
{
///- Command line parsing
char const* cfg_file = REALMD_CONFIG_LOCATION;
char const* options = ":c:s:";
ACE_Get_Opt cmd_opts(argc, argv, options);
cmd_opts.long_option("version", 'v');
char serviceDaemonMode = '\0';
int option;
while ((option = cmd_opts()) != EOF)
{
switch (option)
{
case 'c':
cfg_file = cmd_opts.opt_arg();
break;
case 'v':
printf("%s\n", GitRevision::GetProjectRevision());
return 0;
case 's':
{
const char* mode = cmd_opts.opt_arg();
if (!strcmp(mode, "run"))
{
serviceDaemonMode = 'r';
}
#ifdef WIN32
else if (!strcmp(mode, "install"))
{
serviceDaemonMode = 'i';
}
else if (!strcmp(mode, "uninstall"))
{
serviceDaemonMode = 'u';
}
#else
else if (!strcmp(mode, "stop"))
{
serviceDaemonMode = 's';
}
#endif
else
{
sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
}
break;
}
case ':':
sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
default:
sLog.outError("Runtime-Error: bad format of commandline arguments");
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
}
}
#ifdef WIN32 // windows service command need execute before config read
switch (serviceDaemonMode)
{
case 'i':
if (WinServiceInstall())
{
sLog.outString("Installing service");
}
return 1;
case 'u':
if (WinServiceUninstall())
{
sLog.outString("Uninstalling service");
}
return 1;
case 'r':
WinServiceRun();
break;
}
#endif
if (!sConfig.SetSource(cfg_file))
{
sLog.outError("Could not find configuration file %s.", cfg_file);
Log::WaitBeforeContinueIfNeed();
return 1;
}
#ifndef WIN32 // posix daemon commands need apply after config read
switch (serviceDaemonMode)
{
case 'r':
startDaemon();
break;
case 's':
stopDaemon();
break;
}
#endif
sLog.Initialize();
sLog.outString("%s [realm-daemon]", GitRevision::GetProjectRevision());
sLog.outString("%s", GitRevision::GetFullRevision());
sLog.outString("<Ctrl-C> to stop.\n");
sLog.outString("Using configuration file %s.", cfg_file);
///- Check the version of the configuration file
uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
if (confVersion < REALMD_CONFIG_VERSION)
{
sLog.outError("*****************************************************************************");
sLog.outError(" WARNING: Your realmd.conf version indicates your conf file is out of date!");
sLog.outError(" Please check for updates, as your current default values may cause");
sLog.outError(" strange behavior.");
sLog.outError("*****************************************************************************");
Log::WaitBeforeContinueIfNeed();
}
DETAIL_LOG("Using SSL version: %s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
OSSL_PROVIDER* legacy;
OSSL_PROVIDER* deflt;
/* Load Multiple providers into the default (NULL) library context */
legacy = OSSL_PROVIDER_load(NULL, "legacy");
if (legacy == NULL)
{
sLog.outError("Failed to load OpenSSL 3.x Legacy provider\n");
#ifdef WIN32
sLog.outError("\nPlease check you have set the following Enviroment Varible:\n");
sLog.outError("OPENSSL_MODULES=C:\\OpenSSL-Win64\\bin\n");
sLog.outError("(where C:\\OpenSSL-Win64\\bin is the location you installed OpenSSL\n");
#endif
Log::WaitBeforeContinueIfNeed();
return 0;
}
deflt = OSSL_PROVIDER_load(NULL, "default");
if (deflt == NULL)
{
sLog.outError("Failed to load OpenSSL 3.x Default provider\n");
OSSL_PROVIDER_unload(legacy);
Log::WaitBeforeContinueIfNeed();
return 0;
}
#else
if (SSLeay() < 0x10100000L || SSLeay() > 0x10200000L)
{
DETAIL_LOG("WARNING: OpenSSL version may be out of date or unsupported. Logins to server may not work!");
DETAIL_LOG("WARNING: Minimal required version [OpenSSL 1.1.x] and Maximum supported version [OpenSSL 1.2]");
}
#endif
DETAIL_LOG("Using ACE: %s", ACE_VERSION);
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif
sLog.outBasic("Max allowed open files is %d", ACE::max_handles());
/// realmd PID file creation
std::string pidfile = sConfig.GetStringDefault("PidFile", "");
if (!pidfile.empty())
{
uint32 pid = CreatePIDFile(pidfile);
if (!pid)
{
sLog.outError("Can not create PID file %s.\n", pidfile.c_str());
Log::WaitBeforeContinueIfNeed();
return 1;
}
sLog.outString("Daemon PID: %u\n", pid);
}
///- Initialize the database connection
if (!StartDB())
{
Log::WaitBeforeContinueIfNeed();
return 1;
}
///- Get the list of realms for the server
sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
if (sRealmList.size() == 0)
{
sLog.outError("No valid realms specified.");
Log::WaitBeforeContinueIfNeed();
return 1;
}
// cleanup query
// set expired bans to inactive
LoginDatabase.BeginTransaction();
LoginDatabase.Execute("UPDATE `account_banned` SET `active` = 0 WHERE `unbandate`<=UNIX_TIMESTAMP() AND `unbandate`<>`bandate`");
LoginDatabase.Execute("DELETE FROM `ip_banned` WHERE `unbandate`<=UNIX_TIMESTAMP() AND `unbandate`<>`bandate`");
LoginDatabase.CommitTransaction();
///- Launch the listening network socket
ACE_Acceptor<AuthSocket, ACE_SOCK_Acceptor> acceptor;
uint16 rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");
ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());
if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
{
sLog.outError("MaNGOS realmd can not bind to %s:%d", bind_ip.c_str(), rmport);
Log::WaitBeforeContinueIfNeed();
return 1;
}
///- Catch termination signals
HookSignals();
///- Handle affinity for multiple processors and process priority on Windows
#ifdef WIN32
{
HANDLE hProcess = GetCurrentProcess();
uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
if (Aff > 0)
{
ULONG_PTR appAff;
ULONG_PTR sysAff;
if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
{
ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
if (!curAff)
{
sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff, appAff);
}
else
{
if (SetProcessAffinityMask(hProcess, curAff))
{
sLog.outString("Using processors (bitmask, hex): %x", curAff);
}
else
{
sLog.outError("Can't set used processors (hex): %x", curAff);
}
}
}
sLog.outString();
}
bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
if (Prio)
{
if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
{
sLog.outString("realmd process priority class set to HIGH");
}
else
{
sLog.outError("Can't set realmd process priority class.");
}
sLog.outString();
}
}
#endif
// server has started up successfully => enable async DB requests
LoginDatabase.AllowAsyncTransactions();
// maximum counter for next ping
uint32 numLoops = (sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
uint32 loopCounter = 0;
#ifndef WIN32
detachDaemon();
#endif
///- Wait for termination signal
while (!stopEvent)
{
// dont move this outside the loop, the reactor will modify it
ACE_Time_Value interval(0, 100000);
if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
{
break;
}
if ((++loopCounter) == numLoops)
{
loopCounter = 0;
DETAIL_LOG("Ping MySQL to keep connection alive");
LoginDatabase.Ping();
}
#ifdef WIN32
if (m_ServiceStatus == 0)
{
stopEvent = true;
}
while (m_ServiceStatus == 2) { Sleep(1000); }
#endif
}
///- Wait for the delay thread to exit
LoginDatabase.HaltDelayThread();
///- Remove signal handling before leaving
UnhookSignals();
sLog.outString("Halting process...");
return 0;
}
/// Handle termination signals
/** Put the global variable stopEvent to 'true' if a termination signal is caught **/
void OnSignal(int s)
{
switch (s)
{
case SIGINT:
case SIGTERM:
stopEvent = true;
break;
#ifdef _WIN32
case SIGBREAK:
stopEvent = true;
break;
#endif
}
signal(s, OnSignal);
}
/// Initialize connection to the database
bool StartDB()
{
std::string dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if (dbstring.empty())
{
sLog.outError("Database not specified");
return false;
}
sLog.outString("Login Database total connections: %i", 1 + 1);
if (!LoginDatabase.Initialize(dbstring.c_str()))
{
sLog.outError("Can not connect to database");
return false;
}
if (!LoginDatabase.CheckDatabaseVersion(DATABASE_REALMD))
{
///- Wait for already started DB delay threads to end
LoginDatabase.HaltDelayThread();
return false;
}
return true;
}
/// Define hook 'OnSignal' for all termination signals
void HookSignals()
{
signal(SIGINT, OnSignal);
signal(SIGTERM, OnSignal);
#ifdef _WIN32
signal(SIGBREAK, OnSignal);
#endif
}
/// Unhook the signals before leaving
void UnhookSignals()
{
signal(SIGINT, 0);
signal(SIGTERM, 0);
#ifdef _WIN32
signal(SIGBREAK, 0);
#endif
}
/// @}