2 * Copyright (C) 2005-2013 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /// \addtogroup realmd Realm Daemon
24 #include "Database/DatabaseEnv.h"
25 #include "RealmList.h"
27 #include "Config/Config.h"
29 #include "AuthSocket.h"
30 #include "SystemConfig.h"
32 #include "revision_nr.h"
33 #include "revision_sql.h"
35 #include <openssl/opensslv.h>
36 #include <openssl/crypto.h>
38 #include <ace/Get_Opt.h>
39 #include <ace/Dev_Poll_Reactor.h>
40 #include <ace/TP_Reactor.h>
42 #include <ace/Acceptor.h>
43 #include <ace/SOCK_Acceptor.h>
46 #include "ServiceWin32.h"
47 char serviceName
[] = "realmd";
48 char serviceLongName
[] = "MaNGOS realmd service";
49 char serviceDescription
[] = "Massive Network Game Object Server";
51 * -1 - not in service mode
56 int m_ServiceStatus
= -1;
58 #include "PosixDaemon.h"
65 bool stopEvent
= false; ///< Setting it to true stops the server
67 DatabaseType LoginDatabase
; ///< Accessor to the realm server database
69 /// Print out the usage string for this program on the console.
70 void usage(const char* prog
)
72 sLog
.outString("Usage: \n %s [<options>]\n"
73 " -v, --version print version and exist\n\r"
74 " -c config_file use config_file as configuration file\n\r"
76 " Running as service functions:\n\r"
77 " -s run run as service\n\r"
78 " -s install install service\n\r"
79 " -s uninstall uninstall service\n\r"
81 " Running as daemon functions:\n\r"
82 " -s run run as daemon\n\r"
83 " -s stop stop daemon\n\r"
88 /// Launch the realm server
89 extern int main(int argc
, char** argv
)
91 ///- Command line parsing
92 char const* cfg_file
= _REALMD_CONFIG
;
94 char const* options
= ":c:s:";
96 ACE_Get_Opt
cmd_opts(argc
, argv
, options
);
97 cmd_opts
.long_option("version", 'v');
99 char serviceDaemonMode
= '\0';
102 while ((option
= cmd_opts()) != EOF
)
107 cfg_file
= cmd_opts
.opt_arg();
110 printf("%s\n", _FULLVERSION(REVISION_DATE
, REVISION_TIME
, REVISION_NR
, REVISION_ID
));
115 const char* mode
= cmd_opts
.opt_arg();
117 if (!strcmp(mode
, "run"))
118 serviceDaemonMode
= 'r';
120 else if (!strcmp(mode
, "install"))
121 serviceDaemonMode
= 'i';
122 else if (!strcmp(mode
, "uninstall"))
123 serviceDaemonMode
= 'u';
125 else if (!strcmp(mode
, "stop"))
126 serviceDaemonMode
= 's';
130 sLog
.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts
.opt_opt(), mode
);
132 Log::WaitBeforeContinueIfNeed();
138 sLog
.outError("Runtime-Error: -%c option requires an input argument", cmd_opts
.opt_opt());
140 Log::WaitBeforeContinueIfNeed();
143 sLog
.outError("Runtime-Error: bad format of commandline arguments");
145 Log::WaitBeforeContinueIfNeed();
150 #ifdef WIN32 // windows service command need execute before config read
151 switch (serviceDaemonMode
)
154 if (WinServiceInstall())
155 sLog
.outString("Installing service");
158 if (WinServiceUninstall())
159 sLog
.outString("Uninstalling service");
167 if (!sConfig
.SetSource(cfg_file
))
169 sLog
.outError("Could not find configuration file %s.", cfg_file
);
170 Log::WaitBeforeContinueIfNeed();
174 #ifndef WIN32 // posix daemon commands need apply after config read
175 switch (serviceDaemonMode
)
188 sLog
.outString("%s [realm-daemon]", _FULLVERSION(REVISION_DATE
, REVISION_TIME
, REVISION_NR
, REVISION_ID
));
189 sLog
.outString("<Ctrl-C> to stop.\n");
190 sLog
.outString("Using configuration file %s.", cfg_file
);
192 ///- Check the version of the configuration file
193 uint32 confVersion
= sConfig
.GetIntDefault("ConfVersion", 0);
194 if (confVersion
< _REALMDCONFVERSION
)
196 sLog
.outError("*****************************************************************************");
197 sLog
.outError(" WARNING: Your realmd.conf version indicates your conf file is out of date!");
198 sLog
.outError(" Please check for updates, as your current default values may cause");
199 sLog
.outError(" strange behavior.");
200 sLog
.outError("*****************************************************************************");
201 Log::WaitBeforeContinueIfNeed();
204 DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT
, SSLeay_version(SSLEAY_VERSION
));
205 if (SSLeay() < 0x009080bfL
)
207 DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
208 DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
211 DETAIL_LOG("Using ACE: %s", ACE_VERSION
);
213 #if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
214 ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
216 ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
219 sLog
.outBasic("Max allowed open files is %d", ACE::max_handles());
221 /// realmd PID file creation
222 std::string pidfile
= sConfig
.GetStringDefault("PidFile", "");
223 if (!pidfile
.empty())
225 uint32 pid
= CreatePIDFile(pidfile
);
228 sLog
.outError("Cannot create PID file %s.\n", pidfile
.c_str());
229 Log::WaitBeforeContinueIfNeed();
233 sLog
.outString("Daemon PID: %u\n", pid
);
236 ///- Initialize the database connection
239 Log::WaitBeforeContinueIfNeed();
243 ///- Get the list of realms for the server
244 sRealmList
.Initialize(sConfig
.GetIntDefault("RealmsStateUpdateDelay", 20));
245 if (sRealmList
.size() == 0)
247 sLog
.outError("No valid realms specified.");
248 Log::WaitBeforeContinueIfNeed();
253 // set expired bans to inactive
254 LoginDatabase
.BeginTransaction();
255 LoginDatabase
.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
256 LoginDatabase
.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
257 LoginDatabase
.CommitTransaction();
259 ///- Launch the listening network socket
260 ACE_Acceptor
<AuthSocket
, ACE_SOCK_Acceptor
> acceptor
;
262 uint16 rmport
= sConfig
.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT
);
263 std::string bind_ip
= sConfig
.GetStringDefault("BindIP", "0.0.0.0");
265 ACE_INET_Addr
bind_addr(rmport
, bind_ip
.c_str());
267 if (acceptor
.open(bind_addr
, ACE_Reactor::instance(), ACE_NONBLOCK
) == -1)
269 sLog
.outError("MaNGOS realmd can not bind to %s:%d", bind_ip
.c_str(), rmport
);
270 Log::WaitBeforeContinueIfNeed();
274 ///- Catch termination signals
277 ///- Handle affinity for multiple processors and process priority on Windows
280 HANDLE hProcess
= GetCurrentProcess();
282 uint32 Aff
= sConfig
.GetIntDefault("UseProcessors", 0);
288 if (GetProcessAffinityMask(hProcess
, &appAff
, &sysAff
))
290 ULONG_PTR curAff
= Aff
& appAff
; // remove non accessible processors
294 sLog
.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff
, appAff
);
298 if (SetProcessAffinityMask(hProcess
, curAff
))
299 sLog
.outString("Using processors (bitmask, hex): %x", curAff
);
301 sLog
.outError("Can't set used processors (hex): %x", curAff
);
307 bool Prio
= sConfig
.GetBoolDefault("ProcessPriority", false);
311 if (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
))
312 sLog
.outString("realmd process priority class set to HIGH");
314 sLog
.outError("Can't set realmd process priority class.");
320 // server has started up successfully => enable async DB requests
321 LoginDatabase
.AllowAsyncTransactions();
323 // maximum counter for next ping
324 uint32 numLoops
= (sConfig
.GetIntDefault("MaxPingTime", 30) * (MINUTE
* 1000000 / 100000));
325 uint32 loopCounter
= 0;
330 ///- Wait for termination signal
333 // dont move this outside the loop, the reactor will modify it
334 ACE_Time_Value
interval(0, 100000);
336 if (ACE_Reactor::instance()->run_reactor_event_loop(interval
) == -1)
339 if ((++loopCounter
) == numLoops
)
342 DETAIL_LOG("Ping MySQL to keep connection alive");
343 LoginDatabase
.Ping();
346 if (m_ServiceStatus
== 0) stopEvent
= true;
347 while (m_ServiceStatus
== 2) Sleep(1000);
351 ///- Wait for the delay thread to exit
352 LoginDatabase
.HaltDelayThread();
354 ///- Remove signal handling before leaving
357 sLog
.outString("Halting process...");
361 /// Handle termination signals
362 /** Put the global variable stopEvent to 'true' if a termination signal is caught **/
381 /// Initialize connection to the database
384 std::string dbstring
= sConfig
.GetStringDefault("LoginDatabaseInfo", "");
385 if (dbstring
.empty())
387 sLog
.outError("Database not specified");
391 sLog
.outString("Login Database total connections: %i", 1 + 1);
393 if (!LoginDatabase
.Initialize(dbstring
.c_str()))
395 sLog
.outError("Cannot connect to database");
399 if (!LoginDatabase
.CheckRequiredField("realmd_db_version", REVISION_DB_REALMD
))
401 ///- Wait for already started DB delay threads to end
402 LoginDatabase
.HaltDelayThread();
409 /// Define hook 'OnSignal' for all termination signals
412 signal(SIGINT
, OnSignal
);
413 signal(SIGTERM
, OnSignal
);
415 signal(SIGBREAK
, OnSignal
);
419 /// Unhook the signals before leaving