From da98d24d8c38e3b4b8695b9f6007e73faa8586ea Mon Sep 17 00:00:00 2001 From: wcollins Date: Tue, 18 Nov 2014 15:09:21 -0500 Subject: [PATCH 1/9] added trusted sources to servatrice --- servatrice/servatrice.ini.example | 7 +- servatrice/src/servatrice.cpp | 122 ++++++++-------- servatrice/src/serversocketinterface.cpp | 174 ++++++++++++----------- 3 files changed, 161 insertions(+), 142 deletions(-) diff --git a/servatrice/servatrice.ini.example b/servatrice/servatrice.ini.example index 05a5ba3a..a7429d33 100644 --- a/servatrice/servatrice.ini.example +++ b/servatrice/servatrice.ini.example @@ -22,7 +22,7 @@ port=4747 ; long delays (lag), you may want to try increasing this value; default is 1. number_pools=1 -; 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) statusupdate=15000 @@ -125,6 +125,11 @@ max_game_inactivity_time=120 ; Maximum number of users that can connect from the same IP address; useful to avoid bots, default is 4 max_users_per_address=4 +; You may want to allow an unlimited number of users from a trusted source. This setting can contain a +; comma-separed list of IP addresses which will allow an unlimited number of connections from each of the +; IP addresses listed (ignoring the max_users_per_address). Default is "127.0.0.1,::1"; example: "192.73.233.244,81.4.100.74" +trusted_sources="" + ; Servatrice can avoid users from flooding rooms with large number messages in an interval of time. ; This setting defines the length in seconds of the considered interval; default is 10 message_counting_interval=10 diff --git a/servatrice/src/servatrice.cpp b/servatrice/src/servatrice.cpp index 168c230c..e0eb40fb 100644 --- a/servatrice/src/servatrice.cpp +++ b/servatrice/src/servatrice.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "servatrice.h" #include "servatrice_database_interface.h" @@ -34,7 +35,10 @@ #include "main.h" #include "decklist.h" #include "pb/event_server_message.pb.h" -#include "pb/event_server_shutdown.pb.h" +#include "pb/event_server_shutdo; You may want to allow an unlimited number of users from a trusted source. This setting can contain a +; comma-separed list of IP addresses which will allow an unlimited number of connections from each of the +; IP addresses listed (ignoring the max_users_per_address). Default is "127.0.0.1,::1"; example: "192.73.233.244,81.4.100.74" +trusted_sources=""wn.pb.h" #include "pb/event_connection_closed.pb.h" Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent) @@ -45,25 +49,25 @@ Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPoo server->setThreaded(false); Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(0, server); Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface); - + server->addDatabaseInterface(thread(), newDatabaseInterface); newDatabaseInterface->initDatabase(_sqlDatabase); - + connectionPools.append(newPool); } else for (int i = 0; i < _numberPools; ++i) { Servatrice_DatabaseInterface *newDatabaseInterface = new Servatrice_DatabaseInterface(i, server); Servatrice_ConnectionPool *newPool = new Servatrice_ConnectionPool(newDatabaseInterface); - + QThread *newThread = new QThread; newThread->setObjectName("pool_" + QString::number(i)); newPool->moveToThread(newThread); newDatabaseInterface->moveToThread(newThread); server->addDatabaseInterface(newThread, newDatabaseInterface); - + newThread->start(); QMetaObject::invokeMethod(newDatabaseInterface, "initDatabase", Qt::BlockingQueuedConnection, Q_ARG(QSqlDatabase, _sqlDatabase)); - + connectionPools.append(newPool); } } @@ -98,12 +102,12 @@ void Servatrice_GameServer::incomingConnection(qintptr socketDescriptor) } qDebug() << "Pool utilisation:" << debugStr; Servatrice_ConnectionPool *pool = connectionPools[poolIndex]; - + ServerSocketInterface *ssi = new ServerSocketInterface(server, pool->getDatabaseInterface()); ssi->moveToThread(pool->thread()); pool->addClient(); connect(ssi, SIGNAL(destroyed()), pool, SLOT(removeClient())); - + QMetaObject::invokeMethod(ssi, "initConnection", Qt::QueuedConnection, Q_ARG(int, socketDescriptor)); } @@ -111,11 +115,11 @@ void Servatrice_IslServer::incomingConnection(int socketDescriptor) { QThread *thread = new QThread; connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); - + IslInterface *interface = new IslInterface(socketDescriptor, cert, privateKey, server); interface->moveToThread(thread); connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); - + thread->start(); QMetaObject::invokeMethod(interface, "initServer", Qt::QueuedConnection); } @@ -137,7 +141,7 @@ bool Servatrice::initServer() serverName = settingsCache->value("server/name", "My Cockatrice server").toString(); serverId = settingsCache->value("server/id", 0).toInt(); bool regServerOnly = settingsCache->value("authentication/regonly", 0).toBool(); - + const QString authenticationMethodStr = settingsCache->value("authentication/method").toString(); if (authenticationMethodStr == "sql") { qDebug() << "Authenticating method: sql"; @@ -148,22 +152,22 @@ bool Servatrice::initServer() } else { if (regServerOnly) { qDebug() << "Registration only server enabled but no authentication method defined: Error."; - return false; + return false; } qDebug() << "Authenticating method: none"; authenticationMethod = AuthenticationNone; } - + QString dbTypeStr = settingsCache->value("database/type").toString(); if (dbTypeStr == "mysql") databaseType = DatabaseMySql; else databaseType = DatabaseNone; - + servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this); setDatabaseInterface(servatriceDatabaseInterface); - + if (databaseType != DatabaseNone) { settingsCache->beginGroup("database"); dbPrefix = settingsCache->value("prefix").toString(); @@ -173,13 +177,13 @@ bool Servatrice::initServer() settingsCache->value("user").toString(), settingsCache->value("password").toString()); settingsCache->endGroup(); - + updateServerList(); - + qDebug() << "Clearing previous sessions..."; servatriceDatabaseInterface->clearSessionTables(); } - + const QString roomMethod = settingsCache->value("rooms/method").toString(); if (roomMethod == "sql") { QSqlQuery query(servatriceDatabaseInterface->getDatabase()); @@ -193,7 +197,7 @@ bool Servatrice::initServer() QStringList gameTypes; while (query2.next()) gameTypes.append(query2.value(0).toString()); - + addRoom(new Server_Room(query.value(0).toInt(), query.value(1).toString(), query.value(2).toString(), @@ -207,7 +211,7 @@ bool Servatrice::initServer() int size = settingsCache->beginReadArray("rooms/roomlist"); for (int i = 0; i < size; ++i) { settingsCache->setArrayIndex(i); - + QStringList gameTypes; int size2 = settingsCache->beginReadArray("game_types"); for (int j = 0; j < size2; ++j) { @@ -215,7 +219,7 @@ bool Servatrice::initServer() gameTypes.append(settingsCache->value("name").toString()); } settingsCache->endArray(); - + Server_Room *newRoom = new Server_Room( i, settingsCache->value("name").toString(), @@ -240,17 +244,17 @@ bool Servatrice::initServer() QStringList("Standard"), this ); - addRoom(newRoom); + addRoom(newRoom); } settingsCache->endArray(); } - + updateLoginMessage(); - + maxGameInactivityTime = settingsCache->value("game/max_game_inactivity_time", 120).toInt(); maxPlayerInactivityTime = settingsCache->value("game/max_player_inactivity_time", 15).toInt(); - + maxUsersPerAddress = settingsCache->value("security/max_users_per_address", 4).toInt(); messageCountingInterval = settingsCache->value("security/message_counting_interval", 10).toInt(); maxMessageCountPerInterval = settingsCache->value("security/max_message_count_per_interval", 10).toInt(); @@ -283,7 +287,7 @@ bool Servatrice::initServer() QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); if (key.isNull()) throw QString("Invalid private key."); - + QMutableListIterator serverIterator(serverList); while (serverIterator.hasNext()) { const ServerProperties &prop = serverIterator.next(); @@ -291,22 +295,22 @@ bool Servatrice::initServer() serverIterator.remove(); continue; } - + QThread *thread = new QThread; thread->setObjectName("isl_" + QString::number(prop.id)); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); - + IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this); interface->moveToThread(thread); connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); - + thread->start(); QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection); } - + const int networkPort = settingsCache->value("servernetwork/port", 14747).toInt(); qDebug() << "Starting ISL server on port" << networkPort; - + islServer = new Servatrice_IslServer(this, cert, key, this); if (islServer->listen(QHostAddress::Any, networkPort)) qDebug() << "ISL server listening."; @@ -316,11 +320,11 @@ bool Servatrice::initServer() qDebug() << "ERROR --" << error; return false; } - + pingClock = new QTimer(this); connect(pingClock, SIGNAL(timeout()), this, SIGNAL(pingClockTimeout())); pingClock->start(1000); - + int statusUpdateTime = settingsCache->value("server/statusupdate", 15000).toInt(); statusUpdateClock = new QTimer(this); connect(statusUpdateClock, SIGNAL(timeout()), this, SLOT(statusUpdate())); @@ -328,7 +332,7 @@ bool Servatrice::initServer() qDebug() << "Starting status update clock, interval " << statusUpdateTime << " ms"; statusUpdateClock->start(statusUpdateTime); } - + const int numberPools = settingsCache->value("server/number_pools", 1).toInt(); gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this); gameServer->setMaxPendingConnections(1000); @@ -351,10 +355,10 @@ void Servatrice::addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterf void Servatrice::updateServerList() { qDebug() << "Updating server list..."; - + serverListMutex.lock(); serverList.clear(); - + QSqlQuery query(servatriceDatabaseInterface->getDatabase()); query.prepare("select id, ssl_cert, hostname, address, game_port, control_port from " + dbPrefix + "_servers order by id asc"); servatriceDatabaseInterface->execSqlQuery(query); @@ -363,7 +367,7 @@ void Servatrice::updateServerList() serverList.append(prop); qDebug() << QString("#%1 CERT=%2 NAME=%3 IP=%4:%5 CPORT=%6").arg(prop.id).arg(QString(prop.cert.digest().toHex())).arg(prop.hostname).arg(prop.address.toString()).arg(prop.gamePort).arg(prop.controlPort); } - + serverListMutex.unlock(); } @@ -372,17 +376,23 @@ QList Servatrice::getServerList() const serverListMutex.lock(); QList result = serverList; serverListMutex.unlock(); - + return result; } int Servatrice::getUsersWithAddress(const QHostAddress &address) const { int result = 0; - QReadLocker locker(&clientsLock); - for (int i = 0; i < clients.size(); ++i) - if (static_cast(clients[i])->getPeerAddress() == address) - ++result; + QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); + + if (trustedSources.contains(address.toString(),Qt::CaseInsensitive)) { + //allow all clients from trusted sources regardsless of number of connections + } else { + QReadLocker locker(&clientsLock); + for (int i = 0; i < clients.size(); ++i) + if (static_cast(clients[i])->getPeerAddress() == address) + ++result; + } return result; } @@ -400,18 +410,18 @@ void Servatrice::updateLoginMessage() { if (!servatriceDatabaseInterface->checkSql()) return; - + QSqlQuery query(servatriceDatabaseInterface->getDatabase()); query.prepare("select message from " + dbPrefix + "_servermessages where id_server = :id_server order by timest desc limit 1"); query.bindValue(":id_server", serverId); if (servatriceDatabaseInterface->execSqlQuery(query)) if (query.next()) { const QString newLoginMessage = query.value(0).toString(); - + loginMessageMutex.lock(); loginMessage = newLoginMessage; loginMessageMutex.unlock(); - + Event_ServerMessage event; event.set_message(newLoginMessage.toStdString()); SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); @@ -426,12 +436,12 @@ void Servatrice::statusUpdate() { if (!servatriceDatabaseInterface->checkSql()) return; - + const int uc = getUsersCount(); // for correct mutex locking order const int gc = getGamesCount(); - + uptime += statusUpdateClock->interval() / 1000; - + txBytesMutex.lock(); quint64 tx = txBytes; txBytes = 0; @@ -440,7 +450,7 @@ void Servatrice::statusUpdate() quint64 rx = rxBytes; rxBytes = 0; rxBytesMutex.unlock(); - + QSqlQuery query(servatriceDatabaseInterface->getDatabase()); query.prepare("insert into " + dbPrefix + "_uptime (id_server, timest, uptime, users_count, games_count, tx_bytes, rx_bytes) values(:id, NOW(), :uptime, :users_count, :games_count, :tx, :rx)"); query.bindValue(":id", serverId); @@ -481,7 +491,7 @@ void Servatrice::incRxBytes(quint64 num) void Servatrice::shutdownTimeout() { --shutdownMinutes; - + SessionEvent *se; if (shutdownMinutes) { Event_ServerShutdown event; @@ -493,13 +503,13 @@ void Servatrice::shutdownTimeout() event.set_reason(Event_ConnectionClosed::SERVER_SHUTDOWN); se = Server_ProtocolHandler::prepareSessionEvent(event); } - + clientsLock.lockForRead(); for (int i = 0; i < clients.size(); ++i) clients[i]->sendProtocolItem(*se); clientsLock.unlock(); delete se; - + if (!shutdownMinutes) deleteLater(); } @@ -507,14 +517,14 @@ void Servatrice::shutdownTimeout() bool Servatrice::islConnectionExists(int serverId) const { // Only call with islLock locked at least for reading - + return islInterfaces.contains(serverId); } void Servatrice::addIslInterface(int serverId, IslInterface *interface) { // Only call with islLock locked for writing - + islInterfaces.insert(serverId, interface); connect(interface, SIGNAL(externalUserJoined(ServerInfo_User)), this, SLOT(externalUserJoined(ServerInfo_User))); connect(interface, SIGNAL(externalUserLeft(QString)), this, SLOT(externalUserLeft(QString))); @@ -531,7 +541,7 @@ void Servatrice::addIslInterface(int serverId, IslInterface *interface) void Servatrice::removeIslInterface(int serverId) { // Only call with islLock locked for writing - + // XXX we probably need to delete everything that belonged to it... islInterfaces.remove(serverId); } @@ -539,7 +549,7 @@ void Servatrice::removeIslInterface(int serverId) void Servatrice::doSendIslMessage(const IslMessage &msg, int serverId) { QReadLocker locker(&islLock); - + if (serverId == -1) { QMapIterator islIterator(islInterfaces); while (islIterator.hasNext()) diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index f91029d7..705e2edf 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -22,6 +22,7 @@ #include #include #include +#include "settingscache.h" #include "serversocketinterface.h" #include "servatrice.h" #include "servatrice_database_interface.h" @@ -72,7 +73,7 @@ ServerSocketInterface::ServerSocketInterface(Servatrice *_server, Servatrice_Dat socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); connect(socket, SIGNAL(readyRead()), this, SLOT(readClient())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); - + // Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error, // it could lead to this object being destroyed while another function is still on the call stack. -> mutex deadlocks etc. connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection); @@ -81,7 +82,7 @@ ServerSocketInterface::ServerSocketInterface(Servatrice *_server, Servatrice_Dat ServerSocketInterface::~ServerSocketInterface() { logger->logMessage("ServerSocketInterface destructor", this); - + flushOutputQueue(); } @@ -90,7 +91,7 @@ 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(); @@ -99,7 +100,7 @@ void ServerSocketInterface::initConnection(int socketDescriptor) void ServerSocketInterface::initSessionDeprecated() { // dirty hack to make v13 client display the correct error message - + QByteArray buf; buf.append(""); socket->write(buf); @@ -115,7 +116,7 @@ bool ServerSocketInterface::initSession() SessionEvent *identSe = prepareSessionEvent(identEvent); sendProtocolItem(*identSe); delete identSe; - + int maxUsers = servatrice->getMaxUsersPerAddress(); if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { Event_ConnectionClosed event; @@ -123,10 +124,10 @@ bool ServerSocketInterface::initSession() SessionEvent *se = prepareSessionEvent(event); sendProtocolItem(*se); delete se; - + return false; } - + return true; } @@ -135,7 +136,7 @@ void ServerSocketInterface::readClient() QByteArray data = socket->readAll(); servatrice->incRxBytes(data.size()); inputBuffer.append(data); - + do { if (!messageInProgress) { if (inputBuffer.size() >= 4) { @@ -150,12 +151,12 @@ void ServerSocketInterface::readClient() } if (inputBuffer.size() < messageLength) return; - + CommandContainer newCommandContainer; newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength); inputBuffer.remove(0, messageLength); messageInProgress = false; - + // dirty hack to make v13 client display the correct error message if (handshakeStarted) processCommandContainer(newCommandContainer); @@ -171,7 +172,7 @@ void ServerSocketInterface::readClient() void ServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError) { qDebug() << "Socket error:" << socketError; - + prepareDestroy(); } @@ -180,7 +181,7 @@ void ServerSocketInterface::transmitProtocolItem(const ServerMessage &item) outputQueueMutex.lock(); outputQueue.append(item); outputQueueMutex.unlock(); - + emit outputQueueChanged(); } @@ -189,12 +190,12 @@ void ServerSocketInterface::flushOutputQueue() QMutexLocker locker(&outputQueueMutex); if (outputQueue.isEmpty()) return; - + int totalBytes = 0; while (!outputQueue.isEmpty()) { ServerMessage item = outputQueue.takeFirst(); locker.unlock(); - + QByteArray buf; unsigned int size = item.ByteSize(); buf.resize(size + 4); @@ -205,7 +206,7 @@ void ServerSocketInterface::flushOutputQueue() 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(); } @@ -260,39 +261,39 @@ Response::ResponseCode ServerSocketInterface::cmdAddToList(const Command_AddToLi { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + QString list = QString::fromStdString(cmd.list()); QString user = QString::fromStdString(cmd.user_name()); - + if ((list != "buddy") && (list != "ignore")) return Response::RespContextError; - + if (list == "buddy") if (databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) return Response::RespContextError; if (list == "ignore") if (databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) return Response::RespContextError; - + int id1 = userInfo->id(); int id2 = sqlInterface->getUserIdInDB(user); if (id2 < 0) return Response::RespNameNotFound; if (id1 == id2) return Response::RespContextError; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("insert into " + servatrice->getDbPrefix() + "_" + list + "list (id_user1, id_user2) values(:id1, :id2)"); query.bindValue(":id1", id1); query.bindValue(":id2", id2); if (!sqlInterface->execSqlQuery(query)) return Response::RespInternalError; - + Event_AddToList event; event.set_list_name(cmd.list()); event.mutable_user_info()->CopyFrom(databaseInterface->getUserData(user)); rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); - + return Response::RespOk; } @@ -300,37 +301,37 @@ Response::ResponseCode ServerSocketInterface::cmdRemoveFromList(const Command_Re { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + QString list = QString::fromStdString(cmd.list()); QString user = QString::fromStdString(cmd.user_name()); - + if ((list != "buddy") && (list != "ignore")) return Response::RespContextError; - + if (list == "buddy") if (!databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) return Response::RespContextError; if (list == "ignore") if (!databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) return Response::RespContextError; - + int id1 = userInfo->id(); int id2 = sqlInterface->getUserIdInDB(user); if (id2 < 0) return Response::RespNameNotFound; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("delete from " + servatrice->getDbPrefix() + "_" + list + "list where id_user1 = :id1 and id_user2 = :id2"); query.bindValue(":id1", id1); query.bindValue(":id2", id2); if (!sqlInterface->execSqlQuery(query)) return Response::RespInternalError; - + Event_RemoveFromList event; event.set_list_name(cmd.list()); event.set_user_name(cmd.user_name()); rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); - + return Response::RespOk; } @@ -340,7 +341,7 @@ int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path) return 0; if (path[0].isEmpty()) return 0; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent and name = :name and id_user = :id_user"); query.bindValue(":id_parent", basePathId); @@ -370,31 +371,31 @@ bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_ query.bindValue(":id_user", userInfo->id()); if (!sqlInterface->execSqlQuery(query)) return false; - + while (query.next()) { ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); newItem->set_id(query.value(0).toInt()); newItem->set_name(query.value(1).toString().toStdString()); - + if (!deckListHelper(newItem->id(), newItem->mutable_folder())) return false; } - + query.prepare("select id, name, upload_time from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder and id_user = :id_user"); query.bindValue(":id_folder", folderId); query.bindValue(":id_user", userInfo->id()); if (!sqlInterface->execSqlQuery(query)) return false; - + while (query.next()) { ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); newItem->set_id(query.value(0).toInt()); newItem->set_name(query.value(1).toString().toStdString()); - + ServerInfo_DeckStorage_File *newFile = newItem->mutable_file(); newFile->set_creation_time(query.value(2).toDateTime().toTime_t()); } - + return true; } @@ -405,15 +406,15 @@ Response::ResponseCode ServerSocketInterface::cmdDeckList(const Command_DeckList { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + sqlInterface->checkSql(); - + Response_DeckList *re = new Response_DeckList; ServerInfo_DeckStorage_Folder *root = re->mutable_root(); - + if (!deckListHelper(0, root)) return Response::RespContextError; - + rc.setResponseExtension(re); return Response::RespOk; } @@ -422,13 +423,13 @@ Response::ResponseCode ServerSocketInterface::cmdDeckNewDir(const Command_DeckNe { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + sqlInterface->checkSql(); - + int folderId = getDeckPathId(QString::fromStdString(cmd.path())); if (folderId == -1) return Response::RespNameNotFound; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_folders (id_parent, id_user, name) values(:id_parent, :id_user, :name)"); query.bindValue(":id_parent", folderId); @@ -443,17 +444,17 @@ void ServerSocketInterface::deckDelDirHelper(int basePathId) { sqlInterface->checkSql(); QSqlQuery query(sqlInterface->getDatabase()); - + query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent"); query.bindValue(":id_parent", basePathId); sqlInterface->execSqlQuery(query); while (query.next()) deckDelDirHelper(query.value(0).toInt()); - + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder"); query.bindValue(":id_folder", basePathId); sqlInterface->execSqlQuery(query); - + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_folders where id = :id"); query.bindValue(":id", basePathId); sqlInterface->execSqlQuery(query); @@ -463,9 +464,9 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDelDir(const Command_DeckDe { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + sqlInterface->checkSql(); - + int basePathId = getDeckPathId(QString::fromStdString(cmd.path())); if ((basePathId == -1) || (basePathId == 0)) return Response::RespNameNotFound; @@ -477,21 +478,21 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDel(const Command_DeckDel & { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + sqlInterface->checkSql(); QSqlQuery query(sqlInterface->getDatabase()); - + query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_files where id = :id and id_user = :id_user"); query.bindValue(":id", cmd.deck_id()); query.bindValue(":id_user", userInfo->id()); sqlInterface->execSqlQuery(query); if (!query.next()) return Response::RespNameNotFound; - + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id = :id"); query.bindValue(":id", cmd.deck_id()); sqlInterface->execSqlQuery(query); - + return Response::RespOk; } @@ -499,24 +500,24 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + if (!cmd.has_deck_list()) return Response::RespInvalidData; - + sqlInterface->checkSql(); - + QString deckStr = QString::fromStdString(cmd.deck_list()); DeckList deck(deckStr); - + QString deckName = deck.getName(); if (deckName.isEmpty()) deckName = "Unnamed deck"; - + if (cmd.has_path()) { int folderId = getDeckPathId(QString::fromStdString(cmd.path())); if (folderId == -1) return Response::RespNameNotFound; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_files (id_folder, id_user, name, upload_time, content) values(:id_folder, :id_user, :name, NOW(), :content)"); query.bindValue(":id_folder", folderId); @@ -524,7 +525,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp query.bindValue(":name", deckName); query.bindValue(":content", deckStr); sqlInterface->execSqlQuery(query); - + Response_DeckUpload *re = new Response_DeckUpload; ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); fileInfo->set_id(query.lastInsertId().toInt()); @@ -539,10 +540,10 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp query.bindValue(":name", deckName); query.bindValue(":content", deckStr); sqlInterface->execSqlQuery(query); - + if (query.numRowsAffected() == 0) return Response::RespNameNotFound; - + Response_DeckUpload *re = new Response_DeckUpload; ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); fileInfo->set_id(cmd.deck_id()); @@ -551,7 +552,7 @@ Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUp rc.setResponseExtension(re); } else return Response::RespInvalidData; - + return Response::RespOk; } @@ -559,19 +560,19 @@ Response::ResponseCode ServerSocketInterface::cmdDeckDownload(const Command_Deck { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + DeckList *deck; try { deck = sqlInterface->getDeckFromDatabase(cmd.deck_id(), userInfo->id()); } catch(Response::ResponseCode r) { return r; } - + Response_DeckDownload *re = new Response_DeckDownload; re->set_deck(deck->writeToString_Native().toStdString()); rc.setResponseExtension(re); delete deck; - + return Response::RespOk; } @@ -579,16 +580,16 @@ Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_Replay { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + Response_ReplayList *re = new Response_ReplayList; - + QSqlQuery query1(sqlInterface->getDatabase()); query1.prepare("select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from cockatrice_replays_access a left join cockatrice_games b on b.id = a.id_game where a.id_player = :id_player and (a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())"); query1.bindValue(":id_player", userInfo->id()); sqlInterface->execSqlQuery(query1); while (query1.next()) { ServerInfo_ReplayMatch *matchInfo = re->add_match_list(); - + const int gameId = query1.value(0).toInt(); matchInfo->set_game_id(gameId); matchInfo->set_room_name(query1.value(2).toString().toStdString()); @@ -599,7 +600,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_Replay matchInfo->set_game_name(query1.value(5).toString().toStdString()); const QString replayName = query1.value(1).toString(); matchInfo->set_do_not_hide(query1.value(6).toBool()); - + { QSqlQuery query2(sqlInterface->getDatabase()); query2.prepare("select player_name from cockatrice_games_players where id_game = :id_game"); @@ -621,7 +622,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_Replay } } } - + rc.setResponseExtension(re); return Response::RespOk; } @@ -630,7 +631,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_Re { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + { QSqlQuery query(sqlInterface->getDatabase()); query.prepare("select 1 from " + servatrice->getDbPrefix() + "_replays_access a left join " + servatrice->getDbPrefix() + "_replays b on a.id_game = b.id_game where b.id = :id_replay and a.id_player = :id_player"); @@ -641,7 +642,7 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_Re if (!query.next()) return Response::RespAccessDenied; } - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("select replay from " + servatrice->getDbPrefix() + "_replays where id = :id_replay"); query.bindValue(":id_replay", cmd.replay_id()); @@ -649,13 +650,13 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_Re return Response::RespInternalError; if (!query.next()) return Response::RespNameNotFound; - + QByteArray data = query.value(0).toByteArray(); - + Response_ReplayDownload *re = new Response_ReplayDownload; re->set_replay_data(data.data(), data.size()); rc.setResponseExtension(re); - + return Response::RespOk; } @@ -663,16 +664,16 @@ Response::ResponseCode ServerSocketInterface::cmdReplayModifyMatch(const Command { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + if (!sqlInterface->checkSql()) return Response::RespInternalError; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("update " + servatrice->getDbPrefix() + "_replays_access set do_not_hide=:do_not_hide where id_player = :id_player and id_game = :id_game"); query.bindValue(":id_player", userInfo->id()); query.bindValue(":id_game", cmd.game_id()); query.bindValue(":do_not_hide", cmd.do_not_hide()); - + if (!sqlInterface->execSqlQuery(query)) return Response::RespInternalError; return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; @@ -682,15 +683,15 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command { if (authState != PasswordRight) return Response::RespFunctionNotAllowed; - + if (!sqlInterface->checkSql()) return Response::RespInternalError; - + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("delete from " + servatrice->getDbPrefix() + "_replays_access where id_player = :id_player and id_game = :id_game"); query.bindValue(":id_player", userInfo->id()); query.bindValue(":id_game", cmd.game_id()); - + if (!sqlInterface->execSqlQuery(query)) return Response::RespInternalError; return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; @@ -704,11 +705,14 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban { if (!sqlInterface->checkSql()) return Response::RespInternalError; - + QString userName = QString::fromStdString(cmd.user_name()); QString address = QString::fromStdString(cmd.address()); + QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); int minutes = cmd.minutes(); - + if (trustedSources.contains(address,Qt::CaseInsensitive)) + address = ""; + QSqlQuery query(sqlInterface->getDatabase()); query.prepare("insert into " + servatrice->getDbPrefix() + "_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason)"); query.bindValue(":user_name", userName); @@ -718,7 +722,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban query.bindValue(":reason", QString::fromStdString(cmd.reason())); query.bindValue(":visible_reason", QString::fromStdString(cmd.visible_reason())); sqlInterface->execSqlQuery(query); - + servatrice->clientsLock.lockForRead(); QList userList = servatrice->getUsersWithAddressAsList(QHostAddress(address)); ServerSocketInterface *user = static_cast(server->getUsers().value(userName)); @@ -739,7 +743,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban } } servatrice->clientsLock.unlock(); - + return Response::RespOk; } From 74f8a82a73573fd330c8231db18a0519320c5ffc Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 15:25:47 -0500 Subject: [PATCH 2/9] corrected miss-pasting --- servatrice/src/servatrice.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/servatrice/src/servatrice.cpp b/servatrice/src/servatrice.cpp index e0eb40fb..9aaf23e5 100644 --- a/servatrice/src/servatrice.cpp +++ b/servatrice/src/servatrice.cpp @@ -35,10 +35,7 @@ #include "main.h" #include "decklist.h" #include "pb/event_server_message.pb.h" -#include "pb/event_server_shutdo; You may want to allow an unlimited number of users from a trusted source. This setting can contain a -; comma-separed list of IP addresses which will allow an unlimited number of connections from each of the -; IP addresses listed (ignoring the max_users_per_address). Default is "127.0.0.1,::1"; example: "192.73.233.244,81.4.100.74" -trusted_sources=""wn.pb.h" +#include "pb/event_server_shutdown.pb.h" #include "pb/event_connection_closed.pb.h" Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent) From 44a302a2d6431379d2f344052246829e8a630101 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 15:25:47 -0500 Subject: [PATCH 3/9] added trusted sources to servatrice --- servatrice/src/servatrice.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/servatrice/src/servatrice.cpp b/servatrice/src/servatrice.cpp index e0eb40fb..9aaf23e5 100644 --- a/servatrice/src/servatrice.cpp +++ b/servatrice/src/servatrice.cpp @@ -35,10 +35,7 @@ #include "main.h" #include "decklist.h" #include "pb/event_server_message.pb.h" -#include "pb/event_server_shutdo; You may want to allow an unlimited number of users from a trusted source. This setting can contain a -; comma-separed list of IP addresses which will allow an unlimited number of connections from each of the -; IP addresses listed (ignoring the max_users_per_address). Default is "127.0.0.1,::1"; example: "192.73.233.244,81.4.100.74" -trusted_sources=""wn.pb.h" +#include "pb/event_server_shutdown.pb.h" #include "pb/event_connection_closed.pb.h" Servatrice_GameServer::Servatrice_GameServer(Servatrice *_server, int _numberPools, const QSqlDatabase &_sqlDatabase, QObject *parent) From 3c513b4bfc900d65774f348b02e1d0dda02d6ad0 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 16:55:19 -0500 Subject: [PATCH 4/9] moved code logic to callling function & indent fix --- servatrice/src/servatrice.cpp | 15 +++++---------- servatrice/src/serversocketinterface.cpp | 10 ++++++++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/servatrice/src/servatrice.cpp b/servatrice/src/servatrice.cpp index 9aaf23e5..dd561846 100644 --- a/servatrice/src/servatrice.cpp +++ b/servatrice/src/servatrice.cpp @@ -380,16 +380,11 @@ QList Servatrice::getServerList() const int Servatrice::getUsersWithAddress(const QHostAddress &address) const { int result = 0; - QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); - - if (trustedSources.contains(address.toString(),Qt::CaseInsensitive)) { - //allow all clients from trusted sources regardsless of number of connections - } else { - QReadLocker locker(&clientsLock); - for (int i = 0; i < clients.size(); ++i) - if (static_cast(clients[i])->getPeerAddress() == address) - ++result; - } + QReadLocker locker(&clientsLock); + for (int i = 0; i < clients.size(); ++i) + if (static_cast(clients[i])->getPeerAddress() == address) + ++result; + return result; } diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index 705e2edf..c141b796 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include "settingscache.h" #include "serversocketinterface.h" #include "servatrice.h" @@ -117,6 +118,11 @@ bool ServerSocketInterface::initSession() sendProtocolItem(*identSe); delete identSe; + //allow unlimited number of connections from the trusted sources + QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); + if (trustedSources.contains(address.toString(),Qt::CaseInsensitive)) + return true; + int maxUsers = servatrice->getMaxUsersPerAddress(); if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { Event_ConnectionClosed event; @@ -708,9 +714,9 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban QString userName = QString::fromStdString(cmd.user_name()); QString address = QString::fromStdString(cmd.address()); - QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); + QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); int minutes = cmd.minutes(); - if (trustedSources.contains(address,Qt::CaseInsensitive)) + if (trustedSources.contains(address,Qt::CaseInsensitive)) address = ""; QSqlQuery query(sqlInterface->getDatabase()); From 26f5110fea009e0218d394790066b63acd82dd92 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 16:59:08 -0500 Subject: [PATCH 5/9] convert file tab to 4 space indent --- servatrice/src/serversocketinterface.cpp | 948 +++++++++++------------ 1 file changed, 474 insertions(+), 474 deletions(-) diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index c141b796..2431b840 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -64,345 +64,345 @@ static const int protocolVersion = 14; ServerSocketInterface::ServerSocketInterface(Servatrice *_server, Servatrice_DatabaseInterface *_databaseInterface, QObject *parent) - : Server_ProtocolHandler(_server, _databaseInterface, parent), - servatrice(_server), - sqlInterface(reinterpret_cast(databaseInterface)), - messageInProgress(false), - handshakeStarted(false) + : Server_ProtocolHandler(_server, _databaseInterface, parent), + servatrice(_server), + sqlInterface(reinterpret_cast(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))); + socket = new QTcpSocket(this); + socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); + connect(socket, SIGNAL(readyRead()), this, SLOT(readClient())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); - // Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error, - // it could lead to this object being destroyed while another function is still on the call stack. -> mutex deadlocks etc. - connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection); + // Never call flushOutputQueue directly from outputQueueChanged. In case of a socket error, + // it could lead to this object being destroyed while another function is still on the call stack. -> mutex deadlocks etc. + connect(this, SIGNAL(outputQueueChanged()), this, SLOT(flushOutputQueue()), Qt::QueuedConnection); } ServerSocketInterface::~ServerSocketInterface() { - logger->logMessage("ServerSocketInterface destructor", this); + logger->logMessage("ServerSocketInterface destructor", this); - flushOutputQueue(); + 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); + // 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(); + 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 + // dirty hack to make v13 client display the correct error message - QByteArray buf; - buf.append(""); - socket->write(buf); - socket->flush(); + QByteArray buf; + buf.append(""); + socket->write(buf); + socket->flush(); } bool ServerSocketInterface::initSession() { - Event_ServerIdentification identEvent; - identEvent.set_server_name(servatrice->getServerName().toStdString()); - identEvent.set_server_version(VERSION_STRING); - identEvent.set_protocol_version(protocolVersion); - SessionEvent *identSe = prepareSessionEvent(identEvent); - sendProtocolItem(*identSe); - delete identSe; + Event_ServerIdentification identEvent; + identEvent.set_server_name(servatrice->getServerName().toStdString()); + identEvent.set_server_version(VERSION_STRING); + identEvent.set_protocol_version(protocolVersion); + SessionEvent *identSe = prepareSessionEvent(identEvent); + sendProtocolItem(*identSe); + delete identSe; //allow unlimited number of connections from the trusted sources QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); if (trustedSources.contains(address.toString(),Qt::CaseInsensitive)) return true; - int maxUsers = servatrice->getMaxUsersPerAddress(); - if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { - Event_ConnectionClosed event; - event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS); - SessionEvent *se = prepareSessionEvent(event); - sendProtocolItem(*se); - delete se; + int maxUsers = servatrice->getMaxUsersPerAddress(); + if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { + Event_ConnectionClosed event; + event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS); + SessionEvent *se = prepareSessionEvent(event); + sendProtocolItem(*se); + delete se; - return false; - } + return false; + } - return true; + return true; } void ServerSocketInterface::readClient() { - QByteArray data = socket->readAll(); - servatrice->incRxBytes(data.size()); - inputBuffer.append(data); + 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; + 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; - newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength); - inputBuffer.remove(0, messageLength); - messageInProgress = false; + CommandContainer newCommandContainer; + newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength); + 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()); + // 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) { - outputQueueMutex.lock(); - outputQueue.append(item); - outputQueueMutex.unlock(); + outputQueueMutex.lock(); + outputQueue.append(item); + outputQueueMutex.unlock(); - emit outputQueueChanged(); + emit outputQueueChanged(); } void ServerSocketInterface::flushOutputQueue() { - QMutexLocker locker(&outputQueueMutex); - if (outputQueue.isEmpty()) - return; + QMutexLocker locker(&outputQueueMutex); + if (outputQueue.isEmpty()) + return; - int totalBytes = 0; - while (!outputQueue.isEmpty()) { - ServerMessage item = outputQueue.takeFirst(); - locker.unlock(); + 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); + 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(); + 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) { - switch ((SessionCommand::SessionCommandType) cmdType) { - case SessionCommand::ADD_TO_LIST: return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc); - case SessionCommand::REMOVE_FROM_LIST: return cmdRemoveFromList(cmd.GetExtension(Command_RemoveFromList::ext), rc); - case SessionCommand::DECK_LIST: return cmdDeckList(cmd.GetExtension(Command_DeckList::ext), rc); - case SessionCommand::DECK_NEW_DIR: return cmdDeckNewDir(cmd.GetExtension(Command_DeckNewDir::ext), rc); - case SessionCommand::DECK_DEL_DIR: return cmdDeckDelDir(cmd.GetExtension(Command_DeckDelDir::ext), rc); - case SessionCommand::DECK_DEL: return cmdDeckDel(cmd.GetExtension(Command_DeckDel::ext), rc); - case SessionCommand::DECK_UPLOAD: return cmdDeckUpload(cmd.GetExtension(Command_DeckUpload::ext), rc); - case SessionCommand::DECK_DOWNLOAD: return cmdDeckDownload(cmd.GetExtension(Command_DeckDownload::ext), rc); - case SessionCommand::REPLAY_LIST: return cmdReplayList(cmd.GetExtension(Command_ReplayList::ext), rc); - case SessionCommand::REPLAY_DOWNLOAD: return cmdReplayDownload(cmd.GetExtension(Command_ReplayDownload::ext), rc); - case SessionCommand::REPLAY_MODIFY_MATCH: return cmdReplayModifyMatch(cmd.GetExtension(Command_ReplayModifyMatch::ext), rc); - case SessionCommand::REPLAY_DELETE_MATCH: return cmdReplayDeleteMatch(cmd.GetExtension(Command_ReplayDeleteMatch::ext), rc); - default: return Response::RespFunctionNotAllowed; - } + switch ((SessionCommand::SessionCommandType) cmdType) { + case SessionCommand::ADD_TO_LIST: return cmdAddToList(cmd.GetExtension(Command_AddToList::ext), rc); + case SessionCommand::REMOVE_FROM_LIST: return cmdRemoveFromList(cmd.GetExtension(Command_RemoveFromList::ext), rc); + case SessionCommand::DECK_LIST: return cmdDeckList(cmd.GetExtension(Command_DeckList::ext), rc); + case SessionCommand::DECK_NEW_DIR: return cmdDeckNewDir(cmd.GetExtension(Command_DeckNewDir::ext), rc); + case SessionCommand::DECK_DEL_DIR: return cmdDeckDelDir(cmd.GetExtension(Command_DeckDelDir::ext), rc); + case SessionCommand::DECK_DEL: return cmdDeckDel(cmd.GetExtension(Command_DeckDel::ext), rc); + case SessionCommand::DECK_UPLOAD: return cmdDeckUpload(cmd.GetExtension(Command_DeckUpload::ext), rc); + case SessionCommand::DECK_DOWNLOAD: return cmdDeckDownload(cmd.GetExtension(Command_DeckDownload::ext), rc); + case SessionCommand::REPLAY_LIST: return cmdReplayList(cmd.GetExtension(Command_ReplayList::ext), rc); + case SessionCommand::REPLAY_DOWNLOAD: return cmdReplayDownload(cmd.GetExtension(Command_ReplayDownload::ext), rc); + case SessionCommand::REPLAY_MODIFY_MATCH: return cmdReplayModifyMatch(cmd.GetExtension(Command_ReplayModifyMatch::ext), rc); + case SessionCommand::REPLAY_DELETE_MATCH: return cmdReplayDeleteMatch(cmd.GetExtension(Command_ReplayDeleteMatch::ext), rc); + default: return Response::RespFunctionNotAllowed; + } } Response::ResponseCode ServerSocketInterface::processExtendedModeratorCommand(int cmdType, const ModeratorCommand &cmd, ResponseContainer &rc) { - switch ((ModeratorCommand::ModeratorCommandType) cmdType) { - case ModeratorCommand::BAN_FROM_SERVER: return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc); - default: return Response::RespFunctionNotAllowed; - } + switch ((ModeratorCommand::ModeratorCommandType) cmdType) { + case ModeratorCommand::BAN_FROM_SERVER: return cmdBanFromServer(cmd.GetExtension(Command_BanFromServer::ext), rc); + default: return Response::RespFunctionNotAllowed; + } } Response::ResponseCode ServerSocketInterface::processExtendedAdminCommand(int cmdType, const AdminCommand &cmd, ResponseContainer &rc) { - switch ((AdminCommand::AdminCommandType) cmdType) { - case AdminCommand::SHUTDOWN_SERVER: return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc); - case AdminCommand::UPDATE_SERVER_MESSAGE: return cmdUpdateServerMessage(cmd.GetExtension(Command_UpdateServerMessage::ext), rc); - default: return Response::RespFunctionNotAllowed; - } + switch ((AdminCommand::AdminCommandType) cmdType) { + case AdminCommand::SHUTDOWN_SERVER: return cmdShutdownServer(cmd.GetExtension(Command_ShutdownServer::ext), rc); + case AdminCommand::UPDATE_SERVER_MESSAGE: return cmdUpdateServerMessage(cmd.GetExtension(Command_UpdateServerMessage::ext), rc); + default: return Response::RespFunctionNotAllowed; + } } Response::ResponseCode ServerSocketInterface::cmdAddToList(const Command_AddToList &cmd, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - QString list = QString::fromStdString(cmd.list()); - QString user = QString::fromStdString(cmd.user_name()); + QString list = QString::fromStdString(cmd.list()); + QString user = QString::fromStdString(cmd.user_name()); - if ((list != "buddy") && (list != "ignore")) - return Response::RespContextError; + if ((list != "buddy") && (list != "ignore")) + return Response::RespContextError; - if (list == "buddy") - if (databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) - return Response::RespContextError; - if (list == "ignore") - if (databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) - return Response::RespContextError; + if (list == "buddy") + if (databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) + return Response::RespContextError; + if (list == "ignore") + if (databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) + return Response::RespContextError; - int id1 = userInfo->id(); - int id2 = sqlInterface->getUserIdInDB(user); - if (id2 < 0) - return Response::RespNameNotFound; - if (id1 == id2) - return Response::RespContextError; + int id1 = userInfo->id(); + int id2 = sqlInterface->getUserIdInDB(user); + if (id2 < 0) + return Response::RespNameNotFound; + if (id1 == id2) + return Response::RespContextError; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("insert into " + servatrice->getDbPrefix() + "_" + list + "list (id_user1, id_user2) values(:id1, :id2)"); - query.bindValue(":id1", id1); - query.bindValue(":id2", id2); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("insert into " + servatrice->getDbPrefix() + "_" + list + "list (id_user1, id_user2) values(:id1, :id2)"); + query.bindValue(":id1", id1); + query.bindValue(":id2", id2); + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; - Event_AddToList event; - event.set_list_name(cmd.list()); - event.mutable_user_info()->CopyFrom(databaseInterface->getUserData(user)); - rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); + Event_AddToList event; + event.set_list_name(cmd.list()); + event.mutable_user_info()->CopyFrom(databaseInterface->getUserData(user)); + rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); - return Response::RespOk; + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdRemoveFromList(const Command_RemoveFromList &cmd, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - QString list = QString::fromStdString(cmd.list()); - QString user = QString::fromStdString(cmd.user_name()); + QString list = QString::fromStdString(cmd.list()); + QString user = QString::fromStdString(cmd.user_name()); - if ((list != "buddy") && (list != "ignore")) - return Response::RespContextError; + if ((list != "buddy") && (list != "ignore")) + return Response::RespContextError; - if (list == "buddy") - if (!databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) - return Response::RespContextError; - if (list == "ignore") - if (!databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) - return Response::RespContextError; + if (list == "buddy") + if (!databaseInterface->isInBuddyList(QString::fromStdString(userInfo->name()), user)) + return Response::RespContextError; + if (list == "ignore") + if (!databaseInterface->isInIgnoreList(QString::fromStdString(userInfo->name()), user)) + return Response::RespContextError; - int id1 = userInfo->id(); - int id2 = sqlInterface->getUserIdInDB(user); - if (id2 < 0) - return Response::RespNameNotFound; + int id1 = userInfo->id(); + int id2 = sqlInterface->getUserIdInDB(user); + if (id2 < 0) + return Response::RespNameNotFound; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("delete from " + servatrice->getDbPrefix() + "_" + list + "list where id_user1 = :id1 and id_user2 = :id2"); - query.bindValue(":id1", id1); - query.bindValue(":id2", id2); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("delete from " + servatrice->getDbPrefix() + "_" + list + "list where id_user1 = :id1 and id_user2 = :id2"); + query.bindValue(":id1", id1); + query.bindValue(":id2", id2); + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; - Event_RemoveFromList event; - event.set_list_name(cmd.list()); - event.set_user_name(cmd.user_name()); - rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); + Event_RemoveFromList event; + event.set_list_name(cmd.list()); + event.set_user_name(cmd.user_name()); + rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); - return Response::RespOk; + return Response::RespOk; } int ServerSocketInterface::getDeckPathId(int basePathId, QStringList path) { - if (path.isEmpty()) - return 0; - if (path[0].isEmpty()) - return 0; + if (path.isEmpty()) + return 0; + if (path[0].isEmpty()) + return 0; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent and name = :name and id_user = :id_user"); - query.bindValue(":id_parent", basePathId); - query.bindValue(":name", path.takeFirst()); - query.bindValue(":id_user", userInfo->id()); - if (!sqlInterface->execSqlQuery(query)) - return -1; - if (!query.next()) - return -1; - int id = query.value(0).toInt(); - if (path.isEmpty()) - return id; - else - return getDeckPathId(id, path); + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent and name = :name and id_user = :id_user"); + query.bindValue(":id_parent", basePathId); + query.bindValue(":name", path.takeFirst()); + query.bindValue(":id_user", userInfo->id()); + if (!sqlInterface->execSqlQuery(query)) + return -1; + if (!query.next()) + return -1; + int id = query.value(0).toInt(); + if (path.isEmpty()) + return id; + else + return getDeckPathId(id, path); } int ServerSocketInterface::getDeckPathId(const QString &path) { - return getDeckPathId(0, path.split("/")); + return getDeckPathId(0, path.split("/")); } bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_Folder *folder) { - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select id, name from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent and id_user = :id_user"); - query.bindValue(":id_parent", folderId); - query.bindValue(":id_user", userInfo->id()); - if (!sqlInterface->execSqlQuery(query)) - return false; + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("select id, name from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent and id_user = :id_user"); + query.bindValue(":id_parent", folderId); + query.bindValue(":id_user", userInfo->id()); + if (!sqlInterface->execSqlQuery(query)) + return false; - while (query.next()) { - ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); - newItem->set_id(query.value(0).toInt()); - newItem->set_name(query.value(1).toString().toStdString()); + while (query.next()) { + ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); + newItem->set_id(query.value(0).toInt()); + newItem->set_name(query.value(1).toString().toStdString()); - if (!deckListHelper(newItem->id(), newItem->mutable_folder())) - return false; - } + if (!deckListHelper(newItem->id(), newItem->mutable_folder())) + return false; + } - query.prepare("select id, name, upload_time from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder and id_user = :id_user"); - query.bindValue(":id_folder", folderId); - query.bindValue(":id_user", userInfo->id()); - if (!sqlInterface->execSqlQuery(query)) - return false; + query.prepare("select id, name, upload_time from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder and id_user = :id_user"); + query.bindValue(":id_folder", folderId); + query.bindValue(":id_user", userInfo->id()); + if (!sqlInterface->execSqlQuery(query)) + return false; - while (query.next()) { - ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); - newItem->set_id(query.value(0).toInt()); - newItem->set_name(query.value(1).toString().toStdString()); + while (query.next()) { + ServerInfo_DeckStorage_TreeItem *newItem = folder->add_items(); + newItem->set_id(query.value(0).toInt()); + newItem->set_name(query.value(1).toString().toStdString()); - ServerInfo_DeckStorage_File *newFile = newItem->mutable_file(); - newFile->set_creation_time(query.value(2).toDateTime().toTime_t()); - } + ServerInfo_DeckStorage_File *newFile = newItem->mutable_file(); + newFile->set_creation_time(query.value(2).toDateTime().toTime_t()); + } - return true; + return true; } // CHECK AUTHENTICATION! @@ -410,297 +410,297 @@ bool ServerSocketInterface::deckListHelper(int folderId, ServerInfo_DeckStorage_ Response::ResponseCode ServerSocketInterface::cmdDeckList(const Command_DeckList & /*cmd*/, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - sqlInterface->checkSql(); + sqlInterface->checkSql(); - Response_DeckList *re = new Response_DeckList; - ServerInfo_DeckStorage_Folder *root = re->mutable_root(); + Response_DeckList *re = new Response_DeckList; + ServerInfo_DeckStorage_Folder *root = re->mutable_root(); - if (!deckListHelper(0, root)) - return Response::RespContextError; + if (!deckListHelper(0, root)) + return Response::RespContextError; - rc.setResponseExtension(re); - return Response::RespOk; + rc.setResponseExtension(re); + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdDeckNewDir(const Command_DeckNewDir &cmd, ResponseContainer & /*rc*/) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - sqlInterface->checkSql(); + sqlInterface->checkSql(); - int folderId = getDeckPathId(QString::fromStdString(cmd.path())); - if (folderId == -1) - return Response::RespNameNotFound; + int folderId = getDeckPathId(QString::fromStdString(cmd.path())); + if (folderId == -1) + return Response::RespNameNotFound; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_folders (id_parent, id_user, name) values(:id_parent, :id_user, :name)"); - query.bindValue(":id_parent", folderId); - query.bindValue(":id_user", userInfo->id()); - query.bindValue(":name", QString::fromStdString(cmd.dir_name())); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespContextError; - return Response::RespOk; + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_folders (id_parent, id_user, name) values(:id_parent, :id_user, :name)"); + query.bindValue(":id_parent", folderId); + query.bindValue(":id_user", userInfo->id()); + query.bindValue(":name", QString::fromStdString(cmd.dir_name())); + if (!sqlInterface->execSqlQuery(query)) + return Response::RespContextError; + return Response::RespOk; } void ServerSocketInterface::deckDelDirHelper(int basePathId) { - sqlInterface->checkSql(); - QSqlQuery query(sqlInterface->getDatabase()); + sqlInterface->checkSql(); + QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent"); - query.bindValue(":id_parent", basePathId); - sqlInterface->execSqlQuery(query); - while (query.next()) - deckDelDirHelper(query.value(0).toInt()); + query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_folders where id_parent = :id_parent"); + query.bindValue(":id_parent", basePathId); + sqlInterface->execSqlQuery(query); + while (query.next()) + deckDelDirHelper(query.value(0).toInt()); - query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder"); - query.bindValue(":id_folder", basePathId); - sqlInterface->execSqlQuery(query); + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id_folder = :id_folder"); + query.bindValue(":id_folder", basePathId); + sqlInterface->execSqlQuery(query); - query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_folders where id = :id"); - query.bindValue(":id", basePathId); - sqlInterface->execSqlQuery(query); + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_folders where id = :id"); + query.bindValue(":id", basePathId); + sqlInterface->execSqlQuery(query); } Response::ResponseCode ServerSocketInterface::cmdDeckDelDir(const Command_DeckDelDir &cmd, ResponseContainer & /*rc*/) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - sqlInterface->checkSql(); + sqlInterface->checkSql(); - int basePathId = getDeckPathId(QString::fromStdString(cmd.path())); - if ((basePathId == -1) || (basePathId == 0)) - return Response::RespNameNotFound; - deckDelDirHelper(basePathId); - return Response::RespOk; + int basePathId = getDeckPathId(QString::fromStdString(cmd.path())); + if ((basePathId == -1) || (basePathId == 0)) + return Response::RespNameNotFound; + deckDelDirHelper(basePathId); + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdDeckDel(const Command_DeckDel &cmd, ResponseContainer & /*rc*/) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - sqlInterface->checkSql(); - QSqlQuery query(sqlInterface->getDatabase()); + sqlInterface->checkSql(); + QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_files where id = :id and id_user = :id_user"); - query.bindValue(":id", cmd.deck_id()); - query.bindValue(":id_user", userInfo->id()); - sqlInterface->execSqlQuery(query); - if (!query.next()) - return Response::RespNameNotFound; + query.prepare("select id from " + servatrice->getDbPrefix() + "_decklist_files where id = :id and id_user = :id_user"); + query.bindValue(":id", cmd.deck_id()); + query.bindValue(":id_user", userInfo->id()); + sqlInterface->execSqlQuery(query); + if (!query.next()) + return Response::RespNameNotFound; - query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id = :id"); - query.bindValue(":id", cmd.deck_id()); - sqlInterface->execSqlQuery(query); + query.prepare("delete from " + servatrice->getDbPrefix() + "_decklist_files where id = :id"); + query.bindValue(":id", cmd.deck_id()); + sqlInterface->execSqlQuery(query); - return Response::RespOk; + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdDeckUpload(const Command_DeckUpload &cmd, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - if (!cmd.has_deck_list()) - return Response::RespInvalidData; + if (!cmd.has_deck_list()) + return Response::RespInvalidData; - sqlInterface->checkSql(); + sqlInterface->checkSql(); - QString deckStr = QString::fromStdString(cmd.deck_list()); - DeckList deck(deckStr); + QString deckStr = QString::fromStdString(cmd.deck_list()); + DeckList deck(deckStr); - QString deckName = deck.getName(); - if (deckName.isEmpty()) - deckName = "Unnamed deck"; + QString deckName = deck.getName(); + if (deckName.isEmpty()) + deckName = "Unnamed deck"; - if (cmd.has_path()) { - int folderId = getDeckPathId(QString::fromStdString(cmd.path())); - if (folderId == -1) - return Response::RespNameNotFound; + if (cmd.has_path()) { + int folderId = getDeckPathId(QString::fromStdString(cmd.path())); + if (folderId == -1) + return Response::RespNameNotFound; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_files (id_folder, id_user, name, upload_time, content) values(:id_folder, :id_user, :name, NOW(), :content)"); - query.bindValue(":id_folder", folderId); - query.bindValue(":id_user", userInfo->id()); - query.bindValue(":name", deckName); - query.bindValue(":content", deckStr); - sqlInterface->execSqlQuery(query); + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("insert into " + servatrice->getDbPrefix() + "_decklist_files (id_folder, id_user, name, upload_time, content) values(:id_folder, :id_user, :name, NOW(), :content)"); + query.bindValue(":id_folder", folderId); + query.bindValue(":id_user", userInfo->id()); + query.bindValue(":name", deckName); + query.bindValue(":content", deckStr); + sqlInterface->execSqlQuery(query); - Response_DeckUpload *re = new Response_DeckUpload; - ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); - fileInfo->set_id(query.lastInsertId().toInt()); - fileInfo->set_name(deckName.toStdString()); - fileInfo->mutable_file()->set_creation_time(QDateTime::currentDateTime().toTime_t()); - rc.setResponseExtension(re); - } else if (cmd.has_deck_id()) { - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("update " + servatrice->getDbPrefix() + "_decklist_files set name=:name, upload_time=NOW(), content=:content where id = :id_deck and id_user = :id_user"); - query.bindValue(":id_deck", cmd.deck_id()); - query.bindValue(":id_user", userInfo->id()); - query.bindValue(":name", deckName); - query.bindValue(":content", deckStr); - sqlInterface->execSqlQuery(query); + Response_DeckUpload *re = new Response_DeckUpload; + ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); + fileInfo->set_id(query.lastInsertId().toInt()); + fileInfo->set_name(deckName.toStdString()); + fileInfo->mutable_file()->set_creation_time(QDateTime::currentDateTime().toTime_t()); + rc.setResponseExtension(re); + } else if (cmd.has_deck_id()) { + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("update " + servatrice->getDbPrefix() + "_decklist_files set name=:name, upload_time=NOW(), content=:content where id = :id_deck and id_user = :id_user"); + query.bindValue(":id_deck", cmd.deck_id()); + query.bindValue(":id_user", userInfo->id()); + query.bindValue(":name", deckName); + query.bindValue(":content", deckStr); + sqlInterface->execSqlQuery(query); - if (query.numRowsAffected() == 0) - return Response::RespNameNotFound; + if (query.numRowsAffected() == 0) + return Response::RespNameNotFound; - Response_DeckUpload *re = new Response_DeckUpload; - ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); - fileInfo->set_id(cmd.deck_id()); - fileInfo->set_name(deckName.toStdString()); - fileInfo->mutable_file()->set_creation_time(QDateTime::currentDateTime().toTime_t()); - rc.setResponseExtension(re); - } else - return Response::RespInvalidData; + Response_DeckUpload *re = new Response_DeckUpload; + ServerInfo_DeckStorage_TreeItem *fileInfo = re->mutable_new_file(); + fileInfo->set_id(cmd.deck_id()); + fileInfo->set_name(deckName.toStdString()); + fileInfo->mutable_file()->set_creation_time(QDateTime::currentDateTime().toTime_t()); + rc.setResponseExtension(re); + } else + return Response::RespInvalidData; - return Response::RespOk; + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdDeckDownload(const Command_DeckDownload &cmd, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - DeckList *deck; - try { - deck = sqlInterface->getDeckFromDatabase(cmd.deck_id(), userInfo->id()); - } catch(Response::ResponseCode r) { - return r; - } + DeckList *deck; + try { + deck = sqlInterface->getDeckFromDatabase(cmd.deck_id(), userInfo->id()); + } catch(Response::ResponseCode r) { + return r; + } - Response_DeckDownload *re = new Response_DeckDownload; - re->set_deck(deck->writeToString_Native().toStdString()); - rc.setResponseExtension(re); - delete deck; + Response_DeckDownload *re = new Response_DeckDownload; + re->set_deck(deck->writeToString_Native().toStdString()); + rc.setResponseExtension(re); + delete deck; - return Response::RespOk; + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - Response_ReplayList *re = new Response_ReplayList; + Response_ReplayList *re = new Response_ReplayList; - QSqlQuery query1(sqlInterface->getDatabase()); - query1.prepare("select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from cockatrice_replays_access a left join cockatrice_games b on b.id = a.id_game where a.id_player = :id_player and (a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())"); - query1.bindValue(":id_player", userInfo->id()); - sqlInterface->execSqlQuery(query1); - while (query1.next()) { - ServerInfo_ReplayMatch *matchInfo = re->add_match_list(); + QSqlQuery query1(sqlInterface->getDatabase()); + query1.prepare("select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from cockatrice_replays_access a left join cockatrice_games b on b.id = a.id_game where a.id_player = :id_player and (a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())"); + query1.bindValue(":id_player", userInfo->id()); + sqlInterface->execSqlQuery(query1); + while (query1.next()) { + ServerInfo_ReplayMatch *matchInfo = re->add_match_list(); - const int gameId = query1.value(0).toInt(); - matchInfo->set_game_id(gameId); - matchInfo->set_room_name(query1.value(2).toString().toStdString()); - const int timeStarted = query1.value(3).toDateTime().toTime_t(); - const int timeFinished = query1.value(4).toDateTime().toTime_t(); - matchInfo->set_time_started(timeStarted); - matchInfo->set_length(timeFinished - timeStarted); - matchInfo->set_game_name(query1.value(5).toString().toStdString()); - const QString replayName = query1.value(1).toString(); - matchInfo->set_do_not_hide(query1.value(6).toBool()); + const int gameId = query1.value(0).toInt(); + matchInfo->set_game_id(gameId); + matchInfo->set_room_name(query1.value(2).toString().toStdString()); + const int timeStarted = query1.value(3).toDateTime().toTime_t(); + const int timeFinished = query1.value(4).toDateTime().toTime_t(); + matchInfo->set_time_started(timeStarted); + matchInfo->set_length(timeFinished - timeStarted); + matchInfo->set_game_name(query1.value(5).toString().toStdString()); + const QString replayName = query1.value(1).toString(); + matchInfo->set_do_not_hide(query1.value(6).toBool()); - { - QSqlQuery query2(sqlInterface->getDatabase()); - query2.prepare("select player_name from cockatrice_games_players where id_game = :id_game"); - query2.bindValue(":id_game", gameId); - sqlInterface->execSqlQuery(query2); - while (query2.next()) - matchInfo->add_player_names(query2.value(0).toString().toStdString()); - } - { - QSqlQuery query3(sqlInterface->getDatabase()); - query3.prepare("select id, duration from " + servatrice->getDbPrefix() + "_replays where id_game = :id_game"); - query3.bindValue(":id_game", gameId); - sqlInterface->execSqlQuery(query3); - while (query3.next()) { - ServerInfo_Replay *replayInfo = matchInfo->add_replay_list(); - replayInfo->set_replay_id(query3.value(0).toInt()); - replayInfo->set_replay_name(replayName.toStdString()); - replayInfo->set_duration(query3.value(1).toInt()); - } - } - } + { + QSqlQuery query2(sqlInterface->getDatabase()); + query2.prepare("select player_name from cockatrice_games_players where id_game = :id_game"); + query2.bindValue(":id_game", gameId); + sqlInterface->execSqlQuery(query2); + while (query2.next()) + matchInfo->add_player_names(query2.value(0).toString().toStdString()); + } + { + QSqlQuery query3(sqlInterface->getDatabase()); + query3.prepare("select id, duration from " + servatrice->getDbPrefix() + "_replays where id_game = :id_game"); + query3.bindValue(":id_game", gameId); + sqlInterface->execSqlQuery(query3); + while (query3.next()) { + ServerInfo_Replay *replayInfo = matchInfo->add_replay_list(); + replayInfo->set_replay_id(query3.value(0).toInt()); + replayInfo->set_replay_name(replayName.toStdString()); + replayInfo->set_duration(query3.value(1).toInt()); + } + } + } - rc.setResponseExtension(re); - return Response::RespOk; + rc.setResponseExtension(re); + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdReplayDownload(const Command_ReplayDownload &cmd, ResponseContainer &rc) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - { - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select 1 from " + servatrice->getDbPrefix() + "_replays_access a left join " + servatrice->getDbPrefix() + "_replays b on a.id_game = b.id_game where b.id = :id_replay and a.id_player = :id_player"); - query.bindValue(":id_replay", cmd.replay_id()); - query.bindValue(":id_player", userInfo->id()); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; - if (!query.next()) - return Response::RespAccessDenied; - } + { + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("select 1 from " + servatrice->getDbPrefix() + "_replays_access a left join " + servatrice->getDbPrefix() + "_replays b on a.id_game = b.id_game where b.id = :id_replay and a.id_player = :id_player"); + query.bindValue(":id_replay", cmd.replay_id()); + query.bindValue(":id_player", userInfo->id()); + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; + if (!query.next()) + return Response::RespAccessDenied; + } - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("select replay from " + servatrice->getDbPrefix() + "_replays where id = :id_replay"); - query.bindValue(":id_replay", cmd.replay_id()); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; - if (!query.next()) - return Response::RespNameNotFound; + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("select replay from " + servatrice->getDbPrefix() + "_replays where id = :id_replay"); + query.bindValue(":id_replay", cmd.replay_id()); + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; + if (!query.next()) + return Response::RespNameNotFound; - QByteArray data = query.value(0).toByteArray(); + QByteArray data = query.value(0).toByteArray(); - Response_ReplayDownload *re = new Response_ReplayDownload; - re->set_replay_data(data.data(), data.size()); - rc.setResponseExtension(re); + Response_ReplayDownload *re = new Response_ReplayDownload; + re->set_replay_data(data.data(), data.size()); + rc.setResponseExtension(re); - return Response::RespOk; + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdReplayModifyMatch(const Command_ReplayModifyMatch &cmd, ResponseContainer & /*rc*/) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - if (!sqlInterface->checkSql()) - return Response::RespInternalError; + if (!sqlInterface->checkSql()) + return Response::RespInternalError; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("update " + servatrice->getDbPrefix() + "_replays_access set do_not_hide=:do_not_hide where id_player = :id_player and id_game = :id_game"); - query.bindValue(":id_player", userInfo->id()); - query.bindValue(":id_game", cmd.game_id()); - query.bindValue(":do_not_hide", cmd.do_not_hide()); + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("update " + servatrice->getDbPrefix() + "_replays_access set do_not_hide=:do_not_hide where id_player = :id_player and id_game = :id_game"); + query.bindValue(":id_player", userInfo->id()); + query.bindValue(":id_game", cmd.game_id()); + query.bindValue(":do_not_hide", cmd.do_not_hide()); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; - return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; + return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; } Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command_ReplayDeleteMatch &cmd, ResponseContainer & /*rc*/) { - if (authState != PasswordRight) - return Response::RespFunctionNotAllowed; + if (authState != PasswordRight) + return Response::RespFunctionNotAllowed; - if (!sqlInterface->checkSql()) - return Response::RespInternalError; + if (!sqlInterface->checkSql()) + return Response::RespInternalError; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("delete from " + servatrice->getDbPrefix() + "_replays_access where id_player = :id_player and id_game = :id_game"); - query.bindValue(":id_player", userInfo->id()); - query.bindValue(":id_game", cmd.game_id()); + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("delete from " + servatrice->getDbPrefix() + "_replays_access where id_player = :id_player and id_game = :id_game"); + query.bindValue(":id_player", userInfo->id()); + query.bindValue(":id_game", cmd.game_id()); - if (!sqlInterface->execSqlQuery(query)) - return Response::RespInternalError; - return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; + if (!sqlInterface->execSqlQuery(query)) + return Response::RespInternalError; + return query.numRowsAffected() > 0 ? Response::RespOk : Response::RespNameNotFound; } @@ -709,48 +709,48 @@ Response::ResponseCode ServerSocketInterface::cmdReplayDeleteMatch(const Command Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/) { - if (!sqlInterface->checkSql()) - return Response::RespInternalError; + if (!sqlInterface->checkSql()) + return Response::RespInternalError; - QString userName = QString::fromStdString(cmd.user_name()); - QString address = QString::fromStdString(cmd.address()); + QString userName = QString::fromStdString(cmd.user_name()); + QString address = QString::fromStdString(cmd.address()); QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); - int minutes = cmd.minutes(); + int minutes = cmd.minutes(); if (trustedSources.contains(address,Qt::CaseInsensitive)) address = ""; - QSqlQuery query(sqlInterface->getDatabase()); - query.prepare("insert into " + servatrice->getDbPrefix() + "_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason)"); - query.bindValue(":user_name", userName); - query.bindValue(":ip_address", address); - query.bindValue(":id_admin", userInfo->id()); - query.bindValue(":minutes", minutes); - query.bindValue(":reason", QString::fromStdString(cmd.reason())); - query.bindValue(":visible_reason", QString::fromStdString(cmd.visible_reason())); - sqlInterface->execSqlQuery(query); + QSqlQuery query(sqlInterface->getDatabase()); + query.prepare("insert into " + servatrice->getDbPrefix() + "_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason)"); + query.bindValue(":user_name", userName); + query.bindValue(":ip_address", address); + query.bindValue(":id_admin", userInfo->id()); + query.bindValue(":minutes", minutes); + query.bindValue(":reason", QString::fromStdString(cmd.reason())); + query.bindValue(":visible_reason", QString::fromStdString(cmd.visible_reason())); + sqlInterface->execSqlQuery(query); - servatrice->clientsLock.lockForRead(); - QList userList = servatrice->getUsersWithAddressAsList(QHostAddress(address)); - ServerSocketInterface *user = static_cast(server->getUsers().value(userName)); - if (user && !userList.contains(user)) - userList.append(user); - if (!userList.isEmpty()) { - Event_ConnectionClosed event; - event.set_reason(Event_ConnectionClosed::BANNED); - if (cmd.has_visible_reason()) - event.set_reason_str(cmd.visible_reason()); - if (minutes) - event.set_end_time(QDateTime::currentDateTime().addSecs(60 * minutes).toTime_t()); - for (int i = 0; i < userList.size(); ++i) { - SessionEvent *se = userList[i]->prepareSessionEvent(event); - userList[i]->sendProtocolItem(*se); - delete se; - QMetaObject::invokeMethod(userList[i], "prepareDestroy", Qt::QueuedConnection); - } - } - servatrice->clientsLock.unlock(); + servatrice->clientsLock.lockForRead(); + QList userList = servatrice->getUsersWithAddressAsList(QHostAddress(address)); + ServerSocketInterface *user = static_cast(server->getUsers().value(userName)); + if (user && !userList.contains(user)) + userList.append(user); + if (!userList.isEmpty()) { + Event_ConnectionClosed event; + event.set_reason(Event_ConnectionClosed::BANNED); + if (cmd.has_visible_reason()) + event.set_reason_str(cmd.visible_reason()); + if (minutes) + event.set_end_time(QDateTime::currentDateTime().addSecs(60 * minutes).toTime_t()); + for (int i = 0; i < userList.size(); ++i) { + SessionEvent *se = userList[i]->prepareSessionEvent(event); + userList[i]->sendProtocolItem(*se); + delete se; + QMetaObject::invokeMethod(userList[i], "prepareDestroy", Qt::QueuedConnection); + } + } + servatrice->clientsLock.unlock(); - return Response::RespOk; + return Response::RespOk; } // ADMIN FUNCTIONS. @@ -758,12 +758,12 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban Response::ResponseCode ServerSocketInterface::cmdUpdateServerMessage(const Command_UpdateServerMessage & /*cmd*/, ResponseContainer & /*rc*/) { - QMetaObject::invokeMethod(server, "updateLoginMessage"); - return Response::RespOk; + QMetaObject::invokeMethod(server, "updateLoginMessage"); + return Response::RespOk; } Response::ResponseCode ServerSocketInterface::cmdShutdownServer(const Command_ShutdownServer &cmd, ResponseContainer & /*rc*/) { - QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), Q_ARG(int, cmd.minutes())); - return Response::RespOk; + QMetaObject::invokeMethod(server, "scheduleShutdown", Q_ARG(QString, QString::fromStdString(cmd.reason())), Q_ARG(int, cmd.minutes())); + return Response::RespOk; } From 197ae9213c70931f32769772d9a202be0ccf6f69 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 17:20:45 -0500 Subject: [PATCH 6/9] corrected invalid variable call & added log file debug information --- servatrice/src/serversocketinterface.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index 2431b840..a682b0c7 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -120,7 +120,8 @@ bool ServerSocketInterface::initSession() //allow unlimited number of connections from the trusted sources QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); - if (trustedSources.contains(address.toString(),Qt::CaseInsensitive)) + if (trustedSources.contains(socket->peerAddress().toString(),Qt::CaseInsensitive)) + qDebug() << "Allowing user from trusted source: " << socket->peerAddress().toString(); return true; int maxUsers = servatrice->getMaxUsersPerAddress(); From 37e08cfbb615d61516fc269a73bbf6da852ae25f Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 17:27:57 -0500 Subject: [PATCH 7/9] added logic to only write debug if max user value is reached --- servatrice/src/serversocketinterface.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index a682b0c7..4f4e2293 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -117,14 +117,16 @@ bool ServerSocketInterface::initSession() SessionEvent *identSe = prepareSessionEvent(identEvent); sendProtocolItem(*identSe); delete identSe; + + int maxUsers = servatrice->getMaxUsersPerAddress(); //allow unlimited number of connections from the trusted sources QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); if (trustedSources.contains(socket->peerAddress().toString(),Qt::CaseInsensitive)) - qDebug() << "Allowing user from trusted source: " << socket->peerAddress().toString(); + if (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers) + qDebug() << "Allowing user from trusted source: " << socket->peerAddress().toString(); return true; - int maxUsers = servatrice->getMaxUsersPerAddress(); if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) { Event_ConnectionClosed event; event.set_reason(Event_ConnectionClosed::TOO_MANY_CONNECTIONS); From 1195e4c77b28e9941ad6e1fd5de37efc98194482 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 17:32:10 -0500 Subject: [PATCH 8/9] corrected default ini value --- servatrice/servatrice.ini.example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/servatrice/servatrice.ini.example b/servatrice/servatrice.ini.example index a7429d33..b3e431a1 100644 --- a/servatrice/servatrice.ini.example +++ b/servatrice/servatrice.ini.example @@ -128,7 +128,7 @@ max_users_per_address=4 ; You may want to allow an unlimited number of users from a trusted source. This setting can contain a ; comma-separed list of IP addresses which will allow an unlimited number of connections from each of the ; IP addresses listed (ignoring the max_users_per_address). Default is "127.0.0.1,::1"; example: "192.73.233.244,81.4.100.74" -trusted_sources="" +trusted_sources="127.0.0.1,::1" ; Servatrice can avoid users from flooding rooms with large number messages in an interval of time. ; This setting defines the length in seconds of the considered interval; default is 10 From ff8e25bb7ec13350a50ce8ddfd309fab27162b16 Mon Sep 17 00:00:00 2001 From: woogerboy21 Date: Tue, 18 Nov 2014 18:31:06 -0500 Subject: [PATCH 9/9] removed qdebug line for >= maxuser (no need to fill log) --- servatrice/src/serversocketinterface.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp index 4f4e2293..87e17596 100644 --- a/servatrice/src/serversocketinterface.cpp +++ b/servatrice/src/serversocketinterface.cpp @@ -123,8 +123,6 @@ bool ServerSocketInterface::initSession() //allow unlimited number of connections from the trusted sources QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString(); if (trustedSources.contains(socket->peerAddress().toString(),Qt::CaseInsensitive)) - if (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers) - qDebug() << "Allowing user from trusted source: " << socket->peerAddress().toString(); return true; if ((maxUsers > 0) && (servatrice->getUsersWithAddress(socket->peerAddress()) >= maxUsers)) {