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 *
* brukie@gmx.net *
* *
@ -225,8 +225,6 @@ void MainWindow::actAbout()
+ tr("French:") + " Yannick Hammer, Arnaud Faes<br>"
+ tr("Japanese:") + " Nagase Task<br>"
+ tr("Russian:") + " Alexander Davidov<br>"
// + tr("Czech:") + " Ondřej Trhoň<br>"
// + tr("Slovak:") + " Ganjalf Rendy<br>"
+ tr("Italian:") + " Luigi Sciolla<br>"
+ tr("Swedish:") + " Jessica Dahl<br>"
));
@ -261,6 +259,9 @@ void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32
case Response::RespUsernameInvalid:
QMessageBox::critical(this, tr("Error"), tr("Invalid username."));
break;
case Response::RespRegistrationRequired:
QMessageBox::critical(this, tr("Error"), tr("This server requires user registration."));
break;
default:
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;
RespAccessDenied = 20;
RespUsernameInvalid = 21;
RespRegistrationRequired = 22;
}
enum ResponseType {
JOIN_ROOM = 1000;

View file

@ -34,6 +34,7 @@
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QSettings>
Server::Server(bool _threaded, QObject *parent)
: QObject(parent), threaded(_threaded), nextLocalGameId(0)
@ -131,6 +132,14 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
} else if (authState == UnknownUser) {
// Change user name so that no two users have the same names,
// 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;
int i = 0;
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);
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();
usersBySessionId.insert(data.session_id(), session);
@ -478,7 +487,7 @@ void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl
clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i)
if (clients[i]->getAcceptsRoomListChanges())
if (clients[i]->getAcceptsRoomListChanges())
clients[i]->sendProtocolItem(*se);
clientsLock.unlock();

View file

@ -27,7 +27,7 @@ class GameEventContainer;
class CommandContainer;
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
{

View file

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

View file

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

View file

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