added trusted sources to servatrice

This commit is contained in:
wcollins
2014-11-18 15:09:21 -05:00
parent b351abcce4
commit da98d24d8c
3 changed files with 161 additions and 142 deletions

View File

@@ -22,6 +22,7 @@
#include <QHostAddress>
#include <QDebug>
#include <QDateTime>
#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("<?xml version=\"1.0\"?><cockatrice_server_stream version=\"14\">");
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<ServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));
ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
@@ -739,7 +743,7 @@ Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_Ban
}
}
servatrice->clientsLock.unlock();
return Response::RespOk;
}