diff options
author | Robert <krzmbrzl@gmail.com> | 2020-09-11 19:29:33 +0300 |
---|---|---|
committer | Robert <krzmbrzl@gmail.com> | 2020-09-11 19:29:33 +0300 |
commit | af7dac72f4063dd8d4dac71973ea51c25896089a (patch) | |
tree | 35558695aea94d48fd9e77d164d63fd8b7c76e90 /src/murmur/Server.cpp | |
parent | 40b28b03c150b453e00c6bc4f8d6957caea59c51 (diff) |
FORMAT: Run clang-format 10 on all C/CXX source-files
Diffstat (limited to 'src/murmur/Server.cpp')
-rw-r--r-- | src/murmur/Server.cpp | 930 |
1 files changed, 482 insertions, 448 deletions
diff --git a/src/murmur/Server.cpp b/src/murmur/Server.cpp index 305a0f682..d01dd31df 100644 --- a/src/murmur/Server.cpp +++ b/src/murmur/Server.cpp @@ -6,53 +6,53 @@ #include "Server.h" #include "ACL.h" +#include "Channel.h" +#include "ChannelListener.h" #include "Connection.h" +#include "EnvUtils.h" #include "Group.h" -#include "User.h" -#include "Channel.h" +#include "HTMLFilter.h" +#include "HostAddress.h" #include "Message.h" #include "Meta.h" #include "PacketDataStream.h" #include "ServerDB.h" #include "ServerUser.h" -#include "Version.h" -#include "HTMLFilter.h" -#include "HostAddress.h" -#include "ChannelListener.h" #include "SpeechFlags.h" -#include "EnvUtils.h" +#include "User.h" +#include "Version.h" #ifdef USE_BONJOUR -# include "BonjourServer.h" -# include "BonjourServiceRegister.h" +# include "BonjourServer.h" +# include "BonjourServiceRegister.h" #endif #include "Utils.h" #include <QtCore/QCoreApplication> +#include <QtCore/QSet> #include <QtCore/QXmlStreamAttributes> #include <QtCore/QtEndian> -#include <QtCore/QSet> #include <QtNetwork/QHostInfo> #include <QtNetwork/QSslConfiguration> #include <boost/bind.hpp> #ifdef Q_OS_WIN -# include <qos2.h> -# include <ws2tcpip.h> +# include <qos2.h> +# include <ws2tcpip.h> #else -# include <netinet/in.h> -# include <poll.h> +# include <netinet/in.h> +# include <poll.h> #endif #ifndef MAX -# define MAX(a,b) ((a)>(b) ? (a):(b)) +# define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #define UDP_PACKET_SIZE 1024 -ExecEvent::ExecEvent(boost::function<void ()> f) : QEvent(static_cast<QEvent::Type>(EXEC_QEVENT)) { +ExecEvent::ExecEvent(boost::function< void() > f) : QEvent(static_cast< QEvent::Type >(EXEC_QEVENT)) { func = f; } @@ -73,7 +73,8 @@ bool SslServer::hasDualStackSupport() { int s = ::socket(AF_INET6, SOCK_STREAM, 0); if (s != -1) { const int ipv6only = 0; - if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), sizeof(ipv6only)) == 0) { + if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), sizeof(ipv6only)) + == 0) { result = true; } ::close(s); @@ -89,7 +90,8 @@ bool SslServer::hasDualStackSupport() { SOCKET s = ::WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); if (s != INVALID_SOCKET) { const int ipv6only = 0; - if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), sizeof(ipv6only)) == 0) { + if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), sizeof(ipv6only)) + == 0) { result = true; } closesocket(s); @@ -112,7 +114,7 @@ QSslSocket *SslServer::nextPendingSSLConnection() { } Server::Server(int snum, QObject *p) : QThread(p) { - bValid = true; + bValid = true; iServerNum = snum; #ifdef USE_BONJOUR bsRegistration = nullptr; @@ -127,60 +129,62 @@ Server::Server(int snum, QObject *p) : QThread(p) { qtTimeout = new QTimer(this); iCodecAlpha = iCodecBeta = 0; - bPreferAlpha = false; - bOpus = true; + bPreferAlpha = false; + bOpus = true; qnamNetwork = nullptr; readParams(); initialize(); - foreach(const QHostAddress &qha, qlBind) { + foreach (const QHostAddress &qha, qlBind) { SslServer *ss = new SslServer(this); connect(ss, SIGNAL(newConnection()), this, SLOT(newClient()), Qt::QueuedConnection); - if (! ss->listen(qha, usPort)) { - log(QString("Server: TCP Listen on %1 failed: %2").arg(addressToString(qha,usPort), ss->errorString())); + if (!ss->listen(qha, usPort)) { + log(QString("Server: TCP Listen on %1 failed: %2").arg(addressToString(qha, usPort), ss->errorString())); bValid = false; } else { - log(QString("Server listening on %1").arg(addressToString(qha,usPort))); + log(QString("Server listening on %1").arg(addressToString(qha, usPort))); } qlServer << ss; } - if (! bValid) + if (!bValid) return; - foreach(SslServer *ss, qlServer) { + foreach (SslServer *ss, qlServer) { sockaddr_storage addr; #ifdef Q_OS_UNIX - int tcpsock = static_cast<int>(ss->socketDescriptor()); + int tcpsock = static_cast< int >(ss->socketDescriptor()); socklen_t len = sizeof(addr); #else - SOCKET tcpsock = ss->socketDescriptor(); - int len = sizeof(addr); + SOCKET tcpsock = ss->socketDescriptor(); + int len = sizeof(addr); #endif memset(&addr, 0, sizeof(addr)); - getsockname(tcpsock, reinterpret_cast<struct sockaddr *>(&addr), &len); + getsockname(tcpsock, reinterpret_cast< struct sockaddr * >(&addr), &len); #ifdef Q_OS_UNIX int sock = ::socket(addr.ss_family, SOCK_DGRAM, 0); -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX int sockopt = 1; if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &sockopt, sizeof(sockopt))) log(QString("Failed to set IP_PKTINFO for %1").arg(addressToString(ss->serverAddress(), usPort))); sockopt = 1; if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &sockopt, sizeof(sockopt))) log(QString("Failed to set IPV6_RECVPKTINFO for %1").arg(addressToString(ss->serverAddress(), usPort))); -#endif +# endif #else -#ifndef SIO_UDP_CONNRESET -#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12) -#endif - SOCKET sock = ::WSASocket(addr.ss_family, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, WSA_FLAG_OVERLAPPED); +# ifndef SIO_UDP_CONNRESET +# define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12) +# endif + SOCKET sock = ::WSASocket(addr.ss_family, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, WSA_FLAG_OVERLAPPED); DWORD dwBytesReturned = 0; - BOOL bNewBehaviour = FALSE; - if (WSAIoctl(sock, SIO_UDP_CONNRESET, &bNewBehaviour, sizeof(bNewBehaviour), nullptr, 0, &dwBytesReturned, nullptr, nullptr) == SOCKET_ERROR) { + BOOL bNewBehaviour = FALSE; + if (WSAIoctl(sock, SIO_UDP_CONNRESET, &bNewBehaviour, sizeof(bNewBehaviour), nullptr, 0, &dwBytesReturned, + nullptr, nullptr) + == SOCKET_ERROR) { log(QString("Failed to set SIO_UDP_CONNRESET: %1").arg(WSAGetLastError())); } #endif @@ -194,16 +198,19 @@ Server::Server(int snum, QObject *p) : QThread(p) { // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms738574%28v=vs.85%29.aspx // This will fail for WindowsXP which is ok. Our TCP code will have split that up // into two sockets. - int ipv6only = 0; + int ipv6only = 0; socklen_t optlen = sizeof(ipv6only); - if (::getsockopt(tcpsock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char*>(&ipv6only), &optlen) == 0) { - if (::setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), optlen) == SOCKET_ERROR) { + if (::getsockopt(tcpsock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< char * >(&ipv6only), &optlen) + == 0) { + if (::setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), + optlen) + == SOCKET_ERROR) { log(QString("Failed to copy IPV6_V6ONLY socket attribute from tcp to udp socket")); } } } - if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) == SOCKET_ERROR) { + if (::bind(sock, reinterpret_cast< sockaddr * >(&addr), len) == SOCKET_ERROR) { log(QString("Failed to bind UDP Socket to %1").arg(addressToString(ss->serverAddress(), usPort))); } else { #ifdef Q_OS_UNIX @@ -213,7 +220,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { if (setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val))) log("Server: Failed to set TOS for UDP Socket"); } -#if defined(SO_PRIORITY) +# if defined(SO_PRIORITY) socklen_t optlen = sizeof(val); if (getsockopt(sock, SOL_SOCKET, SO_PRIORITY, &val, &optlen) == 0) { if (val == 0) { @@ -221,7 +228,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &val, sizeof(val)); } } -#endif +# endif #endif } QSocketNotifier *qsn = new QSocketNotifier(sock, QSocketNotifier::Read, this); @@ -232,7 +239,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { } bValid = bValid && (qlServer.count() == qlBind.count()) && (qlUdpSocket.count() == qlBind.count()); - if (! bValid) + if (!bValid) return; #ifdef Q_OS_UNIX @@ -245,10 +252,11 @@ Server::Server(int snum, QObject *p) : QThread(p) { hNotify = CreateEvent(nullptr, FALSE, FALSE, nullptr); #endif - connect(this, SIGNAL(tcpTransmit(QByteArray, unsigned int)), this, SLOT(tcpTransmitData(QByteArray, unsigned int)), Qt::QueuedConnection); + connect(this, SIGNAL(tcpTransmit(QByteArray, unsigned int)), this, SLOT(tcpTransmitData(QByteArray, unsigned int)), + Qt::QueuedConnection); connect(this, SIGNAL(reqSync(unsigned int)), this, SLOT(doSync(unsigned int))); - for (int i=1;i<iMaxUsers*2;++i) + for (int i = 1; i < iMaxUsers * 2; ++i) qqIds.enqueue(i); connect(qtTimeout, SIGNAL(timeout()), this, SLOT(checkTimeout())); @@ -262,7 +270,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { QString release; Meta::getVersion(major, minor, patch, release); - uiVersionBlob = qToBigEndian(static_cast<quint32>((major<<16) | (minor << 8) | patch)); + uiVersionBlob = qToBigEndian(static_cast< quint32 >((major << 16) | (minor << 8) | patch)); if (bValid) { #ifdef USE_BONJOUR @@ -270,16 +278,15 @@ Server::Server(int snum, QObject *p) : QThread(p) { initBonjour(); #endif initRegister(); - } } void Server::startThread() { - if (! isRunning()) { + if (!isRunning()) { log("Starting voice thread"); bRunning = true; - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) qsn->setEnabled(false); start(QThread::HighestPriority); #ifdef Q_OS_LINUX @@ -288,14 +295,14 @@ void Server::startThread() { struct sched_param param; if (pthread_getschedparam(pthread_self(), &policy, ¶m) == 0) { if (policy == SCHED_OTHER) { - policy = SCHED_FIFO; + policy = SCHED_FIFO; param.sched_priority = 1; pthread_setschedparam(pthread_self(), policy, ¶m); } } #endif } - if (! qtTimeout->isActive()) + if (!qtTimeout->isActive()) qtTimeout->start(15500); } @@ -313,7 +320,7 @@ void Server::stopThread() { #endif wait(); - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) qsn->setEnabled(true); } qtTimeout->stop(); @@ -326,11 +333,11 @@ Server::~Server() { stopThread(); - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) delete qsn; #ifdef Q_OS_UNIX - foreach(int s, qlUdpSocket) + foreach (int s, qlUdpSocket) close(s); if (aiNotify[0] >= 0) @@ -338,7 +345,7 @@ Server::~Server() { if (aiNotify[1] >= 0) close(aiNotify[1]); #else - foreach(SOCKET s, qlUdpSocket) + foreach (SOCKET s, qlUdpSocket) closesocket(s); if (hNotify) CloseHandle(hNotify); @@ -384,87 +391,88 @@ static QVariant normalizeSuggestVersion(QVariant suggestVersion) { } void Server::readParams() { - qsPassword = Meta::mp.qsPassword; - usPort = static_cast<unsigned short>(Meta::mp.usPort + iServerNum - 1); - iTimeout = Meta::mp.iTimeout; - iMaxBandwidth = Meta::mp.iMaxBandwidth; - iMaxUsers = Meta::mp.iMaxUsers; - iMaxUsersPerChannel = Meta::mp.iMaxUsersPerChannel; - iMaxTextMessageLength = Meta::mp.iMaxTextMessageLength; + qsPassword = Meta::mp.qsPassword; + usPort = static_cast< unsigned short >(Meta::mp.usPort + iServerNum - 1); + iTimeout = Meta::mp.iTimeout; + iMaxBandwidth = Meta::mp.iMaxBandwidth; + iMaxUsers = Meta::mp.iMaxUsers; + iMaxUsersPerChannel = Meta::mp.iMaxUsersPerChannel; + iMaxTextMessageLength = Meta::mp.iMaxTextMessageLength; iMaxImageMessageLength = Meta::mp.iMaxImageMessageLength; - bAllowHTML = Meta::mp.bAllowHTML; - iDefaultChan = Meta::mp.iDefaultChan; - bRememberChan = Meta::mp.bRememberChan; - iRememberChanDuration = Meta::mp.iRememberChanDuration; - qsWelcomeText = Meta::mp.qsWelcomeText; - qsWelcomeTextFile = Meta::mp.qsWelcomeTextFile; - qlBind = Meta::mp.qlBind; - qsRegName = Meta::mp.qsRegName; - qsRegPassword = Meta::mp.qsRegPassword; - qsRegHost = Meta::mp.qsRegHost; - qsRegLocation = Meta::mp.qsRegLocation; - qurlRegWeb = Meta::mp.qurlRegWeb; - bBonjour = Meta::mp.bBonjour; - bAllowPing = Meta::mp.bAllowPing; - bCertRequired = Meta::mp.bCertRequired; - bForceExternalAuth = Meta::mp.bForceExternalAuth; - qrUserName = Meta::mp.qrUserName; - qrChannelName = Meta::mp.qrChannelName; - iMessageLimit = Meta::mp.iMessageLimit; - iMessageBurst = Meta::mp.iMessageBurst; - qvSuggestVersion = Meta::mp.qvSuggestVersion; - qvSuggestPositional = Meta::mp.qvSuggestPositional; - qvSuggestPushToTalk = Meta::mp.qvSuggestPushToTalk; - iOpusThreshold = Meta::mp.iOpusThreshold; - iChannelNestingLimit = Meta::mp.iChannelNestingLimit; - iChannelCountLimit = Meta::mp.iChannelCountLimit; + bAllowHTML = Meta::mp.bAllowHTML; + iDefaultChan = Meta::mp.iDefaultChan; + bRememberChan = Meta::mp.bRememberChan; + iRememberChanDuration = Meta::mp.iRememberChanDuration; + qsWelcomeText = Meta::mp.qsWelcomeText; + qsWelcomeTextFile = Meta::mp.qsWelcomeTextFile; + qlBind = Meta::mp.qlBind; + qsRegName = Meta::mp.qsRegName; + qsRegPassword = Meta::mp.qsRegPassword; + qsRegHost = Meta::mp.qsRegHost; + qsRegLocation = Meta::mp.qsRegLocation; + qurlRegWeb = Meta::mp.qurlRegWeb; + bBonjour = Meta::mp.bBonjour; + bAllowPing = Meta::mp.bAllowPing; + bCertRequired = Meta::mp.bCertRequired; + bForceExternalAuth = Meta::mp.bForceExternalAuth; + qrUserName = Meta::mp.qrUserName; + qrChannelName = Meta::mp.qrChannelName; + iMessageLimit = Meta::mp.iMessageLimit; + iMessageBurst = Meta::mp.iMessageBurst; + qvSuggestVersion = Meta::mp.qvSuggestVersion; + qvSuggestPositional = Meta::mp.qvSuggestPositional; + qvSuggestPushToTalk = Meta::mp.qvSuggestPushToTalk; + iOpusThreshold = Meta::mp.iOpusThreshold; + iChannelNestingLimit = Meta::mp.iChannelNestingLimit; + iChannelCountLimit = Meta::mp.iChannelCountLimit; QString qsHost = getConf("host", QString()).toString(); - if (! qsHost.isEmpty()) { + if (!qsHost.isEmpty()) { qlBind.clear(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { #else // Qt 5.14 introduced the Qt::SplitBehavior flags deprecating the QString fields - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { #endif QHostAddress qhaddr; if (qhaddr.setAddress(qsHost)) { qlBind << qhaddr; } else { - bool found = false; + bool found = false; QHostInfo hi = QHostInfo::fromName(host); - foreach(QHostAddress qha, hi.addresses()) { - if ((qha.protocol() == QAbstractSocket::IPv4Protocol) || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { + foreach (QHostAddress qha, hi.addresses()) { + if ((qha.protocol() == QAbstractSocket::IPv4Protocol) + || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { qlBind << qha; found = true; } } - if (! found) { + if (!found) { log(QString("Lookup of bind hostname %1 failed").arg(host)); } } } - foreach(const QHostAddress &qha, qlBind) + foreach (const QHostAddress &qha, qlBind) log(QString("Binding to address %1").arg(qha.toString())); if (qlBind.isEmpty()) qlBind = Meta::mp.qlBind; } - qsPassword = getConf("password", qsPassword).toString(); - usPort = static_cast<unsigned short>(getConf("port", usPort).toUInt()); - iTimeout = getConf("timeout", iTimeout).toInt(); - iMaxBandwidth = getConf("bandwidth", iMaxBandwidth).toInt(); - iMaxUsers = getConf("users", iMaxUsers).toInt(); - iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toInt(); - iMaxTextMessageLength = getConf("textmessagelength", iMaxTextMessageLength).toInt(); + qsPassword = getConf("password", qsPassword).toString(); + usPort = static_cast< unsigned short >(getConf("port", usPort).toUInt()); + iTimeout = getConf("timeout", iTimeout).toInt(); + iMaxBandwidth = getConf("bandwidth", iMaxBandwidth).toInt(); + iMaxUsers = getConf("users", iMaxUsers).toInt(); + iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toInt(); + iMaxTextMessageLength = getConf("textmessagelength", iMaxTextMessageLength).toInt(); iMaxImageMessageLength = getConf("imagemessagelength", iMaxImageMessageLength).toInt(); - bAllowHTML = getConf("allowhtml", bAllowHTML).toBool(); - iDefaultChan = getConf("defaultchannel", iDefaultChan).toInt(); - bRememberChan = getConf("rememberchannel", bRememberChan).toBool(); - iRememberChanDuration = getConf("rememberchannelduration", iRememberChanDuration).toInt(); - qsWelcomeText = getConf("welcometext", qsWelcomeText).toString(); - qsWelcomeTextFile = getConf("welcometextfile", qsWelcomeTextFile).toString(); + bAllowHTML = getConf("allowhtml", bAllowHTML).toBool(); + iDefaultChan = getConf("defaultchannel", iDefaultChan).toInt(); + bRememberChan = getConf("rememberchannel", bRememberChan).toBool(); + iRememberChanDuration = getConf("rememberchannelduration", iRememberChanDuration).toInt(); + qsWelcomeText = getConf("welcometext", qsWelcomeText).toString(); + qsWelcomeTextFile = getConf("welcometextfile", qsWelcomeTextFile).toString(); if (!qsWelcomeTextFile.isEmpty()) { if (qsWelcomeText.isEmpty()) { @@ -481,14 +489,14 @@ void Server::readParams() { } } - qsRegName = getConf("registername", qsRegName).toString(); - qsRegPassword = getConf("registerpassword", qsRegPassword).toString(); - qsRegHost = getConf("registerhostname", qsRegHost).toString(); - qsRegLocation = getConf("registerlocation", qsRegLocation).toString(); - qurlRegWeb = QUrl(getConf("registerurl", qurlRegWeb.toString()).toString()); - bBonjour = getConf("bonjour", bBonjour).toBool(); - bAllowPing = getConf("allowping", bAllowPing).toBool(); - bCertRequired = getConf("certrequired", bCertRequired).toBool(); + qsRegName = getConf("registername", qsRegName).toString(); + qsRegPassword = getConf("registerpassword", qsRegPassword).toString(); + qsRegHost = getConf("registerhostname", qsRegHost).toString(); + qsRegLocation = getConf("registerlocation", qsRegLocation).toString(); + qurlRegWeb = QUrl(getConf("registerurl", qurlRegWeb.toString()).toString()); + bBonjour = getConf("bonjour", bBonjour).toBool(); + bAllowPing = getConf("allowping", bAllowPing).toBool(); + bCertRequired = getConf("certrequired", bCertRequired).toBool(); bForceExternalAuth = getConf("forceExternalAuth", bForceExternalAuth).toBool(); qvSuggestVersion = normalizeSuggestVersion(getConf("suggestversion", qvSuggestVersion)); @@ -506,16 +514,16 @@ void Server::readParams() { iOpusThreshold = getConf("opusthreshold", iOpusThreshold).toInt(); iChannelNestingLimit = getConf("channelnestinglimit", iChannelNestingLimit).toInt(); - iChannelCountLimit = getConf("channelcountlimit", iChannelCountLimit).toInt(); + iChannelCountLimit = getConf("channelcountlimit", iChannelCountLimit).toInt(); - qrUserName=QRegExp(getConf("username", qrUserName.pattern()).toString()); - qrChannelName=QRegExp(getConf("channelname", qrChannelName.pattern()).toString()); + qrUserName = QRegExp(getConf("username", qrUserName.pattern()).toString()); + qrChannelName = QRegExp(getConf("channelname", qrChannelName.pattern()).toString()); - iMessageLimit=getConf("messagelimit", iMessageLimit).toUInt(); + iMessageLimit = getConf("messagelimit", iMessageLimit).toUInt(); if (iMessageLimit < 1) { // Prevent disabling messages entirely iMessageLimit = 1; } - iMessageBurst=getConf("messageburst", iMessageBurst).toUInt(); + iMessageBurst = getConf("messageburst", iMessageBurst).toUInt(); if (iMessageBurst < 1) { // Prevent disabling messages entirely iMessageBurst = 1; } @@ -523,7 +531,7 @@ void Server::readParams() { void Server::setLiveConf(const QString &key, const QString &value) { QString v = value.trimmed().isEmpty() ? QString() : value; - int i = v.toInt(); + int i = v.toInt(); if ((key == "password") || (key == "serverpassword")) qsPassword = !v.isNull() ? v : Meta::mp.qsPassword; else if (key == "timeout") @@ -597,7 +605,7 @@ void Server::setLiveConf(const QString &key, const QString &value) { QString text = !v.isNull() ? v : Meta::mp.qsRegName; if (text != qsRegName) { qsRegName = text; - if (! qsRegName.isEmpty()) { + if (!qsRegName.isEmpty()) { MumbleProto::ChannelState mpcs; mpcs.set_channel_id(0); mpcs.set_name(u8(qsRegName)); @@ -627,15 +635,16 @@ void Server::setLiveConf(const QString &key, const QString &value) { } else if (key == "allowping") bAllowPing = !v.isNull() ? QVariant(v).toBool() : Meta::mp.bAllowPing; else if (key == "username") - qrUserName=!v.isNull() ? QRegExp(v) : Meta::mp.qrUserName; + qrUserName = !v.isNull() ? QRegExp(v) : Meta::mp.qrUserName; else if (key == "channelname") - qrChannelName=!v.isNull() ? QRegExp(v) : Meta::mp.qrChannelName; + qrChannelName = !v.isNull() ? QRegExp(v) : Meta::mp.qrChannelName; else if (key == "suggestversion") - qvSuggestVersion = ! v.isNull() ? (v.isEmpty() ? QVariant() : normalizeSuggestVersion(v)) : Meta::mp.qvSuggestVersion; + qvSuggestVersion = + !v.isNull() ? (v.isEmpty() ? QVariant() : normalizeSuggestVersion(v)) : Meta::mp.qvSuggestVersion; else if (key == "suggestpositional") - qvSuggestPositional = ! v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPositional; + qvSuggestPositional = !v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPositional; else if (key == "suggestpushtotalk") - qvSuggestPushToTalk = ! v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPushToTalk; + qvSuggestPushToTalk = !v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPushToTalk; else if (key == "opusthreshold") iOpusThreshold = (i >= 0 && !v.isNull()) ? qBound(0, i, 100) : Meta::mp.iOpusThreshold; else if (key == "channelnestinglimit") @@ -660,8 +669,7 @@ void Server::initBonjour() { bsRegistration = new BonjourServer(); if (bsRegistration->bsrRegister) { log("Announcing server via bonjour"); - bsRegistration->bsrRegister->registerService(BonjourRecord(qsRegName, "_mumble._tcp", ""), - usPort); + bsRegistration->bsrRegister->registerService(BonjourRecord(qsRegName, "_mumble._tcp", ""), usPort); } } @@ -674,7 +682,7 @@ void Server::removeBonjour() { void Server::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) - static_cast<ExecEvent *>(evt)->execute(); + static_cast< ExecEvent * >(evt)->execute(); } void Server::udpActivated(int socket) { @@ -682,43 +690,44 @@ void Server::udpActivated(int socket) { char encrypt[UDP_PACKET_SIZE]; sockaddr_storage from; #ifdef Q_OS_UNIX -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = encrypt; - iov[0].iov_len = UDP_PACKET_SIZE; + iov[0].iov_len = UDP_PACKET_SIZE; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(&from); - msg.msg_namelen = sizeof(from); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; + msg.msg_name = reinterpret_cast< struct sockaddr * >(&from); + msg.msg_namelen = sizeof(from); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; msg.msg_controllen = sizeof(controldata); int &sock = socket; - len=static_cast<quint32>(::recvmsg(sock, &msg, MSG_TRUNC)); -#else + len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); +# else socklen_t fromlen = sizeof(from); - int &sock = socket; - len=static_cast<qint32>(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast<struct sockaddr *>(&from), &fromlen)); -#endif + int &sock = socket; + len = static_cast< qint32 >( + ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast< struct sockaddr * >(&from), &fromlen)); +# endif #else int fromlen = sizeof(from); - SOCKET sock = static_cast<SOCKET>(socket); - len=::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast<struct sockaddr *>(&from), &fromlen); + SOCKET sock = static_cast< SOCKET >(socket); + len = ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast< struct sockaddr * >(&from), &fromlen); #endif // Cloned from ::run(), as it's the only UDP data we care about until the thread is started. - quint32 *ping = reinterpret_cast<quint32 *>(encrypt); + quint32 *ping = reinterpret_cast< quint32 * >(encrypt); if ((len == 12) && (*ping == 0) && bAllowPing) { ping[0] = uiVersionBlob; - ping[3] = qToBigEndian(static_cast<quint32>(qhUsers.count())); - ping[4] = qToBigEndian(static_cast<quint32>(iMaxUsers)); - ping[5] = qToBigEndian(static_cast<quint32>(iMaxBandwidth)); + ping[3] = qToBigEndian(static_cast< quint32 >(qhUsers.count())); + ping[4] = qToBigEndian(static_cast< quint32 >(iMaxUsers)); + ping[5] = qToBigEndian(static_cast< quint32 >(iMaxBandwidth)); #ifdef Q_OS_LINUX // There will be space for only one header, and the only data we have asked for is the incoming @@ -726,7 +735,7 @@ void Server::udpActivated(int socket) { iov[0].iov_len = 6 * sizeof(quint32); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast<struct sockaddr *>(&from), fromlen); + ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast< struct sockaddr * >(&from), fromlen); #endif } } @@ -734,7 +743,7 @@ void Server::udpActivated(int socket) { void Server::run() { qint32 len; #if defined(__LP64__) - char encbuff[UDP_PACKET_SIZE+8]; + char encbuff[UDP_PACKET_SIZE + 8]; char *encrypt = encbuff + 4; #else char encrypt[UDP_PACKET_SIZE]; @@ -746,23 +755,23 @@ void Server::run() { #ifdef Q_OS_UNIX socklen_t fromlen; - STACKVAR(struct pollfd, fds, nfds+1); + STACKVAR(struct pollfd, fds, nfds + 1); - for (int i=0;i<nfds;++i) { - fds[i].fd = qlUdpSocket.at(i); - fds[i].events = POLLIN; + for (int i = 0; i < nfds; ++i) { + fds[i].fd = qlUdpSocket.at(i); + fds[i].events = POLLIN; fds[i].revents = 0; } - fds[nfds].fd=aiNotify[0]; - fds[nfds].events = POLLIN; + fds[nfds].fd = aiNotify[0]; + fds[nfds].events = POLLIN; fds[nfds].revents = 0; #else int fromlen; STACKVAR(SOCKET, fds, nfds); - STACKVAR(HANDLE, events, nfds+1); - for (int i=0;i<nfds;++i) { - fds[i] = qlUdpSocket.at(i); + STACKVAR(HANDLE, events, nfds + 1); + for (int i = 0; i < nfds; ++i) { + fds[i] = qlUdpSocket.at(i); events[i] = CreateEvent(nullptr, FALSE, FALSE, nullptr); ::WSAEventSelect(fds[i], events[i], FD_READ); } @@ -785,11 +794,12 @@ void Server::run() { if (fds[nfds - 1].revents) { // Drain pipe unsigned char val; - while (::recv(aiNotify[0], &val, 1, MSG_DONTWAIT) == 1) {}; + while (::recv(aiNotify[0], &val, 1, MSG_DONTWAIT) == 1) { + }; break; } - for (int i=0;i<nfds-1;++i) { + for (int i = 0; i < nfds - 1; ++i) { if (fds[i].revents) { if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) { qCritical("poll event failure"); @@ -799,7 +809,7 @@ void Server::run() { int sock = fds[i].fd; #else - for (int i=0;i<1;++i) { + for (int i = 0; i < 1; ++i) { { DWORD ret = WaitForMultipleObjects(nfds, events, FALSE, INFINITE); if (ret == (WAIT_OBJECT_0 + nfds - 1)) { @@ -815,30 +825,32 @@ void Server::run() { fromlen = sizeof(from); #ifdef Q_OS_WIN - len=::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast<struct sockaddr *>(&from), &fromlen); + len = ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast< struct sockaddr * >(&from), + &fromlen); #else -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = encrypt; - iov[0].iov_len = UDP_PACKET_SIZE; + iov[0].iov_len = UDP_PACKET_SIZE; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(&from); - msg.msg_namelen = sizeof(from); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; + msg.msg_name = reinterpret_cast< struct sockaddr * >(&from); + msg.msg_namelen = sizeof(from); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; msg.msg_controllen = sizeof(controldata); - len=static_cast<quint32>(::recvmsg(sock, &msg, MSG_TRUNC)); + len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); Q_UNUSED(fromlen); -#else - len=static_cast<qint32>(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast<struct sockaddr *>(&from), &fromlen)); -#endif +# else + len = static_cast< qint32 >(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, + reinterpret_cast< struct sockaddr * >(&from), &fromlen)); +# endif #endif if (len == 0) { break; @@ -853,38 +865,40 @@ void Server::run() { QReadLocker rl(&qrwlVoiceThread); - quint32 *ping = reinterpret_cast<quint32 *>(encrypt); + quint32 *ping = reinterpret_cast< quint32 * >(encrypt); if ((len == 12) && (*ping == 0) && bAllowPing) { ping[0] = uiVersionBlob; // 1 and 2 will be the timestamp, which we return unmodified. - ping[3] = qToBigEndian(static_cast<quint32>(qhUsers.count())); - ping[4] = qToBigEndian(static_cast<quint32>(iMaxUsers)); - ping[5] = qToBigEndian(static_cast<quint32>(iMaxBandwidth)); + ping[3] = qToBigEndian(static_cast< quint32 >(qhUsers.count())); + ping[4] = qToBigEndian(static_cast< quint32 >(iMaxUsers)); + ping[5] = qToBigEndian(static_cast< quint32 >(iMaxBandwidth)); #ifdef Q_OS_LINUX iov[0].iov_len = 6 * sizeof(quint32); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast<struct sockaddr *>(&from), fromlen); + ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast< struct sockaddr * >(&from), + fromlen); #endif continue; } - quint16 port = (from.ss_family == AF_INET6) ? (reinterpret_cast<sockaddr_in6 *>(&from)->sin6_port) : (reinterpret_cast<sockaddr_in *>(&from)->sin_port); + quint16 port = (from.ss_family == AF_INET6) ? (reinterpret_cast< sockaddr_in6 * >(&from)->sin6_port) + : (reinterpret_cast< sockaddr_in * >(&from)->sin_port); const HostAddress &ha = HostAddress(from); - const QPair<HostAddress, quint16> &key = QPair<HostAddress, quint16>(ha, port); + const QPair< HostAddress, quint16 > &key = QPair< HostAddress, quint16 >(ha, port); ServerUser *u = qhPeerUsers.value(key); if (u) { - if (! checkDecrypt(u, encrypt, buffer, len)) { + if (!checkDecrypt(u, encrypt, buffer, len)) { continue; } } else { // Unknown peer - foreach(ServerUser *usr, qhHostUsers.value(ha)) { + foreach (ServerUser *usr, qhHostUsers.value(ha)) { if (checkDecrypt(usr, encrypt, buffer, len)) { // checkDecrypt takes the User's qrwlCrypt lock. // Every time we relock, reverify users' existance. // The main thread might delete the user while the lock isn't held. @@ -892,9 +906,9 @@ void Server::run() { rl.unlock(); qrwlVoiceThread.lockForWrite(); if (qhUsers.contains(uiSession)) { - u = usr; + u = usr; u->sUdpSocket = sock; - memcpy(& u->saiUdpAddress, &from, sizeof(from)); + memcpy(&u->saiUdpAddress, &from, sizeof(from)); qhHostUsers[from].remove(u); qhPeerUsers.insert(key, u); } @@ -905,19 +919,17 @@ void Server::run() { break; } } - if (! u) { + if (!u) { continue; } } len -= 4; - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((buffer[0] >> 5) & 0x7); - - if (msgType == MessageHandler::UDPVoiceSpeex || - msgType == MessageHandler::UDPVoiceCELTAlpha || - msgType == MessageHandler::UDPVoiceCELTBeta || - msgType == MessageHandler::UDPVoiceOpus) { + MessageHandler::UDPMessageType msgType = + static_cast< MessageHandler::UDPMessageType >((buffer[0] >> 5) & 0x7); + if (msgType == MessageHandler::UDPVoiceSpeex || msgType == MessageHandler::UDPVoiceCELTAlpha + || msgType == MessageHandler::UDPVoiceCELTBeta || msgType == MessageHandler::UDPVoiceOpus) { // Allow all voice packets through by default. bool ok = true; // ...Unless we're in Opus mode. In Opus mode, only Opus packets are allowed. @@ -940,7 +952,7 @@ void Server::run() { } } #ifdef Q_OS_WIN - for (int i=0;i<nfds-1;++i) { + for (int i = 0; i < nfds - 1; ++i) { ::WSAEventSelect(fds[i], nullptr, 0); CloseHandle(events[i]); } @@ -950,7 +962,9 @@ void Server::run() { bool Server::checkDecrypt(ServerUser *u, const char *encrypt, char *plain, unsigned int len) { QMutexLocker l(&u->qmCrypt); - if (u->csCrypt->isValid() && u->csCrypt->decrypt(reinterpret_cast<const unsigned char *>(encrypt), reinterpret_cast<unsigned char *>(plain), len)) + if (u->csCrypt->isValid() + && u->csCrypt->decrypt(reinterpret_cast< const unsigned char * >(encrypt), + reinterpret_cast< unsigned char * >(plain), len)) return true; if (u->csCrypt->tLastGood.elapsed() > 5000000ULL) { @@ -970,10 +984,10 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c if ((u->aiUdpFlag.load() == 1 || force) && (u->sUdpSocket != INVALID_SOCKET)) { #endif #if defined(__LP64__) - STACKVAR(char, ebuffer, len+4+16); - char *buffer = reinterpret_cast<char *>(((reinterpret_cast<quint64>(ebuffer) + 8) & ~7) + 4); + STACKVAR(char, ebuffer, len + 4 + 16); + char *buffer = reinterpret_cast< char * >(((reinterpret_cast< quint64 >(ebuffer) + 8) & ~7) + 4); #else - STACKVAR(char, buffer, len+4); + STACKVAR(char, buffer, len + 4); #endif { QMutexLocker wl(&u->qmCrypt); @@ -982,47 +996,51 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c return; } - if (!u->csCrypt->encrypt(reinterpret_cast<const unsigned char *>(data), reinterpret_cast<unsigned char *>(buffer), len)) { + if (!u->csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), + reinterpret_cast< unsigned char * >(buffer), len)) { return; } } #ifdef Q_OS_WIN DWORD dwFlow = 0; if (Meta::hQoS) - QOSAddSocketToFlow(Meta::hQoS, u->sUdpSocket, reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress), QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast<PQOS_FLOWID>(&dwFlow)); + QOSAddSocketToFlow(Meta::hQoS, u->sUdpSocket, reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress), + QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast< PQOS_FLOWID >(&dwFlow)); #endif #ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = buffer; - iov[0].iov_len = len+4; + iov[0].iov_len = len + 4; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(controldata, 0, sizeof(controldata)); memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress); - msg.msg_namelen = static_cast<socklen_t>((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; - msg.msg_controllen = CMSG_SPACE((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct in6_pktinfo) : sizeof(struct in_pktinfo)); + msg.msg_name = reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress); + msg.msg_namelen = static_cast< socklen_t >( + (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; + msg.msg_controllen = CMSG_SPACE((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct in6_pktinfo) + : sizeof(struct in_pktinfo)); struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); HostAddress tcpha(u->saiTcpLocalAddress); if (u->saiUdpAddress.ss_family == AF_INET6) { - cmsg->cmsg_level = IPPROTO_IPV6; - cmsg->cmsg_type = IPV6_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); - struct in6_pktinfo *pktinfo = reinterpret_cast<struct in6_pktinfo *>(CMSG_DATA(cmsg)); + cmsg->cmsg_level = IPPROTO_IPV6; + cmsg->cmsg_type = IPV6_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); + struct in6_pktinfo *pktinfo = reinterpret_cast< struct in6_pktinfo * >(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(*pktinfo)); memcpy(&pktinfo->ipi6_addr.s6_addr[0], &tcpha.qip6.c[0], sizeof(pktinfo->ipi6_addr.s6_addr)); } else { - cmsg->cmsg_level = IPPROTO_IP; - cmsg->cmsg_type = IP_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); - struct in_pktinfo *pktinfo = reinterpret_cast<struct in_pktinfo *>(CMSG_DATA(cmsg)); + cmsg->cmsg_level = IPPROTO_IP; + cmsg->cmsg_type = IP_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); + struct in_pktinfo *pktinfo = reinterpret_cast< struct in_pktinfo * >(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(*pktinfo)); if (tcpha.isV6()) return; @@ -1032,7 +1050,8 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c ::sendmsg(u->sUdpSocket, &msg, 0); #else - ::sendto(u->sUdpSocket, buffer, len+4, 0, reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress), (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); + ::sendto(u->sUdpSocket, buffer, len + 4, 0, reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress), + (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); #endif #ifdef Q_OS_WIN if (Meta::hQoS && dwFlow) @@ -1042,17 +1061,17 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c } else { if (cache.isEmpty()) cache = QByteArray(data, len); - emit tcpTransmit(cache,u->uiSession); + emit tcpTransmit(cache, u->uiSession); } } -#define SENDTO \ - if ((!pDst->bDeaf) && (!pDst->bSelfDeaf) && (pDst != u)) { \ - if ((poslen > 0) && (pDst->ssContext == u->ssContext)) \ - sendMessage(pDst, buffer, len, qba); \ - else \ - sendMessage(pDst, buffer, len - poslen, qba_npos); \ - } +#define SENDTO \ + if ((!pDst->bDeaf) && (!pDst->bSelfDeaf) && (pDst != u)) { \ + if ((poslen > 0) && (pDst->ssContext == u->ssContext)) \ + sendMessage(pDst, buffer, len, qba); \ + else \ + sendMessage(pDst, buffer, len - poslen, qba_npos); \ + } void Server::processMsg(ServerUser *u, const char *data, int len) { // Note that in this function we never have to aquire a read-lock on qrwlVoiceThread @@ -1067,8 +1086,8 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { unsigned int counter; char buffer[UDP_PACKET_SIZE]; PacketDataStream pdi(data + 1, len - 1); - PacketDataStream pds(buffer+1, UDP_PACKET_SIZE-1); - unsigned int type = data[0] & 0xe0; + PacketDataStream pds(buffer + 1, UDP_PACKET_SIZE - 1); + unsigned int type = data[0] & 0xe0; unsigned int target = data[0] & 0x1f; unsigned int poslen; @@ -1079,9 +1098,9 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { // IP + UDP + Crypt + Data const int packetsize = 20 + 8 + 4 + len; - if (! bw->addFrame(packetsize, iMaxBandwidth / 8)) { + if (!bw->addFrame(packetsize, iMaxBandwidth / 8)) { // Suppress packet. - return; + return; } } @@ -1110,7 +1129,7 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { len = pds.size() + 1; - if (poslen > static_cast<unsigned int>(len)) { + if (poslen > static_cast< unsigned int >(len)) { // poslen must never ever be bigger than len as this could lead to negative buffer sizes (len - poslen) being // used when further processing the packet. // Usually this shouldn't happen in the first place but can happen with malformed/malicious packets in certain @@ -1120,49 +1139,50 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { /// A set of users that'll receive the audio buffer because they are listening /// to a channel that received that audio. - QSet<ServerUser *> listeningUsers; + QSet< ServerUser * > listeningUsers; if (target == 0x1f) { // Server loopback - buffer[0] = static_cast<char>(type | SpeechFlags::Normal); + buffer[0] = static_cast< char >(type | SpeechFlags::Normal); sendMessage(u, buffer, len, qba); return; } else if (target == 0) { // Normal speech Channel *c = u->cChannel; - buffer[0] = static_cast<char>(type | SpeechFlags::Normal); + buffer[0] = static_cast< char >(type | SpeechFlags::Normal); // Send audio to all users that are listening to the channel - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(c)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(c)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listeningUsers << pDst; } } // Send audio to all users in the same channel - foreach(User *p, c->qlUsers) { - ServerUser *pDst = static_cast<ServerUser *>(p); + foreach (User *p, c->qlUsers) { + ServerUser *pDst = static_cast< ServerUser * >(p); - // As we send the audio to this particular user here, we want to make sure to not send it again due to a listener proxy + // As we send the audio to this particular user here, we want to make sure to not send it again due to a + // listener proxy listeningUsers -= pDst; SENDTO; } // Send audio to all linked channels the user has speak-permission - if (! c->qhLinks.isEmpty()) { - QSet<Channel *> chans = c->allLinks(); + if (!c->qhLinks.isEmpty()) { + QSet< Channel * > chans = c->allLinks(); chans.remove(c); QMutexLocker qml(&qmCache); - foreach(Channel *l, chans) { + foreach (Channel *l, chans) { if (ChanACL::hasPermission(u, l, ChanACL::Speak, &acCache)) { // Send the audio stream to all users that are listening to the linked channel but are not // in the original channel the audio is coming from nor are they listening to the orignal // channel (in these cases they have received the audio already). - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(l)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(l)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst && pDst->cChannel != c && !ChannelListener::isListening(pDst, c)) { listeningUsers << pDst; } @@ -1171,11 +1191,12 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { // Send audio to users in the linked channel but only if they // haven't received the audio already (because they are listening // to the original channel). - foreach(User *p, l->qlUsers) { + foreach (User *p, l->qlUsers) { if (!ChannelListener::isListening(p->uiSession, c->iId)) { - ServerUser *pDst = static_cast<ServerUser *>(p); + ServerUser *pDst = static_cast< ServerUser * >(p); - // As we send the audio to this particular user here, we want to make sure to not send it again due to a listener proxy + // As we send the audio to this particular user here, we want to make sure to not send it + // again due to a listener proxy listeningUsers -= pDst; SENDTO; @@ -1185,35 +1206,33 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } } } else if (u->qmTargets.contains(target)) { // Whisper/Shout - QSet<ServerUser *> channel; - QSet<ServerUser *> direct; - QSet<ServerUser *> listener; + QSet< ServerUser * > channel; + QSet< ServerUser * > direct; + QSet< ServerUser * > listener; if (u->qmTargetCache.contains(target)) { const WhisperTargetCache &cache = u->qmTargetCache.value(target); - channel = cache.channelTargets; - direct = cache.directTargets; - listener = cache.listeningTargets; + channel = cache.channelTargets; + direct = cache.directTargets; + listener = cache.listeningTargets; } else { const WhisperTarget &wt = u->qmTargets.value(target); - if (! wt.qlChannels.isEmpty()) { + if (!wt.qlChannels.isEmpty()) { QMutexLocker qml(&qmCache); - foreach(const WhisperTarget::Channel &wtc, wt.qlChannels) { + foreach (const WhisperTarget::Channel &wtc, wt.qlChannels) { Channel *wc = qhChannels.value(wtc.iId); if (wc) { - bool link = wtc.bLinks && ! wc->qhLinks.isEmpty(); - bool dochildren = wtc.bChildren && ! wc->qlChannels.isEmpty(); - bool group = ! wtc.qsGroup.isEmpty(); - if (!link && !dochildren && ! group) { + bool link = wtc.bLinks && !wc->qhLinks.isEmpty(); + bool dochildren = wtc.bChildren && !wc->qlChannels.isEmpty(); + bool group = !wtc.qsGroup.isEmpty(); + if (!link && !dochildren && !group) { // Common case if (ChanACL::hasPermission(u, wc, ChanACL::Whisper, &acCache)) { - foreach(User *p, wc->qlUsers) { - channel.insert(static_cast<ServerUser *>(p)); - } + foreach (User *p, wc->qlUsers) { channel.insert(static_cast< ServerUser * >(p)); } - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(wc)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(wc)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listener << pDst; @@ -1221,7 +1240,7 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } } } else { - QSet<Channel *> channels; + QSet< Channel * > channels; if (link) channels = wc->allLinks(); else @@ -1229,18 +1248,18 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { if (dochildren) channels.unite(wc->allChildren()); const QString &redirect = u->qmWhisperRedirect.value(wtc.qsGroup); - const QString &qsg = redirect.isEmpty() ? wtc.qsGroup : redirect; - foreach(Channel *tc, channels) { + const QString &qsg = redirect.isEmpty() ? wtc.qsGroup : redirect; + foreach (Channel *tc, channels) { if (ChanACL::hasPermission(u, tc, ChanACL::Whisper, &acCache)) { - foreach(User *p, tc->qlUsers) { - ServerUser *su = static_cast<ServerUser *>(p); - if (! group || Group::isMember(tc, tc, qsg, su)) { + foreach (User *p, tc->qlUsers) { + ServerUser *su = static_cast< ServerUser * >(p); + if (!group || Group::isMember(tc, tc, qsg, su)) { channel.insert(su); } } - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(tc)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(tc)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listener << pDst; @@ -1260,9 +1279,10 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { { QMutexLocker qml(&qmCache); - foreach(unsigned int id, wt.qlSessions) { + foreach (unsigned int id, wt.qlSessions) { ServerUser *pDst = qhUsers.value(id); - if (pDst && ChanACL::hasPermission(u, pDst->cChannel, ChanACL::Whisper, &acCache) && !channel.contains(pDst)) + if (pDst && ChanACL::hasPermission(u, pDst->cChannel, ChanACL::Whisper, &acCache) + && !channel.contains(pDst)) direct.insert(pDst); } } @@ -1275,25 +1295,21 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { u->qmTargetCache.insert(target, { channel, direct, listener }); qrwlVoiceThread.unlock(); qrwlVoiceThread.lockForRead(); - if (! qhUsers.contains(uiSession)) + if (!qhUsers.contains(uiSession)) return; } - if (! channel.isEmpty()) { + if (!channel.isEmpty()) { // These users receive the audio because someone is shouting to their channel - buffer[0] = static_cast<char>(type | SpeechFlags::Shout); - foreach(ServerUser *pDst, channel) { - SENDTO; - } - if (! direct.isEmpty()) { + buffer[0] = static_cast< char >(type | SpeechFlags::Shout); + foreach (ServerUser *pDst, channel) { SENDTO; } + if (!direct.isEmpty()) { qba.clear(); qba_npos.clear(); } } - if (! direct.isEmpty()) { - buffer[0] = static_cast<char>(type | SpeechFlags::Whisper); - foreach(ServerUser *pDst, direct) { - SENDTO; - } + if (!direct.isEmpty()) { + buffer[0] = static_cast< char >(type | SpeechFlags::Whisper); + foreach (ServerUser *pDst, direct) { SENDTO; } } // Add the listening users to the set of current listeners @@ -1301,17 +1317,12 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } // Send the audio to all listening users - buffer[0] = static_cast<char>(type | SpeechFlags::Listen); - foreach(ServerUser *pDst, listeningUsers) { - SENDTO; - } + buffer[0] = static_cast< char >(type | SpeechFlags::Listen); + foreach (ServerUser *pDst, listeningUsers) { SENDTO; } } void Server::log(ServerUser *u, const QString &str) const { - QString msg = QString("<%1:%2(%3)> %4").arg(QString::number(u->uiSession), - u->qsName, - QString::number(u->iId), - str); + QString msg = QString("<%1:%2(%3)> %4").arg(QString::number(u->uiSession), u->qsName, QString::number(u->iId), str); log(msg); } @@ -1321,18 +1332,19 @@ void Server::log(const QString &msg) const { } void Server::newClient() { - SslServer *ss = qobject_cast<SslServer *>(sender()); - if (! ss) + SslServer *ss = qobject_cast< SslServer * >(sender()); + if (!ss) return; forever { QSslSocket *sock = ss->nextPendingSSLConnection(); - if (! sock) + if (!sock) return; QHostAddress adr = sock->peerAddress(); if (meta->banCheck(adr)) { - log(QString("Ignoring connection: %1 (Global ban)").arg(addressToString(sock->peerAddress(), sock->peerPort()))); + log(QString("Ignoring connection: %1 (Global ban)") + .arg(addressToString(sock->peerAddress(), sock->peerPort()))); sock->disconnectFromHost(); sock->deleteLater(); return; @@ -1340,8 +1352,8 @@ void Server::newClient() { HostAddress ha(adr); - QList<Ban> tmpBans = qlBans; - foreach(const Ban &ban, qlBans) { + QList< Ban > tmpBans = qlBans; + foreach (const Ban &ban, qlBans) { if (ban.isExpired()) tmpBans.removeOne(ban); } @@ -1350,9 +1362,11 @@ void Server::newClient() { saveBans(); } - foreach(const Ban &ban, qlBans) { + foreach (const Ban &ban, qlBans) { if (ban.haAddress.match(ha, ban.iMask)) { - log(QString("Ignoring connection: %1, Reason: %2, Username: %3, Hash: %4 (Server ban)").arg(addressToString(sock->peerAddress(), sock->peerPort()), ban.qsReason, ban.qsUsername, ban.qsHash)); + log(QString("Ignoring connection: %1, Reason: %2, Username: %3, Hash: %4 (Server ban)") + .arg(addressToString(sock->peerAddress(), sock->peerPort()), ban.qsReason, ban.qsUsername, + ban.qsHash)); sock->disconnectFromHost(); sock->deleteLater(); return; @@ -1374,9 +1388,10 @@ void Server::newClient() { sock->setLocalCertificate(qscCert); QSslConfiguration config; -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) config = sock->sslConfiguration(); - // Qt 5.15 introduced QSslConfiguration::addCaCertificate(s) that should be preferred over the functions in QSslSocket + // Qt 5.15 introduced QSslConfiguration::addCaCertificate(s) that should be preferred over the functions in + // QSslSocket // Treat the leaf certificate as a root. // This shouldn't strictly be necessary, @@ -1426,9 +1441,9 @@ void Server::newClient() { } ServerUser *u = new ServerUser(this, sock); - u->uiSession = qqIds.dequeue(); - u->haAddress = ha; - HostAddress(sock->localAddress()).toSockaddr(& u->saiTcpLocalAddress); + u->uiSession = qqIds.dequeue(); + u->haAddress = ha; + HostAddress(sock->localAddress()).toSockaddr(&u->saiTcpLocalAddress); { QWriteLocker wl(&qrwlVoiceThread); @@ -1436,9 +1451,12 @@ void Server::newClient() { qhHostUsers[ha].insert(u); } - connect(u, SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, SLOT(connectionClosed(QAbstractSocket::SocketError, const QString &))); - connect(u, SIGNAL(message(unsigned int, const QByteArray &)), this, SLOT(message(unsigned int, const QByteArray &))); - connect(u, SIGNAL(handleSslErrors(const QList<QSslError> &)), this, SLOT(sslError(const QList<QSslError> &))); + connect(u, SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, + SLOT(connectionClosed(QAbstractSocket::SocketError, const QString &))); + connect(u, SIGNAL(message(unsigned int, const QByteArray &)), this, + SLOT(message(unsigned int, const QByteArray &))); + connect(u, SIGNAL(handleSslErrors(const QList< QSslError > &)), this, + SLOT(sslError(const QList< QSslError > &))); connect(u, SIGNAL(encrypted()), this, SLOT(encrypted())); log(u, QString("New connection: %1").arg(addressToString(sock->peerAddress(), sock->peerPort()))); @@ -1461,7 +1479,7 @@ void Server::newClient() { } void Server::encrypted() { - ServerUser *uSource = qobject_cast<ServerUser *>(sender()); + ServerUser *uSource = qobject_cast< ServerUser * >(sender()); int major, minor, patch; QString release; @@ -1476,44 +1494,48 @@ void Server::encrypted() { } sendMessage(uSource, mpv); - QList<QSslCertificate> certs = uSource->peerCertificateChain(); + QList< QSslCertificate > certs = uSource->peerCertificateChain(); if (!certs.isEmpty()) { const QSslCertificate &cert = certs.last(); - uSource->qslEmail = cert.subjectAlternativeNames().values(QSsl::EmailEntry); - uSource->qsHash = QString::fromLatin1(cert.digest(QCryptographicHash::Sha1).toHex()); - if (! uSource->qslEmail.isEmpty() && uSource->bVerified) { + uSource->qslEmail = cert.subjectAlternativeNames().values(QSsl::EmailEntry); + uSource->qsHash = QString::fromLatin1(cert.digest(QCryptographicHash::Sha1).toHex()); + if (!uSource->qslEmail.isEmpty() && uSource->bVerified) { QString subject; QString issuer; QStringList subjectList = cert.subjectInfo(QSslCertificate::CommonName); - if (! subjectList.isEmpty()) { + if (!subjectList.isEmpty()) { subject = subjectList.first(); } QStringList issuerList = certs.first().issuerInfo(QSslCertificate::CommonName); - if (! issuerList.isEmpty()) { + if (!issuerList.isEmpty()) { issuer = issuerList.first(); } - log(uSource, QString::fromUtf8("Strong certificate for %1 <%2> (signed by %3)").arg(subject).arg(uSource->qslEmail.join(", ")).arg(issuer)); + log(uSource, QString::fromUtf8("Strong certificate for %1 <%2> (signed by %3)") + .arg(subject) + .arg(uSource->qslEmail.join(", ")) + .arg(issuer)); } - foreach(const Ban &ban, qlBans) { + foreach (const Ban &ban, qlBans) { if (ban.qsHash == uSource->qsHash) { - log(uSource, QString("Certificate hash is banned: %1, Username: %2, Reason: %3.").arg(ban.qsHash, ban.qsUsername, ban.qsReason)); + log(uSource, QString("Certificate hash is banned: %1, Username: %2, Reason: %3.") + .arg(ban.qsHash, ban.qsUsername, ban.qsReason)); uSource->disconnectSocket(); } } } } -void Server::sslError(const QList<QSslError> &errors) { - ServerUser *u = qobject_cast<ServerUser *>(sender()); +void Server::sslError(const QList< QSslError > &errors) { + ServerUser *u = qobject_cast< ServerUser * >(sender()); if (!u) return; bool ok = true; - foreach(QSslError e, errors) { + foreach (QSslError e, errors) { switch (e.error()) { case QSslError::InvalidPurpose: // Allow email certificates. @@ -1584,18 +1606,18 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r // "Error while reading: error:140E0197:SSL routines:SSL_shutdown:shutdown while in init [20]" // // Definitely not ideal, but it fixes a critical vulnerability. - qWarning("Ignored OpenSSL error 140E0197 for %p", static_cast<void *>(sender())); + qWarning("Ignored OpenSSL error 140E0197 for %p", static_cast< void * >(sender())); return; } - Connection *c = qobject_cast<Connection *>(sender()); - if (! c) + Connection *c = qobject_cast< Connection * >(sender()); + if (!c) return; if (c->bDisconnectedEmitted) return; c->bDisconnectedEmitted = true; - ServerUser *u = static_cast<ServerUser *>(c); + ServerUser *u = static_cast< ServerUser * >(c); log(u, QString("Connection closed: %1 [%2]").arg(reason).arg(err)); @@ -1608,7 +1630,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r MumbleProto::UserState mpus; mpus.set_session(u->uiSession); - foreach(int channelID, ChannelListener::getListenedChannelsForUser(u)) { + foreach (int channelID, ChannelListener::getListenedChannelsForUser(u)) { mpus.add_listening_channel_remove(channelID); // Also remove the client from the list on the server @@ -1633,8 +1655,10 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r qhUsers.remove(u->uiSession); qhHostUsers[u->haAddress].remove(u); - quint16 port = (u->saiUdpAddress.ss_family == AF_INET6) ? (reinterpret_cast<sockaddr_in6 *>(&u->saiUdpAddress)->sin6_port) : (reinterpret_cast<sockaddr_in *>(&u->saiUdpAddress)->sin_port); - const QPair<HostAddress, quint16> &key = QPair<HostAddress, quint16>(u->haAddress, port); + quint16 port = (u->saiUdpAddress.ss_family == AF_INET6) + ? (reinterpret_cast< sockaddr_in6 * >(&u->saiUdpAddress)->sin6_port) + : (reinterpret_cast< sockaddr_in * >(&u->saiUdpAddress)->sin_port); + const QPair< HostAddress, quint16 > &key = QPair< HostAddress, quint16 >(u->haAddress, port); qhPeerUsers.remove(key); if (old) @@ -1642,13 +1666,14 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r } if (old && old->bTemporary && old->qlUsers.isEmpty()) - QCoreApplication::instance()->postEvent(this, new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); + QCoreApplication::instance()->postEvent(this, + new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); - if (static_cast<int>(u->uiSession) < iMaxUsers * 2) + if (static_cast< int >(u->uiSession) < iMaxUsers * 2) qqIds.enqueue(u->uiSession); // Reinsert session id into pool if (u->sState == ServerUser::Authenticated) { - clearTempGroups(u); // Also clears ACL cache + clearTempGroups(u); // Also clears ACL cache recheckCodecVersions(); // Maybe can choose a better codec now } @@ -1660,7 +1685,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser *u) { if (!u) { - u = static_cast<ServerUser *>(sender()); + u = static_cast< ServerUser * >(sender()); } if (u->sState == ServerUser::Authenticated) { @@ -1680,13 +1705,10 @@ void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser * const char *buffer = qbaMsg.constData(); - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((buffer[0] >> 5) & 0x7); - - if (msgType == MessageHandler::UDPVoiceSpeex || - msgType == MessageHandler::UDPVoiceCELTAlpha || - msgType == MessageHandler::UDPVoiceCELTBeta || - msgType == MessageHandler::UDPVoiceOpus) { + MessageHandler::UDPMessageType msgType = static_cast< MessageHandler::UDPMessageType >((buffer[0] >> 5) & 0x7); + if (msgType == MessageHandler::UDPVoiceSpeex || msgType == MessageHandler::UDPVoiceCELTAlpha + || msgType == MessageHandler::UDPVoiceCELTBeta || msgType == MessageHandler::UDPVoiceOpus) { // Allow all voice packets through by default. bool ok = true; // ...Unless we're in Opus mode. In Opus mode, only Opus packets are allowed. @@ -1703,46 +1725,46 @@ void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser * } #ifdef QT_NO_DEBUG -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ - msg.DiscardUnknownFields(); \ - msg##x(u, msg); \ - } \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ + msg.DiscardUnknownFields(); \ + msg##x(u, msg); \ + } \ + break; \ + } #else -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ - if (uiType != MessageHandler::Ping) { \ - printf("== %s:\n", #x); \ - msg.PrintDebugString(); \ - } \ - msg.DiscardUnknownFields(); \ - msg##x(u, msg); \ - } \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ + if (uiType != MessageHandler::Ping) { \ + printf("== %s:\n", #x); \ + msg.PrintDebugString(); \ + } \ + msg.DiscardUnknownFields(); \ + msg##x(u, msg); \ + } \ + break; \ + } #endif - switch (uiType) { - MUMBLE_MH_ALL - } + switch (uiType) { MUMBLE_MH_ALL } } void Server::checkTimeout() { - QList<ServerUser *> qlClose; + QList< ServerUser * > qlClose; qrwlVoiceThread.lockForRead(); - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->activityTime() > (iTimeout * 1000)) { log(u, "Timeout"); qlClose.append(u); } } qrwlVoiceThread.unlock(); - foreach(ServerUser *u, qlClose) + foreach (ServerUser *u, qlClose) u->disconnectSocket(true); } @@ -1753,9 +1775,9 @@ void Server::tcpTransmitData(QByteArray a, unsigned int id) { int len = a.size(); qba.resize(len + 6); - unsigned char *uc = reinterpret_cast<unsigned char *>(qba.data()); - * reinterpret_cast<quint16 *>(& uc[0]) = qToBigEndian(static_cast<quint16>(MessageHandler::UDPTunnel)); - * reinterpret_cast<quint32 *>(& uc[2]) = qToBigEndian(static_cast<quint32>(len)); + unsigned char *uc = reinterpret_cast< unsigned char * >(qba.data()); + *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(MessageHandler::UDPTunnel)); + *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); memcpy(uc + 6, a.constData(), len); c->sendMessage(qba); @@ -1781,11 +1803,13 @@ void Server::sendProtoAll(const ::google::protobuf::Message &msg, unsigned int m sendProtoExcept(nullptr, msg, msgType, version); } -void Server::sendProtoExcept(ServerUser *u, const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int version) { +void Server::sendProtoExcept(ServerUser *u, const ::google::protobuf::Message &msg, unsigned int msgType, + unsigned int version) { QByteArray cache; - foreach(ServerUser *usr, qhUsers) + foreach (ServerUser *usr, qhUsers) if ((usr != u) && (usr->sState == ServerUser::Authenticated)) - if ((version == 0) || (usr->uiVersion >= version) || ((version & 0x80000000) && (usr->uiVersion < (~version)))) + if ((version == 0) || (usr->uiVersion >= version) + || ((version & 0x80000000) && (usr->uiVersion < (~version)))) usr->sendMessage(msg, msgType, cache); } @@ -1807,18 +1831,18 @@ void Server::removeChannel(Channel *chan, Channel *dest) { chan->unlink(nullptr); } - foreach(c, chan->qlChannels) { - removeChannel(c, dest); - } + foreach (c, chan->qlChannels) { removeChannel(c, dest); } - foreach(p, chan->qlUsers) { + foreach (p, chan->qlUsers) { { QWriteLocker wl(&qrwlVoiceThread); chan->removeUser(p); } Channel *target = dest; - while (target->cParent && (! hasPermission(static_cast<ServerUser *>(p), target, ChanACL::Enter) || isChannelFull(target, static_cast<ServerUser *>(p)))) + while (target->cParent + && (!hasPermission(static_cast< ServerUser * >(p), target, ChanACL::Enter) + || isChannelFull(target, static_cast< ServerUser * >(p)))) target = target->cParent; MumbleProto::UserState mpus; @@ -1829,7 +1853,7 @@ void Server::removeChannel(Channel *chan, Channel *dest) { emit userStateChanged(p); } - foreach(unsigned int userSession, ChannelListener::getListenersForChannel(chan)) { + foreach (unsigned int userSession, ChannelListener::getListenersForChannel(chan)) { ChannelListener::removeListener(userSession, chan->iId); // Notify that all clients that have been listening to this channel, will do so no more @@ -1856,33 +1880,33 @@ void Server::removeChannel(Channel *chan, Channel *dest) { } bool Server::unregisterUser(int id) { - if (! unregisterUserDB(id)) + if (!unregisterUserDB(id)) return false; { QMutexLocker lock(&qmCache); - foreach(Channel *c, qhChannels) { - bool write = false; - QList<ChanACL *> ql = c->qlACL; + foreach (Channel *c, qhChannels) { + bool write = false; + QList< ChanACL * > ql = c->qlACL; - foreach(ChanACL *acl, ql) { + foreach (ChanACL *acl, ql) { if (acl->iUserId == id) { c->qlACL.removeAll(acl); write = true; } } - foreach(Group *g, c->qhGroups) { + foreach (Group *g, c->qhGroups) { bool addrem = g->qsAdd.remove(id); bool remrem = g->qsRemove.remove(id); - write = write || addrem || remrem; + write = write || addrem || remrem; } if (write) updateChannel(c); } } - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->iId == id) { clearACLCache(u); MumbleProto::UserState mpus; @@ -1907,12 +1931,12 @@ void Server::userEnterChannel(User *p, Channel *c, MumbleProto::UserState &mpus) QWriteLocker wl(&qrwlVoiceThread); c->addUser(p); - bool mayspeak = ChanACL::hasPermission(static_cast<ServerUser *>(p), c, ChanACL::Speak, nullptr); - bool sup = p->bSuppress; + bool mayspeak = ChanACL::hasPermission(static_cast< ServerUser * >(p), c, ChanACL::Speak, nullptr); + bool sup = p->bSuppress; if (mayspeak == sup) { // Ok, he can speak and was suppressed, or vice versa - p->bSuppress = ! mayspeak; + p->bSuppress = !mayspeak; mpus.set_suppress(p->bSuppress); } } @@ -1921,20 +1945,21 @@ void Server::userEnterChannel(User *p, Channel *c, MumbleProto::UserState &mpus) setLastChannel(p); if (old && old->bTemporary && old->qlUsers.isEmpty()) { - QCoreApplication::instance()->postEvent(this, new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); + QCoreApplication::instance()->postEvent(this, + new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); } - sendClientPermission(static_cast<ServerUser *>(p), c); + sendClientPermission(static_cast< ServerUser * >(p), c); if (c->cParent) - sendClientPermission(static_cast<ServerUser *>(p), c->cParent); + sendClientPermission(static_cast< ServerUser * >(p), c->cParent); } -bool Server::hasPermission(ServerUser *p, Channel *c, QFlags<ChanACL::Perm> perm) { +bool Server::hasPermission(ServerUser *p, Channel *c, QFlags< ChanACL::Perm > perm) { QMutexLocker qml(&qmCache); return ChanACL::hasPermission(p, c, perm, &acCache); } -QFlags<ChanACL::Perm> Server::effectivePermissions(ServerUser *p, Channel *c) { +QFlags< ChanACL::Perm > Server::effectivePermissions(ServerUser *p, Channel *c) { QMutexLocker qml(&qmCache); return ChanACL::effectivePermissions(p, c, &acCache); } @@ -1974,11 +1999,11 @@ void Server::sendClientPermission(ServerUser *u, Channel *c, bool forceupdate) { */ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mppq) { - QMap<int, unsigned int>::const_iterator i; + QMap< int, unsigned int >::const_iterator i; bool match = (u->qmPermissionSent.count() < 20); for (i = u->qmPermissionSent.constBegin(); (match && (i != u->qmPermissionSent.constEnd())); ++i) { Channel *c = qhChannels.value(i.key()); - if (! c) { + if (!c) { match = false; } else { ChanACL::hasPermission(u, c, ChanACL::Enter, &acCache); @@ -1994,8 +2019,8 @@ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQu u->qmPermissionSent.clear(); Channel *c = qhChannels.value(u->iLastPermissionCheck); - if (! c) { - c = u->cChannel; + if (!c) { + c = u->cChannel; u->iLastPermissionCheck = c->iId; } @@ -2021,13 +2046,13 @@ void Server::clearACLCache(User *p) { ChanACL::ChanCache *h = acCache.take(p); delete h; - flushClientPermissionCache(static_cast<ServerUser *>(p), mppq); + flushClientPermissionCache(static_cast< ServerUser * >(p), mppq); } else { - foreach(ChanACL::ChanCache *h, acCache) + foreach (ChanACL::ChanCache *h, acCache) delete h; acCache.clear(); - foreach(ServerUser *u, qhUsers) + foreach (ServerUser *u, qhUsers) if (u->sState == ServerUser::Authenticated) flushClientPermissionCache(u, mppq); } @@ -2041,9 +2066,7 @@ void Server::clearACLCache(User *p) { void Server::clearWhisperTargetCache() { QWriteLocker lock(&qrwlVoiceThread); - foreach(ServerUser *u, qhUsers) { - u->qmTargetCache.clear(); - } + foreach (ServerUser *u, qhUsers) { u->qmTargetCache.clear(); } } QString Server::addressToString(const QHostAddress &adr, unsigned short port) { @@ -2051,13 +2074,13 @@ QString Server::addressToString(const QHostAddress &adr, unsigned short port) { if ((Meta::mp.iObfuscate != 0)) { QCryptographicHash h(QCryptographicHash::Sha1); - h.addData(reinterpret_cast<const char *>(&Meta::mp.iObfuscate), sizeof(Meta::mp.iObfuscate)); + h.addData(reinterpret_cast< const char * >(&Meta::mp.iObfuscate), sizeof(Meta::mp.iObfuscate)); if (adr.protocol() == QAbstractSocket::IPv4Protocol) { quint32 num = adr.toIPv4Address(); - h.addData(reinterpret_cast<const char *>(&num), sizeof(num)); + h.addData(reinterpret_cast< const char * >(&num), sizeof(num)); } else if (adr.protocol() == QAbstractSocket::IPv6Protocol) { Q_IPV6ADDR num = adr.toIPv6Address(); - h.addData(reinterpret_cast<const char *>(num.c), sizeof(num.c)); + h.addData(reinterpret_cast< const char * >(num.c), sizeof(num.c)); } return QString("<<%1:%2>>").arg(QString::fromLatin1(h.result().toHex()), QString::number(port)); } @@ -2073,38 +2096,38 @@ bool Server::validateChannelName(const QString &name) { } void Server::recheckCodecVersions(ServerUser *connectingUser) { - QMap<int, int> qmCodecUsercount; - QMap<int, int>::const_iterator i; + QMap< int, int > qmCodecUsercount; + QMap< int, int >::const_iterator i; int users = 0; - int opus = 0; + int opus = 0; // Count how many users use which codec - foreach(ServerUser *u, qhUsers) { - if (u->qlCodecs.isEmpty() && ! u->bOpus) + foreach (ServerUser *u, qhUsers) { + if (u->qlCodecs.isEmpty() && !u->bOpus) continue; ++users; if (u->bOpus) ++opus; - foreach(int version, u->qlCodecs) + foreach (int version, u->qlCodecs) ++qmCodecUsercount[version]; } - if (! users) + if (!users) return; // Enable Opus if the number of users with Opus is higher than the threshold bool enableOpus = ((opus * 100 / users) >= iOpusThreshold); // Find the best possible codec most users support - int version = 0; + int version = 0; int maximum_users = 0; - i = qmCodecUsercount.constEnd(); + i = qmCodecUsercount.constEnd(); do { --i; if (i.value() > maximum_users) { - version = i.key(); + version = i.key(); maximum_users = i.value(); } } while (i != qmCodecUsercount.constBegin()); @@ -2117,10 +2140,10 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { // and announce it. if (current_version != version) { - if (version == static_cast<qint32>(0x8000000b)) + if (version == static_cast< qint32 >(0x8000000b)) bPreferAlpha = true; else - bPreferAlpha = ! bPreferAlpha; + bPreferAlpha = !bPreferAlpha; if (bPreferAlpha) iCodecAlpha = version; @@ -2128,7 +2151,11 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { iCodecBeta = version; } else if (bOpus == enableOpus) { if (bOpus && connectingUser && !connectingUser->bOpus) { - sendTextMessage(nullptr, connectingUser, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is using, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); + sendTextMessage( + nullptr, connectingUser, false, + QLatin1String( + "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is using, you " + "won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); } return; } @@ -2143,17 +2170,25 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { sendAll(mpcv); if (bOpus) { - foreach(ServerUser *u, qhUsers) { - // Prevent connected users that could not yet declare their opus capability during msgAuthenticate from being spammed. - // Only authenticated users and the currently connecting user (if recheck is called in that context) have a reliable u->bOpus. - if((u->sState == ServerUser::Authenticated || u == connectingUser) - && !u->bOpus) { - sendTextMessage(nullptr, u, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is switching to, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); + foreach (ServerUser *u, qhUsers) { + // Prevent connected users that could not yet declare their opus capability during msgAuthenticate from + // being spammed. Only authenticated users and the currently connecting user (if recheck is called in that + // context) have a reliable u->bOpus. + if ((u->sState == ServerUser::Authenticated || u == connectingUser) && !u->bOpus) { + sendTextMessage( + nullptr, u, false, + QLatin1String( + "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is switching " + "to, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); } } } - log(QString::fromLatin1("CELT codec switch %1 %2 (prefer %3) (Opus %4)").arg(iCodecAlpha,0,16).arg(iCodecBeta,0,16).arg(bPreferAlpha ? iCodecAlpha : iCodecBeta,0,16).arg(bOpus)); + log(QString::fromLatin1("CELT codec switch %1 %2 (prefer %3) (Opus %4)") + .arg(iCodecAlpha, 0, 16) + .arg(iCodecBeta, 0, 16) + .arg(bPreferAlpha ? iCodecAlpha : iCodecBeta, 0, 16) + .arg(bOpus)); } void Server::hashAssign(QString &dest, QByteArray &hash, const QString &src) { @@ -2175,11 +2210,11 @@ void Server::hashAssign(QByteArray &dest, QByteArray &hash, const QByteArray &sr bool Server::isTextAllowed(QString &text, bool &changed) { changed = false; - if (! bAllowHTML) { + if (!bAllowHTML) { QString out; if (HTMLFilter::filter(text, out)) { changed = true; - text = out; + text = out; } return ((iMaxTextMessageLength == 0) || (text.length() <= iMaxTextMessageLength)); } else { @@ -2198,7 +2233,7 @@ bool Server::isTextAllowed(QString &text, bool &changed) { return true; // Over textlength, under imagelength. If no XML, this is a fail. - if (! text.contains(QLatin1Char('<'))) + if (!text.contains(QLatin1Char('<'))) return false; // Strip value from <img>s src attributes to check text-length only - @@ -2206,21 +2241,20 @@ bool Server::isTextAllowed(QString &text, bool &changed) { QString qsOut; QXmlStreamReader qxsr(QString::fromLatin1("<document>%1</document>").arg(text)); QXmlStreamWriter qxsw(&qsOut); - while (! qxsr.atEnd()) { + while (!qxsr.atEnd()) { switch (qxsr.readNext()) { case QXmlStreamReader::Invalid: return false; case QXmlStreamReader::StartElement: { - if (qxsr.name() == QLatin1String("img")) { - qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); - foreach(const QXmlStreamAttribute &a, qxsr.attributes()) - if (a.name() != QLatin1String("src")) - qxsw.writeAttribute(a); - } else { - qxsw.writeCurrentToken(qxsr); - } + if (qxsr.name() == QLatin1String("img")) { + qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); + foreach (const QXmlStreamAttribute &a, qxsr.attributes()) + if (a.name() != QLatin1String("src")) + qxsw.writeAttribute(a); + } else { + qxsw.writeCurrentToken(qxsr); } - break; + } break; default: qxsw.writeCurrentToken(qxsr); break; @@ -2238,7 +2272,7 @@ bool Server::isChannelFull(Channel *c, ServerUser *u) { return false; } if (c->uiMaxUsers) { - return static_cast<unsigned int>(c->qlUsers.count()) >= c->uiMaxUsers; + return static_cast< unsigned int >(c->qlUsers.count()) >= c->uiMaxUsers; } if (iMaxUsersPerChannel) { return c->qlUsers.count() >= iMaxUsersPerChannel; @@ -2247,8 +2281,8 @@ bool Server::isChannelFull(Channel *c, ServerUser *u) { } bool Server::canNest(Channel *newParent, Channel *channel) const { - const int parentLevel = newParent ? static_cast<int>(newParent->getLevel()) : -1; - const int channelDepth = channel ? static_cast<int>(channel->getDepth()) : 0; + const int parentLevel = newParent ? static_cast< int >(newParent->getLevel()) : -1; + const int channelDepth = channel ? static_cast< int >(channel->getDepth()) : 0; return (parentLevel + channelDepth) < iChannelNestingLimit; } |