Implementation of websockets in servatrice and test js client

This commit is contained in:
Fabio Bas 2015-12-24 17:40:49 +01:00
parent e81a6d497b
commit 5b21dc8cde
42 changed files with 39592 additions and 287 deletions

View file

@ -3,7 +3,7 @@
#include "server_room.h" #include "server_room.h"
LocalServer::LocalServer(QObject *parent) LocalServer::LocalServer(QObject *parent)
: Server(false, parent) : Server(parent)
{ {
setDatabaseInterface(new LocalServer_DatabaseInterface(this)); setDatabaseInterface(new LocalServer_DatabaseInterface(this));
addRoom(new Server_Room(0, 0, QString(), QString(), QString(), false, QString(), QStringList(), this)); addRoom(new Server_Room(0, 0, QString(), QString(), QString(), false, QString(), QStringList(), this));

View file

@ -27,7 +27,7 @@ public:
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, const QString &clientId, QString &reasonStr, int &secondsLeft); AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, const QString &clientId, QString &reasonStr, int &secondsLeft);
int getNextGameId() { return localServer->getNextLocalGameId(); } int getNextGameId() { return localServer->getNextLocalGameId(); }
int getNextReplayId() { return -1; } int getNextReplayId() { return -1; }
int getActiveUserCount() { return 0; } int getActiveUserCount(QString /* connectionType */) { return 0; }
}; };
#endif #endif

View file

@ -13,6 +13,7 @@ public:
~LocalServerInterface(); ~LocalServerInterface();
QString getAddress() const { return QString(); } QString getAddress() const { return QString(); }
QString getConnectionType() const { return "local"; };
void transmitProtocolItem(const ServerMessage &item); void transmitProtocolItem(const ServerMessage &item);
signals: signals:
void itemToClient(const ServerMessage &item); void itemToClient(const ServerMessage &item);

View file

@ -37,8 +37,8 @@
#include <QThread> #include <QThread>
#include <QDebug> #include <QDebug>
Server::Server(bool _threaded, QObject *parent) Server::Server(QObject *parent)
: QObject(parent), threaded(_threaded), nextLocalGameId(0) : QObject(parent), nextLocalGameId(0)
{ {
qRegisterMetaType<ServerInfo_Ban>("ServerInfo_Ban"); qRegisterMetaType<ServerInfo_Ban>("ServerInfo_Ban");
qRegisterMetaType<ServerInfo_Game>("ServerInfo_Game"); qRegisterMetaType<ServerInfo_Game>("ServerInfo_Game");
@ -60,32 +60,26 @@ Server::~Server()
void Server::prepareDestroy() void Server::prepareDestroy()
{ {
// dirty :( // dirty :(
if (threaded) { clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i)
QMetaObject::invokeMethod(clients.at(i), "prepareDestroy", Qt::QueuedConnection);
clientsLock.unlock();
bool done = false;
class SleeperThread : public QThread
{
public:
static void msleep(unsigned long msecs) { QThread::usleep(msecs); }
};
do {
SleeperThread::msleep(10);
clientsLock.lockForRead(); clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i) if (clients.isEmpty())
QMetaObject::invokeMethod(clients.at(i), "prepareDestroy", Qt::QueuedConnection); done = true;
clientsLock.unlock(); clientsLock.unlock();
} while (!done);
bool done = false;
class SleeperThread : public QThread
{
public:
static void msleep(unsigned long msecs) { QThread::usleep(msecs); }
};
do {
SleeperThread::msleep(10);
clientsLock.lockForRead();
if (clients.isEmpty())
done = true;
clientsLock.unlock();
} while (!done);
} else {
// no locking is needed in unthreaded mode
while (!clients.isEmpty())
clients.first()->prepareDestroy();
}
roomsLock.lockForWrite(); roomsLock.lockForWrite();
QMapIterator<int, Server_Room *> roomIterator(rooms); QMapIterator<int, Server_Room *> roomIterator(rooms);
@ -106,7 +100,7 @@ Server_DatabaseInterface *Server::getDatabaseInterface() const
return databaseInterfaces.value(QThread::currentThread()); return databaseInterfaces.value(QThread::currentThread());
} }
AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft, QString &clientid, QString &clientVersion) AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft, QString &clientid, QString &clientVersion, QString & /* connectionType */)
{ {
if (name.size() > 35) if (name.size() > 35)
name = name.left(35); name = name.left(35);
@ -162,7 +156,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(), clientid)); data.set_session_id(databaseInterface->startSession(name, session->getAddress(), clientid, session->getConnectionType()));
databaseInterface->unlockSessionTables(); databaseInterface->unlockSessionTables();
usersBySessionId.insert(data.session_id(), session); usersBySessionId.insert(data.session_id(), session);

View file

@ -44,10 +44,9 @@ private slots:
void broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl = false); void broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl = false);
public: public:
mutable QReadWriteLock clientsLock, roomsLock; // locking order: roomsLock before clientsLock mutable QReadWriteLock clientsLock, roomsLock; // locking order: roomsLock before clientsLock
Server(bool _threaded, QObject *parent = 0); Server(QObject *parent = 0);
~Server(); ~Server();
void setThreaded(bool _threaded) { threaded = _threaded; } AuthenticationResult loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reason, int &secondsLeft, QString &clientid, QString &clientVersion, QString &connectionType);
AuthenticationResult loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reason, int &secondsLeft, QString &clientid, QString &clientVersion);
const QMap<int, Server_Room *> &getRooms() { return rooms; } const QMap<int, Server_Room *> &getRooms() { return rooms; }
@ -73,8 +72,6 @@ public:
virtual int getCommandCountingInterval() const { return 0; } virtual int getCommandCountingInterval() const { return 0; }
virtual int getMaxCommandCountPerInterval() const { return 0; } virtual int getMaxCommandCountPerInterval() const { return 0; }
virtual bool getThreaded() const { return false; }
Server_DatabaseInterface *getDatabaseInterface() const; Server_DatabaseInterface *getDatabaseInterface() const;
int getNextLocalGameId() { QMutexLocker locker(&nextLocalGameIdMutex); return ++nextLocalGameId; } int getNextLocalGameId() { QMutexLocker locker(&nextLocalGameIdMutex); return ++nextLocalGameId; }
@ -93,7 +90,6 @@ public:
void removePersistentPlayer(const QString &userName, int roomId, int gameId, int playerId); void removePersistentPlayer(const QString &userName, int roomId, int gameId, int playerId);
QList<PlayerReference> getPersistentPlayerReferences(const QString &userName) const; QList<PlayerReference> getPersistentPlayerReferences(const QString &userName) const;
private: private:
bool threaded;
QMultiMap<QString, PlayerReference> persistentPlayers; QMultiMap<QString, PlayerReference> persistentPlayers;
mutable QReadWriteLock persistentPlayersLock; mutable QReadWriteLock persistentPlayersLock;
int nextLocalGameId; int nextLocalGameId;

View file

@ -22,14 +22,14 @@ public:
virtual void storeGameInformation(const QString & /* roomName */, const QStringList & /* roomGameTypes */, const ServerInfo_Game & /* gameInfo */, const QSet<QString> & /* allPlayersEver */, const QSet<QString> & /* allSpectatorsEver */, const QList<GameReplay *> & /* replayList */) { } virtual void storeGameInformation(const QString & /* roomName */, const QStringList & /* roomGameTypes */, const ServerInfo_Game & /* gameInfo */, const QSet<QString> & /* allPlayersEver */, const QSet<QString> & /* allSpectatorsEver */, const QList<GameReplay *> & /* replayList */) { }
virtual DeckList *getDeckFromDatabase(int /* deckId */, int /* userId */) { return 0; } virtual DeckList *getDeckFromDatabase(int /* deckId */, int /* userId */) { return 0; }
virtual qint64 startSession(const QString & /* userName */, const QString & /* address */, const QString & /* clientId */) { return 0; } virtual qint64 startSession(const QString & /* userName */, const QString & /* address */, const QString & /* clientId */, const QString & /* connectionType */) { return 0; }
virtual bool usernameIsValid(const QString & /*userName */, QString & /* error */) { return true; }; virtual bool usernameIsValid(const QString & /*userName */, QString & /* error */) { return true; };
public slots: public slots:
virtual void endSession(qint64 /* sessionId */ ) { } virtual void endSession(qint64 /* sessionId */ ) { }
public: public:
virtual int getNextGameId() = 0; virtual int getNextGameId() = 0;
virtual int getNextReplayId() = 0; virtual int getNextReplayId() = 0;
virtual int getActiveUserCount() = 0; virtual int getActiveUserCount(QString connectionType = QString()) = 0;
virtual void clearSessionTables() { } virtual void clearSessionTables() { }
virtual void lockSessionTables() { } virtual void lockSessionTables() { }

View file

@ -414,7 +414,8 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
QString reasonStr; QString reasonStr;
int banSecondsLeft = 0; int banSecondsLeft = 0;
AuthenticationResult res = server->loginUser(this, userName, QString::fromStdString(cmd.password()), reasonStr, banSecondsLeft, clientId, clientVersion); QString connectionType = getConnectionType();
AuthenticationResult res = server->loginUser(this, userName, QString::fromStdString(cmd.password()), reasonStr, banSecondsLeft, clientId, clientVersion, connectionType);
switch (res) { switch (res) {
case UserIsBanned: { case UserIsBanned: {
Response_Login *re = new Response_Login; Response_Login *re = new Response_Login;

View file

@ -92,6 +92,7 @@ public:
bool getAcceptsUserListChanges() const { return acceptsUserListChanges; } bool getAcceptsUserListChanges() const { return acceptsUserListChanges; }
bool getAcceptsRoomListChanges() const { return acceptsRoomListChanges; } bool getAcceptsRoomListChanges() const { return acceptsRoomListChanges; }
virtual QString getAddress() const = 0; virtual QString getAddress() const = 0;
virtual QString getConnectionType() const = 0;
Server_DatabaseInterface *getDatabaseInterface() const { return databaseInterface; } Server_DatabaseInterface *getDatabaseInterface() const { return databaseInterface; }
int getLastCommandTime() const { return timeRunning - lastDataReceived; } int getLastCommandTime() const { return timeRunning - lastDataReceived; }

View file

@ -57,6 +57,13 @@ if(Qt5Widgets_FOUND)
list(APPEND SERVATRICE_LIBS Sql) list(APPEND SERVATRICE_LIBS Sql)
endif() endif()
# QtWebsockets
find_package(Qt5WebSockets)
if(Qt5WebSockets_FOUND)
include_directories(${Qt5WebSockets_INCLUDE_DIRS})
list(APPEND SERVATRICE_LIBS WebSockets)
endif()
QT5_ADD_RESOURCES(servatrice_RESOURCES_RCC ${servatrice_RESOURCES}) QT5_ADD_RESOURCES(servatrice_RESOURCES_RCC ${servatrice_RESOURCES})
# guess plugins and libraries directory # guess plugins and libraries directory

View file

@ -0,0 +1,6 @@
-- Servatrice db migration from version 13 to version 14
alter table cockatrice_sessions add `connection_type` ENUM('tcp', 'websocket');
UPDATE cockatrice_sessions SET connection_type = 'tcp';
UPDATE cockatrice_schema_version SET version=14 WHERE version=13;

View file

@ -20,8 +20,16 @@ port=4747
; Servatrice can scale up to serve big number of users using more than one parallel thread of execution; ; Servatrice can scale up to serve big number of users using more than one parallel thread of execution;
; If your server is hosting a lot of players and they frequently report of being unable to login or ; If your server is hosting a lot of players and they frequently report of being unable to login or
; long delays (lag), you may want to try increasing this value; default is 1. ; long delays (lag), you may want to try increasing this value; default is 1.
; Set to 0 to disable the tcp server.
number_pools=1 number_pools=1
; Servatrice can listen for clients on websockets, too. Unfortunately it can't support more than one thread.
; Set to 0 to disable the websocket server.
websocket_number_pools=1
; The TCP port number servatrice will listen on for websockets clients; default is 4748
websocket_port=4748
; When database is enabled, servatrice writes the server status in the "update" database table; this ; When database is enabled, servatrice writes the server status in the "update" database table; this
; setting defines every how many milliseconds servatrice will update its status; default is 15000 (15 secs) ; setting defines every how many milliseconds servatrice will update its status; default is 15000 (15 secs)
statusupdate=15000 statusupdate=15000
@ -227,6 +235,12 @@ enable_max_user_limit=false
; Maximum number of users that can connect to the server, default is 500. ; Maximum number of users that can connect to the server, default is 500.
max_users_total=500 max_users_total=500
; Maximum number of users that can connect to the server using a tcp connection, default is 500.
max_users_tcp=500
; Maximum number of users that can connect to the server using a websocket connection, default is 500.
max_users_websocket=500
; Maximum number of users that can connect from the same IP address; useful to avoid bots, default is 4 ; Maximum number of users that can connect from the same IP address; useful to avoid bots, default is 4
max_users_per_address=4 max_users_per_address=4

View file

@ -20,7 +20,7 @@ CREATE TABLE IF NOT EXISTS `cockatrice_schema_version` (
PRIMARY KEY (`version`) PRIMARY KEY (`version`)
) ENGINE=INNODB DEFAULT CHARSET=utf8; ) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO cockatrice_schema_version VALUES(13); INSERT INTO cockatrice_schema_version VALUES(14);
-- users and user data tables -- users and user data tables
CREATE TABLE IF NOT EXISTS `cockatrice_users` ( CREATE TABLE IF NOT EXISTS `cockatrice_users` (
@ -190,6 +190,7 @@ CREATE TABLE IF NOT EXISTS `cockatrice_sessions` (
`start_time` datetime NOT NULL, `start_time` datetime NOT NULL,
`end_time` datetime DEFAULT NULL, `end_time` datetime DEFAULT NULL,
`clientid` varchar(15) NOT NULL, `clientid` varchar(15) NOT NULL,
`connection_type` ENUM('tcp', 'websocket'),
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
KEY `username` (`user_name`) KEY `username` (`user_name`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

View file

@ -44,16 +44,6 @@ Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPoo
: QTcpServer(parent), : QTcpServer(parent),
server(_server) 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) { 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);
@ -83,7 +73,18 @@ Servatrice_GameServer::~Servatrice_GameServer()
void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor) 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 minClientCount = -1;
int poolIndex = -1; int poolIndex = -1;
QStringList debugStr; QStringList debugStr;
@ -96,16 +97,68 @@ void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor)
debugStr.append(QString::number(clientCount)); debugStr.append(QString::number(clientCount));
} }
qDebug() << "Pool utilisation:" << debugStr; qDebug() << "Pool utilisation:" << debugStr;
Servatrice_ConnectionPool *pool = connectionPools[poolIndex]; return connectionPools[poolIndex];
}
ServerSocketInterface *ssi = new ServerSocketInterface(server, pool->getDatabaseInterface()); #if QT_VERSION > 0x050300
ssi->moveToThread(pool->thread()); #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(); 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(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) void Servatrice_IslServer::incomingConnection(qintptr socketDescriptor)
{ {
QThread *thread = new QThread; QThread *thread = new QThread;
@ -120,7 +173,7 @@ void Servatrice_IslServer::incomingConnection(qintptr socketDescriptor)
} }
Servatrice::Servatrice(QObject *parent) Servatrice::Servatrice(QObject *parent)
: Server(true, parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true) : Server(parent), uptime(0), shutdownTimer(0), isFirstShutdownMessage(true)
{ {
qRegisterMetaType<QSqlDatabase>("QSqlDatabase"); qRegisterMetaType<QSqlDatabase>("QSqlDatabase");
} }
@ -162,7 +215,11 @@ bool Servatrice::initServer()
if (maxUserLimitEnabled){ if (maxUserLimitEnabled){
int maxUserLimit = settingsCache->value("security/max_users_total", 500).toInt(); 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(); bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool();
@ -369,17 +426,39 @@ bool Servatrice::initServer()
statusUpdateClock->start(statusUpdateTime); statusUpdateClock->start(statusUpdateTime);
} }
// SOCKET SERVER
const int numberPools = settingsCache->value("server/number_pools", 1).toInt(); const int numberPools = settingsCache->value("server/number_pools", 1).toInt();
gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this); if(numberPools > 0)
gameServer->setMaxPendingConnections(1000); {
const int gamePort = settingsCache->value("server/port", 4747).toInt(); gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
qDebug() << "Starting server on port" << gamePort; gameServer->setMaxPendingConnections(1000);
if (gameServer->listen(QHostAddress::Any, gamePort)) const int gamePort = settingsCache->value("server/port", 4747).toInt();
qDebug() << "Server listening."; qDebug() << "Starting server on port" << gamePort;
else { if (gameServer->listen(QHostAddress::Any, gamePort))
qDebug() << "gameServer->listen(): Error:" << gameServer->errorString(); qDebug() << "Server listening.";
return false; 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; return true;
} }
@ -420,19 +499,19 @@ 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<AbstractServerSocketInterface *>(clients[i])->getPeerAddress() == address)
++result; ++result;
return 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); 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<AbstractServerSocketInterface *>(clients[i])->getPeerAddress() == address)
result.append(static_cast<ServerSocketInterface *>(clients[i])); result.append(static_cast<AbstractServerSocketInterface *>(clients[i]));
return result; return result;
} }

View file

@ -21,6 +21,9 @@
#define SERVATRICE_H #define SERVATRICE_H
#include <QTcpServer> #include <QTcpServer>
#if QT_VERSION > 0x050300
#include <QWebSocketServer>
#endif
#include <QMutex> #include <QMutex>
#include <QSslCertificate> #include <QSslCertificate>
#include <QSslKey> #include <QSslKey>
@ -40,7 +43,7 @@ class GameReplay;
class Servatrice; class Servatrice;
class Servatrice_ConnectionPool; class Servatrice_ConnectionPool;
class Servatrice_DatabaseInterface; class Servatrice_DatabaseInterface;
class ServerSocketInterface; class AbstractServerSocketInterface;
class IslInterface; class IslInterface;
class FeatureSet; class FeatureSet;
@ -54,8 +57,25 @@ public:
~Servatrice_GameServer(); ~Servatrice_GameServer();
protected: protected:
void incomingConnection(qintptr socketDescriptor); 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 { class Servatrice_IslServer : public QTcpServer {
Q_OBJECT Q_OBJECT
private: private:
@ -98,6 +118,9 @@ private:
DatabaseType databaseType; DatabaseType databaseType;
QTimer *pingClock, *statusUpdateClock; QTimer *pingClock, *statusUpdateClock;
Servatrice_GameServer *gameServer; Servatrice_GameServer *gameServer;
#if QT_VERSION > 0x050300
Servatrice_WebsocketGameServer *websocketGameServer;
#endif
Servatrice_IslServer *islServer; Servatrice_IslServer *islServer;
QString serverName; QString serverName;
mutable QMutex loginMessageMutex; mutable QMutex loginMessageMutex;
@ -154,7 +177,7 @@ public:
QString getDbPrefix() const { return dbPrefix; } QString getDbPrefix() const { return dbPrefix; }
int getServerId() const { return serverId; } int getServerId() const { return serverId; }
int getUsersWithAddress(const QHostAddress &address) const; 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 incTxBytes(quint64 num);
void incRxBytes(quint64 num); void incRxBytes(quint64 num);
void addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface); void addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface);

View file

@ -579,7 +579,7 @@ bool Servatrice_DatabaseInterface::userSessionExists(const QString &userName)
return query->next(); 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) if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
return -1; return -1;
@ -587,11 +587,12 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const
if (!checkSql()) if (!checkSql())
return -1; 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(":user_name", userName);
query->bindValue(":id_server", server->getServerId()); query->bindValue(":id_server", server->getServerId());
query->bindValue(":ip_address", address); query->bindValue(":ip_address", address);
query->bindValue(":client_id", clientId); query->bindValue(":client_id", clientId);
query->bindValue(":connection_type", connectionType);
if (execSqlQuery(query)) if (execSqlQuery(query))
return query->lastInsertId().toInt(); return query->lastInsertId().toInt();
return -1; return -1;
@ -850,22 +851,27 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user, const
return false; return false;
} }
int Servatrice_DatabaseInterface::getActiveUserCount() int Servatrice_DatabaseInterface::getActiveUserCount(QString connectionType)
{ {
int userCount = 0; int userCount = 0;
if (!checkSql()) if (!checkSql())
return userCount; return userCount;
QSqlQuery *query = prepareQuery("select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL"); QString text = "select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL";
query->bindValue(":serverid", server->getServerId()); if(!connectionType.isEmpty())
if (!execSqlQuery(query)){ text +=" AND connection_type = :connection_type";
return userCount; 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(); userCount = query->value(0).toInt();
}
return userCount; return userCount;
} }

View file

@ -9,7 +9,7 @@
#include "server.h" #include "server.h"
#include "server_database_interface.h" #include "server_database_interface.h"
#define DATABASE_SCHEMA_VERSION 13 #define DATABASE_SCHEMA_VERSION 14
class Servatrice; class Servatrice;
@ -59,8 +59,9 @@ public:
int getNextGameId(); int getNextGameId();
int getNextReplayId(); int getNextReplayId();
int getActiveUserCount(); int getActiveUserCount(QString connectionType = QString());
qint64 startSession(const QString &userName, const QString &address, const QString &clientId);
qint64 startSession(const QString &userName, const QString &address, const QString &clientId, const QString & connectionType);
void endSession(qint64 sessionId); void endSession(qint64 sessionId);
void clearSessionTables(); void clearSessionTables();
void lockSessionTables(); void lockSessionTables();

View file

@ -74,52 +74,17 @@
static const int protocolVersion = 14; 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), : Server_ProtocolHandler(_server, _databaseInterface, parent),
servatrice(_server), servatrice(_server),
sqlInterface(reinterpret_cast<Servatrice_DatabaseInterface *>(databaseInterface)), sqlInterface(reinterpret_cast<Servatrice_DatabaseInterface *>(databaseInterface))
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)));
// Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error, // 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. // 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); connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection);
} }
ServerSocketInterface::~ServerSocketInterface() bool AbstractServerSocketInterface::initSession()
{
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()
{ {
Event_ServerIdentification identEvent; Event_ServerIdentification identEvent;
identEvent.set_server_name(servatrice->getServerName().toStdString()); identEvent.set_server_name(servatrice->getServerName().toStdString());
@ -148,11 +113,11 @@ bool ServerSocketInterface::initSession()
//allow unlimited number of connections from the trusted sources //allow unlimited number of connections from the trusted sources
QString trustedSources = settingsCache->value("security/trusted_sources","127.0.0.1,::1").toString(); 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; return true;
int maxUsers = servatrice->getMaxUsersPerAddress(); int maxUsers = servatrice->getMaxUsersPerAddress();
if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { if ((maxUsers > 0) && (servatrice->getUsersWithAddress(getPeerAddress()) >= maxUsers)) {
Event_ConnectionClosed event; Event_ConnectionClosed event;
event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS); event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS);
SessionEvent *se = prepareSessionEvent(event); SessionEvent *se = prepareSessionEvent(event);
@ -165,76 +130,14 @@ bool ServerSocketInterface::initSession()
return true; return true;
} }
void ServerSocketInterface::readClient() void AbstractServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError)
{
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)
{ {
qDebug() << "Socket error:" << socketError; qDebug() << "Socket error:" << socketError;
prepareDestroy(); prepareDestroy();
} }
void ServerSocketInterface::transmitProtocolItem(const ServerMessage &item) void AbstractServerSocketInterface::transmitProtocolItem(const ServerMessage &item)
{ {
outputQueueMutex.lock(); outputQueueMutex.lock();
outputQueue.append(item); outputQueue.append(item);
@ -243,43 +146,12 @@ void ServerSocketInterface::transmitProtocolItem(const ServerMessage &item)
emit outputQueueChanged(); emit outputQueueChanged();
} }
void ServerSocketInterface::flushOutputQueue() void AbstractServerSocketInterface::logDebugMessage(const QString &message)
{
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)
{ {
logger->logMessage(message, this); 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) { switch ((SessionCommand::SessionCommandType) cmdType) {
case SessionCommand::ADD_TO_LIST: return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc); 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) { switch ((ModeratorCommand::ModeratorCommandType) cmdType) {
case ModeratorCommand::BAN_FROM_SERVER: return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc); 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) { switch ((AdminCommand::AdminCommandType) cmdType) {
case AdminCommand::SHUTDOWN_SERVER: return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc); 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -367,7 +239,7 @@ Response::ResponseCode ServerSocketInterface::cmdAddToList(const Command_AddToLi
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -404,7 +276,7 @@ Response::ResponseCode ServerSocketInterface::cmdRemoveFromList(const Command_Re
return Response::RespOk; return Response::RespOk;
} }
int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path) int AbstractServerSocketInterface::getDeckPathId(int basePathId, QStringList path)
{ {
if (path.isEmpty()) if (path.isEmpty())
return 0; return 0;
@ -426,12 +298,12 @@ int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path)
return getDeckPathId(id, path); return getDeckPathId(id, path);
} }
int ServerSocketInterface::getDeckPathId(const QString &path) int AbstractServerSocketInterface::getDeckPathId(const QString &path)
{ {
return getDeckPathId(0, path.split("/")); 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"); 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); query->bindValue(":id_parent", folderId);
@ -474,7 +346,7 @@ bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_
// CHECK AUTHENTICATION! // CHECK AUTHENTICATION!
// Also check for every function that data belonging to other users cannot be accessed. // 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -491,7 +363,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckList(const Command_DeckList
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -511,7 +383,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckNewDir(const Command_DeckNe
return Response::RespOk; return Response::RespOk;
} }
void ServerSocketInterface::deckDelDirHelper(int basePathId) void AbstractServerSocketInterface::deckDelDirHelper(int basePathId)
{ {
sqlInterface->checkSql(); sqlInterface->checkSql();
QSqlQuery *query = sqlInterface->prepareQuery("select id from {prefix}_decklist_folders where id_parent = :id_parent"); 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); 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) if (!user)
return; return;
@ -544,7 +416,7 @@ void ServerSocketInterface::sendServerMessage(const QString userName, const QStr
delete se; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -558,7 +430,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDelDir(const Command_DeckDe
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -578,7 +450,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDel(const Command_DeckDel &
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -636,7 +508,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -656,7 +528,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDownload(const Command_Deck
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -704,7 +576,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_Replay
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -735,7 +607,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_Re
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -753,7 +625,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayModifyMatch(const Command
return query->numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -773,7 +645,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command
// MODERATOR FUNCTIONS. // MODERATOR FUNCTIONS.
// May be called by admins and moderators. Permission is checked by the calling function. // 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; QList<ServerInfo_ChatMessage> messageList;
@ -806,7 +678,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetLogHistory(const Command_Vie
return Response::RespOk; 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; QList<ServerInfo_Ban> banList;
QString userName = QString::fromStdString(cmd.user_name()); QString userName = QString::fromStdString(cmd.user_name());
@ -819,7 +691,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetBanHistory(const Command_Get
return Response::RespOk; 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; Response_WarnList *re = new Response_WarnList;
@ -834,7 +706,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetWarnList(const Command_GetWa
return Response::RespOk; 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; QList<ServerInfo_Warning> warnList;
QString userName = QString::fromStdString(cmd.user_name()); QString userName = QString::fromStdString(cmd.user_name());
@ -847,7 +719,7 @@ Response::ResponseCode ServerSocketInterface::cmdGetWarnHistory(const Command_Ge
return Response::RespOk; 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()) if (!sqlInterface->checkSql())
return Response::RespInternalError; return Response::RespInternalError;
@ -859,7 +731,7 @@ Response::ResponseCode ServerSocketInterface::cmdWarnUser(const Command_WarnUser
if (sqlInterface->addWarning(userName, sendingModerator, warningReason, clientID)) { if (sqlInterface->addWarning(userName, sendingModerator, warningReason, clientID)) {
servatrice->clientsLock.lockForRead(); 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(); QList<QString> moderatorList = server->getOnlineModeratorList();
servatrice->clientsLock.unlock(); 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()) if (!sqlInterface->checkSql())
return Response::RespInternalError; return Response::RespInternalError;
@ -915,10 +787,10 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
servatrice->clientsLock.lockForRead(); servatrice->clientsLock.lockForRead();
QList<QString> moderatorList = server->getOnlineModeratorList(); QList<QString> moderatorList = server->getOnlineModeratorList();
QList<ServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address)); QList<AbstractServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));
if (!userName.isEmpty()) { 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)) if (user && !userList.contains(user))
userList.append(user); userList.append(user);
} }
@ -932,7 +804,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
} else { } else {
while (query->next()) { while (query->next()) {
userName = query->value(0).toString(); 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)) if (user && !userList.contains(user))
userList.append(user); userList.append(user);
} }
@ -974,7 +846,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
return Response::RespOk; 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 userName = QString::fromStdString(cmd.user_name());
QString clientId = QString::fromStdString(cmd.clientid()); 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 // TODO: implement
Q_UNUSED(ipAddress); Q_UNUSED(ipAddress);
return false; 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 userName = QString::fromStdString(cmd.user_name());
QString token = QString::fromStdString(cmd.token()); 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -1108,7 +980,7 @@ Response::ResponseCode ServerSocketInterface::cmdAccountEdit(const Command_Accou
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -1126,7 +998,7 @@ Response::ResponseCode ServerSocketInterface::cmdAccountImage(const Command_Acco
return Response::RespOk; 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) if (authState != PasswordRight)
return Response::RespFunctionNotAllowed; return Response::RespFunctionNotAllowed;
@ -1151,26 +1023,26 @@ Response::ResponseCode ServerSocketInterface::cmdAccountPassword(const Command_A
// ADMIN FUNCTIONS. // ADMIN FUNCTIONS.
// Permission is checked by the calling function. // 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"); QMetaObject::invokeMethod(server, "updateLoginMessage");
return Response::RespOk; 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())); QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), Q_ARG(int, cmd.minutes()));
return Response::RespOk; 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"); logDebugMessage("Received admin command: reloading configuration");
settingsCache->sync(); settingsCache->sync();
return Response::RespOk; 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()); QString userName = QString::fromStdString(cmd.user_name());
@ -1184,7 +1056,7 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
return Response::RespInternalError; return Response::RespInternalError;
} }
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName)); AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
if (user) { if (user) {
Event_NotifyUser event; Event_NotifyUser event;
event.set_type(Event_NotifyUser::PROMOTED); event.set_type(Event_NotifyUser::PROMOTED);
@ -1201,7 +1073,7 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
return Response::RespInternalError; return Response::RespInternalError;
} }
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName)); AbstractServerSocketInterface *user = static_cast<AbstractServerSocketInterface *>(server->getUsers().value(userName));
if (user) { if (user) {
Event_ConnectionClosed event; Event_ConnectionClosed event;
event.set_reason(Event_ConnectionClosed::DEMOTED); event.set_reason(Event_ConnectionClosed::DEMOTED);
@ -1217,4 +1089,278 @@ Response::ResponseCode ServerSocketInterface::cmdAdjustMod(const Command_AdjustM
} }
return Response::RespOk; 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

View file

@ -21,11 +21,13 @@
#define SERVERSOCKETINTERFACE_H #define SERVERSOCKETINTERFACE_H
#include <QTcpSocket> #include <QTcpSocket>
#if QT_VERSION > 0x050300
#include <QWebSocket>
#endif
#include <QHostAddress> #include <QHostAddress>
#include <QMutex> #include <QMutex>
#include "server_protocolhandler.h" #include "server_protocolhandler.h"
class QTcpSocket;
class Servatrice; class Servatrice;
class Servatrice_DatabaseInterface; class Servatrice_DatabaseInterface;
class DeckList; class DeckList;
@ -53,31 +55,27 @@ class Command_AccountEdit;
class Command_AccountImage; class Command_AccountImage;
class Command_AccountPassword; class Command_AccountPassword;
class AbstractServerSocketInterface : public Server_ProtocolHandler
class ServerSocketInterface : public Server_ProtocolHandler
{ {
Q_OBJECT Q_OBJECT
private slots: protected slots:
void readClient();
void catchSocketError(QAbstractSocket::SocketError socketError); void catchSocketError(QAbstractSocket::SocketError socketError);
void flushOutputQueue(); virtual void flushOutputQueue() = 0;
signals: signals:
void outputQueueChanged(); void outputQueueChanged();
protected: protected:
void logDebugMessage(const QString &message); void logDebugMessage(const QString &message);
bool tooManyRegistrationAttempts(const QString &ipAddress); bool tooManyRegistrationAttempts(const QString &ipAddress);
private:
QMutex outputQueueMutex; virtual void writeToSocket(QByteArray & data) = 0;
virtual void flushSocket() = 0;
Servatrice *servatrice; Servatrice *servatrice;
Servatrice_DatabaseInterface *sqlInterface;
QTcpSocket *socket;
QByteArray inputBuffer;
QList<ServerMessage> outputQueue; QList<ServerMessage> outputQueue;
bool messageInProgress; QMutex outputQueueMutex;
bool handshakeStarted; private:
int messageLength; Servatrice_DatabaseInterface *sqlInterface;
Response::ResponseCode cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc); Response::ResponseCode cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc);
Response::ResponseCode cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc); Response::ResponseCode cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc);
int getDeckPathId(int basePathId, QStringList path); int getDeckPathId(int basePathId, QStringList path);
@ -117,16 +115,67 @@ private:
Response::ResponseCode cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer &rc); Response::ResponseCode cmdAccountImage(const Command_AccountImage &cmd, ResponseContainer &rc);
Response::ResponseCode cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer &rc); Response::ResponseCode cmdAccountPassword(const Command_AccountPassword &cmd, ResponseContainer &rc);
public: public:
ServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0); AbstractServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent = 0);
~ServerSocketInterface(); ~AbstractServerSocketInterface() { };
void initSessionDeprecated();
bool initSession(); 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); 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: public slots:
void initConnection(int socketDescriptor); 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 #endif

226
webclient/index.html Executable file
View file

@ -0,0 +1,226 @@
<!doctype html>
<html>
<head>
<title>Servatrice web client</title>
<link rel="stylesheet" href="js/jquery-ui-1.11.4.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="loading">
Loading servatrice web client...
</div>
<div id="tabs" style="display:none">
<ul>
<li><a href="#tab-login">Login</a></li>
<li><a href="#tab-server">Server</a></li>
<li><a href="#tab-account">Account</a></li>
</ul>
<div id="tab-login">
<h3>Login to server</h3>
<label for="host">Host</label>
<input type="text" id="host" value="127.0.0.1" />
<br/>
<label for="port">Port</label>
<input type="text" id="port" value ="4748" />
<br/>
<label for="user">Username</label>
<input type="text" id="user" />
<br/>
<label for="pass">Password</label>
<input type="password" id="pass" />
<br/>
<button id="loginnow">Connect</button>
<button id="quit" style="display:none">Disconnect</button>
<span id="status"></span>
</div>
<div id="tab-server">
<h3>Rooms</h3>
<span id="roomslist"></span>
<h3>Server messages</h3>
<div id="servermessages"></div>
</div>
<div id="tab-account">
<h3>User info</h3>
<span id="userinfo"></span>
<h3>Buddies</h3>
<select id="buddies" size="10"></select>
<h3>Ignores</h3>
<select id="ignores" size="10"></select>
<h3>Missing features</h3>
<span id="features"></span>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
<script src="js/jquery-ui-1.11.4.js"></script>
<script src="js/long.js"></script>
<script src="js/bytebuffer.js"></script>
<script src="js/protobuf.js"></script>
<script src="webclient.js"></script>
<script>
$("#tabs").tabs();
$("#tabs").tabs("disable").tabs("enable", "tab-login");
$("#loading").hide();
$("#tabs").show();
$( document ).ready(function() {
function ts2time(ts) {
var d = new Date(Number(ts));
return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
}
function getTime() {
var d = new Date();
return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
}
function htmlEscape(msg) {
return $("<div>").text(msg).html();
}
$("#loginnow").click(connect);
$("#host, #port, #user, #pass").keydown(function(e) {
if (e.keyCode == 13) { connect(); }
});
function connect() {
var host = $("#host").val();
var port = $("#port").val();
if(!host.length || !port.length)
{
alert('Please enter a valid host and port.');
return;
}
var options = {
"debug": true,
"autojoinrooms" : true,
"host": host,
"port": port,
"user": $("#user").val(),
"pass": $("#pass").val(),
"statusCallback" : function(id, desc) {
$("#status").text(desc);
if(id == StatusEnum.LOGGEDIN)
{
$("#tabs").tabs("enable").tabs("option", "active", 1);
$("#loginnow").hide();
$("#quit").show();
} else {
$("#tabs").tabs("disable").tabs("enable", "tab-login").tabs("option", "active", 0);
$("#quit").hide();
$("#loginnow").show().prop("disabled", false);
// close rooms
$(".room-header, .room-div").remove();
}
},
"connectionClosedCallback" : function(id, desc) {
$("#status").text('Connection closed: ' + desc);
$("#tabs").tabs("disable").tabs("enable", "tab-login").tabs("option", "active", 0);
$("#quit").hide();
$("#loginnow").show().prop("disabled", false);
// close rooms
$(".room-header, .room-div").remove();
},
"serverMessageCallback" : function(message) {
$("#servermessages").append(htmlEscape(message) + '<br/>');
},
"userInfoCallback" : function(data) {
$("#userinfo").empty();
$.each(data.userInfo, function(key, value) {
// filter out inherited properties
if (data.userInfo.hasOwnProperty(key))
$('#userinfo').append(key + ': ' + value + '<br/>');
});
$('#buddies').empty();
$.each(data.buddyList, function(key, value) {
$('#buddies').append('<option>' + value.name + '</option>');
});
$('#ignores').empty();
$.each(data.ignoreList, function(key, value) {
$('#ignores').append('<option>' + value.name + '</option>');
});
$("#features").text(JSON.stringify(data.missingFeatures, null, 4));
},
"listRoomsCallback" : function(rooms) {
$("#roomslist").text(JSON.stringify(rooms, null, 4));
},
"errorCallback" : function(id, desc) {
$("#roomslist").text(desc);
},
"joinRoomCallback" : function(room) {
$("div#tabs ul").append(
"<li class='room-header'><a href='#tab-room-" + room["roomId"] + "'>" + room["name"] + "</a></li>"
);
$("div#tabs").append(
"<div class='room-div' id='tab-room-" + room["roomId"] + "'>" + room["name"] +
"<h3>Userlist</h3>" +
"<select class=\"userlist\" size=\"10\"></select>" +
"<h3>Chat</h3>" +
"<div class=\"output\"></div>" +
"<br/><input type=\"text\" class=\"input\" />" +
"<button class=\"say\">say</button>" +
"</div>"
);
$("div#tabs").tabs("refresh");
$("#tab-room-" + room["roomId"] + " .userlist").empty();
$.each(room["userList"], function(key, value) {
$("#tab-room-" + room["roomId"] + " .userlist").append('<option>' + value.name + '</option>');
});
$("#tab-room-" + room["roomId"] + " .say").click(function() {
var msg = $("#tab-room-" + room["roomId"] + " .input").val();
$("#tab-room-" + room["roomId"] + " .input").val("");
WebClient.roomSay(room["roomId"], msg);
});
$("#tab-room-" + room["roomId"] + " .input").keydown(function(e) {
if (e.keyCode == 13) {
var msg = $("#tab-room-" + room["roomId"] + " .input").val();
$("#tab-room-" + room["roomId"] + " .input").val("");
WebClient.roomSay(room["roomId"], msg);
}
});
},
"roomMessageCallback" : function(roomId, message) {
var text;
switch(message["messageType"])
{
case WebClient.pb.Event_RoomSay.RoomMessageType.Welcome:
text = "<span class='serverwelcome'>" + htmlEscape(message["message"]) + "</span>";
break;
case WebClient.pb.Event_RoomSay.RoomMessageType.ChatHistory:
text = "<span class='chathistory'>[" + ts2time(message["timeOf"]) + "] " + htmlEscape(message["message"]) + "</span>";
break;
default:
text = "[" + getTime() + "] " + htmlEscape(message["name"]) + ": " + htmlEscape(message["message"]);
break;
}
$("#tab-room-" + roomId + " .output").append(text + '<br/>');
},
};
$(this).prop("disabled", true);
WebClient.connect(options);
};
$("#quit").click(function() {
WebClient.disconnect();
});
});
</script>
</body>
</html>

3651
webclient/js/bytebuffer.js Executable file

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 312 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 328 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

10351
webclient/js/jquery-1.11.3.js vendored Executable file

File diff suppressed because it is too large Load diff

1225
webclient/js/jquery-ui-1.11.4.css vendored Normal file

File diff suppressed because it is too large Load diff

16617
webclient/js/jquery-ui-1.11.4.js vendored Normal file

File diff suppressed because it is too large Load diff

1220
webclient/js/long.js Executable file

File diff suppressed because it is too large Load diff

5211
webclient/js/protobuf.js Executable file

File diff suppressed because it is too large Load diff

1
webclient/pb Symbolic link
View file

@ -0,0 +1 @@
../common/pb

54
webclient/style.css Executable file
View file

@ -0,0 +1,54 @@
p {
position: relative;
}
#tab-login {
padding: 1em;
}
#tab-login label {
display: block;
width: 100px;
float: left;
padding-right: 10px;
clear:left;
}
#tab-login input {
margin-bottom: 10px;
}
#loading {
font-size: 200%;
text-align:center;
margin-top:200px;
}
.output, #servermessages {
width:100%;
min-height: 400px;
overflow-x: hidden;
overflow-y: scroll;
word-wrap: break-word;
word-break:break-all;
background-color: #fff;
box-shadow: inset 1px 1px 3px #999;
padding: .5em;
}
.input {
width:95%;
}
.serverwelcome {
color: #006600;
font-weight: bold;
}
.chathistory {
color: #c0c0c0;
}
#buddies, #ignores, .userlist {
width: 20em;
}

424
webclient/webclient.js Executable file
View file

@ -0,0 +1,424 @@
var StatusEnum = {
DISCONNECTED : 0,
CONNECTING : 1,
CONNECTED : 2,
LOGGINGIN : 3,
LOGGEDIN : 4,
DISCONNECTING : 99
};
var WebClient = {
status : StatusEnum.DISCONNECTED,
socket : 0,
keepalivecb: null,
lastPingPending: false,
cmdId : 0,
initialized: false,
pendingCommands : {},
options : {
host: "",
port: "",
user: "",
pass: "",
debug: false,
autojoinrooms: false,
keepalive: 5000
},
protobuf : null,
builder : null,
pb : null,
pbfiles : [
// commands
"pb/commands.proto",
"pb/session_commands.proto",
"pb/room_commands.proto",
// replies
"pb/server_message.proto",
"pb/response.proto",
"pb/response_login.proto",
"pb/session_event.proto",
"pb/event_server_message.proto",
"pb/event_connection_closed.proto",
"pb/event_list_rooms.proto",
"pb/response_join_room.proto",
"pb/room_event.proto",
"pb/event_room_say.proto"
],
initialize : function()
{
this.protobuf = dcodeIO.ProtoBuf;
this.builder = this.protobuf.newBuilder({ convertFieldsToCamelCase: true });
$.each(this.pbfiles, function(index, fileName) {
WebClient.protobuf.loadProtoFile(fileName, WebClient.builder);
});
this.pb = this.builder.build();
this.initialized=true;
},
guid : function(options)
{
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
},
setStatus : function(status, desc)
{
this.status = status;
if(this.options.debug)
console.log("Stats change:", status, desc)
if(this.options.statusCallback)
this.options.statusCallback(status, desc);
},
resetConnectionvars : function () {
this.cmdId = 0;
this.pendingCommands = {};
},
sendCommand : function (cmd, callback)
{
this.cmdId++;
cmd["cmdId"] = this.cmdId;
this.pendingCommands[this.cmdId] = callback;
if (this.socket.readyState == WebSocket.OPEN) {
this.socket.send(cmd.toArrayBuffer());
if(this.options.debug)
console.log("Sent: " + cmd.toString());
} else {
if(this.options.debug)
console.log("Send: Not connected");
}
},
sendRoomCommand : function(roomId, roomCmd, callback)
{
var cmd = new WebClient.pb.CommandContainer({
"roomId" : roomId,
"roomCommand" : [ roomCmd ]
});
WebClient.sendCommand(cmd, callback);
},
sendSessionCommand : function(ses, callback)
{
var cmd = new WebClient.pb.CommandContainer({
"sessionCommand" : [ ses ]
});
WebClient.sendCommand(cmd, callback);
},
startPingLoop : function()
{
keepalivecb = setInterval(function() {
// check if the previous ping got no reply
if(WebClient.lastPingPending)
{
WebClient.socket.close();
WebClient.setStatus(StatusEnum.DISCONNECTED, 'Connection timeout');
}
// stop the ping loop if we're disconnected
if(WebClient.status != StatusEnum.LOGGEDIN)
{
clearInterval(keepalivecb);
keepalivecb = null;
return;
}
// send a ping
var CmdPing = new WebClient.pb.Command_Ping();
var sc = new WebClient.pb.SessionCommand({
".Command_Ping.ext" : CmdPing
});
WebClient.lastPingPending = true;
WebClient.sendSessionCommand(sc, function() {
WebClient.lastPingPending = false;
});
}, WebClient.options.keepalive);
},
doLogin : function()
{
var CmdLogin = new WebClient.pb.Command_Login({
"userName" : this.options.user,
"password" : this.options.pass,
"clientid" : this.guid(),
"clientver" : "webclient-0.1 (2015-12-23)",
"clientfeatures" : [ "client_id", "client_ver"],
});
var sc = new WebClient.pb.SessionCommand({
".Command_Login.ext" : CmdLogin
});
this.sendSessionCommand(sc, function(raw) {
var resp = raw[".Response_Login.ext"];
switch(raw.responseCode)
{
case WebClient.pb.Response.ResponseCode.RespOk:
WebClient.setStatus(StatusEnum.LOGGEDIN, 'Logged in.');
if(WebClient.options.userInfoCallback)
WebClient.options.userInfoCallback(resp);
WebClient.startPingLoop();
WebClient.doListRooms();
break;
case WebClient.pb.Response.ResponseCode.RespClientUpdateRequired:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: missing features');
break;
case WebClient.pb.Response.ResponseCode.RespWrongPassword:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: incorrect username or password');
break;
case WebClient.pb.Response.ResponseCode.RespWouldOverwriteOldSession:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: duplicated user session');
break;
case WebClient.pb.Response.ResponseCode.RespUserIsBanned:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: banned user');
break;
case WebClient.pb.Response.ResponseCode.RespUsernameInvalid:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: invalid username');
break;
case WebClient.pb.Response.ResponseCode.RespRegistrationRequired:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: registration required');
break;
case WebClient.pb.Response.ResponseCode.RespClientIdRequired:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: missing client ID');
break;
case WebClient.pb.Response.ResponseCode.RespContextError:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: server error');
break;
case WebClient.pb.Response.ResponseCode.RespAccountNotActivated:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: account not activated');
break;
case WebClient.pb.Response.ResponseCode.RespClientUpdateRequired:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: missing features');
break;
default:
WebClient.setStatus(StatusEnum.DISCONNECTING, 'Login failed: unknown error ' + raw.responseCode);
break;
}
});
},
doListRooms : function()
{
var CmdListRooms = new WebClient.pb.Command_ListRooms();
var sc = new WebClient.pb.SessionCommand({
".Command_ListRooms.ext" : CmdListRooms
});
this.sendSessionCommand(sc, function(raw) {
// Command_ListRooms 's response will be received inside a sessionEvent
});
},
processSessionEvent : function (raw)
{
if(raw[".Event_ConnectionClosed.ext"]) {
var message = '';
switch(raw[".Event_ConnectionClosed.ext"]["reason"])
{
case WebClient.pb.Event_ConnectionClosed.CloseReason.USER_LIMIT_REACHED:
message = 'The server has reached its maximum user capacity';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.TOO_MANY_CONNECTIONS:
message = 'There are too many concurrent connections from your address';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.BANNED:
message = 'You are banned';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.SERVER_SHUTDOWN:
message = 'Scheduled server shutdown';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.USERNAMEINVALID:
message = 'Invalid username';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.LOGGEDINELSEWERE:
message = 'You have been logged out due to logging in at another location';
break;
case WebClient.pb.Event_ConnectionClosed.CloseReason.OTHER:
default:
message = 'Unknown reason';
break;
}
if(this.options.connectionClosedCallback)
this.options.connectionClosedCallback(raw[".Event_ConnectionClosed.ext"]["reason"], message);
return;
}
if(raw[".Event_ServerMessage.ext"]) {
if(this.options.serverMessageCallback)
this.options.serverMessageCallback(raw[".Event_ServerMessage.ext"]["message"]);
return;
}
if(raw[".Event_ListRooms.ext"]) {
var roomsList = raw[".Event_ListRooms.ext"]["roomList"];
if(this.options.listRoomsCallback)
this.options.listRoomsCallback(roomsList);
if(this.options.autojoinrooms)
{
$.each(roomsList, function(index, room) {
if(room.autoJoin)
{
var CmdJoinRoom = new WebClient.pb.Command_JoinRoom({
"roomId" : room.roomId
});
var sc = new WebClient.pb.SessionCommand({
".Command_JoinRoom.ext" : CmdJoinRoom
});
WebClient.sendSessionCommand(sc, WebClient.processJoinRoom);
}
});
}
return;
}
},
processRoomEvent : function (raw)
{
if(raw[".Event_RoomSay.ext"]) {
if(this.options.roomMessageCallback)
this.options.roomMessageCallback(raw["roomId"], raw[".Event_RoomSay.ext"]);
return;
}
},
processJoinRoom : function(raw)
{
switch(raw["responseCode"])
{
case WebClient.pb.Response.ResponseCode.RespOk:
var roomInfo = raw[".Response_JoinRoom.ext"]["roomInfo"];
if(WebClient.options.joinRoomCallback)
WebClient.options.joinRoomCallback(roomInfo);
break;
case WebClient.pb.Response.ResponseCode.RespNameNotFound:
if(WebClient.options.errorCallback) WebClient.options.errorCallback(raw["responseCode"], "Failed to join the room: it doesn't exists on the server.");
return;
case WebClient.pb.Response.ResponseCode.RespContextError:
if(WebClient.options.errorCallback) WebClient.options.errorCallback(raw["responseCode"], "The server thinks you are in the room but Cockatrice is unable to display it. Try restarting Cockatrice.");
return;
case WebClient.pb.Response.ResponseCode.RespUserLevelTooLow:
if(WebClient.options.errorCallback) WebClient.options.errorCallback(raw["responseCode"], "You do not have the required permission to join this room.");
return;
default:
if(WebClient.options.errorCallback) WebClient.options.errorCallback(raw["responseCode"], "Failed to join the room due to an unknown error: " + raw["responseCode"]);
return;
}
},
connect : function(options) {
jQuery.extend(this.options, options || {});
if(!this.initialized)
this.initialize();
this.socket = new WebSocket('ws://' + this.options.host + ':' + this.options.port);
this.socket.binaryType = "arraybuffer"; // We are talking binary
this.setStatus(StatusEnum.CONNECTING, 'Connecting...');
this.socket.onclose = function() {
WebClient.setStatus(StatusEnum.DISCONNECTED, 'Connection closed');
}
this.socket.onerror = function() {
WebClient.setStatus(StatusEnum.DISCONNECTED, 'Connection failed');
}
this.socket.onopen = function(){
WebClient.setStatus(StatusEnum.CONNECTED, 'Connected, logging in...');
WebClient.resetConnectionvars();
WebClient.doLogin();
}
this.socket.onmessage = function(event) {
//console.log("Received " + event.data.byteLength + " bytes");
try {
var msg = WebClient.pb.ServerMessage.decode(event.data);
if(WebClient.options.debug)
console.log(msg);
} catch (err) {
console.log("Processing failed:", err);
if(WebClient.options.debug)
{
var view = new Uint8Array(event.data);
var str = "";
for(var i = 0; i < view.length; i++)
{
str += String.fromCharCode(view[i]);
}
console.log(str);
}
return;
}
switch (msg.messageType) {
case WebClient.pb.ServerMessage.MessageType.RESPONSE:
var response = msg.response;
var cmdId = response.cmdId;
if(!WebClient.pendingCommands.hasOwnProperty(cmdId))
return;
WebClient.pendingCommands[cmdId](response);
delete WebClient.pendingCommands[cmdId];
break;
case WebClient.pb.ServerMessage.MessageType.SESSION_EVENT:
WebClient.processSessionEvent(msg.sessionEvent);
break;
case WebClient.pb.ServerMessage.MessageType.GAME_EVENT_CONTAINER:
// TODO
break;
case WebClient.pb.ServerMessage.MessageType.ROOM_EVENT:
WebClient.processRoomEvent(msg.roomEvent);
break;
}
}
},
disconnect : function() {
this.socket.close();
},
roomSay : function(roomId, msg) {
var CmdRoomSay = new WebClient.pb.Command_RoomSay({
"message" : msg
});
var sc = new WebClient.pb.RoomCommand({
".Command_RoomSay.ext" : CmdRoomSay
});
WebClient.sendRoomCommand(roomId, sc, function(raw) {
switch(raw["responseCode"])
{
case WebClient.pb.Response.ResponseCode.RespChatFlood:
console.log("room flood " + roomId);
break;
default:
break;
}
});
}
}