style: Add braces to all control flow statements (#6887)

* style: Add braces to all control flow statements

  Standardize code style by adding explicit braces to all single-statement
  control flow blocks (if, else, for, while) across the entire codebase.

  Also documents the InsertBraces clang-format option (requires v15+) for
  future automated enforcement.

* InsertBraces-check-enabled
This commit is contained in:
DawnFire42 2026-05-16 13:19:53 -04:00 committed by GitHub
parent 7153f7d4c1
commit aadee34238
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
173 changed files with 2725 additions and 1461 deletions

View file

@ -76,8 +76,9 @@ IslInterface::~IslInterface()
QMapIterator<QString, ServerInfo_User_Container> roomUsers(room->getExternalUsers());
while (roomUsers.hasNext()) {
roomUsers.next();
if (roomUsers.value().getUserInfo()->server_id() == serverId)
if (roomUsers.value().getUserInfo()->server_id() == serverId) {
emit externalRoomUserLeft(room->getId(), roomUsers.key());
}
}
room->usersLock.unlock();
}
@ -87,8 +88,9 @@ IslInterface::~IslInterface()
QMapIterator<QString, Server_AbstractUserInterface *> extUsers(server->getExternalUsers());
while (extUsers.hasNext()) {
extUsers.next();
if (extUsers.value()->getUserInfo()->server_id() == serverId)
if (extUsers.value()->getUserInfo()->server_id() == serverId) {
emit externalUserLeft(extUsers.key());
}
}
server->clientsLock.unlock();
}
@ -101,11 +103,12 @@ void IslInterface::initServer()
QList<ServerProperties> serverList = server->getServerList();
int listIndex = -1;
for (int i = 0; i < serverList.size(); ++i)
for (int i = 0; i < serverList.size(); ++i) {
if (serverList[i].address == socket->peerAddress()) {
listIndex = i;
break;
}
}
if (listIndex == -1) {
logger->logMessage(
QString("[ISL] address %1 unknown, terminating connection").arg(socket->peerAddress().toString()));
@ -125,9 +128,9 @@ void IslInterface::initServer()
return;
}
if (serverList[listIndex].cert == socket->peerCertificate())
if (serverList[listIndex].cert == socket->peerCertificate()) {
logger->logMessage(QString("[ISL] Peer authenticated as " + serverList[listIndex].hostname));
else {
} else {
logger->logMessage(QString("[ISL] Authentication failed, terminating connection"));
deleteLater();
return;
@ -139,8 +142,9 @@ void IslInterface::initServer()
server->clientsLock.lockForRead();
QMapIterator<QString, Server_ProtocolHandler *> userIterator(server->getUsers());
while (userIterator.hasNext())
while (userIterator.hasNext()) {
event.add_user_list()->CopyFrom(userIterator.next().value()->copyUserInfo(true, true));
}
server->clientsLock.unlock();
server->roomsLock.lockForRead();
@ -217,8 +221,9 @@ void IslInterface::initClient()
void IslInterface::flushOutputBuffer()
{
QMutexLocker locker(&outputBufferMutex);
if (outputBuffer.isEmpty())
if (outputBuffer.isEmpty()) {
return;
}
server->incTxBytes(outputBuffer.size());
socket->write(outputBuffer);
socket->flush();
@ -240,11 +245,13 @@ void IslInterface::readClient()
((quint32)(unsigned char)inputBuffer[3]);
inputBuffer.remove(0, 4);
messageInProgress = true;
} else
} else {
return;
}
}
if (inputBuffer.size() < messageLength)
if (inputBuffer.size() < messageLength) {
return;
}
IslMessage newMessage;
bool ok = newMessage.ParseFromArray(inputBuffer.data(), messageLength);

View file

@ -69,19 +69,22 @@ void testRNG()
for (int i = 0; i <= maxMax - min; ++i) {
std::cerr << (min + i);
for (auto &number : numbers) {
if (i < number.size())
if (i < number.size()) {
std::cerr << "\t" << number[i];
else
} else {
std::cerr << "\t";
}
}
std::cerr << std::endl;
}
std::cerr << std::endl << "Chi^2 =";
for (double j : chisq)
for (double j : chisq) {
std::cerr << "\t" << QString::number(j, 'f', 3).toStdString();
}
std::cerr << std::endl << "k =";
for (int j = 0; j < chisq.size(); ++j)
for (int j = 0; j < chisq.size(); ++j) {
std::cerr << "\t" << (j - min + minMax);
}
std::cerr << std::endl << std::endl;
}
@ -90,8 +93,9 @@ void testHash()
const int n = 5000;
std::cerr << "Benchmarking password hash function (n =" << n << ")..." << std::endl;
QDateTime startTime = QDateTime::currentDateTime();
for (int i = 0; i < n; ++i)
for (int i = 0; i < n; ++i) {
PasswordHasher::computeHash("aaaaaa", "aaaaaaaaaaaaaaaa");
}
QDateTime endTime = QDateTime::currentDateTime();
std::cerr << startTime.secsTo(endTime) << "secs" << std::endl;
}
@ -157,10 +161,11 @@ int main(int argc, char *argv[])
QMetaObject::invokeMethod(logger, "startLog", Qt::BlockingQueuedConnection,
Q_ARG(QString, settingsCache->value("server/logfile", QString("server.log")).toString()));
if (logToConsole)
if (logToConsole) {
qInstallMessageHandler(myMessageOutput);
else
} else {
qInstallMessageHandler(myMessageOutput2);
}
signalhandler = new SignalHandler();

View file

@ -318,8 +318,9 @@ bool Servatrice::initServer()
query2->bindValue(":id_room", query->value(0).toInt());
servatriceDatabaseInterface->execSqlQuery(query2);
QStringList gameTypes;
while (query2->next())
while (query2->next()) {
gameTypes.append(query2->value(0).toString());
}
addRoom(new Server_Room(query->value(0).toInt(), query->value(7).toInt(), query->value(1).toString(),
query->value(2).toString(), query->value(3).toString().toLower(),
query->value(4).toString().toLower(), static_cast<bool>(query->value(5).toInt()),
@ -362,21 +363,25 @@ bool Servatrice::initServer()
qDebug() << "Connecting to ISL network.";
qDebug() << "Loading certificate...";
QFile certFile(getISLNetworkSSLCertFile());
if (!certFile.open(QIODevice::ReadOnly))
if (!certFile.open(QIODevice::ReadOnly)) {
throw QString("Error opening certificate file: %1").arg(getISLNetworkSSLCertFile());
}
QSslCertificate cert(&certFile);
const QDateTime currentTime = QDateTime::currentDateTime();
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate() || cert.isBlacklisted())
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate() || cert.isBlacklisted()) {
throw QString("Invalid certificate.");
}
qDebug() << "Loading private key...";
QFile keyFile(getISLNetworkSSLKeyFile());
if (!keyFile.open(QIODevice::ReadOnly))
if (!keyFile.open(QIODevice::ReadOnly)) {
throw QString("Error opening private key file: %1").arg(getISLNetworkSSLKeyFile());
}
QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
if (key.isNull())
if (key.isNull()) {
throw QString("Invalid private key.");
}
QMutableListIterator<ServerProperties> serverIterator(serverList);
while (serverIterator.hasNext()) {
@ -401,10 +406,11 @@ bool Servatrice::initServer()
qDebug() << "Starting ISL server on port" << getISLNetworkPort();
islServer = new Servatrice_IslServer(this, cert, key, this);
if (islServer->listen(QHostAddress::Any, static_cast<quint16>(getISLNetworkPort())))
if (islServer->listen(QHostAddress::Any, static_cast<quint16>(getISLNetworkPort()))) {
qDebug() << "ISL server listening.";
else
} else {
throw QString("islServer->listen()");
}
}
} catch (QString &error) {
qDebug() << "ERROR --" << error;
@ -429,9 +435,9 @@ bool Servatrice::initServer()
gameServer->setMaxPendingConnections(1000);
QHostAddress tcpHost = getServerTCPHost();
qDebug() << "Starting server on host" << tcpHost.toString() << "port" << getServerTCPPort();
if (gameServer->listen(tcpHost, static_cast<quint16>(getServerTCPPort())))
if (gameServer->listen(tcpHost, static_cast<quint16>(getServerTCPPort()))) {
qDebug() << "Server listening.";
else {
} else {
qDebug() << "gameServer->listen(): Error:" << gameServer->errorString();
return false;
}
@ -445,9 +451,9 @@ bool Servatrice::initServer()
QHostAddress webSocketHost = getServerWebSocketHost();
qDebug() << "Starting websocket server on host" << webSocketHost.toString() << "port"
<< getServerWebSocketPort();
if (websocketGameServer->listen(webSocketHost, static_cast<quint16>(getServerWebSocketPort())))
if (websocketGameServer->listen(webSocketHost, static_cast<quint16>(getServerWebSocketPort()))) {
qDebug() << "Websocket server listening.";
else {
} else {
qDebug() << "websocketGameServer->listen(): Error:" << websocketGameServer->errorString();
return false;
}
@ -455,11 +461,12 @@ bool Servatrice::initServer()
if (getIdleClientTimeout() > 0) {
qDebug() << "Idle client timeout value:" << getIdleClientTimeout();
if (getIdleClientTimeout() < 300)
if (getIdleClientTimeout() < 300) {
qDebug() << "WARNING: It is not recommended to set the IdleClientTimeout value very low. Doing so will "
"cause clients to very quickly be disconnected. Many players when connected may be searching "
"for card details outside the client in the middle of matches or possibly drafting outside the "
"client and short time out values will remove these players.";
}
}
setRequiredFeatures(getRequiredFeatures());
@ -511,9 +518,11 @@ int Servatrice::getUsersWithAddress(const QHostAddress &address) const
{
int result = 0;
QReadLocker locker(&clientsLock);
for (auto client : clients)
if (static_cast<AbstractServerSocketInterface *>(client)->getPeerAddress() == address)
for (auto client : clients) {
if (static_cast<AbstractServerSocketInterface *>(client)->getPeerAddress() == address) {
++result;
}
}
return result;
}
@ -522,21 +531,24 @@ QList<AbstractServerSocketInterface *> Servatrice::getUsersWithAddressAsList(con
{
QList<AbstractServerSocketInterface *> result;
QReadLocker locker(&clientsLock);
for (auto client : clients)
if (static_cast<AbstractServerSocketInterface *>(client)->getPeerAddress() == address)
for (auto client : clients) {
if (static_cast<AbstractServerSocketInterface *>(client)->getPeerAddress() == address) {
result.append(static_cast<AbstractServerSocketInterface *>(client));
}
}
return result;
}
void Servatrice::updateLoginMessage()
{
if (!servatriceDatabaseInterface->checkSql())
if (!servatriceDatabaseInterface->checkSql()) {
return;
}
QSqlQuery *query = servatriceDatabaseInterface->prepareQuery(
"select message from {prefix}_servermessages where id_server = :id_server order by timest desc limit 1");
query->bindValue(":id_server", serverId);
if (servatriceDatabaseInterface->execSqlQuery(query))
if (servatriceDatabaseInterface->execSqlQuery(query)) {
if (query->next()) {
const QString newLoginMessage = query->value(0).toString();
@ -548,10 +560,12 @@ void Servatrice::updateLoginMessage()
event.set_message(newLoginMessage.toStdString());
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
QMapIterator<QString, Server_ProtocolHandler *> usersIterator(users);
while (usersIterator.hasNext())
while (usersIterator.hasNext()) {
usersIterator.next().value()->sendProtocolItem(*se);
}
delete se;
}
}
}
void Servatrice::setRequiredFeatures(const QString &featureList)
@ -560,18 +574,20 @@ void Servatrice::setRequiredFeatures(const QString &featureList)
serverRequiredFeatureList.clear();
features.initalizeFeatureList(serverRequiredFeatureList);
QStringList listReqFeatures = featureList.split(",", Qt::SkipEmptyParts);
if (!listReqFeatures.isEmpty())
if (!listReqFeatures.isEmpty()) {
for (const QString &reqFeature : listReqFeatures) {
features.enableRequiredFeature(serverRequiredFeatureList, reqFeature);
}
}
qDebug() << "Set required client features to:" << serverRequiredFeatureList;
}
void Servatrice::statusUpdate()
{
if (!servatriceDatabaseInterface->checkSql())
if (!servatriceDatabaseInterface->checkSql()) {
return;
}
const int uc = getUsersCount(); // for correct mutex locking order
@ -611,8 +627,9 @@ void Servatrice::statusUpdate()
auto servDbSelQuery = servatriceDatabaseInterface->prepareQuery("select a.name, b.email, b.token from "
"{prefix}_activation_emails a left join "
"{prefix}_users b on a.name = b.name");
if (!servatriceDatabaseInterface->execSqlQuery(servDbSelQuery))
if (!servatriceDatabaseInterface->execSqlQuery(servDbSelQuery)) {
return;
}
auto *queryDelete =
servatriceDatabaseInterface->prepareQuery("delete from {prefix}_activation_emails where name = :name");
@ -633,8 +650,9 @@ void Servatrice::statusUpdate()
auto *forgotPwQuery = servatriceDatabaseInterface->prepareQuery(
"select a.name, b.email, b.token from {prefix}_forgot_password a left join {prefix}_users b on a.name "
"= b.name where a.emailed = 0");
if (!servatriceDatabaseInterface->execSqlQuery(forgotPwQuery))
if (!servatriceDatabaseInterface->execSqlQuery(forgotPwQuery)) {
return;
}
QSqlQuery *queryDelete = servatriceDatabaseInterface->prepareQuery(
"update {prefix}_forgot_password set emailed = 1 where name = :name");
@ -686,8 +704,9 @@ void Servatrice::shutdownTimeout()
{
// Show every time counter cut in half & every minute for last 5 minutes
if (shutdownMinutes <= 5 || shutdownMinutes == nextShutdownMessageMinutes) {
if (shutdownMinutes == nextShutdownMessageMinutes)
if (shutdownMinutes == nextShutdownMessageMinutes) {
nextShutdownMessageMinutes = shutdownMinutes / 2;
}
SessionEvent *se;
if (shutdownMinutes) {
@ -702,8 +721,9 @@ void Servatrice::shutdownTimeout()
}
clientsLock.lockForRead();
for (auto &client : clients)
for (auto &client : clients) {
client->sendProtocolItem(*se);
}
clientsLock.unlock();
delete se;
@ -759,12 +779,14 @@ void Servatrice::doSendIslMessage(const IslMessage &msg, int _serverId)
if (_serverId == -1) {
QMapIterator<int, IslInterface *> islIterator(islInterfaces);
while (islIterator.hasNext())
while (islIterator.hasNext()) {
islIterator.next().value()->transmitMessage(msg);
}
} else {
IslInterface *interface = islInterfaces.value(_serverId);
if (interface)
if (interface) {
interface->transmitMessage(msg);
}
}
}
@ -968,10 +990,11 @@ bool Servatrice::permitCreateGameAsJudge() const
QHostAddress Servatrice::getServerTCPHost() const
{
QString host = settingsCache->value("server/host", "any").toString();
if (host == "any")
if (host == "any") {
return QHostAddress::Any;
else
} else {
return QHostAddress(host);
}
}
int Servatrice::getServerTCPPort() const
@ -987,10 +1010,11 @@ int Servatrice::getNumberOfWebSocketPools() const
QHostAddress Servatrice::getServerWebSocketHost() const
{
QString host = settingsCache->value("server/websocket_host", "any").toString();
if (host == "any")
if (host == "any") {
return QHostAddress::Any;
else
} else {
return QHostAddress(host);
}
}
int Servatrice::getServerWebSocketPort() const

View file

@ -55,8 +55,9 @@ bool Servatrice_DatabaseInterface::initDatabase(const QString &type,
bool Servatrice_DatabaseInterface::openDatabase()
{
if (sqlDatabase.isOpen())
if (sqlDatabase.isOpen()) {
sqlDatabase.close();
}
const QString poolStr = instanceId == -1 ? QString("main") : QString("pool %1").arg(instanceId);
qCDebug(DatabaseInterfaceLog).noquote() << poolStr << "Opening database...";
@ -139,8 +140,9 @@ QSqlQuery *Servatrice_DatabaseInterface::prepareQuery(const QString &queryText)
bool Servatrice_DatabaseInterface::execSqlQuery(QSqlQuery *query)
{
if (query->exec())
if (query->exec()) {
return true;
}
const QString poolStr = instanceId == -1 ? QString("main") : QString("pool %1").arg(instanceId);
qCCritical(DatabaseInterfaceLog) << poolStr << "Error executing query:" << query->lastError().text();
sqlDatabase.close();
@ -151,8 +153,9 @@ bool Servatrice_DatabaseInterface::execSqlQuery(QSqlQuery *query)
bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString &error)
{
int minNameLength = settingsCache->value("users/minnamelength", 6).toInt();
if (minNameLength < 1)
if (minNameLength < 1) {
minNameLength = 1;
}
int maxNameLength = settingsCache->value("users/maxnamelength", 12).toInt();
bool allowLowercase = settingsCache->value("users/allowlowercase", true).toBool();
bool allowUppercase = settingsCache->value("users/allowuppercase", true).toBool();
@ -184,29 +187,36 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString
.arg(disallowedWordsStr)
.arg(disallowedRegExpStr);
if (user.length() < minNameLength || user.length() > maxNameLength)
if (user.length() < minNameLength || user.length() > maxNameLength) {
return false;
}
if (!allowPunctuationPrefix && allowedPunctuation.contains(user.at(0)))
if (!allowPunctuationPrefix && allowedPunctuation.contains(user.at(0))) {
return false;
}
for (const QString &word : disallowedWords) {
if (user.contains(word, Qt::CaseInsensitive))
if (user.contains(word, Qt::CaseInsensitive)) {
return false;
}
}
for (const QRegularExpression &regExp : settingsCache->disallowedRegExp) {
if (regExp.match(user).hasMatch())
if (regExp.match(user).hasMatch()) {
return false;
}
}
QString regEx("\\A[");
if (allowLowercase)
if (allowLowercase) {
regEx.append("a-z");
if (allowUppercase)
}
if (allowUppercase) {
regEx.append("A-Z");
if (allowNumerics)
}
if (allowNumerics) {
regEx.append("0-9");
}
regEx.append(QRegularExpression::escape(allowedPunctuation));
regEx.append("]+\\z");
@ -222,8 +232,9 @@ bool Servatrice_DatabaseInterface::registerUser(const QString &userName,
const QString &country,
bool active)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
QString passwordSha512;
if (passwordNeedsHash) {
@ -259,8 +270,9 @@ bool Servatrice_DatabaseInterface::registerUser(const QString &userName,
bool Servatrice_DatabaseInterface::activateUser(const QString &userName, const QString &token)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
QSqlQuery *activateQuery =
prepareQuery("select name from {prefix}_users where active=0 and name=:username and token=:token");
@ -306,20 +318,24 @@ AuthenticationResult Servatrice_DatabaseInterface::checkUserPassword(Server_Prot
return UnknownUser;
case Servatrice::AuthenticationPassword: {
QString configPassword = settingsCache->value("authentication/password").toString();
if (configPassword == password)
if (configPassword == password) {
return PasswordRight;
}
return NotLoggedIn;
}
case Servatrice::AuthenticationSql: {
if (!checkSql())
if (!checkSql()) {
return UnknownUser;
}
if (!usernameIsValid(user, reasonStr))
if (!usernameIsValid(user, reasonStr)) {
return UsernameInvalid;
}
if (checkUserIsBanned(handler->getAddress(), user, clientId, reasonStr, banSecondsLeft))
if (checkUserIsBanned(handler->getAddress(), user, clientId, reasonStr, banSecondsLeft)) {
return UserIsBanned;
}
QSqlQuery *passwordQuery =
prepareQuery("select password_sha512, active from {prefix}_users where name = :name");
@ -364,8 +380,9 @@ bool Servatrice_DatabaseInterface::checkUserIsBanned(const QString &ipAddress,
QString &banReason,
int &banSecondsRemaining)
{
if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql)
if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql) {
return false;
}
if (!checkSql()) {
qCWarning(DatabaseInterfaceLog) << "Failed to check if user is banned. Database invalid.";
@ -381,8 +398,9 @@ bool Servatrice_DatabaseInterface::checkUserIsIdBanned(const QString &clientId,
QString &banReason,
int &banSecondsRemaining)
{
if (clientId.isEmpty())
if (clientId.isEmpty()) {
return false;
}
QSqlQuery *idBanQuery =
prepareQuery("select"
@ -487,8 +505,9 @@ bool Servatrice_DatabaseInterface::activeUserExists(const QString &user)
QSqlQuery *query = prepareQuery("select 1 from {prefix}_users where name = :name and active = 1");
query->bindValue(":name", user);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
return query->next();
}
return false;
@ -501,8 +520,9 @@ bool Servatrice_DatabaseInterface::userExists(const QString &user)
QSqlQuery *query = prepareQuery("select 1 from {prefix}_users where name = :name");
query->bindValue(":name", user);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
return query->next();
}
return false;
@ -535,10 +555,12 @@ int Servatrice_DatabaseInterface::getUserIdInDB(const QString &name)
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
QSqlQuery *query = prepareQuery("select id from {prefix}_users where name = :name and active = 1");
query->bindValue(":name", name);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return -1;
if (!query->next())
}
if (!query->next()) {
return -1;
}
return query->value(0).toInt();
}
return -1;
@ -546,11 +568,13 @@ int Servatrice_DatabaseInterface::getUserIdInDB(const QString &name)
bool Servatrice_DatabaseInterface::isInBuddyList(const QString &whoseList, const QString &who)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone) {
return false;
}
if (!checkSql())
if (!checkSql()) {
return false;
}
int id1 = getUserIdInDB(whoseList);
int id2 = getUserIdInDB(who);
@ -559,18 +583,21 @@ bool Servatrice_DatabaseInterface::isInBuddyList(const QString &whoseList, const
prepareQuery("select 1 from {prefix}_buddylist where id_user1 = :id_user1 and id_user2 = :id_user2");
query->bindValue(":id_user1", id1);
query->bindValue(":id_user2", id2);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
return query->next();
}
bool Servatrice_DatabaseInterface::isInIgnoreList(const QString &whoseList, const QString &who)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone) {
return false;
}
if (!checkSql())
if (!checkSql()) {
return false;
}
int id1 = getUserIdInDB(whoseList);
int id2 = getUserIdInDB(who);
@ -579,8 +606,9 @@ bool Servatrice_DatabaseInterface::isInIgnoreList(const QString &whoseList, cons
prepareQuery("select 1 from {prefix}_ignorelist where id_user1 = :id_user1 and id_user2 = :id_user2");
query->bindValue(":id_user1", id1);
query->bindValue(":id_user2", id2);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
return query->next();
}
@ -588,29 +616,34 @@ ServerInfo_User Servatrice_DatabaseInterface::evalUserQueryResult(const QSqlQuer
{
ServerInfo_User result;
if (withId)
if (withId) {
result.set_id(query->value(0).toInt());
}
result.set_name(query->value(1).toString().toStdString());
const int is_admin = query->value(2).toInt();
int userLevel = ServerInfo_User::IsUser | ServerInfo_User::IsRegistered;
if (is_admin & 1)
if (is_admin & 1) {
userLevel |= ServerInfo_User::IsAdmin | ServerInfo_User::IsModerator;
else if (is_admin & 2)
} else if (is_admin & 2) {
userLevel |= ServerInfo_User::IsModerator;
}
if (is_admin & 4)
if (is_admin & 4) {
userLevel |= ServerInfo_User::IsJudge;
}
result.set_user_level(userLevel);
const QString country = query->value(3).toString();
if (!country.isEmpty())
if (!country.isEmpty()) {
result.set_country(country.toStdString());
}
const QString privlevel = query->value(4).toString();
if (!privlevel.isEmpty())
if (!privlevel.isEmpty()) {
result.set_privlevel(privlevel.toStdString());
}
const auto &pawn_left_override = query->value(5).toString();
const auto &pawn_right_override = query->value(6).toString();
@ -623,12 +656,14 @@ ServerInfo_User Servatrice_DatabaseInterface::evalUserQueryResult(const QSqlQuer
if (complete) {
const QString realName = query->value(7).toString();
if (!realName.isEmpty())
if (!realName.isEmpty()) {
result.set_real_name(realName.toStdString());
}
const QByteArray avatarBmp = query->value(8).toByteArray();
if (avatarBmp.size())
if (avatarBmp.size()) {
result.set_avatar_bmp(avatarBmp.data(), avatarBmp.size());
}
const QDateTime regDate = query->value(9).toDateTime();
if (!regDate.toString(Qt::ISODate).isEmpty()) {
@ -638,12 +673,14 @@ ServerInfo_User Servatrice_DatabaseInterface::evalUserQueryResult(const QSqlQuer
}
const QString email = query->value(10).toString();
if (!email.isEmpty())
if (!email.isEmpty()) {
result.set_email(email.toStdString());
}
const QString clientid = query->value(11).toString();
if (!clientid.isEmpty())
if (!clientid.isEmpty()) {
result.set_clientid(clientid.toStdString());
}
}
return result;
}
@ -655,23 +692,27 @@ ServerInfo_User Servatrice_DatabaseInterface::getUserData(const QString &name, b
result.set_user_level(ServerInfo_User::IsUser);
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
if (!checkSql())
if (!checkSql()) {
return result;
}
QSqlQuery *query = prepareQuery("select id, name, admin, country, privlevel, leftPawnColorOverride, "
"rightPawnColorOverride, realname, avatar_bmp, registrationDate, "
"email, clientid from {prefix}_users where "
"name = :name and active = 1");
query->bindValue(":name", name);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return result;
}
if (query->next())
if (query->next()) {
return evalUserQueryResult(query, true, withId);
else
} else {
return result;
} else
}
} else {
return result;
}
}
void Servatrice_DatabaseInterface::clearSessionTables()
@ -715,11 +756,13 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName,
const QString &clientId,
const QString &connectionType)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone) {
return -1;
}
if (!checkSql())
if (!checkSql()) {
return -1;
}
QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time, "
"clientid, connection_type) values(:user_name, :id_server, :ip_address, NOW(), "
@ -729,18 +772,21 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName,
query->bindValue(":ip_address", address);
query->bindValue(":client_id", clientId);
query->bindValue(":connection_type", connectionType);
if (execSqlQuery(query))
if (execSqlQuery(query)) {
return query->lastInsertId().toInt();
}
return -1;
}
void Servatrice_DatabaseInterface::endSession(qint64 sessionId)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone) {
return;
}
if (!checkSql())
if (!checkSql()) {
return;
}
auto *query = prepareQuery("update {prefix}_sessions set end_time=NOW() where id = :id_session");
query->bindValue(":id_session", sessionId);
@ -759,8 +805,9 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getBuddyList(const
"left join {prefix}_buddylist b on a.id = b.id_user2 left join {prefix}_users "
"c on b.id_user1 = c.id where c.name = :name");
query->bindValue(":name", name);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return result;
}
while (query->next()) {
const ServerInfo_User &temp = evalUserQueryResult(query, false);
@ -782,8 +829,9 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getIgnoreList(const
"left join {prefix}_ignorelist b on a.id = b.id_user2 left join {prefix}_users "
"c on b.id_user1 = c.id where c.name = :name");
query->bindValue(":name", name);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return result;
}
while (query->next()) {
ServerInfo_User temp = evalUserQueryResult(query, false);
@ -795,11 +843,13 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getIgnoreList(const
int Servatrice_DatabaseInterface::getNextGameId()
{
if (!sqlDatabase.isValid())
if (!sqlDatabase.isValid()) {
return server->getNextLocalGameId();
}
if (!checkSql())
if (!checkSql()) {
return -1;
}
QSqlQuery *query = prepareQuery("insert into {prefix}_games (time_started) values (now())");
@ -812,8 +862,9 @@ int Servatrice_DatabaseInterface::getNextGameId()
int Servatrice_DatabaseInterface::getNextReplayId()
{
if (!checkSql())
if (!checkSql()) {
return -1;
}
QSqlQuery *query = prepareQuery("insert into {prefix}_replays (id_game) values (NULL)");
@ -831,11 +882,13 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
const QSet<QString> &allSpectatorsEver,
const QList<GameReplay *> &replayList)
{
if (!checkSql())
if (!checkSql()) {
return;
}
if (!settingsCache->value("game/store_replays", 1).toBool())
if (!settingsCache->value("game/store_replays", 1).toBool()) {
return;
}
QVariantList gameIds1, playerNames, gameIds2, userIds, replayNames;
QSetIterator<QString> playerIterator(allPlayersEver);
@ -848,8 +901,9 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
QSetIterator<QString> allUsersIterator(allUsersInGame);
while (allUsersIterator.hasNext()) {
int id = getUserIdInDB(allUsersIterator.next());
if (id == -1)
if (id == -1) {
continue;
}
gameIds2.append(gameInfo.game_id());
userIds.append(id);
replayNames.append(QString::fromStdString(gameInfo.description()));
@ -888,8 +942,9 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
query->bindValue(":password", gameInfo.with_password() ? 1 : 0);
query->bindValue(":game_types", roomGameTypes.isEmpty() ? QString("") : roomGameTypes.join(", "));
query->bindValue(":player_count", gameInfo.max_players());
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return;
}
}
{
QSqlQuery *query =
@ -926,8 +981,9 @@ DeckList *Servatrice_DatabaseInterface::getDeckFromDatabase(int deckId, int user
query->bindValue(":id", deckId);
query->bindValue(":id_user", userId);
execSqlQuery(query);
if (!query->next())
if (!query->next()) {
throw Response::RespNameNotFound;
}
DeckList *deck = new DeckList;
deck->loadFromString_Native(query->value(0).toString());
@ -946,23 +1002,27 @@ void Servatrice_DatabaseInterface::logMessage(const int senderId,
QString targetTypeString;
switch (targetType) {
case MessageTargetRoom:
if (!settingsCache->value("logging/log_user_msg_room", 0).toBool())
if (!settingsCache->value("logging/log_user_msg_room", 0).toBool()) {
return;
}
targetTypeString = "room";
break;
case MessageTargetGame:
if (!settingsCache->value("logging/log_user_msg_game", 0).toBool())
if (!settingsCache->value("logging/log_user_msg_game", 0).toBool()) {
return;
}
targetTypeString = "game";
break;
case MessageTargetChat:
if (!settingsCache->value("logging/log_user_msg_chat", 0).toBool())
if (!settingsCache->value("logging/log_user_msg_chat", 0).toBool()) {
return;
}
targetTypeString = "chat";
break;
case MessageTargetIslRoom:
if (!settingsCache->value("logging/log_user_msg_isl", 0).toBool())
if (!settingsCache->value("logging/log_user_msg_isl", 0).toBool()) {
return;
}
targetTypeString = "room";
break;
default:
@ -995,8 +1055,9 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user,
"passwordLastChangedDate = NOW() where name = :name");
passwordQuery->bindValue(":password", passwordSha512);
passwordQuery->bindValue(":name", user);
if (execSqlQuery(passwordQuery))
if (execSqlQuery(passwordQuery)) {
return true;
}
return false;
}
@ -1007,15 +1068,18 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user,
const QString &newPassword,
bool newPasswordNeedsHash)
{
if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql)
if (server->getAuthenticationMethod() != Servatrice::AuthenticationSql) {
return false;
}
if (!checkSql())
if (!checkSql()) {
return false;
}
QString error;
if (!usernameIsValid(user, error))
if (!usernameIsValid(user, error)) {
return false;
}
QSqlQuery *passwordQuery = prepareQuery("select password_sha512 from {prefix}_users where name = :name");
passwordQuery->bindValue(":name", user);
@ -1025,8 +1089,9 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user,
return false;
}
if (!passwordQuery->next())
if (!passwordQuery->next()) {
return false;
}
const QString correctPasswordSha512 = passwordQuery->value(0).toString();
QString oldPasswordSha512 = oldPassword;
@ -1034,8 +1099,9 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user,
QString salt = correctPasswordSha512.left(16);
oldPasswordSha512 = PasswordHasher::computeHash(oldPassword, salt);
}
if (correctPasswordSha512 != oldPasswordSha512)
if (correctPasswordSha512 != oldPasswordSha512) {
return false;
}
return changeUserPassword(user, newPassword, newPasswordNeedsHash);
}
@ -1044,23 +1110,28 @@ int Servatrice_DatabaseInterface::getActiveUserCount(QString connectionType)
{
int userCount = 0;
if (!checkSql())
if (!checkSql()) {
return userCount;
}
QString text = "select count(*) from {prefix}_sessions where id_server = :serverid AND end_time is NULL";
if (!connectionType.isEmpty())
if (!connectionType.isEmpty()) {
text += " AND connection_type = :connection_type";
}
QSqlQuery *query = prepareQuery(text);
query->bindValue(":serverid", server->getServerID());
if (!connectionType.isEmpty())
if (!connectionType.isEmpty()) {
query->bindValue(":connection_type", connectionType);
}
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return userCount;
}
if (query->next())
if (query->next()) {
userCount = query->value(0).toInt();
}
return userCount;
}
@ -1068,8 +1139,9 @@ int Servatrice_DatabaseInterface::getActiveUserCount(QString connectionType)
void Servatrice_DatabaseInterface::updateUsersClientID(const QString &userName, const QString &userClientID)
{
if (!checkSql())
if (!checkSql()) {
return;
}
QSqlQuery *query = prepareQuery("update {prefix}_users set clientid = :clientid where name = :username");
query->bindValue(":clientid", userClientID);
@ -1080,8 +1152,9 @@ void Servatrice_DatabaseInterface::updateUsersClientID(const QString &userName,
void Servatrice_DatabaseInterface::updateUsersLastLoginData(const QString &userName, const QString &clientVersion)
{
if (!checkSql())
if (!checkSql()) {
return;
}
int usersID = 0;
@ -1100,8 +1173,9 @@ void Servatrice_DatabaseInterface::updateUsersLastLoginData(const QString &userN
int userCount = 0;
query = prepareQuery("select count(id) from {prefix}_user_analytics where id = :user_id");
query->bindValue(":user_id", usersID);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return;
}
if (query->next()) {
userCount = query->value(0).toInt();
@ -1128,8 +1202,9 @@ QList<ServerInfo_Ban> Servatrice_DatabaseInterface::getUserBanHistory(const QStr
QList<ServerInfo_Ban> results;
ServerInfo_Ban banDetails;
if (!checkSql())
if (!checkSql()) {
return results;
}
QSqlQuery *query =
prepareQuery("SELECT A.id_admin, A.time_from, A.minutes, A.reason, A.visible_reason, B.name AS name_admin FROM "
@ -1159,8 +1234,9 @@ bool Servatrice_DatabaseInterface::addWarning(const QString userName,
const QString warningReason,
const QString clientID)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
int userID = getUserIdInDB(userName);
QSqlQuery *query =
@ -1184,8 +1260,9 @@ QList<ServerInfo_Warning> Servatrice_DatabaseInterface::getUserWarnHistory(const
QList<ServerInfo_Warning> results;
ServerInfo_Warning warnDetails;
if (!checkSql())
if (!checkSql()) {
return results;
}
int userID = getUserIdInDB(userName);
QSqlQuery *query =
@ -1223,8 +1300,9 @@ QList<ServerInfo_ChatMessage> Servatrice_DatabaseInterface::getMessageLogHistory
QList<ServerInfo_ChatMessage> results;
ServerInfo_ChatMessage chatMessage;
if (!checkSql())
if (!checkSql()) {
return results;
}
if (user.isEmpty() && ipaddress.isEmpty() && gameid.isEmpty() && gamename.isEmpty()) {
// To ensure quick results and minimal lag, require an indexed field
@ -1233,48 +1311,58 @@ QList<ServerInfo_ChatMessage> Servatrice_DatabaseInterface::getMessageLogHistory
// BUILD QUERY STRING BASED ON PASSED IN VALUES
QString queryString = "SELECT * FROM {prefix}_log WHERE `sender_ip` IS NOT NULL";
if (!user.isEmpty())
if (!user.isEmpty()) {
queryString.append(" AND (`sender_name` = :user_name OR `target_name` = :user_name)");
}
if (!ipaddress.isEmpty())
if (!ipaddress.isEmpty()) {
queryString.append(" AND `sender_ip` = :ip_to_find");
}
if (!gameid.isEmpty())
if (!gameid.isEmpty()) {
queryString.append(" AND (`target_id` = :game_id AND `target_type` = 'game')");
}
if (!gamename.isEmpty())
if (!gamename.isEmpty()) {
queryString.append(" AND (`target_name` = :game_name AND `target_type` = 'game')");
}
if (!message.isEmpty())
if (!message.isEmpty()) {
queryString.append(" AND `log_message` LIKE :log_message");
}
if (chat || game || room) {
queryString.append(" AND (");
if (chat)
if (chat) {
queryString.append("`target_type` = 'chat'");
}
if (game) {
if (chat)
if (chat) {
queryString.append(" OR `target_type` = 'game'");
else
} else {
queryString.append("`target_type` = 'game'");
}
}
if (room) {
if (game || chat)
if (game || chat) {
queryString.append(" OR `target_type` = 'room'");
else
} else {
queryString.append("`target_type` = 'room'");
}
}
queryString.append(")");
}
if (range)
if (range) {
queryString.append(" AND log_time >= DATE_SUB(now(), INTERVAL :range_time HOUR)");
}
if (maxresults)
if (maxresults) {
queryString.append(" LIMIT :limit_size");
}
QSqlQuery *query = prepareQuery(queryString);
if (!user.isEmpty()) {
@ -1321,8 +1409,9 @@ QList<ServerInfo_ChatMessage> Servatrice_DatabaseInterface::getMessageLogHistory
int Servatrice_DatabaseInterface::checkNumberOfUserAccounts(const QString &email)
{
if (!checkSql())
if (!checkSql()) {
return 0;
}
QSqlQuery *query = prepareQuery("SELECT count(email) FROM {prefix}_users WHERE email = :user_email");
query->bindValue(":user_email", email);
@ -1333,75 +1422,88 @@ int Servatrice_DatabaseInterface::checkNumberOfUserAccounts(const QString &email
return 0;
}
if (query->next())
if (query->next()) {
return query->value(0).toInt();
}
return 0;
}
bool Servatrice_DatabaseInterface::addForgotPassword(const QString &user)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
if (!updateUserToken(PasswordHasher::generateActivationToken(), user))
if (!updateUserToken(PasswordHasher::generateActivationToken(), user)) {
return false;
}
QSqlQuery *query = prepareQuery("insert into {prefix}_forgot_password (name,requestDate) values (:username,NOW())");
query->bindValue(":username", user);
if (execSqlQuery(query))
if (execSqlQuery(query)) {
return true;
}
return false;
}
bool Servatrice_DatabaseInterface::removeForgotPassword(const QString &user)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
QSqlQuery *query = prepareQuery("delete from {prefix}_forgot_password where name = :username");
query->bindValue(":username", user);
if (execSqlQuery(query))
if (execSqlQuery(query)) {
return true;
}
return false;
}
bool Servatrice_DatabaseInterface::doesForgotPasswordExist(const QString &user)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
QSqlQuery *query = prepareQuery("select count(name) from {prefix}_forgot_password where name = :user_name AND "
"requestDate > (now() - interval :minutes minute)");
query->bindValue(":user_name", user);
query->bindValue(":minutes", QString::number(server->getForgotPasswordTokenLife()));
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
if (query->next())
if (query->value("count(name)").toInt() > 0)
if (query->next()) {
if (query->value("count(name)").toInt() > 0) {
return true;
}
}
return false;
}
bool Servatrice_DatabaseInterface::updateUserToken(const QString &token, const QString &user)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
if (token.isEmpty() || user.isEmpty())
if (token.isEmpty() || user.isEmpty()) {
return false;
}
QSqlQuery *query = prepareQuery("update {prefix}_users set token = :token where name = :user_name");
query->bindValue(":user_name", user);
query->bindValue(":token", token);
if (execSqlQuery(query))
if (execSqlQuery(query)) {
return true;
}
return false;
}
@ -1411,22 +1513,27 @@ bool Servatrice_DatabaseInterface::validateTableColumnStringData(const QString &
const QString &_user,
const QString &_datatocheck)
{
if (!checkSql())
if (!checkSql()) {
return false;
}
if (table.isEmpty() || column.isEmpty() || _user.isEmpty() || _datatocheck.isEmpty())
if (table.isEmpty() || column.isEmpty() || _user.isEmpty() || _datatocheck.isEmpty()) {
return false;
}
QString formatedQuery = QString("select %1 from %2 where name = :user_name").arg(column).arg(table);
QSqlQuery *query = prepareQuery(formatedQuery);
query->bindValue(":user_name", _user);
if (!execSqlQuery(query))
if (!execSqlQuery(query)) {
return false;
}
if (query->next())
if (query->value(column).toString().toLower() == _datatocheck.toLower())
if (query->next()) {
if (query->value(column).toString().toLower() == _datatocheck.toLower()) {
return true;
}
}
return false;
}
@ -1438,14 +1545,17 @@ void Servatrice_DatabaseInterface::addAuditRecord(const QString &user,
const QString &details,
const bool &results = false)
{
if (!checkSql())
if (!checkSql()) {
return;
}
if (!server->getEnableAudit())
if (!server->getEnableAudit()) {
return;
}
if (user.isEmpty() || ipaddress.isEmpty() || clientid.isEmpty() || action.isEmpty())
if (user.isEmpty() || ipaddress.isEmpty() || clientid.isEmpty() || action.isEmpty()) {
return;
}
QSqlQuery *query = prepareQuery("insert into {prefix}_audit "
"(id_server,name,ip_address,clientid,incidentDate,action,results,details) values "

View file

@ -39,20 +39,23 @@ void ServerLogger::startLog(const QString &logFileName)
logFile = 0;
return;
}
} else
} else {
logFile = 0;
}
connect(this, SIGNAL(sigFlushBuffer()), this, SLOT(flushBuffer()), Qt::QueuedConnection);
}
void ServerLogger::logMessage(const QString &message, void *caller)
{
if (!logFile)
if (!logFile) {
return;
}
QString callerString;
if (caller)
if (caller) {
callerString = QString::number((qulonglong)caller, 16) + " ";
}
// filter out all log entries based on values in configuration file
bool shouldWeWriteLog = settingsCache->value("server/writelog", 1).toBool();
@ -60,8 +63,9 @@ void ServerLogger::logMessage(const QString &message, void *caller)
QStringList listlogFilters = logFilters.split(",", Qt::SkipEmptyParts);
bool shouldWeSkipLine = false;
if (!shouldWeWriteLog)
if (!shouldWeWriteLog) {
return;
}
if (!logFilters.trimmed().isEmpty()) {
shouldWeSkipLine = true;
@ -73,8 +77,9 @@ void ServerLogger::logMessage(const QString &message, void *caller)
}
}
if (shouldWeSkipLine)
if (shouldWeSkipLine) {
return;
}
bufferMutex.lock();
buffer.append(QDateTime::currentDateTime().toString() + " " + callerString + message);
@ -84,8 +89,9 @@ void ServerLogger::logMessage(const QString &message, void *caller)
void ServerLogger::flushBuffer()
{
if (flushRunning)
if (flushRunning) {
return;
}
flushRunning = true;
QTextStream stream(logFile);
@ -103,15 +109,17 @@ void ServerLogger::flushBuffer()
stream << message << "\n";
stream.flush();
if (logToConsole)
if (logToConsole) {
std::cout << message.toStdString() << std::endl;
}
}
}
void ServerLogger::rotateLogs()
{
if (!logFile)
if (!logFile) {
return;
}
flushBuffer();

File diff suppressed because it is too large Load diff

View file

@ -30,14 +30,16 @@ QString SettingsCache::guessConfigurationPath()
// application directory path
guessFileName = QCoreApplication::applicationDirPath() + "/" + fileName;
if (QFile::exists(guessFileName))
if (QFile::exists(guessFileName)) {
return guessFileName;
}
#ifdef Q_OS_UNIX
// /etc
guessFileName = "/etc/servatrice/" + fileName;
if (QFile::exists(guessFileName))
if (QFile::exists(guessFileName)) {
return guessFileName;
}
#endif
guessFileName = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/" + fileName;

View file

@ -86,10 +86,11 @@ void SignalHandler::sigSegvHandler(int sig)
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
if (sig == SIGSEGV)
if (sig == SIGSEGV) {
logger->logMessage("CRASH: SIGSEGV");
else if (sig == SIGABRT)
} else if (sig == SIGABRT) {
logger->logMessage("CRASH: SIGABRT");
}
logger->deleteLater();
loggerThread->wait();

View file

@ -125,11 +125,13 @@ bool SmtpClient::enqueueForgotPasswordTokenMail(const QString &nickname, const Q
void SmtpClient::sendAllEmails()
{
// still connected from the previous round
if (smtp->socket()->state() == QAbstractSocket::ConnectedState)
if (smtp->socket()->state() == QAbstractSocket::ConnectedState) {
return;
}
if (smtp->pendingMessages() == 0)
if (smtp->pendingMessages() == 0) {
return;
}
QString connectionType = settingsCache->value("smtp/connection", "tcp").toString();
QString host = settingsCache->value("smtp/host", "localhost").toString();
@ -143,8 +145,9 @@ void SmtpClient::sendAllEmails()
// Connect
if (connectionType == "ssl") {
if (acceptAllCerts)
if (acceptAllCerts) {
smtp->sslSocket()->setPeerVerifyMode(QSslSocket::QueryPeer);
}
smtp->connectToSecureHost(host, port);
} else {
smtp->connectToHost(host, port);