mirror of
https://github.com/Cockatrice/Cockatrice.git
synced 2026-06-14 19:18:55 -07:00
Implementation of websockets in servatrice and test js client
This commit is contained in:
parent
e81a6d497b
commit
5b21dc8cde
42 changed files with 39592 additions and 287 deletions
|
|
@ -44,16 +44,6 @@ Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPoo
|
|||
: 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);
|
||||
|
|
@ -83,7 +73,18 @@ Servatrice_GameServer::~Servatrice_GameServer()
|
|||
|
||||
void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor)
|
||||
{
|
||||
// Determine connection pool with smallest client count
|
||||
Servatrice_ConnectionPool *pool = findLeastUsedConnectionPool();
|
||||
|
||||
TcpServerSocketInterface *ssi = new TcpServerSocketInterface(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));
|
||||
}
|
||||
|
||||
Servatrice_ConnectionPool *Servatrice_GameServer::findLeastUsedConnectionPool()
|
||||
{
|
||||
int minClientCount = -1;
|
||||
int poolIndex = -1;
|
||||
QStringList debugStr;
|
||||
|
|
@ -96,16 +97,68 @@ void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor)
|
|||
debugStr.append(QString::number(clientCount));
|
||||
}
|
||||
qDebug() << "Pool utilisation:" << debugStr;
|
||||
Servatrice_ConnectionPool *pool = connectionPools[poolIndex];
|
||||
return connectionPools[poolIndex];
|
||||
}
|
||||
|
||||
ServerSocketInterface *ssi = new ServerSocketInterface(server, pool->getDatabaseInterface());
|
||||
ssi->moveToThread(pool->thread());
|
||||
#if QT_VERSION > 0x050300
|
||||
#define WEBSOCKET_POOL_NUMBER 999
|
||||
|
||||
Servatrice_WebsocketGameServer::Servatrice_WebsocketGameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent)
|
||||
: QWebSocketServer("Servatrice", QWebSocketServer::NonSecureMode, parent),
|
||||
server(_server)
|
||||
{
|
||||
// Qt limitation: websockets can't be moved to another thread
|
||||
Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(WEBSOCKET_POOL_NUMBER, server);
|
||||
Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface);
|
||||
|
||||
server->addDatabaseInterface(thread(), newDatabaseInterface);
|
||||
newDatabaseInterface->initDatabase(_sqlDatabase);
|
||||
|
||||
connectionPools.append(newPool);
|
||||
|
||||
connect(this, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
|
||||
}
|
||||
|
||||
Servatrice_WebsocketGameServer::~Servatrice_WebsocketGameServer()
|
||||
{
|
||||
for (int i = 0; i < connectionPools.size(); ++i) {
|
||||
logger->logMessage(QString("Closing websocket pool %1...").arg(i));
|
||||
QThread *poolThread = connectionPools[i]->thread();
|
||||
connectionPools[i]->deleteLater(); // pool destructor calls thread()->quit()
|
||||
poolThread->wait();
|
||||
}
|
||||
}
|
||||
|
||||
void Servatrice_WebsocketGameServer::onNewConnection()
|
||||
{
|
||||
Servatrice_ConnectionPool *pool = findLeastUsedConnectionPool();
|
||||
|
||||
WebsocketServerSocketInterface *ssi = new WebsocketServerSocketInterface(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));
|
||||
QMetaObject::invokeMethod(ssi, "initConnection", Qt::QueuedConnection, Q_ARG(void *, nextPendingConnection()));
|
||||
}
|
||||
|
||||
Servatrice_ConnectionPool *Servatrice_WebsocketGameServer::findLeastUsedConnectionPool()
|
||||
{
|
||||
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;
|
||||
return connectionPools[poolIndex];
|
||||
}
|
||||
#endif
|
||||
|
||||
void Servatrice_IslServer::incomingConnection(qintptr socketDescriptor)
|
||||
{
|
||||
QThread *thread = new QThread;
|
||||
|
|
@ -120,7 +173,7 @@ void Servatrice_IslServer::incomingConnection(qintptr socketDescriptor)
|
|||
}
|
||||
|
||||
Servatrice::Servatrice(QObject *parent)
|
||||
: Server(true, parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true)
|
||||
: Server(parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true)
|
||||
{
|
||||
qRegisterMetaType<QSqlDatabase>("QSqlDatabase");
|
||||
}
|
||||
|
|
@ -162,7 +215,11 @@ bool Servatrice::initServer()
|
|||
|
||||
if (maxUserLimitEnabled){
|
||||
int maxUserLimit = settingsCache->value("security/max_users_total", 500).toInt();
|
||||
qDebug() << "Maximum user limit: " << maxUserLimit;
|
||||
qDebug() << "Maximum total user limit: " << maxUserLimit;
|
||||
int maxTcpUserLimit = settingsCache->value("security/max_users_tcp", 500).toInt();
|
||||
qDebug() << "Maximum tcp user limit: " << maxTcpUserLimit;
|
||||
int maxWebsocketUserLimit = settingsCache->value("security/max_users_websocket", 500).toInt();
|
||||
qDebug() << "Maximum websocket user limit: " << maxWebsocketUserLimit;
|
||||
}
|
||||
|
||||
bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool();
|
||||
|
|
@ -369,17 +426,39 @@ bool Servatrice::initServer()
|
|||
statusUpdateClock->start(statusUpdateTime);
|
||||
}
|
||||
|
||||
// SOCKET SERVER
|
||||
const int numberPools = settingsCache->value("server/number_pools", 1).toInt();
|
||||
gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
|
||||
gameServer->setMaxPendingConnections(1000);
|
||||
const int gamePort = settingsCache->value("server/port", 4747).toInt();
|
||||
qDebug() << "Starting server on port" << gamePort;
|
||||
if (gameServer->listen(QHostAddress::Any, gamePort))
|
||||
qDebug() << "Server listening.";
|
||||
else {
|
||||
qDebug() << "gameServer->listen(): Error:" << gameServer->errorString();
|
||||
return false;
|
||||
if(numberPools > 0)
|
||||
{
|
||||
gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
|
||||
gameServer->setMaxPendingConnections(1000);
|
||||
const int gamePort = settingsCache->value("server/port", 4747).toInt();
|
||||
qDebug() << "Starting server on port" << gamePort;
|
||||
if (gameServer->listen(QHostAddress::Any, gamePort))
|
||||
qDebug() << "Server listening.";
|
||||
else {
|
||||
qDebug() << "gameServer->listen(): Error:" << gameServer->errorString();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#if QT_VERSION > 0x050300
|
||||
// WEBSOCKET SERVER
|
||||
const int wesocketNumberPools = settingsCache->value("server/websocket_number_pools", 1).toInt();
|
||||
if(wesocketNumberPools > 0)
|
||||
{
|
||||
websocketGameServer = new Servatrice_WebsocketGameServer(this, wesocketNumberPools, servatriceDatabaseInterface->getDatabase(), this);
|
||||
websocketGameServer->setMaxPendingConnections(1000);
|
||||
const int websocketGamePort = settingsCache->value("server/websocket_port", 4748).toInt();
|
||||
qDebug() << "Starting websocket server on port" << websocketGamePort;
|
||||
if (websocketGameServer->listen(QHostAddress::Any, websocketGamePort))
|
||||
qDebug() << "Websocket server listening.";
|
||||
else {
|
||||
qDebug() << "websocketGameServer->listen(): Error:" << websocketGameServer->errorString();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -420,19 +499,19 @@ 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)
|
||||
if (static_cast<AbstractServerSocketInterface *>(clients[i])->getPeerAddress() == address)
|
||||
++result;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
QList<ServerSocketInterface *> Servatrice::getUsersWithAddressAsList(const QHostAddress &address) const
|
||||
QList<AbstractServerSocketInterface *> Servatrice::getUsersWithAddressAsList(const QHostAddress &address) const
|
||||
{
|
||||
QList<ServerSocketInterface *> result;
|
||||
QList<AbstractServerSocketInterface *> 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]));
|
||||
if (static_cast<AbstractServerSocketInterface *>(clients[i])->getPeerAddress() == address)
|
||||
result.append(static_cast<AbstractServerSocketInterface *>(clients[i]));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,9 @@
|
|||
#define SERVATRICE_H
|
||||
|
||||
#include <QTcpServer>
|
||||
#if QT_VERSION > 0x050300
|
||||
#include <QWebSocketServer>
|
||||
#endif
|
||||
#include <QMutex>
|
||||
#include <QSslCertificate>
|
||||
#include <QSslKey>
|
||||
|
|
@ -40,7 +43,7 @@ class GameReplay;
|
|||
class Servatrice;
|
||||
class Servatrice_ConnectionPool;
|
||||
class Servatrice_DatabaseInterface;
|
||||
class ServerSocketInterface;
|
||||
class AbstractServerSocketInterface;
|
||||
class IslInterface;
|
||||
class FeatureSet;
|
||||
|
||||
|
|
@ -54,8 +57,25 @@ public:
|
|||
~Servatrice_GameServer();
|
||||
protected:
|
||||
void incomingConnection(qintptr socketDescriptor);
|
||||
Servatrice_ConnectionPool *findLeastUsedConnectionPool();
|
||||
};
|
||||
|
||||
#if QT_VERSION > 0x050300
|
||||
class Servatrice_WebsocketGameServer : public QWebSocketServer {
|
||||
Q_OBJECT
|
||||
private:
|
||||
Servatrice *server;
|
||||
QList<Servatrice_ConnectionPool *> connectionPools;
|
||||
public:
|
||||
Servatrice_WebsocketGameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent = 0);
|
||||
~Servatrice_WebsocketGameServer();
|
||||
protected:
|
||||
Servatrice_ConnectionPool *findLeastUsedConnectionPool();
|
||||
protected slots:
|
||||
void onNewConnection();
|
||||
};
|
||||
#endif
|
||||
|
||||
class Servatrice_IslServer : public QTcpServer {
|
||||
Q_OBJECT
|
||||
private:
|
||||
|
|
@ -98,6 +118,9 @@ private:
|
|||
DatabaseType databaseType;
|
||||
QTimer *pingClock, *statusUpdateClock;
|
||||
Servatrice_GameServer *gameServer;
|
||||
#if QT_VERSION > 0x050300
|
||||
Servatrice_WebsocketGameServer *websocketGameServer;
|
||||
#endif
|
||||
Servatrice_IslServer *islServer;
|
||||
QString serverName;
|
||||
mutable QMutex loginMessageMutex;
|
||||
|
|
@ -154,7 +177,7 @@ public:
|
|||
QString getDbPrefix() const { return dbPrefix; }
|
||||
int getServerId() const { return serverId; }
|
||||
int getUsersWithAddress(const QHostAddress &address) const;
|
||||
QList<ServerSocketInterface *> getUsersWithAddressAsList(const QHostAddress &address) const;
|
||||
QList<AbstractServerSocketInterface *> getUsersWithAddressAsList(const QHostAddress &address) const;
|
||||
void incTxBytes(quint64 num);
|
||||
void incRxBytes(quint64 num);
|
||||
void addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface);
|
||||
|
|
|
|||
|
|
@ -579,7 +579,7 @@ bool Servatrice_DatabaseInterface::userSessionExists(const QString &userName)
|
|||
return query->next();
|
||||
}
|
||||
|
||||
qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const QString &address, const QString &clientId)
|
||||
qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const QString &address, const QString &clientId, const QString & connectionType)
|
||||
{
|
||||
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
|
||||
return -1;
|
||||
|
|
@ -587,11 +587,12 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const
|
|||
if (!checkSql())
|
||||
return -1;
|
||||
|
||||
QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time, clientid) values(:user_name, :id_server, :ip_address, NOW(), :client_id)");
|
||||
QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time, clientid, connection_type) values(:user_name, :id_server, :ip_address, NOW(), :client_id, :connection_type)");
|
||||
query->bindValue(":user_name", userName);
|
||||
query->bindValue(":id_server", server->getServerId());
|
||||
query->bindValue(":ip_address", address);
|
||||
query->bindValue(":client_id", clientId);
|
||||
query->bindValue(":connection_type", connectionType);
|
||||
if (execSqlQuery(query))
|
||||
return query->lastInsertId().toInt();
|
||||
return -1;
|
||||
|
|
@ -850,22 +851,27 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user, const
|
|||
return false;
|
||||
}
|
||||
|
||||
int Servatrice_DatabaseInterface::getActiveUserCount()
|
||||
int Servatrice_DatabaseInterface::getActiveUserCount(QString connectionType)
|
||||
{
|
||||
int userCount = 0;
|
||||
|
||||
if (!checkSql())
|
||||
return userCount;
|
||||
|
||||
QSqlQuery *query = prepareQuery("select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL");
|
||||
query->bindValue(":serverid", server->getServerId());
|
||||
if (!execSqlQuery(query)){
|
||||
return userCount;
|
||||
}
|
||||
QString text = "select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL";
|
||||
if(!connectionType.isEmpty())
|
||||
text +=" AND connection_type = :connection_type";
|
||||
QSqlQuery *query = prepareQuery(text);
|
||||
|
||||
if (query->next()){
|
||||
query->bindValue(":serverid", server->getServerId());
|
||||
if(!connectionType.isEmpty())
|
||||
query->bindValue(":connection_type", connectionType);
|
||||
|
||||
if (!execSqlQuery(query))
|
||||
return userCount;
|
||||
|
||||
if (query->next())
|
||||
userCount = query->value(0).toInt();
|
||||
}
|
||||
|
||||
return userCount;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
#include "server.h"
|
||||
#include "server_database_interface.h"
|
||||
|
||||
#define DATABASE_SCHEMA_VERSION 13
|
||||
#define DATABASE_SCHEMA_VERSION 14
|
||||
|
||||
class Servatrice;
|
||||
|
||||
|
|
@ -59,8 +59,9 @@ public:
|
|||
|
||||
int getNextGameId();
|
||||
int getNextReplayId();
|
||||
int getActiveUserCount();
|
||||
qint64 startSession(const QString &userName, const QString &address, const QString &clientId);
|
||||
int getActiveUserCount(QString connectionType = QString());
|
||||
|
||||
qint64 startSession(const QString &userName, const QString &address, const QString &clientId, const QString & connectionType);
|
||||
void endSession(qint64 sessionId);
|
||||
void clearSessionTables();
|
||||
void lockSessionTables();
|
||||
|
|
|
|||
|
|
@ -74,52 +74,17 @@
|
|||
|
||||
static const int protocolVersion = 14;
|
||||
|
||||
ServerSocketInterface::ServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent)
|
||||
AbstractServerSocketInterface::AbstractServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent)
|
||||
: Server_ProtocolHandler(_server, _databaseInterface, parent),
|
||||
servatrice(_server),
|
||||
sqlInterface(reinterpret_cast<Servatrice_DatabaseInterface *>(databaseInterface)),
|
||||
messageInProgress(false),
|
||||
handshakeStarted(false)
|
||||
sqlInterface(reinterpret_cast<Servatrice_DatabaseInterface *>(databaseInterface))
|
||||
{
|
||||
socket = new QTcpSocket(this);
|
||||
socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
|
||||
connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
|
||||
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError)));
|
||||
|
||||
// Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error,
|
||||
// it could lead to this object being destroyed while another function is still on the call stack. -> mutex deadlocks etc.
|
||||
connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
ServerSocketInterface::~ServerSocketInterface()
|
||||
{
|
||||
logger->logMessage("ServerSocketInterface destructor", this);
|
||||
|
||||
flushOutputQueue();
|
||||
}
|
||||
|
||||
void ServerSocketInterface::initConnection(int socketDescriptor)
|
||||
{
|
||||
// Add this object to the server's list of connections before it can receive socket events.
|
||||
// Otherwise, in case a of a socket error, it could be removed from the list before it is added.
|
||||
server->addClient(this);
|
||||
|
||||
socket->setSocketDescriptor(socketDescriptor);
|
||||
logger->logMessage(QString("Incoming connection: %1").arg(socket->peerAddress().toString()), this);
|
||||
initSessionDeprecated();
|
||||
}
|
||||
|
||||
void ServerSocketInterface::initSessionDeprecated()
|
||||
{
|
||||
// dirty hack to make v13 client display the correct error message
|
||||
|
||||
QByteArray buf;
|
||||
buf.append("<?xml version=\"1.0\"?><cockatrice_server_stream version=\"14\">");
|
||||
socket->write(buf);
|
||||
socket->flush();
|
||||
}
|
||||
|
||||
bool ServerSocketInterface::initSession()
|
||||
bool AbstractServerSocketInterface::initSession()
|
||||
{
|
||||
Event_ServerIdentification identEvent;
|
||||
identEvent.set_server_name(servatrice->getServerName().toStdString());
|
||||
|
|
@ -148,11 +113,11 @@ bool ServerSocketInterface::initSession()
|
|||
|
||||
//allow unlimited number of connections from the trusted sources
|
||||
QString trustedSources = settingsCache->value("security/trusted_sources","127.0.0.1,::1").toString();
|
||||
if (trustedSources.contains(socket->peerAddress().toString(),Qt::CaseInsensitive))
|
||||
if (trustedSources.contains(getAddress(),Qt::CaseInsensitive))
|
||||
return true;
|
||||
|
||||
int maxUsers = servatrice->getMaxUsersPerAddress();
|
||||
if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) {
|
||||
if ((maxUsers > 0) && (servatrice->getUsersWithAddress(getPeerAddress()) >= maxUsers)) {
|
||||
Event_ConnectionClosed event;
|
||||
event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS);
|
||||
SessionEvent *se = prepareSessionEvent(event);
|
||||
|
|
@ -165,76 +130,14 @@ bool ServerSocketInterface::initSession()
|
|||
return true;
|
||||
}
|
||||
|
||||
void ServerSocketInterface::readClient()
|
||||
{
|
||||
QByteArray data = socket->readAll();
|
||||
servatrice->incRxBytes(data.size());
|
||||
inputBuffer.append(data);
|
||||
|
||||
do {
|
||||
if (!messageInProgress) {
|
||||
if (inputBuffer.size() >= 4) {
|
||||
messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24)
|
||||
+ (((quint32) (unsigned char) inputBuffer[1]) << 16)
|
||||
+ (((quint32) (unsigned char) inputBuffer[2]) << 8)
|
||||
+ ((quint32) (unsigned char) inputBuffer[3]);
|
||||
inputBuffer.remove(0, 4);
|
||||
messageInProgress = true;
|
||||
} else
|
||||
return;
|
||||
}
|
||||
if (inputBuffer.size() < messageLength)
|
||||
return;
|
||||
|
||||
CommandContainer newCommandContainer;
|
||||
try {
|
||||
newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength);
|
||||
}
|
||||
catch(std::exception &e) {
|
||||
qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Exception:" << e.what();
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
qDebug() << "Message length:" << messageLength;
|
||||
qDebug() << "Message content:" << inputBuffer.toHex();
|
||||
}
|
||||
catch(...) {
|
||||
qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
}
|
||||
|
||||
inputBuffer.remove(0, messageLength);
|
||||
messageInProgress = false;
|
||||
|
||||
// dirty hack to make v13 client display the correct error message
|
||||
if (handshakeStarted)
|
||||
processCommandContainer(newCommandContainer);
|
||||
else if (!newCommandContainer.has_cmd_id()) {
|
||||
handshakeStarted = true;
|
||||
if (!initSession())
|
||||
prepareDestroy();
|
||||
}
|
||||
// end of hack
|
||||
} while (!inputBuffer.isEmpty());
|
||||
}
|
||||
|
||||
void ServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError)
|
||||
void AbstractServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError)
|
||||
{
|
||||
qDebug() << "Socket error:" << socketError;
|
||||
|
||||
prepareDestroy();
|
||||
}
|
||||
|
||||
void ServerSocketInterface::transmitProtocolItem(const ServerMessage &item)
|
||||
void AbstractServerSocketInterface::transmitProtocolItem(const ServerMessage &item)
|
||||
{
|
||||
outputQueueMutex.lock();
|
||||
outputQueue.append(item);
|
||||
|
|
@ -243,43 +146,12 @@ void ServerSocketInterface::transmitProtocolItem(const ServerMessage &item)
|
|||
emit outputQueueChanged();
|
||||
}
|
||||
|
||||
void ServerSocketInterface::flushOutputQueue()
|
||||
{
|
||||
QMutexLocker locker(&outputQueueMutex);
|
||||
if (outputQueue.isEmpty())
|
||||
return;
|
||||
|
||||
int totalBytes = 0;
|
||||
while (!outputQueue.isEmpty()) {
|
||||
ServerMessage item = outputQueue.takeFirst();
|
||||
locker.unlock();
|
||||
|
||||
QByteArray buf;
|
||||
unsigned int size = item.ByteSize();
|
||||
buf.resize(size + 4);
|
||||
item.SerializeToArray(buf.data() + 4, size);
|
||||
buf.data()[3] = (unsigned char) size;
|
||||
buf.data()[2] = (unsigned char) (size >> 8);
|
||||
buf.data()[1] = (unsigned char) (size >> 16);
|
||||
buf.data()[0] = (unsigned char) (size >> 24);
|
||||
// In case socket->write() calls catchSocketError(), the mutex must not be locked during this call.
|
||||
socket->write(buf);
|
||||
|
||||
totalBytes += size + 4;
|
||||
locker.relock();
|
||||
}
|
||||
locker.unlock();
|
||||
servatrice->incTxBytes(totalBytes);
|
||||
// see above wrt mutex
|
||||
socket->flush();
|
||||
}
|
||||
|
||||
void ServerSocketInterface::logDebugMessage(const QString &message)
|
||||
void AbstractServerSocketInterface::logDebugMessage(const QString &message)
|
||||
{
|
||||
logger->logMessage(message, this);
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::processExtendedSessionCommand(int cmdType, const SessionCommand &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::processExtendedSessionCommand(int cmdType, const SessionCommand &cmd, ResponseContainer &rc)
|
||||
{
|
||||
switch ((SessionCommand::SessionCommandType) cmdType) {
|
||||
case SessionCommand::ADD_TO_LIST: return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc);
|
||||
|
|
@ -304,7 +176,7 @@ Response::ResponseCode ServerSocketInterface::processExtendedSessionCommand(int
|
|||
}
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc)
|
||||
{
|
||||
switch ((ModeratorCommand::ModeratorCommandType) cmdType) {
|
||||
case ModeratorCommand::BAN_FROM_SERVER: return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc);
|
||||
|
|
@ -317,7 +189,7 @@ Response::ResponseCode ServerSocketInterface::processExtendedModeratorCommand(in
|
|||
}
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc)
|
||||
{
|
||||
switch ((AdminCommand::AdminCommandType) cmdType) {
|
||||
case AdminCommand::SHUTDOWN_SERVER: return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc);
|
||||
|
|
@ -328,7 +200,7 @@ Response::ResponseCode ServerSocketInterface::processExtendedAdminCommand(int cm
|
|||
}
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -367,7 +239,7 @@ Response::ResponseCode ServerSocketInterface::cmdAddToList(const Command_AddToLi
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -404,7 +276,7 @@ Response::ResponseCode ServerSocketInterface::cmdRemoveFromList(const Command_Re
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path)
|
||||
int AbstractServerSocketInterface::getDeckPathId(int basePathId, QStringList path)
|
||||
{
|
||||
if (path.isEmpty())
|
||||
return 0;
|
||||
|
|
@ -426,12 +298,12 @@ int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path)
|
|||
return getDeckPathId(id, path);
|
||||
}
|
||||
|
||||
int ServerSocketInterface::getDeckPathId(const QString &path)
|
||||
int AbstractServerSocketInterface::getDeckPathId(const QString &path)
|
||||
{
|
||||
return getDeckPathId(0, path.split("/"));
|
||||
}
|
||||
|
||||
bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_Folder *folder)
|
||||
bool AbstractServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_Folder *folder)
|
||||
{
|
||||
QSqlQuery *query = sqlInterface->prepareQuery("select id, name from {prefix}_decklist_folders where id_parent = :id_parent and id_user = :id_user");
|
||||
query->bindValue(":id_parent", folderId);
|
||||
|
|
@ -474,7 +346,7 @@ bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_
|
|||
// CHECK AUTHENTICATION!
|
||||
// Also check for every function that data belonging to other users cannot be accessed.
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckList(const Command_DeckList & /*cmd*/, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckList(const Command_DeckList & /*cmd*/, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -491,7 +363,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckList(const Command_DeckList
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckNewDir(const Command_DeckNewDir &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckNewDir(const Command_DeckNewDir &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -511,7 +383,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckNewDir(const Command_DeckNe
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
void ServerSocketInterface::deckDelDirHelper(int basePathId)
|
||||
void AbstractServerSocketInterface::deckDelDirHelper(int basePathId)
|
||||
{
|
||||
sqlInterface->checkSql();
|
||||
QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = :id_parent");
|
||||
|
|
@ -529,9 +401,9 @@ void ServerSocketInterface::deckDelDirHelper(int basePathId)
|
|||
sqlInterface->execSqlQuery(query);
|
||||
}
|
||||
|
||||
void ServerSocketInterface::sendServerMessage(const QString userName, const QString message)
|
||||
void AbstractServerSocketInterface::sendServerMessage(const QString userName, const QString message)
|
||||
{
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
if (!user)
|
||||
return;
|
||||
|
||||
|
|
@ -544,7 +416,7 @@ void ServerSocketInterface::sendServerMessage(const QString userName, const QStr
|
|||
delete se;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckDelDir(const Command_DeckDelDir &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckDelDir(const Command_DeckDelDir &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -558,7 +430,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDelDir(const Command_DeckDe
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckDel(const Command_DeckDel &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckDel(const Command_DeckDel &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -578,7 +450,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDel(const Command_DeckDel &
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUpload &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckUpload(const Command_DeckUpload &cmd, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -636,7 +508,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdDeckDownload(const Command_DeckDownload &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdDeckDownload(const Command_DeckDownload &cmd, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -656,7 +528,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDownload(const Command_Deck
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -704,7 +576,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_Replay
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_ReplayDownload &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdReplayDownload(const Command_ReplayDownload &cmd, ResponseContainer &rc)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -735,7 +607,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_Re
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdReplayModifyMatch(const Command_ReplayModifyMatch &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdReplayModifyMatch(const Command_ReplayModifyMatch &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -753,7 +625,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayModifyMatch(const Command
|
|||
return query->numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command_ReplayDeleteMatch &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdReplayDeleteMatch(const Command_ReplayDeleteMatch &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -773,7 +645,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command
|
|||
|
||||
// MODERATOR FUNCTIONS.
|
||||
// May be called by admins and moderators. Permission is checked by the calling function.
|
||||
Response::ResponseCode ServerSocketInterface::cmdGetLogHistory(const Command_ViewLogHistory &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdGetLogHistory(const Command_ViewLogHistory &cmd, ResponseContainer &rc)
|
||||
{
|
||||
|
||||
QList<ServerInfo_ChatMessage> messageList;
|
||||
|
|
@ -806,7 +678,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetLogHistory(const Command_Vie
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdGetBanHistory(const Command_GetBanHistory &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdGetBanHistory(const Command_GetBanHistory &cmd, ResponseContainer &rc)
|
||||
{
|
||||
QList<ServerInfo_Ban> banList;
|
||||
QString userName = QString::fromStdString(cmd.user_name());
|
||||
|
|
@ -819,7 +691,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetBanHistory(const Command_Get
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdGetWarnList(const Command_GetWarnList &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnList(const Command_GetWarnList &cmd, ResponseContainer &rc)
|
||||
{
|
||||
Response_WarnList *re = new Response_WarnList;
|
||||
|
||||
|
|
@ -834,7 +706,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetWarnList(const Command_GetWa
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdGetWarnHistory(const Command_GetWarnHistory &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdGetWarnHistory(const Command_GetWarnHistory &cmd, ResponseContainer &rc)
|
||||
{
|
||||
QList<ServerInfo_Warning> warnList;
|
||||
QString userName = QString::fromStdString(cmd.user_name());
|
||||
|
|
@ -847,7 +719,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetWarnHistory(const Command_Ge
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdWarnUser(const Command_WarnUser &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdWarnUser(const Command_WarnUser &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (!sqlInterface->checkSql())
|
||||
return Response::RespInternalError;
|
||||
|
|
@ -859,7 +731,7 @@ Response::ResponseCode ServerSocketInterface::cmdWarnUser(const Command_WarnUser
|
|||
|
||||
if (sqlInterface->addWarning(userName, sendingModerator, warningReason, clientID)) {
|
||||
servatrice->clientsLock.lockForRead();
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
QList<QString> moderatorList = server->getOnlineModeratorList();
|
||||
servatrice->clientsLock.unlock();
|
||||
|
||||
|
|
@ -886,7 +758,7 @@ Response::ResponseCode ServerSocketInterface::cmdWarnUser(const Command_WarnUser
|
|||
}
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
if (!sqlInterface->checkSql())
|
||||
return Response::RespInternalError;
|
||||
|
|
@ -915,10 +787,10 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
|
|||
|
||||
servatrice->clientsLock.lockForRead();
|
||||
QList<QString> moderatorList = server->getOnlineModeratorList();
|
||||
QList<ServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));
|
||||
QList<AbstractServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));
|
||||
|
||||
if (!userName.isEmpty()) {
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
if (user && !userList.contains(user))
|
||||
userList.append(user);
|
||||
}
|
||||
|
|
@ -932,7 +804,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
|
|||
} else {
|
||||
while (query->next()) {
|
||||
userName = query->value(0).toString();
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
if (user && !userList.contains(user))
|
||||
userList.append(user);
|
||||
}
|
||||
|
|
@ -974,7 +846,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdRegisterAccount(const Command_Register &cmd, ResponseContainer &rc)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdRegisterAccount(const Command_Register &cmd, ResponseContainer &rc)
|
||||
{
|
||||
QString userName = QString::fromStdString(cmd.user_name());
|
||||
QString clientId = QString::fromStdString(cmd.clientid());
|
||||
|
|
@ -1056,14 +928,14 @@ Response::ResponseCode ServerSocketInterface::cmdRegisterAccount(const Command_R
|
|||
}
|
||||
}
|
||||
|
||||
bool ServerSocketInterface::tooManyRegistrationAttempts(const QString &ipAddress)
|
||||
bool AbstractServerSocketInterface::tooManyRegistrationAttempts(const QString &ipAddress)
|
||||
{
|
||||
// TODO: implement
|
||||
Q_UNUSED(ipAddress);
|
||||
return false;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdActivateAccount(const Command_Activate &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdActivateAccount(const Command_Activate &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
QString userName = QString::fromStdString(cmd.user_name());
|
||||
QString token = QString::fromStdString(cmd.token());
|
||||
|
|
@ -1078,7 +950,7 @@ Response::ResponseCode ServerSocketInterface::cmdActivateAccount(const Command_A
|
|||
}
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdAccountEdit(const Command_AccountEdit &cmd, ResponseContainer & /* rc */)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdAccountEdit(const Command_AccountEdit &cmd, ResponseContainer & /* rc */)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -1108,7 +980,7 @@ Response::ResponseCode ServerSocketInterface::cmdAccountEdit(const Command_Accou
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer & /* rc */)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer & /* rc */)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -1126,7 +998,7 @@ Response::ResponseCode ServerSocketInterface::cmdAccountImage(const Command_Acco
|
|||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer & /* rc */)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer & /* rc */)
|
||||
{
|
||||
if (authState != PasswordRight)
|
||||
return Response::RespFunctionNotAllowed;
|
||||
|
|
@ -1151,26 +1023,26 @@ Response::ResponseCode ServerSocketInterface::cmdAccountPassword(const Command_A
|
|||
// ADMIN FUNCTIONS.
|
||||
// Permission is checked by the calling function.
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdUpdateServerMessage(const Command_UpdateServerMessage & /*cmd*/, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdUpdateServerMessage(const Command_UpdateServerMessage & /*cmd*/, ResponseContainer & /*rc*/)
|
||||
{
|
||||
QMetaObject::invokeMethod(server, "updateLoginMessage");
|
||||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdShutdownServer(const Command_ShutdownServer &cmd, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdShutdownServer(const Command_ShutdownServer &cmd, ResponseContainer & /*rc*/)
|
||||
{
|
||||
QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), Q_ARG(int, cmd.minutes()));
|
||||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdReloadConfig(const Command_ReloadConfig & /* cmd */, ResponseContainer & /*rc*/)
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdReloadConfig(const Command_ReloadConfig & /* cmd */, ResponseContainer & /*rc*/)
|
||||
{
|
||||
logDebugMessage("Received admin command: reloading configuration");
|
||||
settingsCache->sync();
|
||||
return Response::RespOk;
|
||||
}
|
||||
|
||||
Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustMod &cmd, ResponseContainer & /*rc*/) {
|
||||
Response::ResponseCode AbstractServerSocketInterface::cmdAdjustMod(const Command_AdjustMod &cmd, ResponseContainer & /*rc*/) {
|
||||
|
||||
QString userName = QString::fromStdString(cmd.user_name());
|
||||
|
||||
|
|
@ -1184,7 +1056,7 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
|
|||
return Response::RespInternalError;
|
||||
}
|
||||
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
if (user) {
|
||||
Event_NotifyUser event;
|
||||
event.set_type(Event_NotifyUser::PROMOTED);
|
||||
|
|
@ -1201,7 +1073,7 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
|
|||
return Response::RespInternalError;
|
||||
}
|
||||
|
||||
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
|
||||
AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
|
||||
if (user) {
|
||||
Event_ConnectionClosed event;
|
||||
event.set_reason(Event_ConnectionClosed::DEMOTED);
|
||||
|
|
@ -1217,4 +1089,278 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
|
|||
}
|
||||
|
||||
return Response::RespOk;
|
||||
}
|
||||
}
|
||||
|
||||
TcpServerSocketInterface::TcpServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent)
|
||||
: AbstractServerSocketInterface(_server, _databaseInterface, parent),
|
||||
messageInProgress(false),
|
||||
handshakeStarted(false)
|
||||
{
|
||||
socket = new QTcpSocket(this);
|
||||
socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
|
||||
connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
|
||||
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError)));
|
||||
}
|
||||
|
||||
|
||||
TcpServerSocketInterface::~TcpServerSocketInterface()
|
||||
{
|
||||
logger->logMessage("TcpServerSocketInterface destructor", this);
|
||||
|
||||
flushOutputQueue();
|
||||
}
|
||||
|
||||
void TcpServerSocketInterface::initConnection(int socketDescriptor)
|
||||
{
|
||||
// Add this object to the server's list of connections before it can receive socket events.
|
||||
// Otherwise, in case a of a socket error, it could be removed from the list before it is added.
|
||||
server->addClient(this);
|
||||
|
||||
socket->setSocketDescriptor(socketDescriptor);
|
||||
logger->logMessage(QString("Incoming connection: %1").arg(socket->peerAddress().toString()), this);
|
||||
initSessionDeprecated();
|
||||
}
|
||||
|
||||
void TcpServerSocketInterface::initSessionDeprecated()
|
||||
{
|
||||
// dirty hack to make v13 client display the correct error message
|
||||
|
||||
QByteArray buf;
|
||||
buf.append("<?xml version=\"1.0\"?><cockatrice_server_stream version=\"14\">");
|
||||
writeToSocket(buf);
|
||||
flushSocket();
|
||||
}
|
||||
|
||||
void TcpServerSocketInterface::flushOutputQueue()
|
||||
{
|
||||
QMutexLocker locker(&outputQueueMutex);
|
||||
if (outputQueue.isEmpty())
|
||||
return;
|
||||
|
||||
int totalBytes = 0;
|
||||
while (!outputQueue.isEmpty()) {
|
||||
ServerMessage item = outputQueue.takeFirst();
|
||||
locker.unlock();
|
||||
|
||||
QByteArray buf;
|
||||
unsigned int size = item.ByteSize();
|
||||
buf.resize(size + 4);
|
||||
item.SerializeToArray(buf.data() + 4, size);
|
||||
buf.data()[3] = (unsigned char) size;
|
||||
buf.data()[2] = (unsigned char) (size >> 8);
|
||||
buf.data()[1] = (unsigned char) (size >> 16);
|
||||
buf.data()[0] = (unsigned char) (size >> 24);
|
||||
// In case socket->write() calls catchSocketError(), the mutex must not be locked during this call.
|
||||
writeToSocket(buf);
|
||||
|
||||
totalBytes += size + 4;
|
||||
locker.relock();
|
||||
}
|
||||
locker.unlock();
|
||||
servatrice->incTxBytes(totalBytes);
|
||||
// see above wrt mutex
|
||||
flushSocket();
|
||||
}
|
||||
|
||||
void TcpServerSocketInterface::readClient()
|
||||
{
|
||||
QByteArray data = socket->readAll();
|
||||
servatrice->incRxBytes(data.size());
|
||||
inputBuffer.append(data);
|
||||
|
||||
do {
|
||||
if (!messageInProgress) {
|
||||
if (inputBuffer.size() >= 4) {
|
||||
messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24)
|
||||
+ (((quint32) (unsigned char) inputBuffer[1]) << 16)
|
||||
+ (((quint32) (unsigned char) inputBuffer[2]) << 8)
|
||||
+ ((quint32) (unsigned char) inputBuffer[3]);
|
||||
inputBuffer.remove(0, 4);
|
||||
messageInProgress = true;
|
||||
} else
|
||||
return;
|
||||
}
|
||||
if (inputBuffer.size() < messageLength)
|
||||
return;
|
||||
|
||||
CommandContainer newCommandContainer;
|
||||
try {
|
||||
newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength);
|
||||
}
|
||||
catch(std::exception &e) {
|
||||
qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Exception:" << e.what();
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
qDebug() << "Message length:" << messageLength;
|
||||
qDebug() << "Message content:" << inputBuffer.toHex();
|
||||
}
|
||||
catch(...) {
|
||||
qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
}
|
||||
|
||||
inputBuffer.remove(0, messageLength);
|
||||
messageInProgress = false;
|
||||
|
||||
// dirty hack to make v13 client display the correct error message
|
||||
if (handshakeStarted)
|
||||
processCommandContainer(newCommandContainer);
|
||||
else if (!newCommandContainer.has_cmd_id()) {
|
||||
handshakeStarted = true;
|
||||
if (!initTcpSession())
|
||||
prepareDestroy();
|
||||
}
|
||||
// end of hack
|
||||
} while (!inputBuffer.isEmpty());
|
||||
}
|
||||
|
||||
bool TcpServerSocketInterface::initTcpSession()
|
||||
{
|
||||
if(!initSession())
|
||||
return false;
|
||||
|
||||
//limit the number of websocket users based on configuration settings
|
||||
bool enforceUserLimit = settingsCache->value("security/enable_max_user_limit", false).toBool();
|
||||
if (enforceUserLimit) {
|
||||
int userLimit = settingsCache->value("security/max_users_tcp", 500).toInt();
|
||||
int playerCount = (databaseInterface->getActiveUserCount(getConnectionType()) + 1);
|
||||
if (playerCount > userLimit){
|
||||
std::cerr << "Max Tcp Users Limit Reached, please increase the max_users_tcp setting." << std::endl;
|
||||
logger->logMessage(QString("Max Tcp Users Limit Reached, please increase the max_users_tcp setting."), this);
|
||||
Event_ConnectionClosed event;
|
||||
event.set_reason(Event_ConnectionClosed::USER_LIMIT_REACHED);
|
||||
SessionEvent *se = prepareSessionEvent(event);
|
||||
sendProtocolItem(*se);
|
||||
delete se;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#if QT_VERSION > 0x050300
|
||||
WebsocketServerSocketInterface::WebsocketServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent)
|
||||
: AbstractServerSocketInterface(_server, _databaseInterface, parent)
|
||||
{
|
||||
}
|
||||
|
||||
WebsocketServerSocketInterface::~WebsocketServerSocketInterface()
|
||||
{
|
||||
logger->logMessage("WebsocketServerSocketInterface destructor", this);
|
||||
|
||||
flushOutputQueue();
|
||||
}
|
||||
|
||||
void WebsocketServerSocketInterface::initConnection(void * _socket)
|
||||
{
|
||||
socket = (QWebSocket*) _socket;
|
||||
connect(socket, SIGNAL(binaryMessageReceived(const QByteArray &)), this, SLOT(binaryMessageReceived(const QByteArray &)));
|
||||
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError)));
|
||||
|
||||
// Add this object to the server's list of connections before it can receive socket events.
|
||||
// Otherwise, in case a of a socket error, it could be removed from the list before it is added.
|
||||
server->addClient(this);
|
||||
|
||||
logger->logMessage(QString("Incoming websocket connection: %1").arg(socket->peerAddress().toString()), this);
|
||||
|
||||
if(!initWebsocketSession())
|
||||
prepareDestroy();
|
||||
}
|
||||
|
||||
bool WebsocketServerSocketInterface::initWebsocketSession()
|
||||
{
|
||||
if(!initSession())
|
||||
return false;
|
||||
|
||||
//limit the number of websocket users based on configuration settings
|
||||
bool enforceUserLimit = settingsCache->value("security/enable_max_user_limit", false).toBool();
|
||||
if (enforceUserLimit) {
|
||||
int userLimit = settingsCache->value("security/max_users_websocket", 500).toInt();
|
||||
int playerCount = (databaseInterface->getActiveUserCount(getConnectionType()) + 1);
|
||||
if (playerCount > userLimit){
|
||||
std::cerr << "Max Websocket Users Limit Reached, please increase the max_users_websocket setting." << std::endl;
|
||||
logger->logMessage(QString("Max Websocket Users Limit Reached, please increase the max_users_websocket setting."), this);
|
||||
Event_ConnectionClosed event;
|
||||
event.set_reason(Event_ConnectionClosed::USER_LIMIT_REACHED);
|
||||
SessionEvent *se = prepareSessionEvent(event);
|
||||
sendProtocolItem(*se);
|
||||
delete se;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void WebsocketServerSocketInterface::flushOutputQueue()
|
||||
{
|
||||
QMutexLocker locker(&outputQueueMutex);
|
||||
if (outputQueue.isEmpty())
|
||||
return;
|
||||
|
||||
int totalBytes = 0;
|
||||
while (!outputQueue.isEmpty()) {
|
||||
ServerMessage item = outputQueue.takeFirst();
|
||||
locker.unlock();
|
||||
|
||||
QByteArray buf;
|
||||
unsigned int size = item.ByteSize();
|
||||
buf.resize(size);
|
||||
item.SerializeToArray(buf.data(), size);
|
||||
// In case socket->write() calls catchSocketError(), the mutex must not be locked during this call.
|
||||
writeToSocket(buf);
|
||||
|
||||
totalBytes += size;
|
||||
locker.relock();
|
||||
}
|
||||
locker.unlock();
|
||||
servatrice->incTxBytes(totalBytes);
|
||||
// see above wrt mutex
|
||||
flushSocket();
|
||||
}
|
||||
|
||||
void WebsocketServerSocketInterface::binaryMessageReceived(const QByteArray & message)
|
||||
{
|
||||
servatrice->incRxBytes(message.size());
|
||||
|
||||
CommandContainer newCommandContainer;
|
||||
try {
|
||||
newCommandContainer.ParseFromArray(message.data(), message.size());
|
||||
}
|
||||
catch(std::exception &e) {
|
||||
qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Exception:" << e.what();
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
qDebug() << "Message length:" << message.size();
|
||||
qDebug() << "Message content:" << message.toHex();
|
||||
}
|
||||
catch(...) {
|
||||
qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ <<
|
||||
#ifdef _MSC_VER // Visual Studio
|
||||
__FUNCTION__;
|
||||
#else
|
||||
__PRETTY_FUNCTION__;
|
||||
#endif
|
||||
qDebug() << "Message coming from:" << getAddress();
|
||||
}
|
||||
|
||||
processCommandContainer(newCommandContainer);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -21,11 +21,13 @@
|
|||
#define SERVERSOCKETINTERFACE_H
|
||||
|
||||
#include <QTcpSocket>
|
||||
#if QT_VERSION > 0x050300
|
||||
#include <QWebSocket>
|
||||
#endif
|
||||
#include <QHostAddress>
|
||||
#include <QMutex>
|
||||
#include "server_protocolhandler.h"
|
||||
|
||||
class QTcpSocket;
|
||||
class Servatrice;
|
||||
class Servatrice_DatabaseInterface;
|
||||
class DeckList;
|
||||
|
|
@ -53,31 +55,27 @@ class Command_AccountEdit;
|
|||
class Command_AccountImage;
|
||||
class Command_AccountPassword;
|
||||
|
||||
|
||||
class ServerSocketInterface : public Server_ProtocolHandler
|
||||
class AbstractServerSocketInterface : public Server_ProtocolHandler
|
||||
{
|
||||
Q_OBJECT
|
||||
private slots:
|
||||
void readClient();
|
||||
protected slots:
|
||||
void catchSocketError(QAbstractSocket::SocketError socketError);
|
||||
void flushOutputQueue();
|
||||
virtual void flushOutputQueue() = 0;
|
||||
signals:
|
||||
void outputQueueChanged();
|
||||
protected:
|
||||
void logDebugMessage(const QString &message);
|
||||
bool tooManyRegistrationAttempts(const QString &ipAddress);
|
||||
private:
|
||||
QMutex outputQueueMutex;
|
||||
|
||||
virtual void writeToSocket(QByteArray & data) = 0;
|
||||
virtual void flushSocket() = 0;
|
||||
|
||||
Servatrice *servatrice;
|
||||
Servatrice_DatabaseInterface *sqlInterface;
|
||||
QTcpSocket *socket;
|
||||
|
||||
QByteArray inputBuffer;
|
||||
QList<ServerMessage> outputQueue;
|
||||
bool messageInProgress;
|
||||
bool handshakeStarted;
|
||||
int messageLength;
|
||||
|
||||
QMutex outputQueueMutex;
|
||||
private:
|
||||
Servatrice_DatabaseInterface *sqlInterface;
|
||||
|
||||
Response::ResponseCode cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc);
|
||||
Response::ResponseCode cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc);
|
||||
int getDeckPathId(int basePathId, QStringList path);
|
||||
|
|
@ -117,16 +115,67 @@ private:
|
|||
Response::ResponseCode cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer &rc);
|
||||
Response::ResponseCode cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer &rc);
|
||||
public:
|
||||
ServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0);
|
||||
~ServerSocketInterface();
|
||||
void initSessionDeprecated();
|
||||
AbstractServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0);
|
||||
~AbstractServerSocketInterface() { };
|
||||
bool initSession();
|
||||
QHostAddress getPeerAddress() const { return socket->peerAddress(); }
|
||||
QString getAddress() const { return socket->peerAddress().toString(); }
|
||||
|
||||
virtual QHostAddress getPeerAddress() const = 0;
|
||||
virtual QString getAddress() const = 0;
|
||||
|
||||
void transmitProtocolItem(const ServerMessage &item);
|
||||
};
|
||||
|
||||
class TcpServerSocketInterface : public AbstractServerSocketInterface
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
TcpServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0);
|
||||
~TcpServerSocketInterface();
|
||||
|
||||
QHostAddress getPeerAddress() const { return socket->peerAddress(); }
|
||||
QString getAddress() const { return socket->peerAddress().toString(); }
|
||||
QString getConnectionType() const { return "tcp"; };
|
||||
private:
|
||||
QTcpSocket *socket;
|
||||
QByteArray inputBuffer;
|
||||
bool messageInProgress;
|
||||
bool handshakeStarted;
|
||||
int messageLength;
|
||||
protected:
|
||||
void writeToSocket(QByteArray & data) { socket->write(data); };
|
||||
void flushSocket() { socket->flush(); };
|
||||
void initSessionDeprecated();
|
||||
bool initTcpSession();
|
||||
protected slots:
|
||||
void readClient();
|
||||
void flushOutputQueue();
|
||||
public slots:
|
||||
void initConnection(int socketDescriptor);
|
||||
};
|
||||
|
||||
#if QT_VERSION > 0x050300
|
||||
class WebsocketServerSocketInterface : public AbstractServerSocketInterface
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
WebsocketServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0);
|
||||
~WebsocketServerSocketInterface();
|
||||
|
||||
QHostAddress getPeerAddress() const { return socket->peerAddress(); }
|
||||
QString getAddress() const { return socket->peerAddress().toString(); }
|
||||
QString getConnectionType() const { return "websocket"; };
|
||||
private:
|
||||
QWebSocket *socket;
|
||||
protected:
|
||||
void writeToSocket(QByteArray & data) { socket->sendBinaryMessage(data); };
|
||||
void flushSocket() { socket->flush(); };
|
||||
bool initWebsocketSession();
|
||||
protected slots:
|
||||
void binaryMessageReceived(const QByteArray & message);
|
||||
void flushOutputQueue();
|
||||
public slots:
|
||||
void initConnection(void * _socket);
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue