Merge pull request #179 from woogerboy21/registered-user-only-server

Registered Only Server
This commit is contained in:
Gavin Bisesi 2014-08-11 09:03:57 -04:00
commit 5c46cfc169
7 changed files with 319 additions and 300 deletions

View file

@ -1,4 +1,4 @@
/*************************************************************************** /***************************************************************************
* Copyright (C) 2008 by Max-Wilhelm Bruker * * Copyright (C) 2008 by Max-Wilhelm Bruker *
* brukie@gmx.net * * brukie@gmx.net *
* * * *
@ -225,8 +225,6 @@ void MainWindow::actAbout()
+ tr("French:") + " Yannick Hammer, Arnaud Faes<br>" + tr("French:") + " Yannick Hammer, Arnaud Faes<br>"
+ tr("Japanese:") + " Nagase Task<br>" + tr("Japanese:") + " Nagase Task<br>"
+ tr("Russian:") + " Alexander Davidov<br>" + tr("Russian:") + " Alexander Davidov<br>"
// + tr("Czech:") + " Ondřej Trhoň<br>"
// + tr("Slovak:") + " Ganjalf Rendy<br>"
+ tr("Italian:") + " Luigi Sciolla<br>" + tr("Italian:") + " Luigi Sciolla<br>"
+ tr("Swedish:") + " Jessica Dahl<br>" + tr("Swedish:") + " Jessica Dahl<br>"
)); ));
@ -261,6 +259,9 @@ void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32
case Response::RespUsernameInvalid: case Response::RespUsernameInvalid:
QMessageBox::critical(this, tr("Error"), tr("Invalid username.")); QMessageBox::critical(this, tr("Error"), tr("Invalid username."));
break; break;
case Response::RespRegistrationRequired:
QMessageBox::critical(this, tr("Error"), tr("This server requires user registration."));
break;
default: default:
QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast<int>(r))); QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast<int>(r)));
} }

View file

@ -23,6 +23,7 @@ message Response {
RespUserIsBanned = 19; RespUserIsBanned = 19;
RespAccessDenied = 20; RespAccessDenied = 20;
RespUsernameInvalid = 21; RespUsernameInvalid = 21;
RespRegistrationRequired = 22;
} }
enum ResponseType { enum ResponseType {
JOIN_ROOM = 1000; JOIN_ROOM = 1000;

View file

@ -34,6 +34,7 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QThread> #include <QThread>
#include <QDebug> #include <QDebug>
#include <QSettings>
Server::Server(bool _threaded, QObject *parent) Server::Server(bool _threaded, QObject *parent)
: QObject(parent), threaded(_threaded), nextLocalGameId(0) : QObject(parent), threaded(_threaded), nextLocalGameId(0)
@ -131,6 +132,14 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
} else if (authState == UnknownUser) { } else if (authState == UnknownUser) {
// Change user name so that no two users have the same names, // Change user name so that no two users have the same names,
// don't interfere with registered user names though. // don't interfere with registered user names though.
QSettings settings("servatrice.ini", QSettings::IniFormat);
bool requireReg = settings.value("authentication/regonly", 0).toBool();
if (requireReg) {
qDebug("Login denied: registration required");
databaseInterface->unlockSessionTables();
return RegistrationRequired;
}
QString tempName = name; QString tempName = name;
int i = 0; int i = 0;
while (users.contains(tempName) || databaseInterface->userExists(tempName) || databaseInterface->userSessionExists(tempName)) while (users.contains(tempName) || databaseInterface->userExists(tempName) || databaseInterface->userSessionExists(tempName))
@ -142,7 +151,7 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
users.insert(name, session); users.insert(name, session);
qDebug() << "Server::loginUser:" << session << "name=" << name; qDebug() << "Server::loginUser:" << session << "name=" << name;
data.set_session_id(databaseInterface->startSession(name, session->getAddress())); data.set_session_id(databaseInterface->startSession(name, session->getAddress()));
databaseInterface->unlockSessionTables(); databaseInterface->unlockSessionTables();
usersBySessionId.insert(data.session_id(), session); usersBySessionId.insert(data.session_id(), session);
@ -478,7 +487,7 @@ void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl
clientsLock.lockForRead(); clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i) for (int i = 0; i < clients.size(); ++i)
if (clients[i]->getAcceptsRoomListChanges()) if (clients[i]->getAcceptsRoomListChanges())
clients[i]->sendProtocolItem(*se); clients[i]->sendProtocolItem(*se);
clientsLock.unlock(); clientsLock.unlock();

View file

@ -27,7 +27,7 @@ class GameEventContainer;
class CommandContainer; class CommandContainer;
class Command_JoinGame; class Command_JoinGame;
enum AuthenticationResult { NotLoggedIn = 0, PasswordRight = 1, UnknownUser = 2, WouldOverwriteOldSession = 3, UserIsBanned = 4, UsernameInvalid = 5 }; enum AuthenticationResult { NotLoggedIn = 0, PasswordRight = 1, UnknownUser = 2, WouldOverwriteOldSession = 3, UserIsBanned = 4, UsernameInvalid = 5, RegistrationRequired = 6 };
class Server : public QObject class Server : public QObject
{ {

View file

@ -345,6 +345,7 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
case NotLoggedIn: return Response::RespWrongPassword; case NotLoggedIn: return Response::RespWrongPassword;
case WouldOverwriteOldSession: return Response::RespWouldOverwriteOldSession; case WouldOverwriteOldSession: return Response::RespWouldOverwriteOldSession;
case UsernameInvalid: return Response::RespUsernameInvalid; case UsernameInvalid: return Response::RespUsernameInvalid;
case RegistrationRequired: return Response::RespRegistrationRequired;
default: authState = res; default: authState = res;
} }

View file

@ -16,6 +16,7 @@ ssl_key=ssl_key.pem
[authentication] [authentication]
method=none method=none
regonly=0
[database] [database]
type=none type=none

View file

@ -38,44 +38,44 @@
#include "pb/event_connection_closed.pb.h" #include "pb/event_connection_closed.pb.h"
Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent) Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent)
: QTcpServer(parent), : QTcpServer(parent),
server(_server) server(_server)
{ {
if (_numberPools == 0) { if (_numberPools == 0) {
server->setThreaded(false); server->setThreaded(false);
Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(0, server); Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(0, server);
Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface); Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface);
server->addDatabaseInterface(thread(), newDatabaseInterface); server->addDatabaseInterface(thread(), newDatabaseInterface);
newDatabaseInterface->initDatabase(_sqlDatabase); newDatabaseInterface->initDatabase(_sqlDatabase);
connectionPools.append(newPool); connectionPools.append(newPool);
} else } else
for (int i = 0; i < _numberPools; ++i) { for (int i = 0; i < _numberPools; ++i) {
Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(i, server); Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(i, server);
Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface); Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface);
QThread *newThread = new QThread; QThread *newThread = new QThread;
newThread->setObjectName("pool_" + QString::number(i)); newThread->setObjectName("pool_" + QString::number(i));
newPool->moveToThread(newThread); newPool->moveToThread(newThread);
newDatabaseInterface->moveToThread(newThread); newDatabaseInterface->moveToThread(newThread);
server->addDatabaseInterface(newThread, newDatabaseInterface); server->addDatabaseInterface(newThread, newDatabaseInterface);
newThread->start(); newThread->start();
QMetaObject::invokeMethod(newDatabaseInterface, "initDatabase", Qt::BlockingQueuedConnection, Q_ARG(QSqlDatabase, _sqlDatabase)); QMetaObject::invokeMethod(newDatabaseInterface, "initDatabase", Qt::BlockingQueuedConnection, Q_ARG(QSqlDatabase, _sqlDatabase));
connectionPools.append(newPool); connectionPools.append(newPool);
} }
} }
Servatrice_GameServer::~Servatrice_GameServer() Servatrice_GameServer::~Servatrice_GameServer()
{ {
for (int i = 0; i < connectionPools.size(); ++i) { for (int i = 0; i < connectionPools.size(); ++i) {
logger->logMessage(QString("Closing pool %1...").arg(i)); logger->logMessage(QString("Closing pool %1...").arg(i));
QThread *poolThread = connectionPools[i]->thread(); QThread *poolThread = connectionPools[i]->thread();
connectionPools[i]->deleteLater(); // pool destructor calls thread()->quit() connectionPools[i]->deleteLater(); // pool destructor calls thread()->quit()
poolThread->wait(); poolThread->wait();
} }
} }
#if QT_VERSION < 0x050000 #if QT_VERSION < 0x050000
@ -84,150 +84,156 @@ void Servatrice_GameServer::incomingConnection(int socketDescriptor)
void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor) void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor)
#endif #endif
{ {
// Determine connection pool with smallest client count // Determine connection pool with smallest client count
int minClientCount = -1; int minClientCount = -1;
int poolIndex = -1; int poolIndex = -1;
QStringList debugStr; QStringList debugStr;
for (int i = 0; i < connectionPools.size(); ++i) { for (int i = 0; i < connectionPools.size(); ++i) {
const int clientCount = connectionPools[i]->getClientCount(); const int clientCount = connectionPools[i]->getClientCount();
if ((poolIndex == -1) || (clientCount < minClientCount)) { if ((poolIndex == -1) || (clientCount < minClientCount)) {
minClientCount = clientCount; minClientCount = clientCount;
poolIndex = i; poolIndex = i;
} }
debugStr.append(QString::number(clientCount)); debugStr.append(QString::number(clientCount));
} }
qDebug() << "Pool utilisation:" << debugStr; qDebug() << "Pool utilisation:" << debugStr;
Servatrice_ConnectionPool *pool = connectionPools[poolIndex]; Servatrice_ConnectionPool *pool = connectionPools[poolIndex];
ServerSocketInterface *ssi = new ServerSocketInterface(server, pool->getDatabaseInterface()); ServerSocketInterface *ssi = new ServerSocketInterface(server, pool->getDatabaseInterface());
ssi->moveToThread(pool->thread()); ssi->moveToThread(pool->thread());
pool->addClient(); pool->addClient();
connect(ssi, SIGNAL(destroyed()), pool, SLOT(removeClient())); connect(ssi, SIGNAL(destroyed()), pool, SLOT(removeClient()));
QMetaObject::invokeMethod(ssi, "initConnection", Qt::QueuedConnection, Q_ARG(int, socketDescriptor)); QMetaObject::invokeMethod(ssi, "initConnection", Qt::QueuedConnection, Q_ARG(int, socketDescriptor));
} }
void Servatrice_IslServer::incomingConnection(int socketDescriptor) void Servatrice_IslServer::incomingConnection(int socketDescriptor)
{ {
QThread *thread = new QThread; QThread *thread = new QThread;
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
IslInterface *interface = new IslInterface(socketDescriptor, cert, privateKey, server); IslInterface *interface = new IslInterface(socketDescriptor, cert, privateKey, server);
interface->moveToThread(thread); interface->moveToThread(thread);
connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); connect(interface, SIGNAL(destroyed()), thread, SLOT(quit()));
thread->start(); thread->start();
QMetaObject::invokeMethod(interface, "initServer", Qt::QueuedConnection); QMetaObject::invokeMethod(interface, "initServer", Qt::QueuedConnection);
} }
Servatrice::Servatrice(QSettings *_settings, QObject *parent) Servatrice::Servatrice(QSettings *_settings, QObject *parent)
: Server(true, parent), settings(_settings), uptime(0), shutdownTimer(0) : Server(true, parent), settings(_settings), uptime(0), shutdownTimer(0)
{ {
qRegisterMetaType<QSqlDatabase>("QSqlDatabase"); qRegisterMetaType<QSqlDatabase>("QSqlDatabase");
} }
Servatrice::~Servatrice() Servatrice::~Servatrice()
{ {
gameServer->close(); gameServer->close();
prepareDestroy(); prepareDestroy();
} }
bool Servatrice::initServer() bool Servatrice::initServer()
{ {
serverName = settings->value("server/name").toString(); serverName = settings->value("server/name").toString();
serverId = settings->value("server/id", 0).toInt(); serverId = settings->value("server/id", 0).toInt();
bool regServerOnly = settings->value("server/regonly", 0).toBool();
const QString authenticationMethodStr = settings->value("authentication/method").toString();
if (authenticationMethodStr == "sql") const QString authenticationMethodStr = settings->value("authentication/method").toString();
authenticationMethod = AuthenticationSql; if (authenticationMethodStr == "sql") {
else authenticationMethod = AuthenticationSql;
authenticationMethod = AuthenticationNone; } else {
if (regServerOnly) {
QString dbTypeStr = settings->value("database/type").toString(); qDebug() << "Registration only server enabled but no DB Connection : Error.";
if (dbTypeStr == "mysql") return false;
databaseType = DatabaseMySql; }
else authenticationMethod = AuthenticationNone;
databaseType = DatabaseNone; }
servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this); QString dbTypeStr = settings->value("database/type").toString();
setDatabaseInterface(servatriceDatabaseInterface); if (dbTypeStr == "mysql")
databaseType = DatabaseMySql;
if (databaseType != DatabaseNone) { else
settings->beginGroup("database"); databaseType = DatabaseNone;
dbPrefix = settings->value("prefix").toString();
servatriceDatabaseInterface->initDatabase("QMYSQL", servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this);
settings->value("hostname").toString(), setDatabaseInterface(servatriceDatabaseInterface);
settings->value("database").toString(),
settings->value("user").toString(), if (databaseType != DatabaseNone) {
settings->value("password").toString()); settings->beginGroup("database");
settings->endGroup(); dbPrefix = settings->value("prefix").toString();
servatriceDatabaseInterface->initDatabase("QMYSQL",
updateServerList(); settings->value("hostname").toString(),
settings->value("database").toString(),
qDebug() << "Clearing previous sessions..."; settings->value("user").toString(),
servatriceDatabaseInterface->clearSessionTables(); settings->value("password").toString());
} settings->endGroup();
const QString roomMethod = settings->value("rooms/method").toString(); updateServerList();
if (roomMethod == "sql") {
QSqlQuery query(servatriceDatabaseInterface->getDatabase()); qDebug() << "Clearing previous sessions...";
query.prepare("select id, name, descr, auto_join, join_message from " + dbPrefix + "_rooms order by id asc"); servatriceDatabaseInterface->clearSessionTables();
servatriceDatabaseInterface->execSqlQuery(query); }
while (query.next()) {
QSqlQuery query2(servatriceDatabaseInterface->getDatabase()); const QString roomMethod = settings->value("rooms/method").toString();
query2.prepare("select name from " + dbPrefix + "_rooms_gametypes where id_room = :id_room"); if (roomMethod == "sql") {
query2.bindValue(":id_room", query.value(0).toInt()); QSqlQuery query(servatriceDatabaseInterface->getDatabase());
servatriceDatabaseInterface->execSqlQuery(query2); query.prepare("select id, name, descr, auto_join, join_message from " + dbPrefix + "_rooms order by id asc");
QStringList gameTypes; servatriceDatabaseInterface->execSqlQuery(query);
while (query2.next()) while (query.next()) {
gameTypes.append(query2.value(0).toString()); QSqlQuery query2(servatriceDatabaseInterface->getDatabase());
query2.prepare("select name from " + dbPrefix + "_rooms_gametypes where id_room = :id_room");
addRoom(new Server_Room(query.value(0).toInt(), query2.bindValue(":id_room", query.value(0).toInt());
query.value(1).toString(), servatriceDatabaseInterface->execSqlQuery(query2);
query.value(2).toString(), QStringList gameTypes;
query.value(3).toInt(), while (query2.next())
query.value(4).toString(), gameTypes.append(query2.value(0).toString());
gameTypes,
this addRoom(new Server_Room(query.value(0).toInt(),
)); query.value(1).toString(),
} query.value(2).toString(),
} else { query.value(3).toInt(),
int size = settings->beginReadArray("rooms/roomlist"); query.value(4).toString(),
for (int i = 0; i < size; ++i) { gameTypes,
settings->setArrayIndex(i); this
));
QStringList gameTypes; }
int size2 = settings->beginReadArray("game_types"); } else {
for (int j = 0; j < size2; ++j) { int size = settings->beginReadArray("rooms/roomlist");
settings->setArrayIndex(j); for (int i = 0; i < size; ++i) {
gameTypes.append(settings->value("name").toString()); settings->setArrayIndex(i);
}
settings->endArray(); QStringList gameTypes;
int size2 = settings->beginReadArray("game_types");
Server_Room *newRoom = new Server_Room( for (int j = 0; j < size2; ++j) {
i, settings->setArrayIndex(j);
settings->value("name").toString(), gameTypes.append(settings->value("name").toString());
settings->value("description").toString(), }
settings->value("autojoin").toBool(), settings->endArray();
settings->value("joinmessage").toString(),
gameTypes, Server_Room *newRoom = new Server_Room(
this i,
); settings->value("name").toString(),
addRoom(newRoom); settings->value("description").toString(),
} settings->value("autojoin").toBool(),
settings->endArray(); settings->value("joinmessage").toString(),
} gameTypes,
this
updateLoginMessage(); );
addRoom(newRoom);
maxGameInactivityTime = settings->value("game/max_game_inactivity_time").toInt(); }
maxPlayerInactivityTime = settings->value("game/max_player_inactivity_time").toInt(); settings->endArray();
}
maxUsersPerAddress = settings->value("security/max_users_per_address").toInt();
messageCountingInterval = settings->value("security/message_counting_interval").toInt(); updateLoginMessage();
maxMessageCountPerInterval = settings->value("security/max_message_count_per_interval").toInt();
maxMessageSizePerInterval = settings->value("security/max_message_size_per_interval").toInt(); maxGameInactivityTime = settings->value("game/max_game_inactivity_time").toInt();
maxGamesPerUser = settings->value("security/max_games_per_user").toInt(); maxPlayerInactivityTime = settings->value("game/max_player_inactivity_time").toInt();
maxUsersPerAddress = settings->value("security/max_users_per_address").toInt();
messageCountingInterval = settings->value("security/message_counting_interval").toInt();
maxMessageCountPerInterval = settings->value("security/max_message_count_per_interval").toInt();
maxMessageSizePerInterval = settings->value("security/max_message_size_per_interval").toInt();
maxGamesPerUser = settings->value("security/max_games_per_user").toInt();
try { if (settings->value("servernetwork/active", 0).toInt()) { try { if (settings->value("servernetwork/active", 0).toInt()) {
qDebug() << "Connecting to ISL network."; qDebug() << "Connecting to ISL network.";
@ -317,7 +323,7 @@ bool Servatrice::initServer()
void Servatrice::addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface) void Servatrice::addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface)
{ {
databaseInterfaces.insert(thread, databaseInterface); databaseInterfaces.insert(thread, databaseInterface);
} }
void Servatrice::updateServerList() void Servatrice::updateServerList()
@ -341,184 +347,184 @@ void Servatrice::updateServerList()
QList<ServerProperties> Servatrice::getServerList() const QList<ServerProperties> Servatrice::getServerList() const
{ {
serverListMutex.lock(); serverListMutex.lock();
QList<ServerProperties> result = serverList; QList<ServerProperties> result = serverList;
serverListMutex.unlock(); serverListMutex.unlock();
return result; return result;
} }
int Servatrice::getUsersWithAddress(const QHostAddress &address) const int Servatrice::getUsersWithAddress(const QHostAddress &address) const
{ {
int result = 0; int result = 0;
QReadLocker locker(&clientsLock); QReadLocker locker(&clientsLock);
for (int i = 0; i < clients.size(); ++i) for (int i = 0; i < clients.size(); ++i)
if (static_cast<ServerSocketInterface *>(clients[i])->getPeerAddress() == address) if (static_cast<ServerSocketInterface *>(clients[i])->getPeerAddress() == address)
++result; ++result;
return result; return result;
} }
QList<ServerSocketInterface *> Servatrice::getUsersWithAddressAsList(const QHostAddress &address) const QList<ServerSocketInterface *> Servatrice::getUsersWithAddressAsList(const QHostAddress &address) const
{ {
QList<ServerSocketInterface *> result; QList<ServerSocketInterface *> result;
QReadLocker locker(&clientsLock); QReadLocker locker(&clientsLock);
for (int i = 0; i < clients.size(); ++i) for (int i = 0; i < clients.size(); ++i)
if (static_cast<ServerSocketInterface *>(clients[i])->getPeerAddress() == address) if (static_cast<ServerSocketInterface *>(clients[i])->getPeerAddress() == address)
result.append(static_cast<ServerSocketInterface *>(clients[i])); result.append(static_cast<ServerSocketInterface *>(clients[i]));
return result; return result;
} }
void Servatrice::updateLoginMessage() void Servatrice::updateLoginMessage()
{ {
if (!servatriceDatabaseInterface->checkSql()) if (!servatriceDatabaseInterface->checkSql())
return; return;
QSqlQuery query(servatriceDatabaseInterface->getDatabase()); QSqlQuery query(servatriceDatabaseInterface->getDatabase());
query.prepare("select message from " + dbPrefix + "_servermessages where id_server = :id_server order by timest desc limit 1"); query.prepare("select message from " + dbPrefix + "_servermessages where id_server = :id_server order by timest desc limit 1");
query.bindValue(":id_server", serverId); query.bindValue(":id_server", serverId);
if (servatriceDatabaseInterface->execSqlQuery(query)) if (servatriceDatabaseInterface->execSqlQuery(query))
if (query.next()) { if (query.next()) {
const QString newLoginMessage = query.value(0).toString(); const QString newLoginMessage = query.value(0).toString();
loginMessageMutex.lock(); loginMessageMutex.lock();
loginMessage = newLoginMessage; loginMessage = newLoginMessage;
loginMessageMutex.unlock(); loginMessageMutex.unlock();
Event_ServerMessage event; Event_ServerMessage event;
event.set_message(newLoginMessage.toStdString()); event.set_message(newLoginMessage.toStdString());
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
QMapIterator<QString, Server_ProtocolHandler *> usersIterator(users); QMapIterator<QString, Server_ProtocolHandler *> usersIterator(users);
while (usersIterator.hasNext()) while (usersIterator.hasNext())
usersIterator.next().value()->sendProtocolItem(*se); usersIterator.next().value()->sendProtocolItem(*se);
delete se; delete se;
} }
} }
void Servatrice::statusUpdate() void Servatrice::statusUpdate()
{ {
if (!servatriceDatabaseInterface->checkSql()) if (!servatriceDatabaseInterface->checkSql())
return; return;
const int uc = getUsersCount(); // for correct mutex locking order const int uc = getUsersCount(); // for correct mutex locking order
const int gc = getGamesCount(); const int gc = getGamesCount();
uptime += statusUpdateClock->interval() / 1000; uptime += statusUpdateClock->interval() / 1000;
txBytesMutex.lock(); txBytesMutex.lock();
quint64 tx = txBytes; quint64 tx = txBytes;
txBytes = 0; txBytes = 0;
txBytesMutex.unlock(); txBytesMutex.unlock();
rxBytesMutex.lock(); rxBytesMutex.lock();
quint64 rx = rxBytes; quint64 rx = rxBytes;
rxBytes = 0; rxBytes = 0;
rxBytesMutex.unlock(); rxBytesMutex.unlock();
QSqlQuery query(servatriceDatabaseInterface->getDatabase()); QSqlQuery query(servatriceDatabaseInterface->getDatabase());
query.prepare("insert into " + dbPrefix + "_uptime (id_server, timest, uptime, users_count, games_count, tx_bytes, rx_bytes) values(:id, NOW(), :uptime, :users_count, :games_count, :tx, :rx)"); query.prepare("insert into " + dbPrefix + "_uptime (id_server, timest, uptime, users_count, games_count, tx_bytes, rx_bytes) values(:id, NOW(), :uptime, :users_count, :games_count, :tx, :rx)");
query.bindValue(":id", serverId); query.bindValue(":id", serverId);
query.bindValue(":uptime", uptime); query.bindValue(":uptime", uptime);
query.bindValue(":users_count", uc); query.bindValue(":users_count", uc);
query.bindValue(":games_count", gc); query.bindValue(":games_count", gc);
query.bindValue(":tx", tx); query.bindValue(":tx", tx);
query.bindValue(":rx", rx); query.bindValue(":rx", rx);
servatriceDatabaseInterface->execSqlQuery(query); servatriceDatabaseInterface->execSqlQuery(query);
} }
void Servatrice::scheduleShutdown(const QString &reason, int minutes) void Servatrice::scheduleShutdown(const QString &reason, int minutes)
{ {
shutdownReason = reason; shutdownReason = reason;
shutdownMinutes = minutes + 1; shutdownMinutes = minutes + 1;
if (minutes > 0) { if (minutes > 0) {
shutdownTimer = new QTimer; shutdownTimer = new QTimer;
connect(shutdownTimer, SIGNAL(timeout()), this, SLOT(shutdownTimeout())); connect(shutdownTimer, SIGNAL(timeout()), this, SLOT(shutdownTimeout()));
shutdownTimer->start(60000); shutdownTimer->start(60000);
} }
shutdownTimeout(); shutdownTimeout();
} }
void Servatrice::incTxBytes(quint64 num) void Servatrice::incTxBytes(quint64 num)
{ {
txBytesMutex.lock(); txBytesMutex.lock();
txBytes += num; txBytes += num;
txBytesMutex.unlock(); txBytesMutex.unlock();
} }
void Servatrice::incRxBytes(quint64 num) void Servatrice::incRxBytes(quint64 num)
{ {
rxBytesMutex.lock(); rxBytesMutex.lock();
rxBytes += num; rxBytes += num;
rxBytesMutex.unlock(); rxBytesMutex.unlock();
} }
void Servatrice::shutdownTimeout() void Servatrice::shutdownTimeout()
{ {
--shutdownMinutes; --shutdownMinutes;
SessionEvent *se; SessionEvent *se;
if (shutdownMinutes) { if (shutdownMinutes) {
Event_ServerShutdown event; Event_ServerShutdown event;
event.set_reason(shutdownReason.toStdString()); event.set_reason(shutdownReason.toStdString());
event.set_minutes(shutdownMinutes); event.set_minutes(shutdownMinutes);
se = Server_ProtocolHandler::prepareSessionEvent(event); se = Server_ProtocolHandler::prepareSessionEvent(event);
} else { } else {
Event_ConnectionClosed event; Event_ConnectionClosed event;
event.set_reason(Event_ConnectionClosed::SERVER_SHUTDOWN); event.set_reason(Event_ConnectionClosed::SERVER_SHUTDOWN);
se = Server_ProtocolHandler::prepareSessionEvent(event); se = Server_ProtocolHandler::prepareSessionEvent(event);
} }
clientsLock.lockForRead(); clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i) for (int i = 0; i < clients.size(); ++i)
clients[i]->sendProtocolItem(*se); clients[i]->sendProtocolItem(*se);
clientsLock.unlock(); clientsLock.unlock();
delete se; delete se;
if (!shutdownMinutes) if (!shutdownMinutes)
deleteLater(); deleteLater();
} }
bool Servatrice::islConnectionExists(int serverId) const bool Servatrice::islConnectionExists(int serverId) const
{ {
// Only call with islLock locked at least for reading // Only call with islLock locked at least for reading
return islInterfaces.contains(serverId); return islInterfaces.contains(serverId);
} }
void Servatrice::addIslInterface(int serverId, IslInterface *interface) void Servatrice::addIslInterface(int serverId, IslInterface *interface)
{ {
// Only call with islLock locked for writing // Only call with islLock locked for writing
islInterfaces.insert(serverId, interface); islInterfaces.insert(serverId, interface);
connect(interface, SIGNAL(externalUserJoined(ServerInfo_User)), this, SLOT(externalUserJoined(ServerInfo_User))); connect(interface, SIGNAL(externalUserJoined(ServerInfo_User)), this, SLOT(externalUserJoined(ServerInfo_User)));
connect(interface, SIGNAL(externalUserLeft(QString)), this, SLOT(externalUserLeft(QString))); connect(interface, SIGNAL(externalUserLeft(QString)), this, SLOT(externalUserLeft(QString)));
connect(interface, SIGNAL(externalRoomUserJoined(int, ServerInfo_User)), this, SLOT(externalRoomUserJoined(int, ServerInfo_User))); connect(interface, SIGNAL(externalRoomUserJoined(int, ServerInfo_User)), this, SLOT(externalRoomUserJoined(int, ServerInfo_User)));
connect(interface, SIGNAL(externalRoomUserLeft(int, QString)), this, SLOT(externalRoomUserLeft(int, QString))); connect(interface, SIGNAL(externalRoomUserLeft(int, QString)), this, SLOT(externalRoomUserLeft(int, QString)));
connect(interface, SIGNAL(externalRoomSay(int, QString, QString)), this, SLOT(externalRoomSay(int, QString, QString))); connect(interface, SIGNAL(externalRoomSay(int, QString, QString)), this, SLOT(externalRoomSay(int, QString, QString)));
connect(interface, SIGNAL(externalRoomGameListChanged(int, ServerInfo_Game)), this, SLOT(externalRoomGameListChanged(int, ServerInfo_Game))); connect(interface, SIGNAL(externalRoomGameListChanged(int, ServerInfo_Game)), this, SLOT(externalRoomGameListChanged(int, ServerInfo_Game)));
connect(interface, SIGNAL(joinGameCommandReceived(Command_JoinGame, int, int, int, qint64)), this, SLOT(externalJoinGameCommandReceived(Command_JoinGame, int, int, int, qint64))); connect(interface, SIGNAL(joinGameCommandReceived(Command_JoinGame, int, int, int, qint64)), this, SLOT(externalJoinGameCommandReceived(Command_JoinGame, int, int, int, qint64)));
connect(interface, SIGNAL(gameCommandContainerReceived(CommandContainer, int, int, qint64)), this, SLOT(externalGameCommandContainerReceived(CommandContainer, int, int, qint64))); connect(interface, SIGNAL(gameCommandContainerReceived(CommandContainer, int, int, qint64)), this, SLOT(externalGameCommandContainerReceived(CommandContainer, int, int, qint64)));
connect(interface, SIGNAL(responseReceived(Response, qint64)), this, SLOT(externalResponseReceived(Response, qint64))); connect(interface, SIGNAL(responseReceived(Response, qint64)), this, SLOT(externalResponseReceived(Response, qint64)));
connect(interface, SIGNAL(gameEventContainerReceived(GameEventContainer, qint64)), this, SLOT(externalGameEventContainerReceived(GameEventContainer, qint64))); connect(interface, SIGNAL(gameEventContainerReceived(GameEventContainer, qint64)), this, SLOT(externalGameEventContainerReceived(GameEventContainer, qint64)));
} }
void Servatrice::removeIslInterface(int serverId) void Servatrice::removeIslInterface(int serverId)
{ {
// Only call with islLock locked for writing // Only call with islLock locked for writing
// XXX we probably need to delete everything that belonged to it... // XXX we probably need to delete everything that belonged to it...
islInterfaces.remove(serverId); islInterfaces.remove(serverId);
} }
void Servatrice::doSendIslMessage(const IslMessage &msg, int serverId) void Servatrice::doSendIslMessage(const IslMessage &msg, int serverId)
{ {
QReadLocker locker(&islLock); QReadLocker locker(&islLock);
if (serverId == -1) { if (serverId == -1) {
QMapIterator<int, IslInterface *> islIterator(islInterfaces); QMapIterator<int, IslInterface *> islIterator(islInterfaces);
while (islIterator.hasNext()) while (islIterator.hasNext())
islIterator.next().value()->transmitMessage(msg); islIterator.next().value()->transmitMessage(msg);
} else { } else {
IslInterface *interface = islInterfaces.value(serverId); IslInterface *interface = islInterfaces.value(serverId);
if (interface) if (interface)
interface->transmitMessage(msg); interface->transmitMessage(msg);
} }
} }