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 | |
parent | 40b28b03c150b453e00c6bc4f8d6957caea59c51 (diff) |
FORMAT: Run clang-format 10 on all C/CXX source-files
Diffstat (limited to 'src/murmur')
32 files changed, 5898 insertions, 5362 deletions
diff --git a/src/murmur/About.cpp b/src/murmur/About.cpp index 1759ef4ae..1906af930 100644 --- a/src/murmur/About.cpp +++ b/src/murmur/About.cpp @@ -4,9 +4,9 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "About.h" -#include "Version.h" #include "License.h" #include "Utils.h" +#include "Version.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLabel> @@ -20,7 +20,7 @@ AboutDialog::AboutDialog(QWidget *p, AboutDialogOptions options) : QDialog(p) { setWindowTitle(tr("About Murmur")); setMinimumSize(QSize(400, 300)); - QTabWidget *qtwTab = new QTabWidget(this); + QTabWidget *qtwTab = new QTabWidget(this); QVBoxLayout *vblMain = new QVBoxLayout(this); QTextEdit *qteLicense = new QTextEdit(qtwTab); @@ -35,31 +35,30 @@ AboutDialog::AboutDialog(QWidget *p, AboutDialogOptions options) : QDialog(p) { qtb3rdPartyLicense->setReadOnly(true); qtb3rdPartyLicense->setOpenExternalLinks(true); - QList<LicenseInfo> thirdPartyLicenses = License::thirdPartyLicenses(); - foreach(LicenseInfo li, thirdPartyLicenses) { + QList< LicenseInfo > thirdPartyLicenses = License::thirdPartyLicenses(); + foreach (LicenseInfo li, thirdPartyLicenses) { qtb3rdPartyLicense->append(QString::fromLatin1("<h3>%1 (<a href=\"%2\">%2</a>)</h3><pre>%3</pre>") - .arg(li.name.toHtmlEscaped()) - .arg(li.url.toHtmlEscaped()) - .arg(li.license.toHtmlEscaped())); + .arg(li.name.toHtmlEscaped()) + .arg(li.url.toHtmlEscaped()) + .arg(li.license.toHtmlEscaped())); } qtb3rdPartyLicense->moveCursor(QTextCursor::Start); QWidget *about = new QWidget(qtwTab); - QLabel *icon = new QLabel(about); + QLabel *icon = new QLabel(about); QIcon windowIcon = QApplication::windowIcon(); icon->setPixmap(windowIcon.pixmap(windowIcon.actualSize(QSize(128, 128)))); QLabel *text = new QLabel(about); text->setOpenExternalLinks(true); - text->setText(tr( - "<h3>Murmur (%1)</h3>" - "<p>%3</p>" - "<p><tt><a href=\"%2\">%2</a></tt></p>" - ).arg(QLatin1String(MUMBLE_RELEASE)) - .arg(QLatin1String("http://www.mumble.info/")) - .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); + text->setText(tr("<h3>Murmur (%1)</h3>" + "<p>%3</p>" + "<p><tt><a href=\"%2\">%2</a></tt></p>") + .arg(QLatin1String(MUMBLE_RELEASE)) + .arg(QLatin1String("http://www.mumble.info/")) + .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); QHBoxLayout *qhbl = new QHBoxLayout(about); qhbl->addWidget(icon); qhbl->addWidget(text); diff --git a/src/murmur/About.h b/src/murmur/About.h index 8c4be64d0..f3efa5a53 100644 --- a/src/murmur/About.h +++ b/src/murmur/About.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MURMUR_ABOUT_H_ #define MUMBLE_MURMUR_ABOUT_H_ -#include <QtCore/QtGlobal> #include <QtCore/QObject> +#include <QtCore/QtGlobal> #include <QtWidgets/QDialog> enum AboutDialogOptions { @@ -20,11 +20,11 @@ enum AboutDialogOptions { }; class AboutDialog : public QDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(AboutDialog) - public: - AboutDialog(QWidget *parent, AboutDialogOptions options = AboutDialogOptionsDefault); +private: + Q_OBJECT + Q_DISABLE_COPY(AboutDialog) +public: + AboutDialog(QWidget *parent, AboutDialogOptions options = AboutDialogOptionsDefault); }; #endif diff --git a/src/murmur/BonjourServer.cpp b/src/murmur/BonjourServer.cpp index de54465a4..9041557b3 100644 --- a/src/murmur/BonjourServer.cpp +++ b/src/murmur/BonjourServer.cpp @@ -11,7 +11,8 @@ BonjourServer::BonjourServer() { bsrRegister = nullptr; #ifdef Q_OS_WIN static bool bDelayLoadFailed = false; - if (bDelayLoadFailed) return; + if (bDelayLoadFailed) + return; HMODULE hLib = LoadLibrary(L"DNSSD.DLL"); if (!hLib) { diff --git a/src/murmur/BonjourServer.h b/src/murmur/BonjourServer.h index bc3611a29..3258aaefb 100644 --- a/src/murmur/BonjourServer.h +++ b/src/murmur/BonjourServer.h @@ -11,14 +11,14 @@ class BonjourServiceRegister; class BonjourServer : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(BonjourServer) - public: - BonjourServer(); - ~BonjourServer(); +private: + Q_OBJECT + Q_DISABLE_COPY(BonjourServer) +public: + BonjourServer(); + ~BonjourServer(); - BonjourServiceRegister *bsrRegister; + BonjourServiceRegister *bsrRegister; }; #endif diff --git a/src/murmur/Cert.cpp b/src/murmur/Cert.cpp index 52adf638c..c9f140564 100644 --- a/src/murmur/Cert.cpp +++ b/src/murmur/Cert.cpp @@ -6,31 +6,31 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Meta.h" -#include "Server.h" #include "SelfSignedCertificate.h" +#include "Server.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif bool Server::isKeyForCert(const QSslKey &key, const QSslCertificate &cert) { if (key.isNull() || cert.isNull() || (key.type() != QSsl::PrivateKey)) return false; - QByteArray qbaKey = key.toDer(); + QByteArray qbaKey = key.toDer(); QByteArray qbaCert = cert.toDer(); - X509 *x509 = nullptr; + X509 *x509 = nullptr; EVP_PKEY *pkey = nullptr; - BIO *mem = nullptr; + BIO *mem = nullptr; mem = BIO_new_mem_buf(qbaKey.data(), qbaKey.size()); Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE)); @@ -80,30 +80,30 @@ void Server::initializeCert() { qsdhpDHParams = QSslDiffieHellmanParameters(); #endif - crt = getConf("certificate", QString()).toByteArray(); - key = getConf("key", QString()).toByteArray(); - pass = getConf("passphrase", QByteArray()).toByteArray(); + crt = getConf("certificate", QString()).toByteArray(); + key = getConf("key", QString()).toByteArray(); + pass = getConf("passphrase", QByteArray()).toByteArray(); dhparams = getConf("sslDHParams", Meta::mp.qbaDHParams).toByteArray(); - QList<QSslCertificate> ql; + QList< QSslCertificate > ql; // Attempt to load the private key. - if (! key.isEmpty()) { + if (!key.isEmpty()) { qskKey = Server::privateKeyFromPEM(key, pass); } // If we still can't load the key, try loading any keys from the certificate - if (qskKey.isNull() && ! crt.isEmpty()) { + if (qskKey.isNull() && !crt.isEmpty()) { qskKey = Server::privateKeyFromPEM(crt); } // If have a key, walk the list of certs, find the one for our key, // remove any certs for our key from the list, what's left is part of // the CA certificate chain. - if (! qskKey.isNull()) { + if (!qskKey.isNull()) { ql << QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); - for (int i=0;i<ql.size();++i) { + for (int i = 0; i < ql.size(); ++i) { const QSslCertificate &c = ql.at(i); if (isKeyForCert(qskKey, c)) { qscCert = c; @@ -114,24 +114,26 @@ void Server::initializeCert() { } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - if (! dhparams.isEmpty()) { + if (!dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters::fromEncoded(dhparams); if (qdhp.isValid()) { qsdhpDHParams = qdhp; } else { - log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1").arg(qdhp.errorString())); + log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1") + .arg(qdhp.errorString())); } } #else - if (! dhparams.isEmpty()) { - log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does not support Diffie-Hellman parameters."); + if (!dhparams.isEmpty()) { + log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does " + "not support Diffie-Hellman parameters."); } #endif QString issuer; QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName); - if (! issuerNames.isEmpty()) { + if (!issuerNames.isEmpty()) { issuer = issuerNames.first(); } @@ -140,16 +142,17 @@ void Server::initializeCert() { if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) { log("Old autogenerated certificate is unusable for registration, invalidating it"); qscCert = QSslCertificate(); - qskKey = QSslKey(); + qskKey = QSslKey(); } // If we have a cert, and it's a self-signed one, but we're binding to // all the same addresses as the Meta server is, use it's cert instead. // This allows a self-signed certificate generated by Murmur to be // replaced by a CA-signed certificate in the .ini file. - if (!qscCert.isNull() && issuer.startsWith(QString::fromUtf8("Murmur Autogenerated Certificate")) && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { - qscCert = Meta::mp.qscCert; - qskKey = Meta::mp.qskKey; + if (!qscCert.isNull() && issuer.startsWith(QString::fromUtf8("Murmur Autogenerated Certificate")) + && !Meta::mp.qscCert.isNull() && !Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { + qscCert = Meta::mp.qscCert; + qskKey = Meta::mp.qskKey; qlIntermediates = Meta::mp.qlIntermediates; if (!qscCert.isNull() && !qskKey.isNull()) { @@ -159,12 +162,12 @@ void Server::initializeCert() { // If we still don't have a certificate by now, try to load the one from Meta if (qscCert.isNull() || qskKey.isNull()) { - if (! key.isEmpty() || ! crt.isEmpty()) { + if (!key.isEmpty() || !crt.isEmpty()) { log("Certificate specified, but failed to load."); } - qskKey = Meta::mp.qskKey; - qscCert = Meta::mp.qscCert; + qskKey = Meta::mp.qskKey; + qscCert = Meta::mp.qscCert; qlIntermediates = Meta::mp.qlIntermediates; if (!qscCert.isNull() && !qskKey.isNull()) { diff --git a/src/murmur/DBus.cpp b/src/murmur/DBus.cpp index db00c3d50..e08cf537f 100644 --- a/src/murmur/DBus.cpp +++ b/src/murmur/DBus.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "DBus.h" @@ -14,8 +14,8 @@ #include "Connection.h" #include "Message.h" #include "Server.h" -#include "ServerUser.h" #include "ServerDB.h" +#include "ServerUser.h" #include <QtCore/QCoreApplication> #include <QtCore/QStack> @@ -26,9 +26,9 @@ #include <QtDBus/QDBusReply> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <arpa/inet.h> +# include <arpa/inet.h> #endif QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfo &s) { @@ -38,7 +38,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, PlayerInfo &s) { a.beginStructure(); a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel; a.endStructure(); @@ -47,14 +47,16 @@ const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfo &s) { QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfoExtended &s) { a.beginStructure(); - a << s.session << s.mute << s.deaf << s.suppressed << s.selfMute << s.selfDeaf << s.channel << s.id << s.name << s.onlinesecs << s.bytespersec; + a << s.session << s.mute << s.deaf << s.suppressed << s.selfMute << s.selfDeaf << s.channel << s.id << s.name + << s.onlinesecs << s.bytespersec; a.endStructure(); return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfoExtended &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, PlayerInfoExtended &s) { a.beginStructure(); - a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel >> s.id >> s.name >> s.onlinesecs >> s.bytespersec; + a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel >> s.id >> s.name + >> s.onlinesecs >> s.bytespersec; a.endStructure(); return a; } @@ -66,7 +68,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const ChannelInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, ChannelInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, ChannelInfo &s) { a.beginStructure(); a >> s.id >> s.name >> s.parent >> s.links; a.endStructure(); @@ -81,7 +83,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const GroupInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, GroupInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, GroupInfo &s) { a.beginStructure(); a >> s.name >> s.inherited >> s.inherit >> s.inheritable; a >> s.add >> s.remove >> s.members; @@ -98,7 +100,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const ACLInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, ACLInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, ACLInfo &s) { a.beginStructure(); a >> s.applyHere >> s.applySubs >> s.inherited; a >> s.playerid >> s.group; @@ -114,7 +116,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const BanInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, BanInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, BanInfo &s) { a.beginStructure(); a >> s.address >> s.bits; a.endStructure(); @@ -128,7 +130,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const RegisteredPlayer &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, RegisteredPlayer &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, RegisteredPlayer &s) { a.beginStructure(); a >> s.id >> s.name >> s.email >> s.pw; a.endStructure(); @@ -143,7 +145,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const LogEntry &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, LogEntry &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, LogEntry &s) { a.beginStructure(); a >> s.timestamp >> s.txt; a.endStructure(); @@ -151,22 +153,22 @@ const QDBusArgument & operator >>(const QDBusArgument &a, LogEntry &s) { } void MurmurDBus::registerTypes() { - qDBusRegisterMetaType<PlayerInfo>(); - qDBusRegisterMetaType<PlayerInfoExtended>(); - qDBusRegisterMetaType<QList<PlayerInfoExtended> >(); - qDBusRegisterMetaType<ChannelInfo>(); - qDBusRegisterMetaType<QList<ChannelInfo> >(); - qDBusRegisterMetaType<GroupInfo>(); - qDBusRegisterMetaType<QList<GroupInfo> >(); - qDBusRegisterMetaType<ACLInfo>(); - qDBusRegisterMetaType<QList<ACLInfo> >(); - qDBusRegisterMetaType<BanInfo>(); - qDBusRegisterMetaType<QList<BanInfo> >(); - qDBusRegisterMetaType<RegisteredPlayer>(); - qDBusRegisterMetaType<QList<RegisteredPlayer> >(); - qDBusRegisterMetaType<ConfigMap>(); - qDBusRegisterMetaType<LogEntry>(); - qDBusRegisterMetaType<QList<LogEntry> >(); + qDBusRegisterMetaType< PlayerInfo >(); + qDBusRegisterMetaType< PlayerInfoExtended >(); + qDBusRegisterMetaType< QList< PlayerInfoExtended > >(); + qDBusRegisterMetaType< ChannelInfo >(); + qDBusRegisterMetaType< QList< ChannelInfo > >(); + qDBusRegisterMetaType< GroupInfo >(); + qDBusRegisterMetaType< QList< GroupInfo > >(); + qDBusRegisterMetaType< ACLInfo >(); + qDBusRegisterMetaType< QList< ACLInfo > >(); + qDBusRegisterMetaType< BanInfo >(); + qDBusRegisterMetaType< QList< BanInfo > >(); + qDBusRegisterMetaType< RegisteredPlayer >(); + qDBusRegisterMetaType< QList< RegisteredPlayer > >(); + qDBusRegisterMetaType< ConfigMap >(); + qDBusRegisterMetaType< LogEntry >(); + qDBusRegisterMetaType< QList< LogEntry > >(); } QDBusConnection *MurmurDBus::qdbc = nullptr; @@ -178,33 +180,35 @@ MurmurDBus::MurmurDBus(Server *srv) : QDBusAbstractAdaptor(srv) { void MurmurDBus::removeAuthenticator() { server->disconnectAuthenticator(this); - qsAuthPath = QString(); + qsAuthPath = QString(); qsAuthService = QString(); } void MurmurDBus::idToNameSlot(QString &name, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QString> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserName",id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QString > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserName", id); if (reply.isValid()) name = reply.value(); else { - server->log(QString("DBus Authenticator failed getUserName for %1: %2").arg(QString::number(id), QString(reply.error().message()))); + server->log(QString("DBus Authenticator failed getUserName for %1: %2") + .arg(QString::number(id), QString(reply.error().message()))); removeAuthenticator(); } } void MurmurDBus::idToTextureSlot(QByteArray &qba, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QByteArray> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserTexture",id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QByteArray > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserTexture", id); if (reply.isValid()) { qba = reply.value(); } } void MurmurDBus::nameToIdSlot(int &id, const QString &name) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserId",name); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserId", name); if (reply.isValid()) id = reply.value(); else { @@ -213,9 +217,10 @@ void MurmurDBus::nameToIdSlot(int &id, const QString &name) { } } -void MurmurDBus::registerUserSlot(int &res, const QMap<int, QString> &info) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "registerPlayer", info.value(ServerDB::User_Name)); +void MurmurDBus::registerUserSlot(int &res, const QMap< int, QString > &info) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "registerPlayer", + info.value(ServerDB::User_Name)); if (reply.isValid()) { res = reply.value(); if ((info.count() > 1) && (res > 0)) @@ -224,68 +229,73 @@ void MurmurDBus::registerUserSlot(int &res, const QMap<int, QString> &info) { } void MurmurDBus::unregisterUserSlot(int &res, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "unregisterPlayer", id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "unregisterPlayer", id); if (reply.isValid()) res = reply.value(); } -void MurmurDBus::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<RegisteredPlayer> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegistration", id); +void MurmurDBus::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< RegisteredPlayer > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegistration", id); if (reply.isValid()) { const RegisteredPlayer &r = reply.value(); info.insert(ServerDB::User_Name, r.name); - if (! r.email.isEmpty()) + if (!r.email.isEmpty()) info.insert(ServerDB::User_Email, r.email); res = 1; } } -void MurmurDBus::getRegisteredUsersSlot(const QString &filter, QMap<int, QString > &m) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QList<RegisteredPlayer> > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegisteredPlayers", filter); +void MurmurDBus::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &m) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QList< RegisteredPlayer > > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegisteredPlayers", filter); if (reply.isValid()) { - const QList<RegisteredPlayer> &r = reply.value(); - foreach(const RegisteredPlayer &p, r) { - m.insert(p.id, p.name); - } + const QList< RegisteredPlayer > &r = reply.value(); + foreach (const RegisteredPlayer &p, r) { m.insert(p.id, p.name); } } } -void MurmurDBus::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { +void MurmurDBus::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { if (info.contains(ServerDB::User_Name)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setName",id, info.value(ServerDB::User_Name)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setName", id, + info.value(ServerDB::User_Name)); if (reply.isValid()) res = reply.value(); } if (info.contains(ServerDB::User_Password)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setPW",id, info.value(ServerDB::User_Password)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setPW", id, + info.value(ServerDB::User_Password)); if (reply.isValid()) res = reply.value(); } if (info.contains(ServerDB::User_Email)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setEmail",id, info.value(ServerDB::User_Email)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setEmail", id, + info.value(ServerDB::User_Email)); if (reply.isValid()) res = reply.value(); } } void MurmurDBus::setTextureSlot(int &res, int id, const QByteArray &texture) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setTexture",id, texture); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setTexture", id, texture); if (reply.isValid()) res = reply.value(); } -void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &, const QString &, bool, const QString &pw) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusMessage msg = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "authenticate",uname,pw); - QDBusError err = msg; - if (! err.isValid()) { +void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &, + const QString &, bool, const QString &pw) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusMessage msg = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "authenticate", uname, pw); + QDBusError err = msg; + if (!err.isValid()) { QString newname; int uid = -2; bool ok = true; @@ -294,7 +304,7 @@ void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const } if (ok && (msg.arguments().count() >= 2)) { newname = msg.arguments().at(1).toString(); - if (! newname.isEmpty()) { + if (!newname.isEmpty()) { uname = newname; } } @@ -313,40 +323,40 @@ void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const } } -#define PLAYER_SETUP_VAR(var) \ - ServerUser *pUser = server->qhUsers.value(var); \ - if (! pUser) { \ - qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.session", "Invalid session id")); \ - return; \ - } +#define PLAYER_SETUP_VAR(var) \ + ServerUser *pUser = server->qhUsers.value(var); \ + if (!pUser) { \ + qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.session", "Invalid session id")); \ + return; \ + } #define PLAYER_SETUP PLAYER_SETUP_VAR(session) -#define CHANNEL_SETUP_VAR2(dst,var) \ - Channel *dst = server->qhChannels.value(var); \ - if (! dst) { \ - qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Invalid channel id")); \ - return; \ - } +#define CHANNEL_SETUP_VAR2(dst, var) \ + Channel *dst = server->qhChannels.value(var); \ + if (!dst) { \ + qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Invalid channel id")); \ + return; \ + } -#define CHANNEL_SETUP_VAR(var) CHANNEL_SETUP_VAR2(cChannel,var) +#define CHANNEL_SETUP_VAR(var) CHANNEL_SETUP_VAR2(cChannel, var) -void MurmurDBus::getPlayers(QList<PlayerInfoExtended> &a) { +void MurmurDBus::getPlayers(QList< PlayerInfoExtended > &a) { a.clear(); - foreach(ServerUser *p, server->qhUsers) { - if (static_cast<ServerUser *>(p)->sState == ServerUser::Authenticated) + foreach (ServerUser *p, server->qhUsers) { + if (static_cast< ServerUser * >(p)->sState == ServerUser::Authenticated) a << PlayerInfoExtended(p); } } -void MurmurDBus::getChannels(QList<ChannelInfo> &a) { +void MurmurDBus::getChannels(QList< ChannelInfo > &a) { a.clear(); - QQueue<Channel *> q; + QQueue< Channel * > q; q << server->qhChannels.value(0); - while (! q.isEmpty()) { + while (!q.isEmpty()) { Channel *c = q.dequeue(); a << ChannelInfo(c); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } } @@ -429,22 +439,23 @@ void MurmurDBus::setChannelState(const ChannelInfo &nci, const QDBusMessage &msg CHANNEL_SETUP_VAR(nci.id); CHANNEL_SETUP_VAR2(cParent, nci.parent); - QSet<Channel *> newset; - foreach(int id, nci.links) { + QSet< Channel * > newset; + foreach (int id, nci.links) { CHANNEL_SETUP_VAR2(cLink, id); newset << cLink; } - if (! server->setChannelState(cChannel, cParent, nci.name, newset)) { + if (!server->setChannelState(cChannel, cParent, nci.name, newset)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Moving channel to subchannel")); return; } } -void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, QList<GroupInfo> &groups, bool &inherit) { +void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList< ACLInfo > &acls, QList< GroupInfo > &groups, + bool &inherit) { CHANNEL_SETUP_VAR(id); - QStack<Channel *> chans; + QStack< Channel * > chans; Channel *p; ChanACL *acl; @@ -454,15 +465,15 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q if ((p == cChannel) || (p->bInheritACL)) p = p->cParent; else - p =nullptr; + p = nullptr; } inherit = cChannel->bInheritACL; - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { - if ((p==cChannel) || (acl->bApplySubs)) { + foreach (acl, p->qlACL) { + if ((p == cChannel) || (acl->bApplySubs)) { ACLInfo ai(acl); if (p != cChannel) ai.inherited = true; @@ -471,24 +482,24 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q } } - p = cChannel->cParent; - QSet<QString> allnames = Group::groupNames(cChannel); + p = cChannel->cParent; + QSet< QString > allnames = Group::groupNames(cChannel); QString name; - foreach(name, allnames) { - Group *g = cChannel->qhGroups.value(name); + foreach (name, allnames) { + Group *g = cChannel->qhGroups.value(name); Group *pg = p ? Group::getGroup(p, name) : nullptr; - if (!g && ! pg) + if (!g && !pg) continue; GroupInfo gi(g ? g : pg); - QSet<int> members; + QSet< int > members; if (pg) members = pg->members(); if (g) { - gi.add = g->qsAdd.values(); - gi.remove = g->qsRemove.values(); + gi.add = g->qsAdd.values(); + gi.remove = g->qsRemove.values(); gi.inherited = false; - members+=g->qsAdd; - members-=g->qsRemove; + members += g->qsAdd; + members -= g->qsRemove; } else { gi.inherited = true; } @@ -497,7 +508,8 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q } } -void MurmurDBus::setACL(int id, const QList<ACLInfo> &acls, const QList<GroupInfo> &groups, bool inherit, const QDBusMessage &msg) { +void MurmurDBus::setACL(int id, const QList< ACLInfo > &acls, const QList< GroupInfo > &groups, bool inherit, + const QDBusMessage &msg) { CHANNEL_SETUP_VAR(id); Group *g; @@ -505,75 +517,71 @@ void MurmurDBus::setACL(int id, const QList<ACLInfo> &acls, const QList<GroupInf ACLInfo ai; GroupInfo gi; - QHash<QString, QSet<int> > hOldTemp; + QHash< QString, QSet< int > > hOldTemp; - foreach(g, cChannel->qhGroups) { + foreach (g, cChannel->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } - foreach(a, cChannel->qlACL) + foreach (a, cChannel->qlACL) delete a; cChannel->qhGroups.clear(); cChannel->qlACL.clear(); cChannel->bInheritACL = inherit; - foreach(gi, groups) { - g = new Group(cChannel, gi.name); - g->bInherit=gi.inherit; - g->bInheritable=gi.inheritable; + foreach (gi, groups) { + g = new Group(cChannel, gi.name); + g->bInherit = gi.inherit; + g->bInheritable = gi.inheritable; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - g->qsAdd = QSet<int>(gi.add.begin(), gi.add.end()); - g->qsRemove = QSet<int>(gi.remove.begin(), gi.remove.end()); + g->qsAdd = QSet< int >(gi.add.begin(), gi.add.end()); + g->qsRemove = QSet< int >(gi.remove.begin(), gi.remove.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now - g->qsAdd = gi.add.toSet(); + g->qsAdd = gi.add.toSet(); g->qsRemove = gi.remove.toSet(); #endif g->qsTemporary = hOldTemp.value(gi.name); } - foreach(ai, acls) { - a = new ChanACL(cChannel); + foreach (ai, acls) { + a = new ChanACL(cChannel); a->bApplyHere = ai.applyHere; a->bApplySubs = ai.applySubs; - a->iUserId = ai.playerid; - a->qsGroup = ai.group; - a->pDeny = static_cast<ChanACL::Permissions>(ai.deny) & ChanACL::All; - a->pAllow = static_cast<ChanACL::Permissions>(ai.allow) & ChanACL::All; + a->iUserId = ai.playerid; + a->qsGroup = ai.group; + a->pDeny = static_cast< ChanACL::Permissions >(ai.deny) & ChanACL::All; + a->pAllow = static_cast< ChanACL::Permissions >(ai.allow) & ChanACL::All; } server->clearACLCache(); server->updateChannel(cChannel); } -void MurmurDBus::getBans(QList<BanInfo> &bi) { +void MurmurDBus::getBans(QList< BanInfo > &bi) { bi.clear(); - foreach(const Ban &b, server->qlBans) { - if (! b.haAddress.isV6()) + foreach (const Ban &b, server->qlBans) { + if (!b.haAddress.isV6()) bi << BanInfo(b); } } -void MurmurDBus::setBans(const QList<BanInfo> &, const QDBusMessage &) { +void MurmurDBus::setBans(const QList< BanInfo > &, const QDBusMessage &) { } -void MurmurDBus::getPlayerNames(const QList<int> &ids, const QDBusMessage &, QStringList &names) { +void MurmurDBus::getPlayerNames(const QList< int > &ids, const QDBusMessage &, QStringList &names) { names.clear(); - foreach(int id, ids) { - names << server->getUserName(id); - } + foreach (int id, ids) { names << server->getUserName(id); } } -void MurmurDBus::getPlayerIds(const QStringList &names, const QDBusMessage &, QList<int> &ids) { +void MurmurDBus::getPlayerIds(const QStringList &names, const QDBusMessage &, QList< int > &ids) { ids.clear(); - foreach(QString name, names) { - ids << server->getUserID(name); - } + foreach (QString name, names) { ids << server->getUserID(name); } } void MurmurDBus::registerPlayer(const QString &name, const QDBusMessage &msg, int &id) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, name); id = server->registerUser(info); if (id < 0) { @@ -583,43 +591,44 @@ void MurmurDBus::registerPlayer(const QString &name, const QDBusMessage &msg, in } void MurmurDBus::unregisterPlayer(int id, const QDBusMessage &msg) { - if (! server->unregisterUser(id)) { + if (!server->unregisterUser(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } } void MurmurDBus::getRegistration(int id, const QDBusMessage &msg, RegisteredPlayer &user) { - QMap<int, QString> info = server->getRegistration(id); + QMap< int, QString > info = server->getRegistration(id); if (info.isEmpty()) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } - user.id = id; - user.name = info.value(ServerDB::User_Name); + user.id = id; + user.name = info.value(ServerDB::User_Name); user.email = info.value(ServerDB::User_Email); } -void MurmurDBus::setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &msg) { +void MurmurDBus::setRegistration(int id, const QString &name, const QString &email, const QString &pw, + const QDBusMessage &msg) { RegisteredPlayer user; - user.id = id; - user.name = name; + user.id = id; + user.name = name; user.email = email; - user.pw = pw; + user.pw = pw; updateRegistration(user, msg); } void MurmurDBus::updateRegistration(const RegisteredPlayer &user, const QDBusMessage &msg) { - QMap<int, QString> info; + QMap< int, QString > info; - if (! user.name.isEmpty()) + if (!user.name.isEmpty()) info.insert(ServerDB::User_Name, user.name); - if (! user.email.isEmpty()) + if (!user.email.isEmpty()) info.insert(ServerDB::User_Email, user.email); - if (! user.pw.isEmpty()) + if (!user.pw.isEmpty()) info.insert(ServerDB::User_Password, user.pw); if (info.isEmpty() || !server->setInfo(user.id, info)) { @@ -629,7 +638,7 @@ void MurmurDBus::updateRegistration(const RegisteredPlayer &user, const QDBusMes } void MurmurDBus::getTexture(int id, const QDBusMessage &msg, QByteArray &texture) { - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } @@ -637,30 +646,30 @@ void MurmurDBus::getTexture(int id, const QDBusMessage &msg, QByteArray &texture } void MurmurDBus::setTexture(int id, const QByteArray &texture, const QDBusMessage &msg) { - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } - if (! server->setTexture(id, texture)) { + if (!server->setTexture(id, texture)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.texture", "Invalid texture")); return; } } -void MurmurDBus::getRegisteredPlayers(const QString &filter, QList<RegisteredPlayer> &users) { +void MurmurDBus::getRegisteredPlayers(const QString &filter, QList< RegisteredPlayer > &users) { users.clear(); - QMap<int, QString > l = server->getRegisteredUsers(filter); - QMap<int, QString >::const_iterator i; + QMap< int, QString > l = server->getRegisteredUsers(filter); + QMap< int, QString >::const_iterator i; for (i = l.constBegin(); i != l.constEnd(); ++i) { RegisteredPlayer r; - r.id = i.key(); + r.id = i.key(); r.name = i.value(); users << r; } } void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &msg, bool &ok) { - QList<int> ids; + QList< int > ids; ids << id; QStringList names; getPlayerNames(ids, msg, names); @@ -671,7 +680,7 @@ void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &m } QString name = names.at(0); - int nid = server->authenticate(name, pw); + int nid = server->authenticate(name, pw); if (nid == id) ok = true; else @@ -679,21 +688,21 @@ void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &m } #ifdef Q_OS_WIN -#undef interface +# undef interface #endif void MurmurDBus::setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &msg) { - if (! qsAuthPath.isNull() || ! qsAuthService.isNull()) + if (!qsAuthPath.isNull() || !qsAuthService.isNull()) removeAuthenticator(); server->connectAuthenticator(this); - qsAuthPath = path.path(); + qsAuthPath = path.path(); qsAuthService = msg.service(); QDBusConnectionInterface *interface = qdbc->interface(); - QDBusReply<QStringList> names = interface->registeredServiceNames(); + QDBusReply< QStringList > names = interface->registeredServiceNames(); if (names.isValid()) { - foreach(const QString &name, names.value()) { - QDBusReply<QString> owner = interface->serviceOwner(name); + foreach (const QString &name, names.value()) { + QDBusReply< QString > owner = interface->serviceOwner(name); if (owner.isValid() && (owner.value() != name) && (owner.value() == qsAuthService)) { qsAuthService = name; break; @@ -702,7 +711,8 @@ void MurmurDBus::setAuthenticator(const QDBusObjectPath &path, bool reentrant, c } bReentrant = reentrant; - server->log(QString("DBus Authenticator set to %1 %2 (%3)").arg(qsAuthService, qsAuthPath, QString::number(reentrant))); + server->log( + QString("DBus Authenticator set to %1 %2 (%3)").arg(qsAuthService, qsAuthPath, QString::number(reentrant))); } void MurmurDBus::setTemporaryGroups(int channel, int userid, const QStringList &groups, const QDBusMessage &msg) { @@ -712,29 +722,29 @@ void MurmurDBus::setTemporaryGroups(int channel, int userid, const QStringList & } PlayerInfo::PlayerInfo(const User *p) { - session = p->uiSession; - mute = p->bMute; - deaf = p->bDeaf; + session = p->uiSession; + mute = p->bMute; + deaf = p->bDeaf; suppressed = p->bSuppress; - selfMute = p->bSelfMute; - selfDeaf = p->bSelfDeaf; - channel = p->cChannel->iId; + selfMute = p->bSelfMute; + selfDeaf = p->bSelfDeaf; + channel = p->cChannel->iId; } PlayerInfoExtended::PlayerInfoExtended(const User *p) : PlayerInfo(p) { - id = p->iId; + id = p->iId; name = p->qsName; - const ServerUser *u = static_cast<const ServerUser *>(p); - onlinesecs = u->bwr.onlineSeconds(); - bytespersec = u->bwr.bandwidth(); + const ServerUser *u = static_cast< const ServerUser * >(p); + onlinesecs = u->bwr.onlineSeconds(); + bytespersec = u->bwr.bandwidth(); } ChannelInfo::ChannelInfo(const Channel *c) { - id = c->iId; - name = c->qsName; + id = c->iId; + name = c->qsName; parent = c->cParent ? c->cParent->iId : -1; - foreach(Channel *chn, c->qsPermLinks) + foreach (Channel *chn, c->qsPermLinks) links << chn->iId; } @@ -742,22 +752,22 @@ ACLInfo::ACLInfo(const ChanACL *acl) { applyHere = acl->bApplyHere; applySubs = acl->bApplySubs; inherited = false; - playerid = acl->iUserId; - group = acl->qsGroup; - allow = acl->pAllow; - deny = acl->pDeny; + playerid = acl->iUserId; + group = acl->qsGroup; + allow = acl->pAllow; + deny = acl->pDeny; } GroupInfo::GroupInfo(const Group *g) : inherited(false) { - name = g->qsName; - inherit = g->bInherit; + name = g->qsName; + inherit = g->bInherit; inheritable = g->bInheritable; members.clear(); } BanInfo::BanInfo(const Ban &b) { address = ntohl(b.haAddress.hash[3]); - bits = b.iMask; + bits = b.iMask; } RegisteredPlayer::RegisteredPlayer() { @@ -770,7 +780,7 @@ LogEntry::LogEntry() { LogEntry::LogEntry(const ServerDB::LogRecord &r) { timestamp = r.first; - txt = r.second; + txt = r.second; } void MurmurDBus::userStateChanged(const User *p) { @@ -822,15 +832,15 @@ void MetaDBus::stopped(Server *s) { void MetaDBus::start(int server_id, const QDBusMessage &msg) { if (meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server already booted")); - } else if (! ServerDB::serverExists(server_id)) { + } else if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); - } else if (! meta->boot(server_id)) { + } else if (!meta->boot(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.bootfail", "Booting server failed")); } } void MetaDBus::stop(int server_id, const QDBusMessage &msg) { - if (! meta->qhServers.contains(server_id)) { + if (!meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server not booted")); } else { meta->kill(server_id); @@ -844,18 +854,18 @@ void MetaDBus::newServer(int &server_id) { void MetaDBus::deleteServer(int server_id, const QDBusMessage &msg) { if (meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server is running")); - } else if (! ServerDB::serverExists(server_id)) { + } else if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::deleteServer(server_id); } } -void MetaDBus::getBootedServers(QList<int> &server_list) { +void MetaDBus::getBootedServers(QList< int > &server_list) { server_list = meta->qhServers.keys(); } -void MetaDBus::getAllServers(QList<int> &server_list) { +void MetaDBus::getAllServers(QList< int > &server_list) { server_list = ServerDB::getAllServers(); } @@ -864,18 +874,19 @@ void MetaDBus::isBooted(int server_id, bool &booted) { } void MetaDBus::getConf(int server_id, const QString &key, const QDBusMessage &msg, QString &value) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { if (key == "key" || key == "passphrase") - MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.writeonly", "Requested read of write-only field.")); + MurmurDBus::qdbc->send( + msg.createErrorReply("net.sourceforge.mumble.Error.writeonly", "Requested read of write-only field.")); else value = ServerDB::getConf(server_id, key).toString(); } } void MetaDBus::setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &msg) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::setConf(server_id, key, value); @@ -886,7 +897,7 @@ void MetaDBus::setConf(int server_id, const QString &key, const QString &value, } void MetaDBus::getAllConf(int server_id, const QDBusMessage &msg, ConfigMap &values) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { values = ServerDB::getAllConf(server_id); @@ -896,15 +907,14 @@ void MetaDBus::getAllConf(int server_id, const QDBusMessage &msg, ConfigMap &val } } -void MetaDBus::getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &msg, QList<LogEntry> &entries) { - if (! ServerDB::serverExists(server_id)) { +void MetaDBus::getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &msg, + QList< LogEntry > &entries) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { entries.clear(); - QList<ServerDB::LogRecord> dblog = ServerDB::getLog(server_id, min_offset, max_offset); - foreach(const ServerDB::LogRecord &e, dblog) { - entries << LogEntry(e); - } + QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min_offset, max_offset); + foreach (const ServerDB::LogRecord &e, dblog) { entries << LogEntry(e); } } } @@ -916,7 +926,7 @@ void MetaDBus::getDefaultConf(ConfigMap &values) { } void MetaDBus::setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &msg) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::setSUPW(server_id, pw); diff --git a/src/murmur/DBus.h b/src/murmur/DBus.h index 9937d201e..64d9fe7d6 100644 --- a/src/murmur/DBus.h +++ b/src/murmur/DBus.h @@ -4,19 +4,19 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_DBUS -#ifndef MUMBLE_MURMUR_DBUS_H_ -#define MUMBLE_MURMUR_DBUS_H_ +# ifndef MUMBLE_MURMUR_DBUS_H_ +# define MUMBLE_MURMUR_DBUS_H_ -#include <QtDBus/QDBusAbstractAdaptor> -#include <QtDBus/QDBusConnection> +# include <QtDBus/QDBusAbstractAdaptor> +# include <QtDBus/QDBusConnection> -#include "ACL.h" -#include "Channel.h" -#include "Group.h" -#include "Meta.h" -#include "Server.h" -#include "ServerDB.h" -#include "User.h" +# include "ACL.h" +# include "Channel.h" +# include "Group.h" +# include "Meta.h" +# include "Server.h" +# include "ServerDB.h" +# include "User.h" struct Ban; class QDBusObjectPath; @@ -27,7 +27,8 @@ struct PlayerInfo { bool mute, deaf, suppressed; bool selfMute, selfDeaf; int channel; - PlayerInfo() : session(0), mute(false), deaf(false), suppressed(false), selfMute(false), selfDeaf(false), channel(-1) { }; + PlayerInfo() + : session(0), mute(false), deaf(false), suppressed(false), selfMute(false), selfDeaf(false), channel(-1){}; PlayerInfo(const User *); }; Q_DECLARE_METATYPE(PlayerInfo); @@ -37,52 +38,52 @@ struct PlayerInfoExtended : public PlayerInfo { QString name; int onlinesecs; int bytespersec; - PlayerInfoExtended() : id(-1), onlinesecs(-1), bytespersec(-1) {}; + PlayerInfoExtended() : id(-1), onlinesecs(-1), bytespersec(-1){}; PlayerInfoExtended(const User *); }; Q_DECLARE_METATYPE(PlayerInfoExtended); -Q_DECLARE_METATYPE(QList<PlayerInfoExtended>); +Q_DECLARE_METATYPE(QList< PlayerInfoExtended >); struct ChannelInfo { int id; QString name; int parent; - QList<int> links; - ChannelInfo() : id(-1), parent(-1) { }; + QList< int > links; + ChannelInfo() : id(-1), parent(-1){}; ChannelInfo(const Channel *c); }; Q_DECLARE_METATYPE(ChannelInfo); -Q_DECLARE_METATYPE(QList<ChannelInfo>); +Q_DECLARE_METATYPE(QList< ChannelInfo >); struct GroupInfo { QString name; bool inherited, inherit, inheritable; - QList<int> add, remove, members; - GroupInfo() : inherited(false), inherit(false), inheritable(false) { }; + QList< int > add, remove, members; + GroupInfo() : inherited(false), inherit(false), inheritable(false){}; GroupInfo(const Group *g); }; Q_DECLARE_METATYPE(GroupInfo); -Q_DECLARE_METATYPE(QList<GroupInfo>); +Q_DECLARE_METATYPE(QList< GroupInfo >); struct ACLInfo { bool applyHere, applySubs, inherited; int playerid; QString group; unsigned int allow, deny; - ACLInfo() : applyHere(false), applySubs(false), inherited(false), playerid(-1), allow(0), deny(0) { }; + ACLInfo() : applyHere(false), applySubs(false), inherited(false), playerid(-1), allow(0), deny(0){}; ACLInfo(const ChanACL *acl); }; Q_DECLARE_METATYPE(ACLInfo); -Q_DECLARE_METATYPE(QList<ACLInfo>); +Q_DECLARE_METATYPE(QList< ACLInfo >); struct BanInfo { unsigned int address; int bits; - BanInfo() : address(0), bits(0) { }; + BanInfo() : address(0), bits(0){}; BanInfo(const Ban &); }; Q_DECLARE_METATYPE(BanInfo); -Q_DECLARE_METATYPE(QList<BanInfo>); +Q_DECLARE_METATYPE(QList< BanInfo >); struct RegisteredPlayer { int id; @@ -92,7 +93,7 @@ struct RegisteredPlayer { RegisteredPlayer(); }; Q_DECLARE_METATYPE(RegisteredPlayer); -Q_DECLARE_METATYPE(QList<RegisteredPlayer>); +Q_DECLARE_METATYPE(QList< RegisteredPlayer >); struct LogEntry { unsigned int timestamp; @@ -101,137 +102,141 @@ struct LogEntry { LogEntry(const ServerDB::LogRecord &); }; Q_DECLARE_METATYPE(LogEntry); -Q_DECLARE_METATYPE(QList<LogEntry>); +Q_DECLARE_METATYPE(QList< LogEntry >); class MurmurDBus : public QDBusAbstractAdaptor { - private: - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Murmur") - Q_DISABLE_COPY(MurmurDBus) - protected: - Server *server; - bool bReentrant; - QString qsAuthService; - QString qsAuthPath; - void removeAuthenticator(); - public: - static QDBusConnection *qdbc; - - MurmurDBus(Server *srv); - static void registerTypes(); - public slots: - // These have the result ref as the first parameter, so won't be converted to DBus - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certs, const QString &certhash, bool strong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); - - // These use private types, so won't be converted to DBus - void userStateChanged(const User *p); - void userTextMessage(const User *, const TextMessage &); - void userConnected(const User *p); - void userDisconnected(const User *p); - - void channelStateChanged(const Channel *c); - void channelCreated(const Channel *c); - void channelRemoved(const Channel *c); - - public slots: - // Order of paremeters is IMPORTANT, or Qt will barf. - // Needs to be: - // First all input parameters (non-ref or const-ref) - // Then const QDbusMessage ref - // Then output paremeters (ref) - // Unfortunately, this makes things look chaotic, but luckily it looks sane again when introspected. - // make SURE arguments have sane names, the argument-name will be exported in introspection xml. - - void getPlayers(QList<PlayerInfoExtended> &player_list); - void getChannels(QList<ChannelInfo> &channel_list); - - void getACL(int channel, const QDBusMessage &, QList<ACLInfo> &acls,QList<GroupInfo> &groups, bool &inherit); - void setACL(int channel, const QList<ACLInfo> &acls, const QList<GroupInfo> &groups, bool inherit, const QDBusMessage &); - - void getBans(QList<BanInfo> &bans); - void setBans(const QList<BanInfo> &bans, const QDBusMessage &); - - void kickPlayer(unsigned int session, const QString &reason, const QDBusMessage &); - void getPlayerState(unsigned int session, const QDBusMessage &, PlayerInfo &state); - void setPlayerState(const PlayerInfo &state, const QDBusMessage &); - void sendMessage(unsigned int session, const QString &text, const QDBusMessage &); - - void getChannelState(int id, const QDBusMessage &, ChannelInfo &state); - void setChannelState(const ChannelInfo &state, const QDBusMessage &); - void removeChannel(int id, const QDBusMessage &); - void addChannel(const QString &name, int parent, const QDBusMessage &, int &newid); - void sendMessageChannel(int id, bool tree, const QString &text, const QDBusMessage &); - - void getPlayerNames(const QList<int> &ids, const QDBusMessage &, QStringList &names); - void getPlayerIds(const QStringList &names, const QDBusMessage &, QList<int> &ids); - - void setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &); - void setTemporaryGroups(int channel, int playerid, const QStringList &groups, const QDBusMessage &); - - void registerPlayer(const QString &name, const QDBusMessage &, int &id); - void unregisterPlayer(int id, const QDBusMessage &); - void updateRegistration(const RegisteredPlayer &player, const QDBusMessage &); - void setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &); - void getRegistration(int id, const QDBusMessage &, RegisteredPlayer &player); - void getRegisteredPlayers(const QString &filter, QList<RegisteredPlayer> &players); - void verifyPassword(int id, const QString &pw, const QDBusMessage &, bool &ok); - void getTexture(int id, const QDBusMessage &, QByteArray &texture); - void setTexture(int id, const QByteArray &, const QDBusMessage &); - signals: - void playerStateChanged(const PlayerInfo &state); - void playerConnected(const PlayerInfo &state); - void playerDisconnected(const PlayerInfo &state); - - void channelStateChanged(const ChannelInfo &state); - void channelCreated(const ChannelInfo &state); - void channelRemoved(const ChannelInfo &state); +private: + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Murmur") + Q_DISABLE_COPY(MurmurDBus) +protected: + Server *server; + bool bReentrant; + QString qsAuthService; + QString qsAuthPath; + void removeAuthenticator(); + +public: + static QDBusConnection *qdbc; + + MurmurDBus(Server *srv); + static void registerTypes(); +public slots: + // These have the result ref as the first parameter, so won't be converted to DBus + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certs, + const QString &certhash, bool strong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); + + // These use private types, so won't be converted to DBus + void userStateChanged(const User *p); + void userTextMessage(const User *, const TextMessage &); + void userConnected(const User *p); + void userDisconnected(const User *p); + + void channelStateChanged(const Channel *c); + void channelCreated(const Channel *c); + void channelRemoved(const Channel *c); + +public slots: + // Order of paremeters is IMPORTANT, or Qt will barf. + // Needs to be: + // First all input parameters (non-ref or const-ref) + // Then const QDbusMessage ref + // Then output paremeters (ref) + // Unfortunately, this makes things look chaotic, but luckily it looks sane again when introspected. + // make SURE arguments have sane names, the argument-name will be exported in introspection xml. + + void getPlayers(QList< PlayerInfoExtended > &player_list); + void getChannels(QList< ChannelInfo > &channel_list); + + void getACL(int channel, const QDBusMessage &, QList< ACLInfo > &acls, QList< GroupInfo > &groups, bool &inherit); + void setACL(int channel, const QList< ACLInfo > &acls, const QList< GroupInfo > &groups, bool inherit, + const QDBusMessage &); + + void getBans(QList< BanInfo > &bans); + void setBans(const QList< BanInfo > &bans, const QDBusMessage &); + + void kickPlayer(unsigned int session, const QString &reason, const QDBusMessage &); + void getPlayerState(unsigned int session, const QDBusMessage &, PlayerInfo &state); + void setPlayerState(const PlayerInfo &state, const QDBusMessage &); + void sendMessage(unsigned int session, const QString &text, const QDBusMessage &); + + void getChannelState(int id, const QDBusMessage &, ChannelInfo &state); + void setChannelState(const ChannelInfo &state, const QDBusMessage &); + void removeChannel(int id, const QDBusMessage &); + void addChannel(const QString &name, int parent, const QDBusMessage &, int &newid); + void sendMessageChannel(int id, bool tree, const QString &text, const QDBusMessage &); + + void getPlayerNames(const QList< int > &ids, const QDBusMessage &, QStringList &names); + void getPlayerIds(const QStringList &names, const QDBusMessage &, QList< int > &ids); + + void setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &); + void setTemporaryGroups(int channel, int playerid, const QStringList &groups, const QDBusMessage &); + + void registerPlayer(const QString &name, const QDBusMessage &, int &id); + void unregisterPlayer(int id, const QDBusMessage &); + void updateRegistration(const RegisteredPlayer &player, const QDBusMessage &); + void setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &); + void getRegistration(int id, const QDBusMessage &, RegisteredPlayer &player); + void getRegisteredPlayers(const QString &filter, QList< RegisteredPlayer > &players); + void verifyPassword(int id, const QString &pw, const QDBusMessage &, bool &ok); + void getTexture(int id, const QDBusMessage &, QByteArray &texture); + void setTexture(int id, const QByteArray &, const QDBusMessage &); +signals: + void playerStateChanged(const PlayerInfo &state); + void playerConnected(const PlayerInfo &state); + void playerDisconnected(const PlayerInfo &state); + + void channelStateChanged(const ChannelInfo &state); + void channelCreated(const ChannelInfo &state); + void channelRemoved(const ChannelInfo &state); }; -typedef QMap<QString, QString> ConfigMap; +typedef QMap< QString, QString > ConfigMap; Q_DECLARE_METATYPE(ConfigMap); class MetaDBus : public QDBusAbstractAdaptor { - private: - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Meta") - Q_DISABLE_COPY(MetaDBus) - protected: - Meta *meta; - public: - MetaDBus(Meta *m); - - public slots: - void started(Server *s); - void stopped(Server *s); - public slots: - void start(int server_id, const QDBusMessage &); - void stop(int server_id, const QDBusMessage &); - void newServer(int &server_id); - void deleteServer(int server_id, const QDBusMessage &); - void getBootedServers(QList<int> &server_list); - void getAllServers(QList<int> &server_list); - void isBooted(int server_id, bool &booted); - void getConf(int server_id, const QString &key, const QDBusMessage &, QString &value); - void getAllConf(int server_id, const QDBusMessage &, ConfigMap &values); - void getDefaultConf(ConfigMap &values); - void setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &); - void setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &); - void getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &, QList<LogEntry> &entries); - void getVersion(int &major, int &minor, int &patch, QString &string); - void quit(); - signals: - void started(int server_id); - void stopped(int server_id); +private: + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Meta") + Q_DISABLE_COPY(MetaDBus) +protected: + Meta *meta; + +public: + MetaDBus(Meta *m); + +public slots: + void started(Server *s); + void stopped(Server *s); +public slots: + void start(int server_id, const QDBusMessage &); + void stop(int server_id, const QDBusMessage &); + void newServer(int &server_id); + void deleteServer(int server_id, const QDBusMessage &); + void getBootedServers(QList< int > &server_list); + void getAllServers(QList< int > &server_list); + void isBooted(int server_id, bool &booted); + void getConf(int server_id, const QString &key, const QDBusMessage &, QString &value); + void getAllConf(int server_id, const QDBusMessage &, ConfigMap &values); + void getDefaultConf(ConfigMap &values); + void setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &); + void setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &); + void getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &, QList< LogEntry > &entries); + void getVersion(int &major, int &minor, int &patch, QString &string); + void quit(); +signals: + void started(int server_id); + void stopped(int server_id); }; -#endif +# endif #endif diff --git a/src/murmur/Messages.cpp b/src/murmur/Messages.cpp index e82b9308b..7ee2b4ef8 100644 --- a/src/murmur/Messages.cpp +++ b/src/murmur/Messages.cpp @@ -3,141 +3,140 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include "User.h" -#include "Channel.h" #include "ACL.h" +#include "Channel.h" +#include "ChannelListener.h" +#include "Connection.h" #include "Group.h" #include "Message.h" -#include "ServerDB.h" -#include "Connection.h" +#include "Meta.h" #include "Server.h" +#include "ServerDB.h" #include "ServerUser.h" +#include "User.h" #include "Version.h" #include "crypto/CryptState.h" -#include "Meta.h" -#include "ChannelListener.h" #include <QtCore/QStack> #include <QtCore/QtEndian> -#define RATELIMIT(user) \ +#define RATELIMIT(user) \ if (user->leakyBucket.ratelimit(1)) { \ - return; \ + return; \ } -#define MSG_SETUP(st) \ +#define MSG_SETUP(st) \ if (uSource->sState != st) { \ - return; \ - } \ + return; \ + } \ uSource->bwr.resetIdleSeconds() #define MSG_SETUP_NO_UNIDLE(st) \ - if (uSource->sState != st) \ - return + if (uSource->sState != st) \ + return -#define VICTIM_SETUP \ - ServerUser *pDstServerUser = uSource; \ - if (msg.has_session()) \ +#define VICTIM_SETUP \ + ServerUser *pDstServerUser = uSource; \ + if (msg.has_session()) \ pDstServerUser = qhUsers.value(msg.session()); \ - if (! pDstServerUser) \ - return; \ + if (!pDstServerUser) \ + return; \ Q_UNUSED(pDstServerUser) -#define PERM_DENIED(who, where, what) \ - { \ - MumbleProto::PermissionDenied mppd; \ - mppd.set_permission(static_cast<int>(what)); \ - mppd.set_channel_id(where->iId); \ - mppd.set_session(who->uiSession); \ - mppd.set_type(MumbleProto::PermissionDenied_DenyType_Permission); \ - sendMessage(uSource, mppd); \ - log(uSource, QString("%1 not allowed to %2 in %3").arg(who->qsName).arg(ChanACL::permName(what)).arg(where->qsName)); \ - } - -#define PERM_DENIED_TYPE(type) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED(who, where, what) \ + { \ + MumbleProto::PermissionDenied mppd; \ + mppd.set_permission(static_cast< int >(what)); \ + mppd.set_channel_id(where->iId); \ + mppd.set_session(who->uiSession); \ + mppd.set_type(MumbleProto::PermissionDenied_DenyType_Permission); \ + sendMessage(uSource, mppd); \ + log(uSource, \ + QString("%1 not allowed to %2 in %3").arg(who->qsName).arg(ChanACL::permName(what)).arg(where->qsName)); \ + } + +#define PERM_DENIED_TYPE(type) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_##type); \ - sendMessage(uSource, mppd); \ + sendMessage(uSource, mppd); \ } -#define PERM_DENIED_FALLBACK(type,version,text) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED_FALLBACK(type, version, text) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_##type); \ - if (uSource->uiVersion < version) \ - mppd.set_reason(u8(text)); \ - sendMessage(uSource, mppd); \ + if (uSource->uiVersion < version) \ + mppd.set_reason(u8(text)); \ + sendMessage(uSource, mppd); \ } -#define PERM_DENIED_HASH(user) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED_HASH(user) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_MissingCertificate); \ - if (user) \ - mppd.set_session(user->uiSession); \ - sendMessage(uSource, mppd); \ + if (user) \ + mppd.set_session(user->uiSession); \ + sendMessage(uSource, mppd); \ } /// A helper class for managing temporary access tokens. /// It will add the tokens in the comstructor and remove them again in the destructor effectively /// turning the tokens into a scope-based property. class TemporaryAccessTokenHelper { - protected: - ServerUser *affectedUser; - QStringList qslTemporaryTokens; - Server *server; - - public: - TemporaryAccessTokenHelper(ServerUser *affectedUser, const QStringList &tokens, Server *server) - : affectedUser(affectedUser) - , qslTemporaryTokens(tokens) - , server(server) { - // Add the temporary tokens - QMutableStringListIterator it(this->qslTemporaryTokens); +protected: + ServerUser *affectedUser; + QStringList qslTemporaryTokens; + Server *server; - { - QMutexLocker qml(&server->qmCache); +public: + TemporaryAccessTokenHelper(ServerUser *affectedUser, const QStringList &tokens, Server *server) + : affectedUser(affectedUser), qslTemporaryTokens(tokens), server(server) { + // Add the temporary tokens + QMutableStringListIterator it(this->qslTemporaryTokens); - while (it.hasNext()) { - QString &token = it.next(); + { + QMutexLocker qml(&server->qmCache); - // If tokens are treated case-insensitively, transform all temp. tokens to lowercase first - if (Group::accessTokenCaseSensitivity == Qt::CaseInsensitive) { - token = token.toLower(); - } + while (it.hasNext()) { + QString &token = it.next(); - if (!this->affectedUser->qslAccessTokens.contains(token, Group::accessTokenCaseSensitivity)) { - // Add token - this->affectedUser->qslAccessTokens << token; - } else { - // It appears, as if the user already has this token set -> it's not a temporary one or a duplicate - it.remove(); - } + // If tokens are treated case-insensitively, transform all temp. tokens to lowercase first + if (Group::accessTokenCaseSensitivity == Qt::CaseInsensitive) { + token = token.toLower(); } - } - if (!this->qslTemporaryTokens.isEmpty()) { - // Clear the cache in order for tokens to take effect - server->clearACLCache(this->affectedUser); + if (!this->affectedUser->qslAccessTokens.contains(token, Group::accessTokenCaseSensitivity)) { + // Add token + this->affectedUser->qslAccessTokens << token; + } else { + // It appears, as if the user already has this token set -> it's not a temporary one or a duplicate + it.remove(); + } } } - ~TemporaryAccessTokenHelper() { - if (!this->qslTemporaryTokens.isEmpty()) { - { - QMutexLocker qml(&server->qmCache); + if (!this->qslTemporaryTokens.isEmpty()) { + // Clear the cache in order for tokens to take effect + server->clearACLCache(this->affectedUser); + } + } - // remove the temporary tokens - foreach(const QString &token, this->qslTemporaryTokens) { - this->affectedUser->qslAccessTokens.removeOne(token); - } - } + ~TemporaryAccessTokenHelper() { + if (!this->qslTemporaryTokens.isEmpty()) { + { + QMutexLocker qml(&server->qmCache); - // Clear cache to actually get rid of the temporary tokens - server->clearACLCache(this->affectedUser); + // remove the temporary tokens + foreach (const QString &token, this->qslTemporaryTokens) { + this->affectedUser->qslAccessTokens.removeOne(token); + } } + + // Clear cache to actually get rid of the temporary tokens + server->clearACLCache(this->affectedUser); } + } }; /// Checks whether the given channel has restrictions affecting the ENTER privilege @@ -146,7 +145,7 @@ class TemporaryAccessTokenHelper { /// @return Whether the provided channel has an ACL denying ENTER bool isChannelEnterRestricted(Channel *c) { // A channel is enter restricted if there's an ACL denying enter privileges - foreach(ChanACL *acl, c->qlACL) { + foreach (ChanACL *acl, c->qlACL) { if (acl->pDeny & ChanACL::Enter) { return true; } @@ -158,7 +157,7 @@ bool isChannelEnterRestricted(Channel *c) { void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg) { if ((msg.tokens_size() > 0) || (uSource->sState == ServerUser::Authenticated)) { QStringList qsl; - for (int i=0;i<msg.tokens_size();++i) + for (int i = 0; i < msg.tokens_size(); ++i) qsl << u8(msg.tokens(i)); { QMutexLocker qml(&qmCache); @@ -168,7 +167,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Send back updated enter states of all channels MumbleProto::ChannelState mpcs; - foreach(Channel *chan, qhChannels) { + foreach (Channel *chan, qhChannels) { mpcs.set_channel_id(chan->iId); mpcs.set_can_enter(ChanACL::hasPermission(uSource, chan, ChanACL::Enter, &acCache)); // As no ACLs have changed, we don't need to update the is_access_restricted message field @@ -183,30 +182,31 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg uSource->qsName = u8(msg.username()); - bool ok = false; + bool ok = false; bool nameok = validateUserName(uSource->qsName); - QString pw = u8(msg.password()); + QString pw = u8(msg.password()); // Fetch ID and stored username. // Since this may call DBus, which may recall our dbus messages, this function needs // to support re-entrancy, and also to support the fact that sessions may go away. - int id = authenticate(uSource->qsName, pw, uSource->uiSession, uSource->qslEmail, uSource->qsHash, uSource->bVerified, uSource->peerCertificateChain()); + int id = authenticate(uSource->qsName, pw, uSource->uiSession, uSource->qslEmail, uSource->qsHash, + uSource->bVerified, uSource->peerCertificateChain()); uSource->iId = id >= 0 ? id : -1; QString reason; MumbleProto::Reject_RejectType rtType = MumbleProto::Reject_RejectType_None; - if (id==-2 && ! nameok) { + if (id == -2 && !nameok) { reason = "Invalid username"; rtType = MumbleProto::Reject_RejectType_InvalidUsername; - } else if (id==-1) { + } else if (id == -1) { reason = "Wrong certificate or password for existing user"; rtType = MumbleProto::Reject_RejectType_WrongUserPW; - } else if (id==-2 && ! qsPassword.isEmpty() && qsPassword != pw) { + } else if (id == -2 && !qsPassword.isEmpty() && qsPassword != pw) { reason = "Invalid server password"; rtType = MumbleProto::Reject_RejectType_WrongServerPW; - } else if (id==-3) { + } else if (id == -3) { reason = "Your account information can not be verified currently. Please try again later"; rtType = MumbleProto::Reject_RejectType_AuthenticatorFail; } else { @@ -214,11 +214,10 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg } ServerUser *uOld = nullptr; - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u == uSource) continue; - if (((u->iId>=0) && (u->iId == uSource->iId)) || - (u->qsName.toLower() == uSource->qsName.toLower())) { + if (((u->iId >= 0) && (u->iId == uSource->iId)) || (u->qsName.toLower() == uSource->qsName.toLower())) { uOld = u; break; } @@ -226,43 +225,44 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Allow reuse of name from same IP if (ok && uOld && (uSource->iId == -1)) { - if ((uOld->peerAddress() != uSource->peerAddress()) && (uSource->qsHash.isEmpty() || (uSource->qsHash != uOld->qsHash))) { + if ((uOld->peerAddress() != uSource->peerAddress()) + && (uSource->qsHash.isEmpty() || (uSource->qsHash != uOld->qsHash))) { reason = "Username already in use"; rtType = MumbleProto::Reject_RejectType_UsernameInUse; - ok = false; + ok = false; } } if ((id != 0) && (qhUsers.count() > iMaxUsers)) { reason = QString::fromLatin1("Server is full (max %1 users)").arg(iMaxUsers); rtType = MumbleProto::Reject_RejectType_ServerFull; - ok = false; + ok = false; } if ((id != 0) && (uSource->qsHash.isEmpty() && bCertRequired)) { reason = QString::fromLatin1("A certificate is required to connect to this server"); rtType = MumbleProto::Reject_RejectType_NoCertificate; - ok = false; + ok = false; } Channel *lc; lc = qhChannels.value(readLastChannel(uSource->iId)); - if (! lc || ! hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { + if (!lc || !hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { lc = qhChannels.value(iDefaultChan); - if (! lc || ! hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { + if (!lc || !hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { lc = root; if (isChannelFull(lc, uSource)) { reason = QString::fromLatin1("Server channels are full"); rtType = MumbleProto::Reject_RejectType_ServerFull; - ok = false; + ok = false; } } } - if (! ok) { + if (!ok) { log(uSource, QString("Rejected connection from %1: %2") - .arg(addressToString(uSource->peerAddress(), uSource->peerPort()), reason)); + .arg(addressToString(uSource->peerAddress(), uSource->peerPort()), reason)); MumbleProto::Reject mpr; mpr.set_reason(u8(reason)); mpr.set_type(rtType); @@ -299,10 +299,10 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg bool fake_celt_support = false; if (msg.celt_versions_size() > 0) { - for (int i=0;i < msg.celt_versions_size(); ++i) + for (int i = 0; i < msg.celt_versions_size(); ++i) uSource->qlCodecs.append(msg.celt_versions(i)); } else { - uSource->qlCodecs.append(static_cast<qint32>(0x8000000b)); + uSource->qlCodecs.append(static_cast< qint32 >(0x8000000b)); fake_celt_support = true; } uSource->bOpus = msg.opus(); @@ -316,15 +316,18 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpcv); if (!bOpus && uSource->bOpus && fake_celt_support) { - sendTextMessage(nullptr, uSource, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the CELT codec, you won't be able to talk to or hear most clients. Please make sure your client was built with CELT support.")); + sendTextMessage( + nullptr, uSource, false, + QLatin1String("<strong>WARNING:</strong> Your client doesn't support the CELT codec, you won't be able to " + "talk to or hear most clients. Please make sure your client was built with CELT support.")); } // Transmit channel tree - QQueue<Channel *> q; - QSet<Channel *> chans; + QQueue< Channel * > q; + QSet< Channel * > chans; q << root; MumbleProto::ChannelState mpcs; - while (! q.isEmpty()) { + while (!q.isEmpty()) { c = q.dequeue(); chans.insert(c); @@ -340,9 +343,9 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpcs.set_position(c->iPosition); - if ((uSource->uiVersion >= 0x010202) && ! c->qbaDescHash.isEmpty()) + if ((uSource->uiVersion >= 0x010202) && !c->qbaDescHash.isEmpty()) mpcs.set_description_hash(blob(c->qbaDescHash)); - else if (! c->qsDesc.isEmpty()) + else if (!c->qsDesc.isEmpty()) mpcs.set_description(u8(c->qsDesc)); mpcs.set_max_users(c->uiMaxUsers); @@ -353,17 +356,17 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpcs); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } // Transmit links - foreach(c, chans) { + foreach (c, chans) { if (c->qhLinks.count() > 0) { mpcs.Clear(); mpcs.set_channel_id(c->iId); - foreach(Channel *l, c->qhLinks.keys()) + foreach (Channel *l, c->qhLinks.keys()) mpcs.add_links(l->iId); sendMessage(uSource, mpcs); } @@ -386,35 +389,37 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg hashAssign(uSource->qbaTexture, uSource->qbaTextureHash, getUserTexture(uSource->iId)); - if (! uSource->qbaTextureHash.isEmpty()) + if (!uSource->qbaTextureHash.isEmpty()) mpus.set_texture_hash(blob(uSource->qbaTextureHash)); - else if (! uSource->qbaTexture.isEmpty()) + else if (!uSource->qbaTexture.isEmpty()) mpus.set_texture(blob(uSource->qbaTexture)); - const QMap<int, QString> &info = getRegistration(uSource->iId); + const QMap< int, QString > &info = getRegistration(uSource->iId); if (info.contains(ServerDB::User_Comment)) { hashAssign(uSource->qsComment, uSource->qbaCommentHash, info.value(ServerDB::User_Comment)); - if (! uSource->qbaCommentHash.isEmpty()) + if (!uSource->qbaCommentHash.isEmpty()) mpus.set_comment_hash(blob(uSource->qbaCommentHash)); - else if (! uSource->qsComment.isEmpty()) + else if (!uSource->qsComment.isEmpty()) mpus.set_comment(u8(uSource->qsComment)); } } - if (! uSource->qsHash.isEmpty()) + if (!uSource->qsHash.isEmpty()) mpus.set_hash(u8(uSource->qsHash)); if (uSource->cChannel->iId != 0) mpus.set_channel_id(uSource->cChannel->iId); sendAll(mpus, 0x010202); - if ((uSource->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(uSource->qbaTexture.constData())) == 600 * 60 * 4)) + if ((uSource->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >(reinterpret_cast< const unsigned char * >(uSource->qbaTexture.constData())) + == 600 * 60 * 4)) mpus.set_texture(blob(uSource->qbaTexture)); - if (! uSource->qsComment.isEmpty()) + if (!uSource->qsComment.isEmpty()) mpus.set_comment(u8(uSource->qsComment)); - sendAll(mpus, ~ 0x010202); + sendAll(mpus, ~0x010202); // Transmit other users profiles - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->sState != ServerUser::Authenticated) continue; @@ -427,11 +432,14 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg if (u->iId >= 0) mpus.set_user_id(u->iId); if (uSource->uiVersion >= 0x010202) { - if (! u->qbaTextureHash.isEmpty()) + if (!u->qbaTextureHash.isEmpty()) mpus.set_texture_hash(blob(u->qbaTextureHash)); - else if (! u->qbaTexture.isEmpty()) + else if (!u->qbaTexture.isEmpty()) mpus.set_texture(blob(u->qbaTexture)); - } else if ((uSource->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(uSource->qbaTexture.constData())) == 600 * 60 * 4)) { + } else if ((uSource->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >( + reinterpret_cast< const unsigned char * >(uSource->qbaTexture.constData())) + == 600 * 60 * 4)) { mpus.set_texture(blob(u->qbaTexture)); } if (u->cChannel->iId != 0) @@ -450,14 +458,14 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpus.set_self_deaf(true); else if (u->bSelfMute) mpus.set_self_mute(true); - if ((uSource->uiVersion >= 0x010202) && ! u->qbaCommentHash.isEmpty()) + if ((uSource->uiVersion >= 0x010202) && !u->qbaCommentHash.isEmpty()) mpus.set_comment_hash(blob(u->qbaCommentHash)); - else if (! u->qsComment.isEmpty()) + else if (!u->qsComment.isEmpty()) mpus.set_comment(u8(u->qsComment)); - if (! u->qsHash.isEmpty()) + if (!u->qsHash.isEmpty()) mpus.set_hash(u8(u->qsHash)); - foreach(int channelID, ChannelListener::getListenedChannelsForUser(u)) { + foreach (int channelID, ChannelListener::getListenedChannelsForUser(u)) { mpus.add_listening_channel_add(channelID); } @@ -467,7 +475,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Send syncronisation packet MumbleProto::ServerSync mpss; mpss.set_session(uSource->uiSession); - if (! qsWelcomeText.isEmpty()) + if (!qsWelcomeText.isEmpty()) mpss.set_welcome_text(u8(qsWelcomeText)); mpss.set_max_bandwidth(iMaxBandwidth); @@ -489,11 +497,11 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpsc); MumbleProto::SuggestConfig mpsug; - if (! qvSuggestVersion.isNull()) + if (!qvSuggestVersion.isNull()) mpsug.set_version(qvSuggestVersion.toUInt()); - if (! qvSuggestPositional.isNull()) + if (!qvSuggestPositional.isNull()) mpsug.set_positional(qvSuggestPositional.toBool()); - if (! qvSuggestPushToTalk.isNull()) + if (!qvSuggestPushToTalk.isNull()) mpsug.set_push_to_talk(qvSuggestPushToTalk.toBool()); #if GOOGLE_PROTOBUF_VERSION >= 3004000 if (mpsug.ByteSizeLong() > 0) { @@ -504,18 +512,23 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpsug); } - if (uSource->uiVersion < 0x010400 && Meta::mp.iMaxListenersPerChannel > 0 && Meta::mp.iMaxListenerProxiesPerUser > 0) { - // The server has the ChannelListener feature enabled but the client that connects doesn't have version 1.4.0 or newer - // meaning that this client doesn't know what ChannelListeners are. Thus we'll send that user a text-message informing - // about this. + if (uSource->uiVersion < 0x010400 && Meta::mp.iMaxListenersPerChannel > 0 + && Meta::mp.iMaxListenerProxiesPerUser > 0) { + // The server has the ChannelListener feature enabled but the client that connects doesn't have version 1.4.0 or + // newer meaning that this client doesn't know what ChannelListeners are. Thus we'll send that user a + // text-message informing about this. MumbleProto::TextMessage mptm; if (Meta::mp.bAllowHTML) { - mptm.set_message("<b>[WARNING]</b>: This server has the <b>ChannelListener</b> feature enabled but your client version does not support it. " - "This means that users <b>might be listening to what you are saying in your channel without you noticing!</b> " - "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); + mptm.set_message("<b>[WARNING]</b>: This server has the <b>ChannelListener</b> feature enabled but your " + "client version does not support it. " + "This means that users <b>might be listening to what you are saying in your channel " + "without you noticing!</b> " + "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); } else { - mptm.set_message("[WARNING]: This server has the ChannelListener feature enabled but your client version does not support it. " + mptm.set_message( + "[WARNING]: This server has the ChannelListener feature enabled but your client version does not " + "support it. " "This means that users might be listening to what you are saying in your channel without you noticing! " "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); } @@ -531,15 +544,15 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { MSG_SETUP(ServerUser::Authenticated); - QSet<Ban> previousBans, newBans; - if (! hasPermission(uSource, qhChannels.value(0), ChanACL::Ban)) { + QSet< Ban > previousBans, newBans; + if (!hasPermission(uSource, qhChannels.value(0), ChanACL::Ban)) { PERM_DENIED(uSource, qhChannels.value(0), ChanACL::Ban); return; } if (msg.query()) { msg.clear_query(); msg.clear_bans(); - foreach(const Ban &b, qlBans) { + foreach (const Ban &b, qlBans) { MumbleProto::BanList_BanEntry *be = msg.add_bans(); be->set_address(b.haAddress.toStdString()); be->set_mask(b.iMask); @@ -552,21 +565,21 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { sendMessage(uSource, msg); } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - previousBans = QSet<Ban>(qlBans.begin(), qlBans.end()); + previousBans = QSet< Ban >(qlBans.begin(), qlBans.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now previousBans = qlBans.toSet(); #endif qlBans.clear(); - for (int i=0;i < msg.bans_size(); ++i) { + for (int i = 0; i < msg.bans_size(); ++i) { const MumbleProto::BanList_BanEntry &be = msg.bans(i); Ban b; - b.haAddress = be.address(); - b.iMask = be.mask(); + b.haAddress = be.address(); + b.iMask = be.mask(); b.qsUsername = u8(be.name()); - b.qsHash = u8(be.hash()); - b.qsReason = u8(be.reason()); + b.qsHash = u8(be.hash()); + b.qsReason = u8(be.reason()); if (be.has_start()) { b.qdtStart = QDateTime::fromString(u8(be.start()), Qt::ISODate); b.qdtStart.setTimeSpec(Qt::UTC); @@ -579,19 +592,15 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { } } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - newBans = QSet<Ban>(qlBans.begin(), qlBans.end()); + newBans = QSet< Ban >(qlBans.begin(), qlBans.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now newBans = qlBans.toSet(); #endif - QSet<Ban> removed = previousBans - newBans; - QSet<Ban> added = newBans - previousBans; - foreach(const Ban &b, removed) { - log(uSource, QString("Removed ban: %1").arg(b.toString())); - } - foreach(const Ban &b, added) { - log(uSource, QString("New ban: %1").arg(b.toString())); - } + QSet< Ban > removed = previousBans - newBans; + QSet< Ban > added = newBans - previousBans; + foreach (const Ban &b, removed) { log(uSource, QString("Removed ban: %1").arg(b.toString())); } + foreach (const Ban &b, added) { log(uSource, QString("New ban: %1").arg(b.toString())); } saveBans(); log(uSource, "Updated banlist"); } @@ -610,7 +619,7 @@ void Server::msgUDPTunnel(ServerUser *uSource, MumbleProto::UDPTunnel &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); const std::string &str = msg.packet(); - int len = static_cast<int>(str.length()); + int len = static_cast< int >(str.length()); if (len < 1) return; QReadLocker rl(&qrwlVoiceThread); @@ -643,10 +652,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (uSource == pDstServerUser) { RATELIMIT(uSource); } - + // Handle potential temporary access tokens QStringList temporaryAccessTokens; - for (int i=0; i < msg.temporary_access_tokens_size(); i++) { + for (int i = 0; i < msg.temporary_access_tokens_size(); i++) { temporaryAccessTokens << u8(msg.temporary_access_tokens(i)); } TemporaryAccessTokenHelper tempTokenHelper(uSource, temporaryAccessTokens, this); @@ -656,12 +665,12 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (!c || (c == pDstServerUser->cChannel)) return; - if ((uSource != pDstServerUser) && (! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Move))) { + if ((uSource != pDstServerUser) && (!hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Move))) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::Move); return; } - if (! hasPermission(uSource, c, ChanACL::Move) && ! hasPermission(pDstServerUser, c, ChanACL::Enter)) { + if (!hasPermission(uSource, c, ChanACL::Move) && !hasPermission(pDstServerUser, c, ChanACL::Enter)) { PERM_DENIED(pDstServerUser, c, ChanACL::Enter); return; } @@ -671,7 +680,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } } - QList<Channel *> listeningChannelsAdd; + QList< Channel * > listeningChannelsAdd; int passedChannelListener = 0; // Check permission for each channel for (int i = 0; i < msg.listening_channel_add_size(); i++) { @@ -687,16 +696,20 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (Meta::mp.iMaxListenersPerChannel >= 0 - && Meta::mp.iMaxListenersPerChannel - ChannelListener::getListenerCountForChannel(c) - 1 < 0) { + && Meta::mp.iMaxListenersPerChannel - ChannelListener::getListenerCountForChannel(c) - 1 < 0) { // A limit for the amount of listener proxies per channel is set and it has been reached already - PERM_DENIED_FALLBACK(ChannelListenerLimit, 0x010400, QLatin1String("No more listeners allowed in this channel")); + PERM_DENIED_FALLBACK(ChannelListenerLimit, 0x010400, + QLatin1String("No more listeners allowed in this channel")); continue; } if (Meta::mp.iMaxListenerProxiesPerUser >= 0 - && Meta::mp.iMaxListenerProxiesPerUser - ChannelListener::getListenedChannelCountForUser(uSource) - passedChannelListener - 1 < 0) { + && Meta::mp.iMaxListenerProxiesPerUser - ChannelListener::getListenedChannelCountForUser(uSource) + - passedChannelListener - 1 + < 0) { // A limit for the amount of listener proxies per user is set and it has been reached already - PERM_DENIED_FALLBACK(UserListenerLimit, 0x010400, QLatin1String("No more listeners allowed in this channel")); + PERM_DENIED_FALLBACK(UserListenerLimit, 0x010400, + QLatin1String("No more listeners allowed in this channel")); continue; } @@ -714,7 +727,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { PERM_DENIED_TYPE(TemporaryChannel); return; } - if (! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen) || msg.suppress()) { + if (!hasPermission(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen) || msg.suppress()) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen); return; } @@ -724,9 +737,9 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_comment()) { bool changed = false; - comment = u8(msg.comment()); + comment = u8(msg.comment()); if (uSource != pDstServerUser) { - if (! hasPermission(uSource, root, ChanACL::ResetUserContent)) { + if (!hasPermission(uSource, root, ChanACL::ResetUserContent)) { PERM_DENIED(uSource, root, ChanACL::ResetUserContent); return; } @@ -737,7 +750,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } - if (! isTextAllowed(comment, changed)) { + if (!isTextAllowed(comment, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -746,12 +759,13 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (msg.has_texture()) { - if (iMaxImageMessageLength > 0 && (msg.texture().length() > static_cast<unsigned int>(iMaxImageMessageLength))) { + if (iMaxImageMessageLength > 0 + && (msg.texture().length() > static_cast< unsigned int >(iMaxImageMessageLength))) { PERM_DENIED_TYPE(TextTooLong); return; } if (uSource != pDstServerUser) { - if (! hasPermission(uSource, root, ChanACL::ResetUserContent)) { + if (!hasPermission(uSource, root, ChanACL::ResetUserContent)) { PERM_DENIED(uSource, root, ChanACL::ResetUserContent); return; } @@ -765,7 +779,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_user_id()) { ChanACL::Perm p = (uSource == pDstServerUser) ? ChanACL::SelfRegister : ChanACL::Register; - if ((pDstServerUser->iId >= 0) || ! hasPermission(uSource, root, p)) { + if ((pDstServerUser->iId >= 0) || !hasPermission(uSource, root, p)) { PERM_DENIED(uSource, root, p); return; } @@ -776,8 +790,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } // Prevent self-targeting state changes from being applied to others - if ((pDstServerUser != uSource) && (msg.has_self_deaf() || msg.has_self_mute() || msg.has_plugin_context() || msg.has_plugin_identity() - || msg.has_recording() || msg.listening_channel_add_size() > 0 || msg.listening_channel_remove_size() > 0)) { + if ((pDstServerUser != uSource) + && (msg.has_self_deaf() || msg.has_self_mute() || msg.has_plugin_context() || msg.has_plugin_identity() + || msg.has_recording() || msg.listening_channel_add_size() > 0 + || msg.listening_channel_remove_size() > 0)) { return; } @@ -790,7 +806,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { QByteArray qba = blob(msg.texture()); if (pDstServerUser->iId > 0) { // For registered users store the texture we just received in the database - if (! setTexture(pDstServerUser->iId, qba)) { + if (!setTexture(pDstServerUser->iId, qba)) { return; } } else { @@ -816,7 +832,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_self_mute()) { uSource->bSelfMute = msg.self_mute(); - if (! uSource->bSelfMute) { + if (!uSource->bSelfMute) { msg.set_self_deaf(false); uSource->bSelfDeaf = false; } @@ -837,11 +853,11 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { msg.clear_plugin_identity(); } - if (! comment.isNull()) { + if (!comment.isNull()) { hashAssign(pDstServerUser->qsComment, pDstServerUser->qbaCommentHash, comment); if (pDstServerUser->iId >= 0) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Comment, pDstServerUser->qsComment); setInfo(pDstServerUser->iId, info); } @@ -862,7 +878,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (msg.has_mute()) { pDstServerUser->bMute = msg.mute(); - if (! pDstServerUser->bMute) { + if (!pDstServerUser->bMute) { msg.set_deaf(false); pDstServerUser->bDeaf = false; } @@ -873,11 +889,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_priority_speaker()) pDstServerUser->bPrioritySpeaker = msg.priority_speaker(); - log(uSource, QString("Changed speak-state of %1 (%2 %3 %4 %5)").arg(QString(*pDstServerUser), - QString::number(pDstServerUser->bMute), - QString::number(pDstServerUser->bDeaf), - QString::number(pDstServerUser->bSuppress), - QString::number(pDstServerUser->bPrioritySpeaker))); + log(uSource, QString("Changed speak-state of %1 (%2 %3 %4 %5)") + .arg(QString(*pDstServerUser), QString::number(pDstServerUser->bMute), + QString::number(pDstServerUser->bDeaf), QString::number(pDstServerUser->bSuppress), + QString::number(pDstServerUser->bPrioritySpeaker))); bBroadcast = true; } @@ -892,7 +907,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { else mptm.set_message(u8(QString(QLatin1String("User '%1' stopped recording")).arg(pDstServerUser->qsName))); - sendAll(mptm, ~ 0x010203); + sendAll(mptm, ~0x010203); bBroadcast = true; } @@ -907,7 +922,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { // Handle channel listening // Note that it is important to handle the listening channels after channel-joins - foreach(Channel *c, listeningChannelsAdd) { + foreach (Channel *c, listeningChannelsAdd) { ChannelListener::addListener(uSource, c); log(QString::fromLatin1("\"%1\" is now listening to channel \"%2\"").arg(QString(*uSource)).arg(QString(*c))); @@ -930,11 +945,11 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { bool bDstAclChanged = false; if (msg.has_user_id()) { // Handle user (Self-)Registration - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, pDstServerUser->qsName); info.insert(ServerDB::User_Hash, pDstServerUser->qsHash); - if (! pDstServerUser->qslEmail.isEmpty()) + if (!pDstServerUser->qslEmail.isEmpty()) info.insert(ServerDB::User_Email, pDstServerUser->qslEmail.first()); int id = registerUser(info); if (id > 0) { @@ -952,24 +967,27 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (bBroadcast) { // Texture handling for clients < 1.2.2. // Send the texture data in the message. - if (msg.has_texture() && (pDstServerUser->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(pDstServerUser->qbaTexture.constData())) != 600 * 60 * 4)) { + if (msg.has_texture() && (pDstServerUser->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >( + reinterpret_cast< const unsigned char * >(pDstServerUser->qbaTexture.constData())) + != 600 * 60 * 4)) { // This is a new style texture, don't send it because the client doesn't handle it correctly / crashes. msg.clear_texture(); - sendAll(msg, ~ 0x010202); + sendAll(msg, ~0x010202); msg.set_texture(blob(pDstServerUser->qbaTexture)); } else { // This is an old style texture, empty texture or there was no texture in this packet, // send the message unchanged. - sendAll(msg, ~ 0x010202); + sendAll(msg, ~0x010202); } // Texture / comment handling for clients >= 1.2.2. // Send only a hash of the texture / comment text. The client will request the actual data if necessary. - if (msg.has_texture() && ! pDstServerUser->qbaTextureHash.isEmpty()) { + if (msg.has_texture() && !pDstServerUser->qbaTextureHash.isEmpty()) { msg.clear_texture(); msg.set_texture_hash(blob(pDstServerUser->qbaTextureHash)); } - if (msg.has_comment() && ! pDstServerUser->qbaCommentHash.isEmpty()) { + if (msg.has_comment() && !pDstServerUser->qbaCommentHash.isEmpty()) { msg.clear_comment(); msg.set_comment_hash(blob(pDstServerUser->qbaCommentHash)); } @@ -996,23 +1014,23 @@ void Server::msgUserRemove(ServerUser *uSource, MumbleProto::UserRemove &msg) { bool ban = msg.has_ban() && msg.ban(); - Channel *c = qhChannels.value(0); - QFlags<ChanACL::Perm> perm = ban ? ChanACL::Ban : (ChanACL::Ban|ChanACL::Kick); + Channel *c = qhChannels.value(0); + QFlags< ChanACL::Perm > perm = ban ? ChanACL::Ban : (ChanACL::Ban | ChanACL::Kick); - if ((pDstServerUser->iId ==0) || ! hasPermission(uSource, c, perm)) { + if ((pDstServerUser->iId == 0) || !hasPermission(uSource, c, perm)) { PERM_DENIED(uSource, c, perm); return; } if (ban) { Ban b; - b.haAddress = pDstServerUser->haAddress; - b.iMask = 128; - b.qsReason = u8(msg.reason()); + b.haAddress = pDstServerUser->haAddress; + b.iMask = 128; + b.qsReason = u8(msg.reason()); b.qsUsername = pDstServerUser->qsName; - b.qsHash = pDstServerUser->qsHash; - b.qdtStart = QDateTime::currentDateTime().toUTC(); - b.iDuration = 0; + b.qsHash = pDstServerUser->qsHash; + b.qdtStart = QDateTime::currentDateTime().toUTC(); + b.iDuration = 0; qlBans << b; saveBans(); } @@ -1034,7 +1052,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // If this message relates to an existing channel check if the id is really valid if (msg.has_channel_id()) { c = qhChannels.value(msg.channel_id()); - if (! c) + if (!c) return; } else { RATELIMIT(uSource); @@ -1043,7 +1061,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // Check if the parent exists if (msg.has_parent()) { p = qhChannels.value(msg.parent()); - if (! p) + if (!p) return; } @@ -1052,9 +1070,9 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg QString qsName; QString qsDesc; if (msg.has_description()) { - qsDesc = u8(msg.description()); + qsDesc = u8(msg.description()); bool changed = false; - if (! isTextAllowed(qsDesc, changed)) { + if (!isTextAllowed(qsDesc, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -1067,7 +1085,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // check if the name is valid and not already in use. qsName = u8(msg.name()); - if (! validateChannelName(qsName)) { + if (!validateChannelName(qsName)) { PERM_DENIED_TYPE(ChannelName); return; } @@ -1079,7 +1097,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg if (p || (c && c->iId != 0)) { Channel *cp = p ? p : c->cParent; - foreach(Channel *sibling, cp->qlChannels) { + foreach (Channel *sibling, cp->qlChannels) { if (sibling->qsName == qsName) { PERM_DENIED_TYPE(ChannelName); return; @@ -1088,7 +1106,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } } - if(p) { + if (p) { // Having a parent channel given means we either want to create // a channel in or move a channel into this parent. @@ -1098,19 +1116,19 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } } - if (! c) { + if (!c) { // If we don't have a channel handle up to now we want to create a new channel // so check if the user has enough rights and we got everything we need. - if (! p || qsName.isNull()) + if (!p || qsName.isNull()) return; if (iChannelCountLimit != 0 && qhChannels.count() >= iChannelCountLimit) { PERM_DENIED_FALLBACK(ChannelCountLimit, 0x010300, QLatin1String("Channel count limit reached")); return; } - + ChanACL::Perm perm = msg.temporary() ? ChanACL::MakeTempChannel : ChanACL::MakeChannel; - if (! hasPermission(uSource, p, perm)) { + if (!hasPermission(uSource, p, perm)) { PERM_DENIED(uSource, p, perm); return; } @@ -1133,16 +1151,16 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg g->qsAdd << uSource->iId; } - if (! hasPermission(uSource, c, ChanACL::Write)) { - ChanACL *a = new ChanACL(c); - a->bApplyHere=true; - a->bApplySubs=false; + if (!hasPermission(uSource, c, ChanACL::Write)) { + ChanACL *a = new ChanACL(c); + a->bApplyHere = true; + a->bApplySubs = false; if (uSource->iId >= 0) - a->iUserId=uSource->iId; + a->iUserId = uSource->iId; else - a->qsGroup=QLatin1Char('$') + uSource->qsHash; - a->pDeny=ChanACL::None; - a->pAllow=ChanACL::Write | ChanACL::Traverse; + a->qsGroup = QLatin1Char('$') + uSource->qsHash; + a->pDeny = ChanACL::None; + a->pAllow = ChanACL::Write | ChanACL::Traverse; clearACLCache(); } @@ -1152,8 +1170,8 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg log(uSource, QString("Added channel %1 under %2").arg(QString(*c), QString(*p))); emit channelCreated(c); - sendAll(msg, ~ 0x010202); - if (! c->qbaDescHash.isEmpty()) { + sendAll(msg, ~0x010202); + if (!c->qbaDescHash.isEmpty()) { msg.clear_description(); msg.set_description_hash(blob(c->qbaDescHash)); } @@ -1171,20 +1189,20 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } else { // The message is related to an existing channel c so check if the user is allowed to modify it // and perform the modifications - if (! qsName.isNull()) { - if (! hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { + if (!qsName.isNull()) { + if (!hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } } - if (! qsDesc.isNull()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!qsDesc.isNull()) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } } if (msg.has_position()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1208,49 +1226,49 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg return; } - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } - if (! hasPermission(uSource, p, ChanACL::MakeChannel)) { + if (!hasPermission(uSource, p, ChanACL::MakeChannel)) { PERM_DENIED(uSource, p, ChanACL::MakeChannel); return; } QString name = qsName.isNull() ? c->qsName : qsName; - foreach(Channel *sibling, p->qlChannels) { + foreach (Channel *sibling, p->qlChannels) { if (sibling->qsName == name) { PERM_DENIED_TYPE(ChannelName); return; } } } - QList<Channel *> qlAdd; - QList<Channel *> qlRemove; + QList< Channel * > qlAdd; + QList< Channel * > qlRemove; if (msg.links_add_size() || msg.links_remove_size()) { - if (! hasPermission(uSource, c, ChanACL::LinkChannel)) { + if (!hasPermission(uSource, c, ChanACL::LinkChannel)) { PERM_DENIED(uSource, c, ChanACL::LinkChannel); return; } if (msg.links_remove_size()) { - for (int i=0;i < msg.links_remove_size(); ++i) { + for (int i = 0; i < msg.links_remove_size(); ++i) { unsigned int link = msg.links_remove(i); - Channel *l = qhChannels.value(link); - if (! l) + Channel *l = qhChannels.value(link); + if (!l) return; qlRemove << l; } } if (msg.links_add_size()) { - for (int i=0;i < msg.links_add_size(); ++i) { + for (int i = 0; i < msg.links_add_size(); ++i) { unsigned int link = msg.links_add(i); - Channel *l = qhChannels.value(link); - if (! l) + Channel *l = qhChannels.value(link); + if (!l) return; - if (! hasPermission(uSource, l, ChanACL::LinkChannel)) { + if (!hasPermission(uSource, l, ChanACL::LinkChannel)) { PERM_DENIED(uSource, l, ChanACL::LinkChannel); return; } @@ -1260,7 +1278,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } if (msg.has_max_users()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1269,9 +1287,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // All permission checks done -- the update is good. if (p) { - log(uSource, QString("Moved channel %1 from %2 to %3").arg(QString(*c), - QString(* c->cParent), - QString(*p))); + log(uSource, QString("Moved channel %1 from %2 to %3").arg(QString(*c), QString(*c->cParent), QString(*p))); { QWriteLocker wl(&qrwlVoiceThread); @@ -1279,23 +1295,18 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg p->addChannel(c); } } - if (! qsName.isNull()) { - log(uSource, QString("Renamed channel %1 to %2").arg(QString(*c), - QString(qsName))); + if (!qsName.isNull()) { + log(uSource, QString("Renamed channel %1 to %2").arg(QString(*c), QString(qsName))); c->qsName = qsName; } - if (! qsDesc.isNull()) + if (!qsDesc.isNull()) hashAssign(c->qsDesc, c->qbaDescHash, qsDesc); if (msg.has_position()) c->iPosition = msg.position(); - foreach(Channel *l, qlAdd) { - addLink(c, l); - } - foreach(Channel *l, qlRemove) { - removeLink(c, l); - } + foreach (Channel *l, qlAdd) { addLink(c, l); } + foreach (Channel *l, qlRemove) { removeLink(c, l); } if (msg.has_max_users()) c->uiMaxUsers = msg.max_users(); @@ -1303,8 +1314,8 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg updateChannel(c); emit channelStateChanged(c); - sendAll(msg, ~ 0x010202); - if (msg.has_description() && ! c->qbaDescHash.isEmpty()) { + sendAll(msg, ~0x010202); + if (msg.has_description() && !c->qbaDescHash.isEmpty()) { msg.clear_description(); msg.set_description_hash(blob(c->qbaDescHash)); } @@ -1319,7 +1330,7 @@ void Server::msgChannelRemove(ServerUser *uSource, MumbleProto::ChannelRemove &m if (!c) return; - if (! hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { + if (!hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1335,8 +1346,8 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) TextMessage tm; // for signal userTextMessage - QSet<ServerUser *> users; - QQueue<Channel *> q; + QSet< ServerUser * > users; + QQueue< Channel * > q; RATELIMIT(uSource); @@ -1359,7 +1370,7 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) QString text = u8(msg.message()); bool changed = false; - if (! isTextAllowed(text, changed)) { + if (!isTextAllowed(text, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -1371,7 +1382,8 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) tm.qsText = text; { // Happy easter - char m[29] = {0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, 0160, 0157, 0144, 040, 0142, 0141, 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, 0}; + char m[29] = { 0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, 0160, 0157, 0144, 040, 0142, 0141, + 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, 0 }; if (msg.channel_id_size() == 1 && msg.channel_id(0) == 0 && msg.message() == m) { PERM_DENIED_TYPE(H9K); return; @@ -1379,32 +1391,32 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) } msg.set_actor(uSource->uiSession); - for (int i=0;i<msg.channel_id_size(); ++i) { + for (int i = 0; i < msg.channel_id_size(); ++i) { unsigned int id = msg.channel_id(i); Channel *c = qhChannels.value(id); - if (! c) + if (!c) return; - if (! ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, c, ChanACL::TextMessage); return; } - foreach(User *p, c->qlUsers) - users.insert(static_cast<ServerUser *>(p)); + foreach (User *p, c->qlUsers) + users.insert(static_cast< ServerUser * >(p)); tm.qlChannels.append(id); } - for (int i=0;i<msg.tree_id_size(); ++i) { + for (int i = 0; i < msg.tree_id_size(); ++i) { unsigned int id = msg.tree_id(i); Channel *c = qhChannels.value(id); - if (! c) + if (!c) return; - if (! ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, c, ChanACL::TextMessage); return; } @@ -1414,21 +1426,21 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) tm.qlTrees.append(id); } - while (! q.isEmpty()) { + while (!q.isEmpty()) { Channel *c = q.dequeue(); if (ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { - foreach(Channel *sub, c->qlChannels) + foreach (Channel *sub, c->qlChannels) q.enqueue(sub); - foreach(User *p, c->qlUsers) - users.insert(static_cast<ServerUser *>(p)); + foreach (User *p, c->qlUsers) + users.insert(static_cast< ServerUser * >(p)); } } - for (int i=0;i < msg.session_size(); ++i) { + for (int i = 0; i < msg.session_size(); ++i) { unsigned int session = msg.session(i); - ServerUser *u = qhUsers.value(session); + ServerUser *u = qhUsers.value(session); if (u) { - if (! ChanACL::hasPermission(uSource, u->cChannel, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, u->cChannel, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, u->cChannel, ChanACL::TextMessage); return; } @@ -1440,7 +1452,7 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) users.remove(uSource); - foreach(ServerUser *u, users) + foreach (ServerUser *u, users) sendMessage(u, msg); emit userTextMessage(uSource, tm); @@ -1460,24 +1472,29 @@ void logGroups(Server *server, const Channel *c, QString prefix = QString()) { server->log(QString::fromLatin1("Channel %1 (%2) has no groups set").arg(c->qsName).arg(c->iId)); return; } else { - server->log(QString::fromLatin1("%1Listing groups specified for channel \"%2\" (%3)...").arg(prefix.isEmpty() - ? QLatin1String("") : QLatin1String("\t")).arg(c->qsName).arg(c->iId)); + server->log(QString::fromLatin1("%1Listing groups specified for channel \"%2\" (%3)...") + .arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")) + .arg(c->qsName) + .arg(c->iId)); } - foreach(Group *currentGroup, c->qhGroups) { + foreach (Group *currentGroup, c->qhGroups) { QString memberList; - foreach(int m, currentGroup->members()) { + foreach (int m, currentGroup->members()) { memberList += QString::fromLatin1("\"%1\"").arg(server->getUserName(m)); memberList += ", "; } if (currentGroup->members().size() > 0) { - memberList.remove(memberList.length() -2, 2); - server->log(QString::fromLatin1("%1Group: \"%2\" contains following users: %3").arg(prefix.isEmpty() - ? QLatin1String("\t") : QLatin1String("\t\t")).arg(currentGroup->qsName).arg(memberList)); + memberList.remove(memberList.length() - 2, 2); + server->log(QString::fromLatin1("%1Group: \"%2\" contains following users: %3") + .arg(prefix.isEmpty() ? QLatin1String("\t") : QLatin1String("\t\t")) + .arg(currentGroup->qsName) + .arg(memberList)); } else { - server->log(QString::fromLatin1("%1Group \"%2\" doesn't contain any users").arg(prefix.isEmpty() - ? QLatin1String("\t") : QLatin1String("\t\t")).arg(currentGroup->qsName)); + server->log(QString::fromLatin1("%1Group \"%2\" doesn't contain any users") + .arg(prefix.isEmpty() ? QLatin1String("\t") : QLatin1String("\t\t")) + .arg(currentGroup->qsName)); } } } @@ -1492,8 +1509,10 @@ void logACLs(Server *server, const Channel *c, QString prefix = QString()) { server->log(prefix); } - foreach(const ChanACL *a, c->qlACL) { - server->log(QString::fromLatin1("%1%2").arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")).arg(static_cast<QString>(*a))); + foreach (const ChanACL *a, c->qlACL) { + server->log(QString::fromLatin1("%1%2") + .arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")) + .arg(static_cast< QString >(*a))); } } @@ -1505,7 +1524,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { if (!c) return; - if (! hasPermission(uSource, c, ChanACL::Write) && !(c->cParent && hasPermission(uSource, c->cParent, ChanACL::Write))) { + if (!hasPermission(uSource, c, ChanACL::Write) + && !(c->cParent && hasPermission(uSource, c->cParent, ChanACL::Write))) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1513,11 +1533,11 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { RATELIMIT(uSource); if (msg.has_query() && msg.query()) { - QStack<Channel *> chans; + QStack< Channel * > chans; Channel *p; ChanACL *acl; - QSet<int> qsId; + QSet< int > qsId; msg.clear_groups(); msg.clear_acls(); @@ -1527,15 +1547,15 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { p = c; while (p) { chans.push(p); - if ((p==c) || p->bInheritACL) + if ((p == c) || p->bInheritACL) p = p->cParent; else p = nullptr; } - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { + foreach (acl, p->qlACL) { if ((p == c) || (acl->bApplySubs)) { MumbleProto::ACL_ChanACL *mpacl = msg.add_acls(); @@ -1553,10 +1573,10 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { } } - p = c->cParent; - QSet<QString> allnames=Group::groupNames(c); - foreach(const QString &name, allnames) { - Group *g = c->qhGroups.value(name); + p = c->cParent; + QSet< QString > allnames = Group::groupNames(c); + foreach (const QString &name, allnames) { + Group *g = c->qhGroups.value(name); Group *pg = p ? Group::getGroup(p, name) : nullptr; MumbleProto::ACL_ChanGroup *group = msg.add_groups(); @@ -1565,17 +1585,17 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { group->set_inheritable(g ? g->bInheritable : true); group->set_inherited(pg && pg->bInheritable); if (g) { - foreach(int id, g->qsAdd) { + foreach (int id, g->qsAdd) { qsId.insert(id); group->add_add(id); } - foreach(int id, g->qsRemove) { + foreach (int id, g->qsRemove) { qsId.insert(id); group->add_remove(id); } } if (pg) { - foreach(int id, pg->members()) { + foreach (int id, pg->members()) { qsId.insert(id); group->add_inherited_members(id); } @@ -1585,9 +1605,9 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { sendMessage(uSource, msg); MumbleProto::QueryUsers mpqu; - foreach(int id, qsId) { - QString uname=getUserName(id); - if (! uname.isEmpty()) { + foreach (int id, qsId) { + QString uname = getUserName(id); + if (!uname.isEmpty()) { mpqu.add_ids(id); mpqu.add_names(u8(uname)); } @@ -1601,7 +1621,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { { QWriteLocker wl(&qrwlVoiceThread); - QHash<QString, QSet<int> > hOldTemp; + QHash< QString, QSet< int > > hOldTemp; if (Meta::mp.bLogGroupChanges || Meta::mp.bLogACLChanges) { log(uSource, QString::fromLatin1("Updating ACL in channel %1").arg(*c)); @@ -1611,7 +1631,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { logGroups(this, c, QLatin1String("These are the groups before applying the change:")); } - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } @@ -1621,9 +1641,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { } // Clear old ACLs - foreach(a, c->qlACL) { - delete a; - } + foreach (a, c->qlACL) { delete a; } c->qhGroups.clear(); c->qlACL.clear(); @@ -1633,9 +1651,9 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { // Add new groups for (int i = 0; i < msg.groups_size(); ++i) { const MumbleProto::ACL_ChanGroup &group = msg.groups(i); - g = new Group(c, u8(group.name())); - g->bInherit = group.inherit(); - g->bInheritable = group.inheritable(); + g = new Group(c, u8(group.name())); + g->bInherit = group.inherit(); + g->bInheritable = group.inheritable(); for (int j = 0; j < group.add_size(); ++j) if (!getUserName(group.add(j)).isEmpty()) g->qsAdd << group.add(j); @@ -1656,30 +1674,29 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { if (mpacl.has_user_id() && getUserName(mpacl.user_id()).isEmpty()) continue; - a = new ChanACL(c); + a = new ChanACL(c); a->bApplyHere = mpacl.apply_here(); a->bApplySubs = mpacl.apply_subs(); if (mpacl.has_user_id()) a->iUserId = mpacl.user_id(); else a->qsGroup = u8(mpacl.group()); - a->pDeny = static_cast<ChanACL::Permissions>(mpacl.deny()) & ChanACL::All; - a->pAllow = static_cast<ChanACL::Permissions>(mpacl.grant()) & ChanACL::All; + a->pDeny = static_cast< ChanACL::Permissions >(mpacl.deny()) & ChanACL::All; + a->pAllow = static_cast< ChanACL::Permissions >(mpacl.grant()) & ChanACL::All; } if (Meta::mp.bLogACLChanges) { logACLs(this, c, QLatin1String("And these are the new ACLs:")); } - } clearACLCache(); - if (! hasPermission(uSource, c, ChanACL::Write) && ((uSource->iId >= 0) || !uSource->qsHash.isEmpty())) { + if (!hasPermission(uSource, c, ChanACL::Write) && ((uSource->iId >= 0) || !uSource->qsHash.isEmpty())) { { QWriteLocker wl(&qrwlVoiceThread); - a = new ChanACL(c); + a = new ChanACL(c); a->bApplyHere = true; a->bApplySubs = false; if (uSource->iId >= 0) @@ -1687,8 +1704,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { else a->qsGroup = QLatin1Char('$') + uSource->qsHash; a->iUserId = uSource->iId; - a->pDeny = ChanACL::None; - a->pAllow = ChanACL::Write | ChanACL::Traverse; + a->pDeny = ChanACL::None; + a->pAllow = ChanACL::Write | ChanACL::Traverse; } clearACLCache(); @@ -1701,7 +1718,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { // Send refreshed enter states of this channel to all clients MumbleProto::ChannelState mpcs; mpcs.set_channel_id(c->iId); - foreach(ServerUser *user, qhUsers) { + foreach (ServerUser *user, qhUsers) { mpcs.set_is_enter_restricted(isChannelEnterRestricted(c)); mpcs.set_can_enter(ChanACL::hasPermission(user, c, ChanACL::Enter, &acCache)); @@ -1715,20 +1732,20 @@ void Server::msgQueryUsers(ServerUser *uSource, MumbleProto::QueryUsers &msg) { MumbleProto::QueryUsers reply; - for (int i=0;i<msg.ids_size();++i) { + for (int i = 0; i < msg.ids_size(); ++i) { int id = msg.ids(i); if (id >= 0) { const QString &name = getUserName(id); - if (! name.isEmpty()) { + if (!name.isEmpty()) { reply.add_ids(id); reply.add_names(u8(name)); } } } - for (int i=0;i<msg.names_size();++i) { + for (int i = 0; i < msg.names_size(); ++i) { QString name = u8(msg.names(i)); - int id = getUserID(name); + int id = getUserID(name); if (id >= 0) { name = getUserName(id); reply.add_ids(id); @@ -1744,16 +1761,16 @@ void Server::msgPing(ServerUser *uSource, MumbleProto::Ping &msg) { QMutexLocker l(&uSource->qmCrypt); - uSource->csCrypt->uiRemoteGood = msg.good(); - uSource->csCrypt->uiRemoteLate = msg.late(); - uSource->csCrypt->uiRemoteLost = msg.lost(); + uSource->csCrypt->uiRemoteGood = msg.good(); + uSource->csCrypt->uiRemoteLate = msg.late(); + uSource->csCrypt->uiRemoteLost = msg.lost(); uSource->csCrypt->uiRemoteResync = msg.resync(); - uSource->dUDPPingAvg = msg.udp_ping_avg(); - uSource->dUDPPingVar = msg.udp_ping_var(); + uSource->dUDPPingAvg = msg.udp_ping_avg(); + uSource->dUDPPingVar = msg.udp_ping_var(); uSource->uiUDPPackets = msg.udp_packets(); - uSource->dTCPPingAvg = msg.tcp_ping_avg(); - uSource->dTCPPingVar = msg.tcp_ping_var(); + uSource->dTCPPingAvg = msg.tcp_ping_avg(); + uSource->dTCPPingVar = msg.tcp_ping_var(); uSource->uiTCPPackets = msg.tcp_packets(); quint64 ts = msg.timestamp(); @@ -1773,14 +1790,14 @@ void Server::msgCryptSetup(ServerUser *uSource, MumbleProto::CryptSetup &msg) { QMutexLocker l(&uSource->qmCrypt); - if (! msg.has_client_nonce()) { + if (!msg.has_client_nonce()) { log(uSource, "Requested crypt-nonce resync"); msg.set_server_nonce(uSource->csCrypt->getEncryptIV()); sendMessage(uSource, msg); } else { const std::string &str = msg.client_nonce(); uSource->csCrypt->uiResync++; - if(!uSource->csCrypt->setDecryptIV(str)){ + if (!uSource->csCrypt->setDecryptIV(str)) { qWarning("Messages: Cipher resync failed: Invalid nonce from the client!"); } } @@ -1793,11 +1810,11 @@ void Server::msgContextAction(ServerUser *uSource, MumbleProto::ContextAction &m MSG_SETUP(ServerUser::Authenticated); unsigned int session = msg.has_session() ? msg.session() : 0; - int id = msg.has_channel_id() ? static_cast<int>(msg.channel_id()) : -1; + int id = msg.has_channel_id() ? static_cast< int >(msg.channel_id()) : -1; - if (session && ! qhUsers.contains(session)) + if (session && !qhUsers.contains(session)) return; - if ((id >= 0) && ! qhChannels.contains(id)) + if ((id >= 0) && !qhChannels.contains(id)) return; emit contextAction(uSource, u8(msg.action()), session, id); } @@ -1819,7 +1836,7 @@ void Server::msgVersion(ServerUser *uSource, MumbleProto::Version &msg) { RATELIMIT(uSource); if (msg.has_version()) { - uSource->uiVersion=msg.version(); + uSource->uiVersion = msg.version(); } if (msg.has_release()) { uSource->qsRelease = convertWithSizeRestriction(msg.release(), 100); @@ -1832,7 +1849,11 @@ void Server::msgVersion(ServerUser *uSource, MumbleProto::Version &msg) { } } - log(uSource, QString("Client version %1 (%2 %3: %4)").arg(MumbleVersion::toString(uSource->uiVersion)).arg(uSource->qsOS).arg(uSource->qsOSVersion).arg(uSource->qsRelease)); + log(uSource, QString("Client version %1 (%2 %3: %4)") + .arg(MumbleVersion::toString(uSource->uiVersion)) + .arg(uSource->qsOS) + .arg(uSource->qsOSVersion) + .arg(uSource->qsRelease)); } void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { @@ -1840,15 +1861,15 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { // The register permission is required on the root channel to be allowed to // view the registered users. - if (! hasPermission(uSource, qhChannels.value(0), ChanACL::Register)) { + if (!hasPermission(uSource, qhChannels.value(0), ChanACL::Register)) { PERM_DENIED(uSource, qhChannels.value(0), ChanACL::Register); return; } if (msg.users_size() == 0) { // Query mode. - QList<UserInfo> users = getRegisteredUsersEx(); - QList<UserInfo>::const_iterator it = users.constBegin(); + QList< UserInfo > users = getRegisteredUsersEx(); + QList< UserInfo >::const_iterator it = users.constBegin(); for (; it != users.constEnd(); ++it) { // Skip the SuperUser if (it->user_id > 0) { @@ -1864,14 +1885,14 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { sendMessage(uSource, msg); } else { // Update mode - for (int i=0; i < msg.users_size(); ++i) { + for (int i = 0; i < msg.users_size(); ++i) { const MumbleProto::UserList_User &user = msg.users(i); int id = user.user_id(); if (id == 0) continue; - if (! user.has_name()) { + if (!user.has_name()) { log(uSource, QString::fromLatin1("Unregistered user %1").arg(id)); unregisterUser(id); } else { @@ -1879,12 +1900,12 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { if (validateUserName(name)) { log(uSource, QString::fromLatin1("Renamed user %1 to '%2'").arg(QString::number(id), name)); - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, name); setInfo(id, info); MumbleProto::UserState mpus; - foreach(ServerUser *serverUser, qhUsers) { + foreach (ServerUser *serverUser, qhUsers) { if (serverUser->iId == id) { serverUser->qsName = name; mpus.set_session(serverUser->uiSession); @@ -1926,9 +1947,9 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) uSource->qmTargets.remove(target); } else { WhisperTarget wt; - for (int i=0;i<count;++i) { + for (int i = 0; i < count; ++i) { const MumbleProto::VoiceTarget_Target &t = msg.targets(i); - for (int j=0;j<t.session_size(); ++j) { + for (int j = 0; j < t.session_size(); ++j) { unsigned int s = t.session(j); if (qhUsers.contains(s)) wt.qlSessions << s; @@ -1937,9 +1958,9 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) unsigned int id = t.channel_id(); if (qhChannels.contains(id)) { WhisperTarget::Channel wtc; - wtc.iId = id; + wtc.iId = id; wtc.bChildren = t.children(); - wtc.bLinks = t.links(); + wtc.bLinks = t.links(); if (t.has_group()) wtc.qsGroup = u8(t.group()); wt.qlChannels << wtc; @@ -1966,21 +1987,21 @@ void Server::msgPermissionQuery(ServerUser *uSource, MumbleProto::PermissionQuer void Server::msgCodecVersion(ServerUser *, MumbleProto::CodecVersion &) { } -void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { +void Server::msgUserStats(ServerUser *uSource, MumbleProto::UserStats &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); VICTIM_SETUP; - const BandwidthRecord &bwr = pDstServerUser->bwr; - const QList<QSslCertificate> &certs = pDstServerUser->peerCertificateChain(); + const BandwidthRecord &bwr = pDstServerUser->bwr; + const QList< QSslCertificate > &certs = pDstServerUser->peerCertificateChain(); bool extend = (uSource == pDstServerUser) || hasPermission(uSource, qhChannels.value(0), ChanACL::Register); - if (! extend && ! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Enter)) { + if (!extend && !hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Enter)) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::Enter); return; } bool details = extend; - bool local = extend || (pDstServerUser->cChannel == uSource->cChannel); + bool local = extend || (pDstServerUser->cChannel == uSource->cChannel); if (msg.stats_only()) details = false; @@ -1989,7 +2010,7 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { msg.set_session(pDstServerUser->uiSession); if (details) { - foreach(const QSslCertificate &cert, certs) { + foreach (const QSslCertificate &cert, certs) { const QByteArray &der = cert.toDer(); msg.add_certificates(blob(der)); } @@ -2027,15 +2048,15 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { mpv = msg.mutable_version(); if (pDstServerUser->uiVersion) mpv->set_version(pDstServerUser->uiVersion); - if (! pDstServerUser->qsRelease.isEmpty()) + if (!pDstServerUser->qsRelease.isEmpty()) mpv->set_release(u8(pDstServerUser->qsRelease)); - if (! pDstServerUser->qsOS.isEmpty()) { + if (!pDstServerUser->qsOS.isEmpty()) { mpv->set_os(u8(pDstServerUser->qsOS)); - if (! pDstServerUser->qsOSVersion.isEmpty()) + if (!pDstServerUser->qsOSVersion.isEmpty()) mpv->set_os_version(u8(pDstServerUser->qsOSVersion)); } - foreach(int v, pDstServerUser->qlCodecs) + foreach (int v, pDstServerUser->qlCodecs) msg.add_celt_versions(v); msg.set_opus(pDstServerUser->bOpus); @@ -2054,16 +2075,16 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); - int ntextures = msg.session_texture_size(); - int ncomments = msg.session_comment_size(); + int ntextures = msg.session_texture_size(); + int ncomments = msg.session_comment_size(); int ndescriptions = msg.channel_description_size(); if (ndescriptions) { MumbleProto::ChannelState mpcs; - for (int i=0;i<ndescriptions;++i) { - int id = msg.channel_description(i); + for (int i = 0; i < ndescriptions; ++i) { + int id = msg.channel_description(i); Channel *c = qhChannels.value(id); - if (c && ! c->qsDesc.isEmpty()) { + if (c && !c->qsDesc.isEmpty()) { mpcs.set_channel_id(id); mpcs.set_description(u8(c->qsDesc)); sendMessage(uSource, mpcs); @@ -2072,10 +2093,10 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) } if (ntextures || ncomments) { MumbleProto::UserState mpus; - for (int i=0;i<ntextures;++i) { - int session = msg.session_texture(i); + for (int i = 0; i < ntextures; ++i) { + int session = msg.session_texture(i); ServerUser *su = qhUsers.value(session); - if (su && ! su->qbaTexture.isEmpty()) { + if (su && !su->qbaTexture.isEmpty()) { mpus.set_session(session); mpus.set_texture(blob(su->qbaTexture)); sendMessage(uSource, mpus); @@ -2083,10 +2104,10 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) } if (ntextures) mpus.clear_texture(); - for (int i=0;i<ncomments;++i) { - int session = msg.session_comment(i); + for (int i = 0; i < ncomments; ++i) { + int session = msg.session_comment(i); ServerUser *su = qhUsers.value(session); - if (su && ! su->qsComment.isEmpty()) { + if (su && !su->qsComment.isEmpty()) { mpus.set_session(session); mpus.set_comment(u8(su->qsComment)); sendMessage(uSource, mpus); diff --git a/src/murmur/Meta.cpp b/src/murmur/Meta.cpp index e149ebeba..a1d30c7a3 100644 --- a/src/murmur/Meta.cpp +++ b/src/murmur/Meta.cpp @@ -6,38 +6,38 @@ #include "Meta.h" #include "Connection.h" +#include "EnvUtils.h" +#include "FFDHE.h" #include "Net.h" -#include "ServerDB.h" -#include "Server.h" #include "OSInfo.h" -#include "Version.h" #include "SSL.h" -#include "EnvUtils.h" -#include "FFDHE.h" +#include "Server.h" +#include "ServerDB.h" +#include "Version.h" #include <QtCore/QCoreApplication> #include <QtCore/QSettings> #ifdef Q_OS_WIN -# include <QtCore/QStandardPaths> +# include <QtCore/QStandardPaths> #endif #include <QtNetwork/QHostInfo> #include <QtNetwork/QNetworkInterface> #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) -# include <QtNetwork/QSslDiffieHellmanParameters> +# include <QtNetwork/QSslDiffieHellmanParameters> #endif #ifdef Q_OS_WIN -# include <qos2.h> +# include <qos2.h> #else -# include <pwd.h> -# include <sys/resource.h> +# include <pwd.h> +# include <sys/resource.h> #endif -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif MetaParams Meta::mp; @@ -47,43 +47,43 @@ HANDLE Meta::hQoS = nullptr; #endif MetaParams::MetaParams() { - qsPassword = QString(); - usPort = DEFAULT_MUMBLE_PORT; - iTimeout = 30; - iMaxBandwidth = 72000; - iMaxUsers = 1000; - iMaxUsersPerChannel = 0; - iMaxListenersPerChannel = -1; + qsPassword = QString(); + usPort = DEFAULT_MUMBLE_PORT; + iTimeout = 30; + iMaxBandwidth = 72000; + iMaxUsers = 1000; + iMaxUsersPerChannel = 0; + iMaxListenersPerChannel = -1; iMaxListenerProxiesPerUser = -1; - iMaxTextMessageLength = 5000; - iMaxImageMessageLength = 131072; - legacyPasswordHash = false; - kdfIterations = -1; - bAllowHTML = true; - iDefaultChan = 0; - bRememberChan = true; - iRememberChanDuration = 0; - qsWelcomeText = QString(); - qsWelcomeTextFile = QString(); - qsDatabase = QString(); - iSQLiteWAL = 0; - iDBPort = 0; - qsDBusService = "net.sourceforge.mumble.murmur"; - qsDBDriver = "QSQLITE"; - qsLogfile = "murmur.log"; + iMaxTextMessageLength = 5000; + iMaxImageMessageLength = 131072; + legacyPasswordHash = false; + kdfIterations = -1; + bAllowHTML = true; + iDefaultChan = 0; + bRememberChan = true; + iRememberChanDuration = 0; + qsWelcomeText = QString(); + qsWelcomeTextFile = QString(); + qsDatabase = QString(); + iSQLiteWAL = 0; + iDBPort = 0; + qsDBusService = "net.sourceforge.mumble.murmur"; + qsDBDriver = "QSQLITE"; + qsLogfile = "murmur.log"; iLogDays = 31; - iObfuscate = 0; - bSendVersion = true; - bBonjour = true; - bAllowPing = true; - bCertRequired = false; + iObfuscate = 0; + bSendVersion = true; + bBonjour = true; + bAllowPing = true; + bCertRequired = false; bForceExternalAuth = false; - iBanTries = 10; - iBanTimeframe = 120; - iBanTime = 300; + iBanTries = 10; + iBanTimeframe = 120; + iBanTime = 300; bBanSuccessful = true; #ifdef Q_OS_UNIX @@ -93,9 +93,9 @@ MetaParams::MetaParams() { iOpusThreshold = 100; iChannelNestingLimit = 10; - iChannelCountLimit = 1000; + iChannelCountLimit = 1000; - qrUserName = QRegExp(QLatin1String("[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+")); + qrUserName = QRegExp(QLatin1String("[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+")); qrChannelName = QRegExp(QLatin1String("[ \\-=\\w\\#\\[\\]\\{\\}\\(\\)\\@\\|]+")); iMessageLimit = 1; @@ -104,7 +104,7 @@ MetaParams::MetaParams() { qsCiphers = MumbleSSL::defaultOpenSSLCipherString(); bLogGroupChanges = false; - bLogACLChanges = false; + bLogACLChanges = false; qsSettings = nullptr; } @@ -127,7 +127,7 @@ MetaParams::~MetaParams() { * @param settings The QSettings object to read from. If null, the Meta's qsSettings will be used. * @return Setting if valid, default if not or setting not set. */ -template <class T> +template< class T > T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue, QSettings *settings) { // Use qsSettings unless a specific QSettings instance // is requested. @@ -137,12 +137,16 @@ T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue QVariant cfgVariable = settings->value(name, defaultValue); - if (!cfgVariable.convert(QVariant(defaultValue).type())) { // Bit convoluted as canConvert<T>() only does a static check without considering whether say a string like "blub" is actually a valid double (which convert does). - qCritical() << "Configuration variable" << name << "is of invalid format. Set to default value of" << defaultValue << "."; + if (!cfgVariable.convert( + QVariant(defaultValue) + .type())) { // Bit convoluted as canConvert<T>() only does a static check without considering whether + // say a string like "blub" is actually a valid double (which convert does). + qCritical() << "Configuration variable" << name << "is of invalid format. Set to default value of" + << defaultValue << "."; return defaultValue; } - return cfgVariable.value<T>(); + return cfgVariable.value< T >(); } void MetaParams::read(QString fname) { @@ -170,11 +174,11 @@ void MetaParams::read(QString fname) { datapaths << QDir::currentPath(); datapaths << QCoreApplication::instance()->applicationDirPath(); - foreach(const QString &p, datapaths) { - if (! p.isEmpty()) { + foreach (const QString &p, datapaths) { + if (!p.isEmpty()) { QFileInfo fi(p, "murmur.ini"); if (fi.exists() && fi.isReadable()) { - qdBasePath = QDir(p); + qdBasePath = QDir(p); qsAbsSettingsFilePath = fi.absoluteFilePath(); break; } @@ -182,15 +186,15 @@ void MetaParams::read(QString fname) { } if (qsAbsSettingsFilePath.isEmpty()) { QDir::root().mkpath(qdBasePath.absolutePath()); - qdBasePath = QDir(datapaths.at(0)); + qdBasePath = QDir(datapaths.at(0)); qsAbsSettingsFilePath = qdBasePath.absolutePath() + QLatin1String("/murmur.ini"); } } else { QFile f(fname); - if (! f.open(QIODevice::ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { qFatal("Specified ini file %s could not be opened", qPrintable(fname)); } - qdBasePath = QFileInfo(f).absoluteDir(); + qdBasePath = QFileInfo(f).absoluteDir(); qsAbsSettingsFilePath = QFileInfo(f).absoluteFilePath(); f.close(); } @@ -198,47 +202,49 @@ void MetaParams::read(QString fname) { qsSettings = new QSettings(qsAbsSettingsFilePath, QSettings::IniFormat); qsSettings->setIniCodec("UTF-8"); - qWarning("Initializing settings from %s (basepath %s)", qPrintable(qsSettings->fileName()), qPrintable(qdBasePath.absolutePath())); + qWarning("Initializing settings from %s (basepath %s)", qPrintable(qsSettings->fileName()), + qPrintable(qdBasePath.absolutePath())); QString qsHost = qsSettings->value("host", QString()).toString(); - if (! qsHost.isEmpty()) { + if (!qsHost.isEmpty()) { #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(host)) { 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) { qFatal("Lookup of bind hostname %s failed", qPrintable(host)); } } } - foreach(const QHostAddress &qha, qlBind) + foreach (const QHostAddress &qha, qlBind) qWarning("Binding to address %s", qPrintable(qha.toString())); } if (qlBind.isEmpty()) { bool hasipv6 = false; bool hasipv4 = false; - int nif = 0; + int nif = 0; - QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces(); + QList< QNetworkInterface > interfaces = QNetworkInterface::allInterfaces(); if (interfaces.isEmpty()) { qWarning("Meta: Unable to acquire list of network interfaces."); } else { - foreach(const QNetworkInterface &qni, interfaces) { + foreach (const QNetworkInterface &qni, interfaces) { if (!(qni.flags() & QNetworkInterface::IsUp)) continue; if (!(qni.flags() & QNetworkInterface::IsRunning)) @@ -246,7 +252,7 @@ void MetaParams::read(QString fname) { if (qni.flags() & QNetworkInterface::IsLoopBack) continue; - foreach(const QNetworkAddressEntry &qna, qni.addressEntries()) { + foreach (const QNetworkAddressEntry &qna, qni.addressEntries()) { const QHostAddress &qha = qna.ip(); switch (qha.protocol()) { case QAbstractSocket::IPv4Protocol: @@ -284,65 +290,65 @@ void MetaParams::read(QString fname) { } } - qsPassword = typeCheckedFromSettings("serverpassword", qsPassword); - usPort = static_cast<unsigned short>(typeCheckedFromSettings("port", static_cast<uint>(usPort))); - iTimeout = typeCheckedFromSettings("timeout", iTimeout); + qsPassword = typeCheckedFromSettings("serverpassword", qsPassword); + usPort = static_cast< unsigned short >(typeCheckedFromSettings("port", static_cast< uint >(usPort))); + iTimeout = typeCheckedFromSettings("timeout", iTimeout); iMaxTextMessageLength = typeCheckedFromSettings("textmessagelength", iMaxTextMessageLength); - iMaxImageMessageLength = typeCheckedFromSettings("imagemessagelength", iMaxImageMessageLength); - legacyPasswordHash = typeCheckedFromSettings("legacypasswordhash", legacyPasswordHash); - kdfIterations = typeCheckedFromSettings("kdfiterations", -1); - bAllowHTML = typeCheckedFromSettings("allowhtml", bAllowHTML); - iMaxBandwidth = typeCheckedFromSettings("bandwidth", iMaxBandwidth); - iDefaultChan = typeCheckedFromSettings("defaultchannel", iDefaultChan); - bRememberChan = typeCheckedFromSettings("rememberchannel", bRememberChan); - iRememberChanDuration = typeCheckedFromSettings("rememberchannelduration", iRememberChanDuration); - iMaxUsers = typeCheckedFromSettings("users", iMaxUsers); - iMaxUsersPerChannel = typeCheckedFromSettings("usersperchannel", iMaxUsersPerChannel); - iMaxListenersPerChannel = typeCheckedFromSettings("listenersperchannel", iMaxListenersPerChannel); + iMaxImageMessageLength = typeCheckedFromSettings("imagemessagelength", iMaxImageMessageLength); + legacyPasswordHash = typeCheckedFromSettings("legacypasswordhash", legacyPasswordHash); + kdfIterations = typeCheckedFromSettings("kdfiterations", -1); + bAllowHTML = typeCheckedFromSettings("allowhtml", bAllowHTML); + iMaxBandwidth = typeCheckedFromSettings("bandwidth", iMaxBandwidth); + iDefaultChan = typeCheckedFromSettings("defaultchannel", iDefaultChan); + bRememberChan = typeCheckedFromSettings("rememberchannel", bRememberChan); + iRememberChanDuration = typeCheckedFromSettings("rememberchannelduration", iRememberChanDuration); + iMaxUsers = typeCheckedFromSettings("users", iMaxUsers); + iMaxUsersPerChannel = typeCheckedFromSettings("usersperchannel", iMaxUsersPerChannel); + iMaxListenersPerChannel = typeCheckedFromSettings("listenersperchannel", iMaxListenersPerChannel); iMaxListenerProxiesPerUser = typeCheckedFromSettings("listenersperuser", iMaxListenerProxiesPerUser); - qsWelcomeText = typeCheckedFromSettings("welcometext", qsWelcomeText); - qsWelcomeTextFile = typeCheckedFromSettings("welcometextfile", qsWelcomeTextFile); - bCertRequired = typeCheckedFromSettings("certrequired", bCertRequired); - bForceExternalAuth = typeCheckedFromSettings("forceExternalAuth", bForceExternalAuth); + qsWelcomeText = typeCheckedFromSettings("welcometext", qsWelcomeText); + qsWelcomeTextFile = typeCheckedFromSettings("welcometextfile", qsWelcomeTextFile); + bCertRequired = typeCheckedFromSettings("certrequired", bCertRequired); + bForceExternalAuth = typeCheckedFromSettings("forceExternalAuth", bForceExternalAuth); qsDatabase = typeCheckedFromSettings("database", qsDatabase); iSQLiteWAL = typeCheckedFromSettings("sqlite_wal", iSQLiteWAL); - qsDBDriver = typeCheckedFromSettings("dbDriver", qsDBDriver); + qsDBDriver = typeCheckedFromSettings("dbDriver", qsDBDriver); qsDBUserName = typeCheckedFromSettings("dbUsername", qsDBUserName); qsDBPassword = typeCheckedFromSettings("dbPassword", qsDBPassword); qsDBHostName = typeCheckedFromSettings("dbHost", qsDBHostName); - qsDBPrefix = typeCheckedFromSettings("dbPrefix", qsDBPrefix); - qsDBOpts = typeCheckedFromSettings("dbOpts", qsDBOpts); - iDBPort = typeCheckedFromSettings("dbPort", iDBPort); + qsDBPrefix = typeCheckedFromSettings("dbPrefix", qsDBPrefix); + qsDBOpts = typeCheckedFromSettings("dbOpts", qsDBOpts); + iDBPort = typeCheckedFromSettings("dbPort", iDBPort); - qsIceEndpoint = typeCheckedFromSettings("ice", qsIceEndpoint); - qsIceSecretRead = typeCheckedFromSettings("icesecret", qsIceSecretRead); - qsIceSecretRead = typeCheckedFromSettings("icesecretread", qsIceSecretRead); + qsIceEndpoint = typeCheckedFromSettings("ice", qsIceEndpoint); + qsIceSecretRead = typeCheckedFromSettings("icesecret", qsIceSecretRead); + qsIceSecretRead = typeCheckedFromSettings("icesecretread", qsIceSecretRead); qsIceSecretWrite = typeCheckedFromSettings("icesecretwrite", qsIceSecretRead); - qsGRPCAddress = typeCheckedFromSettings("grpc", qsGRPCAddress); - qsGRPCCert = typeCheckedFromSettings("grpccert", qsGRPCCert); - qsGRPCKey = typeCheckedFromSettings("grpckey", qsGRPCKey); + qsGRPCAddress = typeCheckedFromSettings("grpc", qsGRPCAddress); + qsGRPCCert = typeCheckedFromSettings("grpccert", qsGRPCCert); + qsGRPCKey = typeCheckedFromSettings("grpckey", qsGRPCKey); qsGRPCAuthorized = typeCheckedFromSettings("grpcauthorized", qsGRPCAuthorized); iLogDays = typeCheckedFromSettings("logdays", iLogDays); - qsDBus = typeCheckedFromSettings("dbus", qsDBus); + qsDBus = typeCheckedFromSettings("dbus", qsDBus); qsDBusService = typeCheckedFromSettings("dbusservice", qsDBusService); - qsLogfile = typeCheckedFromSettings("logfile", qsLogfile); - qsPid = typeCheckedFromSettings("pidfile", qsPid); + qsLogfile = typeCheckedFromSettings("logfile", qsLogfile); + qsPid = typeCheckedFromSettings("pidfile", qsPid); - qsRegName = typeCheckedFromSettings("registerName", qsRegName); + qsRegName = typeCheckedFromSettings("registerName", qsRegName); qsRegPassword = typeCheckedFromSettings("registerPassword", qsRegPassword); - qsRegHost = typeCheckedFromSettings("registerHostname", qsRegHost); + qsRegHost = typeCheckedFromSettings("registerHostname", qsRegHost); qsRegLocation = typeCheckedFromSettings("registerLocation", qsRegLocation); - qurlRegWeb = QUrl(typeCheckedFromSettings("registerUrl", qurlRegWeb).toString()); - bBonjour = typeCheckedFromSettings("bonjour", bBonjour); + qurlRegWeb = QUrl(typeCheckedFromSettings("registerUrl", qurlRegWeb).toString()); + bBonjour = typeCheckedFromSettings("bonjour", bBonjour); - iBanTries = typeCheckedFromSettings("autobanAttempts", iBanTries); - iBanTimeframe = typeCheckedFromSettings("autobanTimeframe", iBanTimeframe); - iBanTime = typeCheckedFromSettings("autobanTime", iBanTime); + iBanTries = typeCheckedFromSettings("autobanAttempts", iBanTries); + iBanTimeframe = typeCheckedFromSettings("autobanTimeframe", iBanTimeframe); + iBanTime = typeCheckedFromSettings("autobanTime", iBanTime); bBanSuccessful = typeCheckedFromSettings("autobanSuccessfulConnections", bBanSuccessful); qvSuggestVersion = MumbleVersion::getRaw(qsSettings->value("suggestVersion").toString()); @@ -358,12 +364,12 @@ void MetaParams::read(QString fname) { qvSuggestPushToTalk = QVariant(); bLogGroupChanges = typeCheckedFromSettings("loggroupchanges", bLogGroupChanges); - bLogACLChanges = typeCheckedFromSettings("logaclchanges", bLogACLChanges); + bLogACLChanges = typeCheckedFromSettings("logaclchanges", bLogACLChanges); iOpusThreshold = typeCheckedFromSettings("opusthreshold", iOpusThreshold); iChannelNestingLimit = typeCheckedFromSettings("channelnestinglimit", iChannelNestingLimit); - iChannelCountLimit = typeCheckedFromSettings("channelcountlimit", iChannelCountLimit); + iChannelCountLimit = typeCheckedFromSettings("channelcountlimit", iChannelCountLimit); #ifdef Q_OS_UNIX qsName = qsSettings->value("uname").toString(); @@ -372,13 +378,13 @@ void MetaParams::read(QString fname) { bool requested = true; if (qsName.isEmpty()) { // default server user name - qsName = "mumble-server"; + qsName = "mumble-server"; requested = false; } struct passwd *pw = getpwnam(qPrintable(qsName)); if (pw) { - uiUid = pw->pw_uid; - uiGid = pw->pw_gid; + uiUid = pw->pw_uid; + uiGid = pw->pw_gid; qsHome = QString::fromUtf8(pw->pw_dir); } else if (requested) { qFatal("Cannot find username %s", qPrintable(qsName)); @@ -387,7 +393,7 @@ void MetaParams::read(QString fname) { } #endif - qrUserName = QRegExp(typeCheckedFromSettings("username", qrUserName.pattern())); + qrUserName = QRegExp(typeCheckedFromSettings("username", qrUserName.pattern())); qrChannelName = QRegExp(typeCheckedFromSettings("channelname", qrChannelName.pattern())); iMessageLimit = typeCheckedFromSettings("messagelimit", 1); @@ -396,7 +402,7 @@ void MetaParams::read(QString fname) { bool bObfuscate = typeCheckedFromSettings("obfuscate", false); if (bObfuscate) { qWarning("IP address obfuscation enabled."); -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) iObfuscate = QRandomGenerator::global()->generate(); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor @@ -404,47 +410,50 @@ void MetaParams::read(QString fname) { #endif } bSendVersion = typeCheckedFromSettings("sendversion", bSendVersion); - bAllowPing = typeCheckedFromSettings("allowping", bAllowPing); + bAllowPing = typeCheckedFromSettings("allowping", bAllowPing); if (!loadSSLSettings()) { qFatal("MetaParams: Failed to load SSL settings. See previous errors."); } QStringList hosts; - foreach(const QHostAddress &qha, qlBind) { - hosts << qha.toString(); - } - qmConfig.insert(QLatin1String("host"),hosts.join(" ")); - qmConfig.insert(QLatin1String("password"),qsPassword); - qmConfig.insert(QLatin1String("port"),QString::number(usPort)); - qmConfig.insert(QLatin1String("timeout"),QString::number(iTimeout)); + foreach (const QHostAddress &qha, qlBind) { hosts << qha.toString(); } + qmConfig.insert(QLatin1String("host"), hosts.join(" ")); + qmConfig.insert(QLatin1String("password"), qsPassword); + qmConfig.insert(QLatin1String("port"), QString::number(usPort)); + qmConfig.insert(QLatin1String("timeout"), QString::number(iTimeout)); qmConfig.insert(QLatin1String("textmessagelength"), QString::number(iMaxTextMessageLength)); - qmConfig.insert(QLatin1String("legacypasswordhash"), legacyPasswordHash ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("legacypasswordhash"), + legacyPasswordHash ? QLatin1String("true") : QLatin1String("false")); qmConfig.insert(QLatin1String("kdfiterations"), QString::number(kdfIterations)); qmConfig.insert(QLatin1String("allowhtml"), bAllowHTML ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("bandwidth"),QString::number(iMaxBandwidth)); - qmConfig.insert(QLatin1String("users"),QString::number(iMaxUsers)); - qmConfig.insert(QLatin1String("defaultchannel"),QString::number(iDefaultChan)); - qmConfig.insert(QLatin1String("rememberchannel"),bRememberChan ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("rememberchannelduration"),QString::number(iRememberChanDuration)); - qmConfig.insert(QLatin1String("welcometext"),qsWelcomeText); - qmConfig.insert(QLatin1String("welcometextfile"),qsWelcomeTextFile); - qmConfig.insert(QLatin1String("registername"),qsRegName); - qmConfig.insert(QLatin1String("registerpassword"),qsRegPassword); - qmConfig.insert(QLatin1String("registerhostname"),qsRegHost); + qmConfig.insert(QLatin1String("bandwidth"), QString::number(iMaxBandwidth)); + qmConfig.insert(QLatin1String("users"), QString::number(iMaxUsers)); + qmConfig.insert(QLatin1String("defaultchannel"), QString::number(iDefaultChan)); + qmConfig.insert(QLatin1String("rememberchannel"), bRememberChan ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("rememberchannelduration"), QString::number(iRememberChanDuration)); + qmConfig.insert(QLatin1String("welcometext"), qsWelcomeText); + qmConfig.insert(QLatin1String("welcometextfile"), qsWelcomeTextFile); + qmConfig.insert(QLatin1String("registername"), qsRegName); + qmConfig.insert(QLatin1String("registerpassword"), qsRegPassword); + qmConfig.insert(QLatin1String("registerhostname"), qsRegHost); qmConfig.insert(QLatin1String("registerlocation"), qsRegLocation); - qmConfig.insert(QLatin1String("registerurl"),qurlRegWeb.toString()); + qmConfig.insert(QLatin1String("registerurl"), qurlRegWeb.toString()); qmConfig.insert(QLatin1String("bonjour"), bBonjour ? QLatin1String("true") : QLatin1String("false")); qmConfig.insert(QLatin1String("certificate"), QString::fromUtf8(qscCert.toPem())); qmConfig.insert(QLatin1String("key"), QString::fromUtf8(qskKey.toPem())); - qmConfig.insert(QLatin1String("obfuscate"),bObfuscate ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("username"),qrUserName.pattern()); - qmConfig.insert(QLatin1String("channelname"),qrChannelName.pattern()); + qmConfig.insert(QLatin1String("obfuscate"), bObfuscate ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("username"), qrUserName.pattern()); + qmConfig.insert(QLatin1String("channelname"), qrChannelName.pattern()); qmConfig.insert(QLatin1String("certrequired"), bCertRequired ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("forceExternalAuth"), bForceExternalAuth ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("suggestversion"), qvSuggestVersion.isNull() ? QString() : qvSuggestVersion.toString()); - qmConfig.insert(QLatin1String("suggestpositional"), qvSuggestPositional.isNull() ? QString() : qvSuggestPositional.toString()); - qmConfig.insert(QLatin1String("suggestpushtotalk"), qvSuggestPushToTalk.isNull() ? QString() : qvSuggestPushToTalk.toString()); + qmConfig.insert(QLatin1String("forceExternalAuth"), + bForceExternalAuth ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("suggestversion"), + qvSuggestVersion.isNull() ? QString() : qvSuggestVersion.toString()); + qmConfig.insert(QLatin1String("suggestpositional"), + qvSuggestPositional.isNull() ? QString() : qvSuggestPositional.toString()); + qmConfig.insert(QLatin1String("suggestpushtotalk"), + qvSuggestPushToTalk.isNull() ? QString() : qvSuggestPushToTalk.toString()); qmConfig.insert(QLatin1String("opusthreshold"), QString::number(iOpusThreshold)); qmConfig.insert(QLatin1String("channelnestinglimit"), QString::number(iChannelNestingLimit)); qmConfig.insert(QLatin1String("channelcountlimit"), QString::number(iChannelCountLimit)); @@ -458,27 +467,27 @@ bool MetaParams::loadSSLSettings() { QString tmpCiphersStr = typeCheckedFromSettings("sslCiphers", qsCiphers); - QString qsSSLCert = qsSettings->value("sslCert").toString(); - QString qsSSLKey = qsSettings->value("sslKey").toString(); - QString qsSSLCA = qsSettings->value("sslCA").toString(); + QString qsSSLCert = qsSettings->value("sslCert").toString(); + QString qsSSLKey = qsSettings->value("sslKey").toString(); + QString qsSSLCA = qsSettings->value("sslCA").toString(); QString qsSSLDHParams = typeCheckedFromSettings(QLatin1String("sslDHParams"), QString(QLatin1String("@ffdhe2048"))); qbaPassPhrase = qsSettings->value("sslPassPhrase").toByteArray(); QSslCertificate tmpCert; - QList<QSslCertificate> tmpCA; - QList<QSslCertificate> tmpIntermediates; + QList< QSslCertificate > tmpCA; + QList< QSslCertificate > tmpIntermediates; QSslKey tmpKey; QByteArray tmpDHParams; - QList<QSslCipher> tmpCiphers; + QList< QSslCipher > tmpCiphers; - if (! qsSSLCA.isEmpty()) { + if (!qsSSLCA.isEmpty()) { QFile pem(qsSSLCA); if (pem.open(QIODevice::ReadOnly)) { QByteArray qba = pem.readAll(); pem.close(); - QList<QSslCertificate> ql = QSslCertificate::fromData(qba); + QList< QSslCertificate > ql = QSslCertificate::fromData(qba); if (ql.isEmpty()) { qCritical("MetaParams: Failed to parse any CA certificates from %s", qPrintable(qsSSLCA)); return false; @@ -493,7 +502,7 @@ bool MetaParams::loadSSLSettings() { QByteArray crt, key; - if (! qsSSLCert.isEmpty()) { + if (!qsSSLCert.isEmpty()) { QFile pem(qsSSLCert); if (pem.open(QIODevice::ReadOnly)) { crt = pem.readAll(); @@ -503,7 +512,7 @@ bool MetaParams::loadSSLSettings() { return false; } } - if (! qsSSLKey.isEmpty()) { + if (!qsSSLKey.isEmpty()) { QFile pem(qsSSLKey); if (pem.open(QIODevice::ReadOnly)) { key = pem.readAll(); @@ -514,13 +523,13 @@ bool MetaParams::loadSSLSettings() { } } - if (! key.isEmpty() || ! crt.isEmpty()) { - if (! key.isEmpty()) { + if (!key.isEmpty() || !crt.isEmpty()) { + if (!key.isEmpty()) { tmpKey = Server::privateKeyFromPEM(key, qbaPassPhrase); } - if (tmpKey.isNull() && ! crt.isEmpty()) { + if (tmpKey.isNull() && !crt.isEmpty()) { tmpKey = Server::privateKeyFromPEM(crt, qbaPassPhrase); - if (! tmpKey.isNull()) + if (!tmpKey.isNull()) qCritical("MetaParams: Using private key found in certificate file."); } if (tmpKey.isNull()) { @@ -528,9 +537,9 @@ bool MetaParams::loadSSLSettings() { return false; } - QList<QSslCertificate> ql = QSslCertificate::fromData(crt); + QList< QSslCertificate > ql = QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); - for (int i=0;i<ql.size(); ++i) { + for (int i = 0; i < ql.size(); ++i) { const QSslCertificate &c = ql.at(i); if (Server::isKeyForCert(tmpKey, c)) { tmpCert = c; @@ -551,18 +560,17 @@ bool MetaParams::loadSSLSettings() { QByteArray dhparams; #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - if (! qsSSLDHParams.isEmpty()) { + if (!qsSSLDHParams.isEmpty()) { if (qsSSLDHParams.startsWith(QLatin1String("@"))) { - QString group = qsSSLDHParams.mid(1).trimmed(); + QString group = qsSSLDHParams.mid(1).trimmed(); QByteArray pem = FFDHE::PEMForNamedGroup(group); if (pem.isEmpty()) { QStringList names = FFDHE::NamedGroups(); QStringList atNames; - foreach (QString name, names) { - atNames << QLatin1String("@") + name; - } + foreach (QString name, names) { atNames << QLatin1String("@") + name; } QString supported = atNames.join(QLatin1String(", ")); - qFatal("MetaParms: Diffie-Hellman parameters with name '%s' is not available. (Supported: %s)", qPrintable(qsSSLDHParams), qPrintable(supported)); + qFatal("MetaParms: Diffie-Hellman parameters with name '%s' is not available. (Supported: %s)", + qPrintable(qsSSLDHParams), qPrintable(supported)); } dhparams = pem; } else { @@ -576,7 +584,7 @@ bool MetaParams::loadSSLSettings() { } } - if (! dhparams.isEmpty()) { + if (!dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters::fromEncoded(dhparams); if (qdhp.isValid()) { tmpDHParams = dhparams; @@ -587,16 +595,19 @@ bool MetaParams::loadSSLSettings() { } #else QString qsSSLDHParamsIniValue = qsSettings->value(QLatin1String("sslDHParams")).toString(); - if (! qsSSLDHParamsIniValue.isEmpty()) { - qFatal("MetaParams: This version of Murmur does not support Diffie-Hellman parameters (sslDHParams). Murmur will not start unless you remove the option from your murmur.ini file."); + if (!qsSSLDHParamsIniValue.isEmpty()) { + qFatal("MetaParams: This version of Murmur does not support Diffie-Hellman parameters (sslDHParams). Murmur " + "will not start unless you remove the option from your murmur.ini file."); return false; } #endif { - QList<QSslCipher> ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(tmpCiphersStr); + QList< QSslCipher > ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(tmpCiphersStr); if (ciphers.isEmpty()) { - qCritical("MetaParams: Invalid sslCiphers option. Either the cipher string is invalid or none of the ciphers are available: \"%s\"", qPrintable(qsCiphers)); + qCritical("MetaParams: Invalid sslCiphers option. Either the cipher string is invalid or none of the " + "ciphers are available: \"%s\"", + qPrintable(qsCiphers)); return false; } @@ -606,7 +617,7 @@ bool MetaParams::loadSSLSettings() { // Hellman cipher suites in order to guarantee that we do not // use Qt's default Diffie-Hellman parameters. { - QList<QSslCipher> filtered; + QList< QSslCipher > filtered; foreach (QSslCipher c, ciphers) { if (c.keyExchangeMethod() == QLatin1String("DH")) { continue; @@ -615,8 +626,8 @@ bool MetaParams::loadSSLSettings() { } if (ciphers.size() != filtered.size()) { qWarning("MetaParams: Warning: all cipher suites in sslCiphers using Diffie-Hellman key exchange " - "have been removed. Qt %s does not support custom Diffie-Hellman parameters.", - qVersion()); + "have been removed. Qt %s does not support custom Diffie-Hellman parameters.", + qVersion()); } tmpCiphers = filtered; @@ -626,19 +637,17 @@ bool MetaParams::loadSSLSettings() { #endif QStringList pref; - foreach (QSslCipher c, tmpCiphers) { - pref << c.name(); - } + foreach (QSslCipher c, tmpCiphers) { pref << c.name(); } qWarning("MetaParams: TLS cipher preference is \"%s\"", qPrintable(pref.join(QLatin1String(":")))); } - qscCert = tmpCert; - qlCA = tmpCA; + qscCert = tmpCert; + qlCA = tmpCA; qlIntermediates = tmpIntermediates; - qskKey = tmpKey; - qbaDHParams = tmpDHParams; - qsCiphers = tmpCiphersStr; - qlCiphers = tmpCiphers; + qskKey = tmpKey; + qbaDHParams = tmpDHParams; + qsCiphers = tmpCiphersStr; + qlCiphers = tmpCiphers; qmConfig.insert(QLatin1String("certificate"), QString::fromUtf8(qscCert.toPem())); qmConfig.insert(QLatin1String("key"), QString::fromUtf8(qskKey.toPem())); @@ -661,7 +670,7 @@ Meta::Meta() { qWarning("Meta: Failed to load qWave.dll, no QoS available"); } else { FreeLibrary(hLib); - if (! QOSCreateHandle(&qvVer, &hQoS)) + if (!QOSCreateHandle(&qvVer, &hQoS)) qWarning("Meta: Failed to create QOS2 handle"); else Connection::setQoS(hQoS); @@ -700,23 +709,23 @@ bool Meta::reloadSSLSettings() { } void Meta::getOSInfo() { - qsOS = OSInfo::getOS(); + qsOS = OSInfo::getOS(); qsOSVersion = OSInfo::getOSDisplayableVersion(); } void Meta::bootAll() { - QList<int> ql = ServerDB::getBootServers(); - foreach(int snum, ql) + QList< int > ql = ServerDB::getBootServers(); + foreach (int snum, ql) boot(snum); } bool Meta::boot(int srvnum) { if (qhServers.contains(srvnum)) return false; - if (! ServerDB::serverExists(srvnum)) + if (!ServerDB::serverExists(srvnum)) return false; Server *s = new Server(srvnum, this); - if (! s->bValid) { + if (!s->bValid) { delete s; return false; } @@ -725,8 +734,8 @@ bool Meta::boot(int srvnum) { #ifdef Q_OS_UNIX unsigned int sockets = 19; // Base - foreach(s, qhServers) { - sockets += 11; // Listen sockets, signal pipes etc. + foreach (s, qhServers) { + sockets += 11; // Listen sockets, signal pipes etc. sockets += s->iMaxUsers; // One per user } @@ -746,7 +755,10 @@ bool Meta::boot(int srvnum) { } } if (r.rlim_cur < sockets) - qCritical("Current booted servers require minimum %d file descriptors when all slots are full, but only %lu file descriptors are allowed for this process. Your server will crash and burn; read the FAQ for details.", sockets, static_cast<unsigned long>(r.rlim_cur)); + qCritical( + "Current booted servers require minimum %d file descriptors when all slots are full, but only %lu file " + "descriptors are allowed for this process. Your server will crash and burn; read the FAQ for details.", + sockets, static_cast< unsigned long >(r.rlim_cur)); } #endif @@ -762,7 +774,7 @@ void Meta::kill(int srvnum) { } void Meta::killAll() { - foreach(Server *s, qhServers) { + foreach (Server *s, qhServers) { emit stopped(s); delete s; } @@ -771,7 +783,7 @@ void Meta::killAll() { void Meta::successfulConnectionFrom(const QHostAddress &addr) { if (!mp.bBanSuccessful) { - QList<Timer> &ql = qhAttempts[addr]; + QList< Timer > &ql = qhAttempts[addr]; // Seems like this is the most efficient way to clear the list, given: // 1. ql.clear() allocates a new array // 2. ql has less than iBanAttempts members @@ -793,10 +805,10 @@ bool Meta::banCheck(const QHostAddress &addr) { qhBans.remove(addr); } - QList<Timer> &ql = qhAttempts[addr]; + QList< Timer > &ql = qhAttempts[addr]; ql.append(Timer()); - while (! ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * mp.iBanTimeframe))) + while (!ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * mp.iBanTimeframe))) ql.removeFirst(); if (ql.count() > mp.iBanTries) { diff --git a/src/murmur/Meta.h b/src/murmur/Meta.h index 0c75fa733..4f98bc87e 100644 --- a/src/murmur/Meta.h +++ b/src/murmur/Meta.h @@ -9,7 +9,7 @@ #include "Timer.h" #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include <QtCore/QDir> @@ -18,8 +18,8 @@ #include <QtCore/QVariant> #include <QtNetwork/QHostAddress> #include <QtNetwork/QSslCertificate> -#include <QtNetwork/QSslKey> #include <QtNetwork/QSslCipher> +#include <QtNetwork/QSslKey> class Server; class QSettings; @@ -28,7 +28,7 @@ class MetaParams { public: QDir qdBasePath; - QList<QHostAddress> qlBind; + QList< QHostAddress > qlBind; unsigned short usPort; int iTimeout; int iMaxBandwidth; @@ -115,22 +115,22 @@ public: /// Simply put: it contains any certificates /// that aren't the main certificate, or "leaf" /// certificate. - QList<QSslCertificate> qlIntermediates; + QList< QSslCertificate > qlIntermediates; /// qlCA contains all certificates read from /// the PEM bundle pointed to by murmur.ini's /// sslCA option. - QList<QSslCertificate> qlCA; + QList< QSslCertificate > qlCA; /// qlCiphers contains the list of supported /// cipher suites. - QList<QSslCipher> qlCiphers; + QList< QSslCipher > qlCiphers; QByteArray qbaDHParams; QByteArray qbaPassPhrase; QString qsCiphers; - QMap<QString, QString> qmConfig; + QMap< QString, QString > qmConfig; #ifdef Q_OS_UNIX unsigned int uiUid, uiGid; @@ -163,50 +163,51 @@ public: bool loadSSLSettings(); private: - template <class T> + template< class T > T typeCheckedFromSettings(const QString &name, const T &variable, QSettings *settings = nullptr); }; class Meta : public QObject { - private: - Q_OBJECT; - Q_DISABLE_COPY(Meta); - public: - static MetaParams mp; - QHash<int, Server *> qhServers; - QHash<QHostAddress, QList<Timer> > qhAttempts; - QHash<QHostAddress, Timer> qhBans; - QString qsOS, qsOSVersion; - Timer tUptime; +private: + Q_OBJECT; + Q_DISABLE_COPY(Meta); + +public: + static MetaParams mp; + QHash< int, Server * > qhServers; + QHash< QHostAddress, QList< Timer > > qhAttempts; + QHash< QHostAddress, Timer > qhBans; + QString qsOS, qsOSVersion; + Timer tUptime; #ifdef Q_OS_WIN - static HANDLE hQoS; + static HANDLE hQoS; #endif - Meta(); - ~Meta(); - - /// reloadSSLSettings reloads Murmur's MetaParams's - /// SSL settings, and updates the certificate and - /// private key for all virtual servers that use the - /// Meta server's certificate and private key. - bool reloadSSLSettings(); - - void bootAll(); - bool boot(int); - bool banCheck(const QHostAddress &); - - /// Called whenever we get a successful connection from a client. - /// Used to reset autoban tracking for the address. - void successfulConnectionFrom(const QHostAddress &); - void kill(int); - void killAll(); - void getOSInfo(); - void connectListener(QObject *); - static void getVersion(int &major, int &minor, int &patch, QString &string); - signals: - void started(Server *); - void stopped(Server *); + Meta(); + ~Meta(); + + /// reloadSSLSettings reloads Murmur's MetaParams's + /// SSL settings, and updates the certificate and + /// private key for all virtual servers that use the + /// Meta server's certificate and private key. + bool reloadSSLSettings(); + + void bootAll(); + bool boot(int); + bool banCheck(const QHostAddress &); + + /// Called whenever we get a successful connection from a client. + /// Used to reset autoban tracking for the address. + void successfulConnectionFrom(const QHostAddress &); + void kill(int); + void killAll(); + void getOSInfo(); + void connectListener(QObject *); + static void getVersion(int &major, int &minor, int &patch, QString &string); +signals: + void started(Server *); + void stopped(Server *); }; extern Meta *meta; diff --git a/src/murmur/MurmurGRPCImpl.cpp b/src/murmur/MurmurGRPCImpl.cpp index a555bccd1..3299ddc94 100644 --- a/src/murmur/MurmurGRPCImpl.cpp +++ b/src/murmur/MurmurGRPCImpl.cpp @@ -4,25 +4,25 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef Q_MOC_RUN -# include <boost/function.hpp> +# include <boost/function.hpp> #endif #include "Mumble.pb.h" -#include "../Message.h" #include "../Group.h" +#include "../Message.h" +#include "Channel.h" #include "MurmurGRPCImpl.h" +#include "Server.h" #include "ServerDB.h" #include "ServerUser.h" -#include "Server.h" -#include "Channel.h" #include "Utils.h" #include <chrono> -#include <QtCore/QStack> #include <QCryptographicHash> #include <QRegularExpression> +#include <QtCore/QStack> #include "MurmurRPC.proto.Wrapper.cpp" @@ -95,12 +95,12 @@ void GRPCStart() { return; } const auto &cert = meta->mp.qsGRPCCert; - const auto &key = meta->mp.qsGRPCKey; - std::shared_ptr<::grpc::ServerCredentials> credentials; + const auto &key = meta->mp.qsGRPCKey; + std::shared_ptr<::grpc::ServerCredentials > credentials; if (cert.isEmpty() || key.isEmpty()) { credentials = ::grpc::InsecureServerCredentials(); } else { - std::shared_ptr<MurmurRPCAuthenticator> authenticator(new MurmurRPCAuthenticator()); + std::shared_ptr< MurmurRPCAuthenticator > authenticator(new MurmurRPCAuthenticator()); ::grpc::SslServerCredentialsOptions options(GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY); ::grpc::SslServerCredentialsOptions::PemKeyCertPair pair; { @@ -110,7 +110,7 @@ void GRPCStart() { return; } QTextStream stream(&file); - auto contents = stream.readAll(); + auto contents = stream.readAll(); pair.cert_chain = contents.toStdString(); } { @@ -120,7 +120,7 @@ void GRPCStart() { return; } QTextStream stream(&file); - auto contents = stream.readAll(); + auto contents = stream.readAll(); pair.private_key = contents.toStdString(); } options.pem_key_cert_pairs.push_back(pair); @@ -143,7 +143,7 @@ MurmurRPCAuthenticator::MurmurRPCAuthenticator() { QRegularExpression re("^(?:[[:xdigit:]]{2}:?){32}$"); const auto &authorized = meta->mp.qsGRPCAuthorized; - for (auto&& user : authorized.split(' ')) { + for (auto &&user : authorized.split(' ')) { if (!re.match(user).hasMatch()) { qWarning("gRPC: %s is not a valid hexadecimal SHA256 digest, ignoring", qUtf8Printable(user)); continue; @@ -153,7 +153,7 @@ MurmurRPCAuthenticator::MurmurRPCAuthenticator() { if (m_gRPCUsers.empty()) { qWarning("gRPC Security is enabled but no users are authorized to use the interface\n" - "Please set grpcauthorized to a list of authorized clients"); + "Please set grpcauthorized to a list of authorized clients"); } return; @@ -165,7 +165,8 @@ bool MurmurRPCAuthenticator::IsBlocking() const { } // We don't use any metadata. Just check to see if the certificate fingerprint matches -grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::grpc::AuthContext *ctx, OutputMetadata *used, OutputMetadata* resp) { +grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::grpc::AuthContext *ctx, + OutputMetadata *used, OutputMetadata *resp) { QByteArray fingerprint; QString identity; QStringList identities; @@ -174,7 +175,7 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr (void) resp; (void) authData; - for (auto&& i : ctx->GetPeerIdentity()) { + for (auto &&i : ctx->GetPeerIdentity()) { identities.append(QString::fromUtf8(i.data(), i.length())); } if (identities.empty()) { @@ -185,7 +186,7 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr qDebug("Incoming connection from: %s", qUtf8Printable(identity)); - for (auto&& pem : ctx->FindPropertyValues("x509_pem_cert")) { + for (auto &&pem : ctx->FindPropertyValues("x509_pem_cert")) { QSslCertificate cert(QByteArray(pem.data(), pem.length())); if (cert.isNull()) { continue; @@ -206,12 +207,12 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr return ::grpc::Status(::grpc::StatusCode::UNAUTHENTICATED, "Certificate invalid or not presented"); } -MurmurRPCImpl::MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials> credentials) { +MurmurRPCImpl::MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials > credentials) { ::grpc::ServerBuilder builder; builder.AddListeningPort(u8(address), credentials); builder.RegisterService(&m_V1Service); m_completionQueue = builder.AddCompletionQueue(); - m_server = builder.BuildAndStart(); + m_server = builder.BuildAndStart(); meta->connectListener(this); m_isRunning = true; start(); @@ -225,7 +226,7 @@ MurmurRPCImpl::~MurmurRPCImpl() { m_completionQueue->Shutdown(); while (m_completionQueue->Next(&ignored_tag, &ignored_ok)) { if (ignored_tag) { - auto op = static_cast<boost::function<void(bool)> *>(ignored_tag); + auto op = static_cast< boost::function< void(bool) > * >(ignored_tag); delete op; } } @@ -243,7 +244,7 @@ void ToRPC(const ::Server *srv, const ::Channel *c, ::MurmurRPC::Channel *rc) { } rc->set_description(u8(c->qsDesc)); rc->set_position(c->iPosition); - foreach(::Channel *chn, c->qsPermLinks) { + foreach (::Channel *chn, c->qsPermLinks) { ::MurmurRPC::Channel *linked = rc->add_links(); linked->mutable_server()->set_id(srv->iServerNum); linked->set_id(chn->iId); @@ -270,7 +271,7 @@ void ToRPC(const ::Server *srv, const ::User *u, ::MurmurRPC::User *ru) { ru->mutable_channel()->set_id(u->cChannel->iId); ru->set_comment(u8(u->qsComment)); - const auto su = static_cast<const ServerUser *>(u); + const auto su = static_cast< const ServerUser * >(u); ru->set_online_secs(su->bwr.onlineSeconds()); ru->set_bytes_per_sec(su->bwr.bandwidth()); ru->mutable_version()->set_version(su->uiVersion); @@ -293,7 +294,8 @@ void ToRPC(const ::Server *srv, const ::User *u, ::MurmurRPC::User *ru) { ru->set_address(su->haAddress.toStdString()); } -void ToRPC(const ::Server *srv, const QMap<int, QString> &info, const QByteArray &texture, ::MurmurRPC::DatabaseUser *du) { +void ToRPC(const ::Server *srv, const QMap< int, QString > &info, const QByteArray &texture, + ::MurmurRPC::DatabaseUser *du) { du->mutable_server()->set_id(srv->iServerNum); if (info.contains(::ServerDB::User_Name)) { @@ -319,7 +321,7 @@ void ToRPC(const ::Server *srv, const QMap<int, QString> &info, const QByteArray } } -void FromRPC(const ::MurmurRPC::DatabaseUser &du, QMap<int, QString> &info) { +void FromRPC(const ::MurmurRPC::DatabaseUser &du, QMap< int, QString > &info) { if (du.has_name()) { info.insert(::ServerDB::User_Name, u8(du.name())); } @@ -376,13 +378,13 @@ void ToRPC(const ::Server *srv, const ::Ban &ban, ::MurmurRPC::Ban *rb) { } void FromRPC(const ::Server *, const ::MurmurRPC::Ban &rb, ::Ban &ban) { - ban.haAddress = HostAddress(rb.address()); - ban.iMask = rb.bits(); + ban.haAddress = HostAddress(rb.address()); + ban.iMask = rb.bits(); ban.qsUsername = u8(rb.name()); - ban.qsHash = u8(rb.hash()); - ban.qsReason = u8(rb.reason()); - ban.qdtStart = QDateTime::fromTime_t(static_cast<quint32>(rb.start())).toUTC(); - ban.iDuration = rb.duration_secs(); + ban.qsHash = u8(rb.hash()); + ban.qsReason = u8(rb.reason()); + ban.qdtStart = QDateTime::fromTime_t(static_cast< quint32 >(rb.start())).toUTC(); + ban.iDuration = rb.duration_secs(); } void ToRPC(int serverID, const ::ServerDB::LogRecord &log, ::MurmurRPC::Log *rl) { @@ -398,19 +400,19 @@ void ToRPC(const ::Server *srv, const ::User *user, const ::TextMessage &message rtm->mutable_actor()->mutable_server()->set_id(srv->iServerNum); rtm->mutable_actor()->set_session(user->uiSession); - foreach(auto session, message.qlSessions) { + foreach (auto session, message.qlSessions) { auto target = rtm->add_users(); target->mutable_server()->set_id(srv->iServerNum); target->set_session(session); } - foreach(auto id, message.qlChannels) { + foreach (auto id, message.qlChannels) { auto target = rtm->add_channels(); target->mutable_server()->set_id(srv->iServerNum); target->set_id(id); } - foreach(auto id, message.qlTrees) { + foreach (auto id, message.qlTrees) { auto target = rtm->add_trees(); target->mutable_server()->set_id(srv->iServerNum); target->set_id(id); @@ -426,7 +428,7 @@ void MurmurRPCImpl::sendMetaEvent(const ::MurmurRPC::Event &e) { for (auto i = listeners.constBegin(); i != listeners.constEnd(); ++i) { auto listener = *i; listener->ref(); - auto cb = [this, listener] (::MurmurRPC::Wrapper::V1_Events *, bool ok) { + auto cb = [this, listener](::MurmurRPC::Wrapper::V1_Events *, bool ok) { if (!ok && m_metaServiceListeners.remove(listener)) { listener->deref(); } @@ -440,8 +442,10 @@ void MurmurRPCImpl::sendMetaEvent(const ::MurmurRPC::Event &e) { void MurmurRPCImpl::started(::Server *server) { server->connectListener(this); server->connectAuthenticator(this); - connect(server, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, SLOT(contextAction(const User *, const QString &, unsigned int, int))); - connect(server, SIGNAL(textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &)), this, SLOT(textMessageFilter(int &, const User *, MumbleProto::TextMessage &))); + connect(server, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, + SLOT(contextAction(const User *, const QString &, unsigned int, int))); + connect(server, SIGNAL(textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &)), this, + SLOT(textMessageFilter(int &, const User *, MumbleProto::TextMessage &))); ::MurmurRPC::Event rpcEvent; rpcEvent.set_type(::MurmurRPC::Event_Type_ServerStarted); @@ -480,9 +484,11 @@ void MurmurRPCImpl::removeAuthenticator(const ::Server *s) { } // Called when a connecting user needs to be authenticated. -void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -493,7 +499,7 @@ void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, co if (!pw.isEmpty()) { request.mutable_authenticate()->set_password(u8(pw)); } - foreach(const auto &cert, certlist) { + foreach (const auto &cert, certlist) { auto data = cert.toDer(); request.mutable_authenticate()->add_certificates(data.constData(), data.size()); } @@ -513,43 +519,44 @@ void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, co auto &response = authenticator->request; switch (response.authenticate().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - if (!response.authenticate().has_id()) { - res = -3; - break; - } - res = response.authenticate().id(); - if (response.authenticate().has_name()) { - uname = u8(response.authenticate().name()); - } - { - QStringList qsl; - for (int i = 0; i < response.authenticate().groups_size(); i++) { - auto &group = response.authenticate().groups(i); - if (group.has_name()) { - qsl << u8(group.name()); - } + case ::MurmurRPC::Authenticator_Response_Status_Success: + if (!response.authenticate().has_id()) { + res = -3; + break; } - if (!qsl.isEmpty()) { - s->setTempGroups(res, sessionId, nullptr, qsl); + res = response.authenticate().id(); + if (response.authenticate().has_name()) { + uname = u8(response.authenticate().name()); } - } - break; - case ::MurmurRPC::Authenticator_Response_Status_TemporaryFailure: - res = -3; - break; - case ::MurmurRPC::Authenticator_Response_Status_Failure: - res = -1; - break; - default: - break; + { + QStringList qsl; + for (int i = 0; i < response.authenticate().groups_size(); i++) { + auto &group = response.authenticate().groups(i); + if (group.has_name()) { + qsl << u8(group.name()); + } + } + if (!qsl.isEmpty()) { + s->setTempGroups(res, sessionId, nullptr, qsl); + } + } + break; + case ::MurmurRPC::Authenticator_Response_Status_TemporaryFailure: + res = -3; + break; + case ::MurmurRPC::Authenticator_Response_Status_Failure: + res = -1; + break; + default: + break; } } // Called when a user is being registered on the server. -void MurmurRPCImpl::registerUserSlot(int &res, const QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::registerUserSlot(int &res, const QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -568,25 +575,26 @@ void MurmurRPCImpl::registerUserSlot(int &res, const QMap<int, QString> &info) { auto &response = authenticator->request; switch (response.register_().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - if (!response.register_().has_user() || !response.register_().user().has_id()) { + case ::MurmurRPC::Authenticator_Response_Status_Success: + if (!response.register_().has_user() || !response.register_().user().has_id()) { + res = -1; + break; + } + res = response.register_().user().id(); + break; + case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: + break; + default: res = -1; break; - } - res = response.register_().user().id(); - break; - case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: - break; - default: - res = -1; - break; } } // Called when a user is being deregistered on the server. void MurmurRPCImpl::unregisterUserSlot(int &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -612,9 +620,10 @@ void MurmurRPCImpl::unregisterUserSlot(int &res, int id) { } // Called when a list of registered users is requested. -void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -645,9 +654,10 @@ void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap<int, QStr } // Called when information about a registered user is requested. -void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -674,9 +684,10 @@ void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap<int, QString> &in } // Called when information about a registered user is being updated. -void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -698,21 +709,22 @@ void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap<int, QString> &info auto &response = authenticator->request; switch (response.update().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - res = 1; - break; - case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: - res = -1; - break; - default: - break; + case ::MurmurRPC::Authenticator_Response_Status_Success: + res = 1; + break; + case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: + res = -1; + break; + default: + break; } } // Called when a texture for a registered user is being updated. void MurmurRPCImpl::setTextureSlot(int &res, int id, const QByteArray &texture) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -738,8 +750,9 @@ void MurmurRPCImpl::setTextureSlot(int &res, int id, const QByteArray &texture) // Called when a user name needs to be converted to a user ID. void MurmurRPCImpl::nameToIdSlot(int &res, const QString &name) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -764,8 +777,9 @@ void MurmurRPCImpl::nameToIdSlot(int &res, const QString &name) { // Called when a user ID needs to be converted to a user name. void MurmurRPCImpl::idToNameSlot(QString &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -790,8 +804,9 @@ void MurmurRPCImpl::idToNameSlot(QString &res, int id) { // Called when a texture for a given registered user is requested. void MurmurRPCImpl::idToTextureSlot(QByteArray &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -811,20 +826,20 @@ void MurmurRPCImpl::idToTextureSlot(QByteArray &res, int id) { auto &response = authenticator->request; if (response.find().has_user() && response.find().user().has_texture()) { const auto &texture = response.find().user().texture(); - res = QByteArray(texture.data(), texture.size()); + res = QByteArray(texture.data(), texture.size()); } } // Sends a server event to subscribed listeners. void MurmurRPCImpl::sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e) { auto listeners = m_serverServiceListeners; - auto serverID = s->iServerNum; - auto i = listeners.find(serverID); + auto serverID = s->iServerNum; + auto i = listeners.find(serverID); - for ( ; i != listeners.end() && i.key() == serverID; ++i) { + for (; i != listeners.end() && i.key() == serverID; ++i) { auto listener = i.value(); listener->ref(); - auto cb = [this, listener, serverID] (::MurmurRPC::Wrapper::V1_ServerEvents *, bool ok) { + auto cb = [this, listener, serverID](::MurmurRPC::Wrapper::V1_ServerEvents *, bool ok) { if (!ok && m_serverServiceListeners.remove(serverID, listener) > 0) { listener->deref(); } @@ -836,7 +851,7 @@ void MurmurRPCImpl::sendServerEvent(const ::Server *s, const ::MurmurRPC::Server // Called when a user's state changes. void MurmurRPCImpl::userStateChanged(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -847,7 +862,7 @@ void MurmurRPCImpl::userStateChanged(const ::User *user) { // Called when a user sends a text message. void MurmurRPCImpl::userTextMessage(const ::User *user, const ::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -859,7 +874,7 @@ void MurmurRPCImpl::userTextMessage(const ::User *user, const ::TextMessage &mes // Called when a user successfully connects to a server. void MurmurRPCImpl::userConnected(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -870,7 +885,7 @@ void MurmurRPCImpl::userConnected(const ::User *user) { // Called when a user disconnects from a server. void MurmurRPCImpl::userDisconnected(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); removeUserActiveContextActions(s, user); @@ -883,7 +898,7 @@ void MurmurRPCImpl::userDisconnected(const ::User *user) { // Called when a channel's state changes. void MurmurRPCImpl::channelStateChanged(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -894,7 +909,7 @@ void MurmurRPCImpl::channelStateChanged(const ::Channel *channel) { // Called when a channel is created. void MurmurRPCImpl::channelCreated(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -905,7 +920,7 @@ void MurmurRPCImpl::channelCreated(const ::Channel *channel) { // Called when a channel is removed. void MurmurRPCImpl::channelRemoved(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -916,8 +931,8 @@ void MurmurRPCImpl::channelRemoved(const ::Channel *channel) { // Called when a user sends a text message. void MurmurRPCImpl::textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto filter = RPCCall::Ref<::MurmurRPC::Wrapper::V1_TextMessageFilter>(m_textMessageFilters.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto filter = RPCCall::Ref<::MurmurRPC::Wrapper::V1_TextMessageFilter >(m_textMessageFilters.value(s->iServerNum)); if (!filter) { return; } @@ -955,15 +970,15 @@ void MurmurRPCImpl::textMessageFilter(int &res, const User *user, MumbleProto::T } auto &response = filter->request; - res = response.action(); + res = response.action(); switch (response.action()) { - case ::MurmurRPC::TextMessage_Filter_Action_Accept: - if (response.has_message() && response.message().has_text()) { - message.set_message(response.message().text()); - } - break; - default: - break; + case ::MurmurRPC::TextMessage_Filter_Action_Accept: + if (response.has_message() && response.message().has_text()) { + message.set_message(response.message().text()); + } + break; + default: + break; } } @@ -1021,7 +1036,7 @@ void MurmurRPCImpl::removeActiveContextActions(const ::Server *s) { // Called when a context action event is triggered. void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, unsigned int session, int channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); if (!hasActiveContextAction(s, user, action)) { return; @@ -1041,13 +1056,13 @@ void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, uns ca.mutable_channel()->set_id(channel); } - auto serverID = s->iServerNum; + auto serverID = s->iServerNum; auto listeners = this->m_contextActionListeners.value(serverID); - auto i = listeners.find(action); - for ( ; i != listeners.end() && i.key() == action; ++i) { + auto i = listeners.find(action); + for (; i != listeners.end() && i.key() == action; ++i) { auto listener = i.value(); listener->ref(); - auto cb = [this, listener, serverID, action] (::MurmurRPC::Wrapper::V1_ContextActionEvents *, bool ok) { + auto cb = [this, listener, serverID, action](::MurmurRPC::Wrapper::V1_ContextActionEvents *, bool ok) { if (!ok && m_contextActionListeners[serverID].remove(action, listener) > 0) { listener->deref(); } @@ -1067,16 +1082,14 @@ void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, uns return user; } -template <class T> -::ServerUser *MustUser(const ::Server *server, const T &msg) { +template< class T >::ServerUser *MustUser(const ::Server *server, const T &msg) { if (!msg.has_user()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing user"); } return MustUser(server, msg.user().session()); } -template <> -::ServerUser *MustUser(const Server *server, const ::MurmurRPC::User &msg) { +template<>::ServerUser *MustUser(const Server *server, const ::MurmurRPC::User &msg) { if (!msg.has_session()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing user session"); } @@ -1099,8 +1112,7 @@ template <> return server; } -template <class T> -::Server *MustServer(const T &msg) { +template< class T >::Server *MustServer(const T &msg) { if (!msg.has_server()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server"); } @@ -1110,16 +1122,14 @@ template <class T> return MustServer(msg.server().id()); } -template <> -::Server *MustServer(const ::MurmurRPC::Server &msg) { +template<>::Server *MustServer(const ::MurmurRPC::Server &msg) { if (!msg.has_id()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server id"); } return MustServer(msg.id()); } -template <class T> -int MustServerID(const T &msg) { +template< class T > int MustServerID(const T &msg) { if (!msg.has_server()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server"); } @@ -1160,16 +1170,14 @@ int MustServerID(const ::MurmurRPC::Server &msg) { return channel; } -template <class T> -::Channel *MustChannel(const Server *server, const T &msg) { +template< class T >::Channel *MustChannel(const Server *server, const T &msg) { if (!msg.has_channel()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing channel"); } return MustChannel(server, msg.channel()); } -template <> -::Channel *MustChannel(const Server *server, const ::MurmurRPC::Channel &msg) { +template<>::Channel *MustChannel(const Server *server, const ::MurmurRPC::Channel &msg) { if (!msg.has_id()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing channel id"); } @@ -1179,7 +1187,7 @@ template <> // Qt event listener for RPCExecEvents. void MurmurRPCImpl::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) { - auto event = static_cast<RPCExecEvent *>(evt); + auto event = static_cast< RPCExecEvent * >(evt); try { event->execute(); } catch (::grpc::Status &ex) { @@ -1200,7 +1208,7 @@ void MurmurRPCImpl::run() { break; } if (tag != nullptr) { - auto op = static_cast<boost::function<void(bool)> *>(tag); + auto op = static_cast< boost::function< void(bool) > * >(tag); (*op)(ok); delete op; } @@ -1219,1044 +1227,1039 @@ void MurmurRPCImpl::run() { namespace MurmurRPC { namespace Wrapper { -void V1_ServerCreate::impl(bool) { - auto id = ServerDB::addServer(); - - ::MurmurRPC::Server rpcServer; - rpcServer.set_id(id); - end(rpcServer); -} - -void V1_ServerQuery::impl(bool) { - ::MurmurRPC::Server_List list; + void V1_ServerCreate::impl(bool) { + auto id = ServerDB::addServer(); - foreach(int id, ServerDB::getAllServers()) { - auto rpcServer = list.add_servers(); - rpcServer->set_id(id); - try { - auto server = MustServer(id); - rpcServer->set_running(true); - rpcServer->mutable_uptime()->set_secs(server->tUptime.elapsed()/1000000LL); - } catch (::grpc::Status &ex) { - } + ::MurmurRPC::Server rpcServer; + rpcServer.set_id(id); + end(rpcServer); } - end(list); -} + void V1_ServerQuery::impl(bool) { + ::MurmurRPC::Server_List list; -void V1_ServerGet::impl(bool) { - auto serverID = MustServerID(request); + foreach (int id, ServerDB::getAllServers()) { + auto rpcServer = list.add_servers(); + rpcServer->set_id(id); + try { + auto server = MustServer(id); + rpcServer->set_running(true); + rpcServer->mutable_uptime()->set_secs(server->tUptime.elapsed() / 1000000LL); + } catch (::grpc::Status &ex) { + } + } - ::MurmurRPC::Server rpcServer; - rpcServer.set_id(serverID); - rpcServer.set_running(false); - try { - auto server = MustServer(serverID); - rpcServer.set_running(true); - rpcServer.mutable_uptime()->set_secs(server->tUptime.elapsed()/1000000LL); - } catch (::grpc::Status &ex) { + end(list); } - end(rpcServer); -} -void V1_ServerStart::impl(bool) { - auto serverID = MustServerID(request); + void V1_ServerGet::impl(bool) { + auto serverID = MustServerID(request); - if (!meta->boot(serverID)) { - throw ::grpc::Status(::grpc::UNKNOWN, "server could not be started, or is already started"); + ::MurmurRPC::Server rpcServer; + rpcServer.set_id(serverID); + rpcServer.set_running(false); + try { + auto server = MustServer(serverID); + rpcServer.set_running(true); + rpcServer.mutable_uptime()->set_secs(server->tUptime.elapsed() / 1000000LL); + } catch (::grpc::Status &ex) { + } + end(rpcServer); } - end(); -} + void V1_ServerStart::impl(bool) { + auto serverID = MustServerID(request); -void V1_ServerStop::impl(bool) { - auto server = MustServer(request); - meta->kill(server->iServerNum); - end(); -} + if (!meta->boot(serverID)) { + throw ::grpc::Status(::grpc::UNKNOWN, "server could not be started, or is already started"); + } -void V1_ServerRemove::impl(bool) { - auto serverID = MustServerID(request); + end(); + } - if (meta->qhServers.value(serverID)) { - throw ::grpc::Status(::grpc::FAILED_PRECONDITION, "cannot remove started server"); + void V1_ServerStop::impl(bool) { + auto server = MustServer(request); + meta->kill(server->iServerNum); + end(); } - ServerDB::deleteServer(serverID); - end(); -} + void V1_ServerRemove::impl(bool) { + auto serverID = MustServerID(request); -void V1_ServerEvents::impl(bool) { - auto server = MustServer(request); - rpc->m_serverServiceListeners.insert(server->iServerNum, this); -} + if (meta->qhServers.value(serverID)) { + throw ::grpc::Status(::grpc::FAILED_PRECONDITION, "cannot remove started server"); + } -void V1_ServerEvents::done(bool) { - auto &ssls = rpc->m_serverServiceListeners; - auto i = std::find(ssls.begin(), ssls.end(), this); - if (i != ssls.end()) { - ssls.erase(i); + ServerDB::deleteServer(serverID); + end(); } - deref(); -} -void V1_GetUptime::impl(bool) { - ::MurmurRPC::Uptime uptime; - uptime.set_secs(meta->tUptime.elapsed()/1000000LL); - end(uptime); -} + void V1_ServerEvents::impl(bool) { + auto server = MustServer(request); + rpc->m_serverServiceListeners.insert(server->iServerNum, this); + } -void V1_GetVersion::impl(bool) { - ::MurmurRPC::Version version; - int major, minor, patch; - QString release; - Meta::getVersion(major, minor, patch, release); - version.set_version(major << 16 | minor << 8 | patch); - version.set_release(u8(release)); - end(version); -} + void V1_ServerEvents::done(bool) { + auto &ssls = rpc->m_serverServiceListeners; + auto i = std::find(ssls.begin(), ssls.end(), this); + if (i != ssls.end()) { + ssls.erase(i); + } + deref(); + } -void V1_Events::impl(bool) { - rpc->m_metaServiceListeners.insert(this); -} + void V1_GetUptime::impl(bool) { + ::MurmurRPC::Uptime uptime; + uptime.set_secs(meta->tUptime.elapsed() / 1000000LL); + end(uptime); + } -void V1_Events::done(bool) { - auto &msls = rpc->m_metaServiceListeners; - auto i = std::find(msls.begin(), msls.end(), this); - if (i != msls.end()) { - msls.erase(i); + void V1_GetVersion::impl(bool) { + ::MurmurRPC::Version version; + int major, minor, patch; + QString release; + Meta::getVersion(major, minor, patch, release); + version.set_version(major << 16 | minor << 8 | patch); + version.set_release(u8(release)); + end(version); } - deref(); -} -void V1_ContextActionAdd::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + void V1_Events::impl(bool) { rpc->m_metaServiceListeners.insert(this); } - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); - } - if (!request.has_text()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing text"); - } - if (!request.has_context()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing context"); + void V1_Events::done(bool) { + auto &msls = rpc->m_metaServiceListeners; + auto i = std::find(msls.begin(), msls.end(), this); + if (i != msls.end()) { + msls.erase(i); + } + deref(); } - rpc->addActiveContextAction(server, user, u8(request.action())); + void V1_ContextActionAdd::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - ::MumbleProto::ContextActionModify mpcam; - mpcam.set_action(request.action()); - mpcam.set_text(request.text()); - mpcam.set_context(request.context()); - mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Add); - server->sendMessage(user, mpcam); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } + if (!request.has_text()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing text"); + } + if (!request.has_context()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing context"); + } - end(); -} + rpc->addActiveContextAction(server, user, u8(request.action())); -void V1_ContextActionRemove::impl(bool) { - auto server = MustServer(request); + ::MumbleProto::ContextActionModify mpcam; + mpcam.set_action(request.action()); + mpcam.set_text(request.text()); + mpcam.set_context(request.context()); + mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Add); + server->sendMessage(user, mpcam); - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + end(); } - auto action = u8(request.action()); + void V1_ContextActionRemove::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::ContextActionModify mpcam; - mpcam.set_action(request.action()); - mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Remove); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } - if (request.has_user()) { - // Remove context action from specific user - auto user = MustUser(server, request); - rpc->removeActiveContextAction(server, user, action); - server->sendMessage(user, mpcam); - } else { - // Remove context action from all users - foreach(::ServerUser *user, server->qhUsers) { - if (user->sState != ServerUser::Authenticated) { - continue; - } + auto action = u8(request.action()); + + ::MumbleProto::ContextActionModify mpcam; + mpcam.set_action(request.action()); + mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Remove); + + if (request.has_user()) { + // Remove context action from specific user + auto user = MustUser(server, request); rpc->removeActiveContextAction(server, user, action); server->sendMessage(user, mpcam); + } else { + // Remove context action from all users + foreach (::ServerUser *user, server->qhUsers) { + if (user->sState != ServerUser::Authenticated) { + continue; + } + rpc->removeActiveContextAction(server, user, action); + server->sendMessage(user, mpcam); + } } + + end(); } - end(); -} + void V1_ContextActionEvents::impl(bool) { + auto server = MustServer(request); -void V1_ContextActionEvents::impl(bool) { - auto server = MustServer(request); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + rpc->m_contextActionListeners[server->iServerNum].insert(u8(request.action()), this); } - rpc->m_contextActionListeners[server->iServerNum].insert(u8(request.action()), this); -} - -void V1_ContextActionEvents::done(bool) { - auto server = MustServer(request); - auto &cals = rpc->m_contextActionListeners; - auto &scals = cals[server->iServerNum]; + void V1_ContextActionEvents::done(bool) { + auto server = MustServer(request); + auto &cals = rpc->m_contextActionListeners; + auto &scals = cals[server->iServerNum]; - auto i = std::find(scals.begin(), scals.end(), this); - if (i != scals.end()) { - scals.erase(i); - } - deref(); - if (scals.isEmpty()) { - auto i = std::find(cals.begin(), cals.end(), scals); - if (i != cals.end()) { - cals.erase(i); + auto i = std::find(scals.begin(), scals.end(), this); + if (i != scals.end()) { + scals.erase(i); + } + deref(); + if (scals.isEmpty()) { + auto i = std::find(cals.begin(), cals.end(), scals); + if (i != cals.end()) { + cals.erase(i); + } } } -} -void V1_TextMessageSend::impl(bool) { - auto server = MustServer(request); + void V1_TextMessageSend::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::TextMessage tm; - tm.set_message(request.text()); - if (request.has_actor() && request.actor().has_session()) { - tm.set_actor(request.actor().session()); - } - for (int i = 0; i < request.users_size(); i++) { - if (request.users(i).has_session()) { - tm.add_session(request.users(i).session()); + ::MumbleProto::TextMessage tm; + tm.set_message(request.text()); + if (request.has_actor() && request.actor().has_session()) { + tm.set_actor(request.actor().session()); } - } - for (int i = 0; i < request.channels_size(); i++) { - if (request.channels(i).has_id()) { - tm.add_channel_id(request.channels(i).id()); + for (int i = 0; i < request.users_size(); i++) { + if (request.users(i).has_session()) { + tm.add_session(request.users(i).session()); + } } - } - for (int i = 0; i < request.trees_size(); i++) { - if (request.trees(i).has_id()) { - tm.add_tree_id(request.trees(i).id()); + for (int i = 0; i < request.channels_size(); i++) { + if (request.channels(i).has_id()) { + tm.add_channel_id(request.channels(i).id()); + } } - } - - server->sendTextMessageGRPC(tm); - - end(); -} - -void V1_TextMessageFilter::impl(bool) { - auto onInitialize = [this] (V1_TextMessageFilter *, bool ok) { - if (!ok) { - finish(ok); - return; + for (int i = 0; i < request.trees_size(); i++) { + if (request.trees(i).has_id()) { + tm.add_tree_id(request.trees(i).id()); + } } - auto server = MustServer(request); - QMutexLocker l(&rpc->qmTextMessageFilterLock); - rpc->removeTextMessageFilter(server); - rpc->m_textMessageFilters.insert(server->iServerNum, this); - }; - stream.Read(&request, callback(onInitialize)); -} - -void V1_TextMessageFilter::done(bool) { - auto server = MustServer(request); - auto filter = rpc->m_textMessageFilters.value(server->iServerNum); - if (filter == this) { - rpc->m_textMessageFilters.remove(server->iServerNum); - } - deref(); -} -void V1_LogQuery::impl(bool) { - auto serverID = MustServerID(request); + server->sendTextMessageGRPC(tm); - int total = ::ServerDB::getLogLen(serverID); - if (total < 0) { - throw ::grpc::Status(::grpc::StatusCode::UNAVAILABLE, "could not access database"); + end(); } - ::MurmurRPC::Log_List list; - list.mutable_server()->set_id(serverID); - list.set_total(total); - - if (!request.has_min() || !request.has_max()) { - end(list); - return; + void V1_TextMessageFilter::impl(bool) { + auto onInitialize = [this](V1_TextMessageFilter *, bool ok) { + if (!ok) { + finish(ok); + return; + } + auto server = MustServer(request); + QMutexLocker l(&rpc->qmTextMessageFilterLock); + rpc->removeTextMessageFilter(server); + rpc->m_textMessageFilters.insert(server->iServerNum, this); + }; + stream.Read(&request, callback(onInitialize)); } - list.set_min(request.min()); - list.set_max(request.max()); - auto dblog = ::ServerDB::getLog(serverID, request.min(), request.max()); - foreach(const ::ServerDB::LogRecord &record, dblog) { - auto rpcLog = list.add_entries(); - ToRPC(serverID, record, rpcLog); + void V1_TextMessageFilter::done(bool) { + auto server = MustServer(request); + auto filter = rpc->m_textMessageFilters.value(server->iServerNum); + if (filter == this) { + rpc->m_textMessageFilters.remove(server->iServerNum); + } + deref(); } - end(list); -} + void V1_LogQuery::impl(bool) { + auto serverID = MustServerID(request); -void V1_ConfigGet::impl(bool) { - auto serverID = MustServerID(request); - auto config = ServerDB::getAllConf(serverID); + int total = ::ServerDB::getLogLen(serverID); + if (total < 0) { + throw ::grpc::Status(::grpc::StatusCode::UNAVAILABLE, "could not access database"); + } - ::MurmurRPC::Config rpcConfig; - rpcConfig.mutable_server()->set_id(serverID); - auto &fields = *rpcConfig.mutable_fields(); - for (auto i = config.constBegin(); i != config.constEnd(); ++i) { - fields[u8(i.key())] = u8(i.value()); - } + ::MurmurRPC::Log_List list; + list.mutable_server()->set_id(serverID); + list.set_total(total); - end(rpcConfig); -} + if (!request.has_min() || !request.has_max()) { + end(list); + return; + } + list.set_min(request.min()); + list.set_max(request.max()); -void V1_ConfigGetField::impl(bool) { - auto serverID = MustServerID(request); - if (!request.has_key()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); - } - ::MurmurRPC::Config_Field rpcField; - rpcField.mutable_server()->set_id(serverID); - rpcField.set_key(request.key()); - rpcField.set_value(u8(ServerDB::getConf(serverID, u8(request.key()), QVariant()).toString())); - end(rpcField); -} + auto dblog = ::ServerDB::getLog(serverID, request.min(), request.max()); + foreach (const ::ServerDB::LogRecord &record, dblog) { + auto rpcLog = list.add_entries(); + ToRPC(serverID, record, rpcLog); + } -void V1_ConfigSetField::impl(bool) { - auto serverID = MustServerID(request); - if (!request.has_key()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); - } - QString key = u8(request.key()); - QString value; - if (request.has_value()) { - value = u8(request.value()); - } - ServerDB::setConf(serverID, key, value); - try { - auto server = MustServer(serverID); - server->setLiveConf(key, value); - } catch (::grpc::Status &ex) { + end(list); } - end(); -} + void V1_ConfigGet::impl(bool) { + auto serverID = MustServerID(request); + auto config = ServerDB::getAllConf(serverID); -void V1_ConfigGetDefault::impl(bool) { - ::MurmurRPC::Config rpcConfig; - auto &fields = *rpcConfig.mutable_fields(); - for (auto i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { - fields[u8(i.key())] = u8(i.value()); - } + ::MurmurRPC::Config rpcConfig; + rpcConfig.mutable_server()->set_id(serverID); + auto &fields = *rpcConfig.mutable_fields(); + for (auto i = config.constBegin(); i != config.constEnd(); ++i) { + fields[u8(i.key())] = u8(i.value()); + } - end(rpcConfig); -} + end(rpcConfig); + } -void V1_ChannelQuery::impl(bool) { - auto server = MustServer(request); + void V1_ConfigGetField::impl(bool) { + auto serverID = MustServerID(request); + if (!request.has_key()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); + } + ::MurmurRPC::Config_Field rpcField; + rpcField.mutable_server()->set_id(serverID); + rpcField.set_key(request.key()); + rpcField.set_value(u8(ServerDB::getConf(serverID, u8(request.key()), QVariant()).toString())); + end(rpcField); + } - ::MurmurRPC::Channel_List list; - list.mutable_server()->set_id(server->iServerNum); + void V1_ConfigSetField::impl(bool) { + auto serverID = MustServerID(request); + if (!request.has_key()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); + } + QString key = u8(request.key()); + QString value; + if (request.has_value()) { + value = u8(request.value()); + } + ServerDB::setConf(serverID, key, value); + try { + auto server = MustServer(serverID); + server->setLiveConf(key, value); + } catch (::grpc::Status &ex) { + } - foreach(const ::Channel *channel, server->qhChannels) { - auto rpcChannel = list.add_channels(); - ToRPC(server, channel, rpcChannel); + end(); } - end(list); -} + void V1_ConfigGetDefault::impl(bool) { + ::MurmurRPC::Config rpcConfig; + auto &fields = *rpcConfig.mutable_fields(); + for (auto i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { + fields[u8(i.key())] = u8(i.value()); + } -void V1_ChannelGet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + end(rpcConfig); + } - ::MurmurRPC::Channel rpcChannel; - ToRPC(server, channel, &rpcChannel); - end(rpcChannel); -} + void V1_ChannelQuery::impl(bool) { + auto server = MustServer(request); -void V1_ChannelAdd::impl(bool) { - auto server = MustServer(request); + ::MurmurRPC::Channel_List list; + list.mutable_server()->set_id(server->iServerNum); - if (!request.has_parent() || !request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "parent channel and name required"); - } - ::Channel *parent; - try { - parent = MustChannel(server, request.parent()); - } catch (::grpc::Status &ex) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid parent channel"); - } + foreach (const ::Channel *channel, server->qhChannels) { + auto rpcChannel = list.add_channels(); + ToRPC(server, channel, rpcChannel); + } - if (!server->canNest(parent)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot nest channel in given parent"); + end(list); } - QString qsName = u8(request.name()); + void V1_ChannelGet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::Channel *nc; - - { - QWriteLocker wl(&server->qrwlVoiceThread); - nc = server->addChannel(parent, qsName, request.temporary(), request.position()); + ::MurmurRPC::Channel rpcChannel; + ToRPC(server, channel, &rpcChannel); + end(rpcChannel); } - nc->qsDesc = u8(request.description()); - - server->updateChannel(nc); - int newid = nc->iId; + void V1_ChannelAdd::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::ChannelState mpcs; - mpcs.set_channel_id(newid); - mpcs.set_parent(parent->iId); - mpcs.set_name(request.name()); - mpcs.set_temporary(request.temporary()); - mpcs.set_position(request.position()); - mpcs.set_description(request.description()); - server->sendAll(mpcs); + if (!request.has_parent() || !request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "parent channel and name required"); + } + ::Channel *parent; + try { + parent = MustChannel(server, request.parent()); + } catch (::grpc::Status &ex) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid parent channel"); + } - ::MurmurRPC::Channel resChannel; - ToRPC(server, nc, &resChannel); - end(resChannel); -} + if (!server->canNest(parent)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot nest channel in given parent"); + } -void V1_ChannelRemove::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + QString qsName = u8(request.name()); - if (!channel->cParent) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot remove the root channel"); - } + ::Channel *nc; - server->removeChannel(channel); + { + QWriteLocker wl(&server->qrwlVoiceThread); + nc = server->addChannel(parent, qsName, request.temporary(), request.position()); + } - end(); -} + nc->qsDesc = u8(request.description()); -void V1_ChannelUpdate::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + server->updateChannel(nc); + int newid = nc->iId; - ::MumbleProto::ChannelState mpcs; - mpcs.set_channel_id(channel->iId); - for (int i = 0; i < request.links_size(); i++) { - if (!request.links(i).has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel link"); - } - mpcs.add_links(request.links(i).id()); - } - if (request.has_parent()) { - if (!request.parent().has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel parent"); - } - mpcs.set_parent(request.parent().id()); - } - if (request.has_name()) { + ::MumbleProto::ChannelState mpcs; + mpcs.set_channel_id(newid); + mpcs.set_parent(parent->iId); mpcs.set_name(request.name()); - } - if (request.has_position()) { + mpcs.set_temporary(request.temporary()); mpcs.set_position(request.position()); - } - if (request.has_description()) { mpcs.set_description(request.description()); - } + server->sendAll(mpcs); - QString err; - if (!server->setChannelStateGRPC(mpcs, err)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, u8(err)); + ::MurmurRPC::Channel resChannel; + ToRPC(server, nc, &resChannel); + end(resChannel); } - ::MurmurRPC::Channel rpcChannel; - ToRPC(server, channel, &rpcChannel); - end(rpcChannel); -} + void V1_ChannelRemove::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); -void V1_UserQuery::impl(bool) { - auto server = MustServer(request); + if (!channel->cParent) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot remove the root channel"); + } - ::MurmurRPC::User_List list; - list.mutable_server()->set_id(server->iServerNum); + server->removeChannel(channel); - foreach(const ::ServerUser *user, server->qhUsers) { - if (user->sState != ServerUser::Authenticated) { - continue; - } - auto rpcUser = list.add_users(); - ToRPC(server, user, rpcUser); + end(); } - end(list); -} + void V1_ChannelUpdate::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); + + ::MumbleProto::ChannelState mpcs; + mpcs.set_channel_id(channel->iId); + for (int i = 0; i < request.links_size(); i++) { + if (!request.links(i).has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel link"); + } + mpcs.add_links(request.links(i).id()); + } + if (request.has_parent()) { + if (!request.parent().has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel parent"); + } + mpcs.set_parent(request.parent().id()); + } + if (request.has_name()) { + mpcs.set_name(request.name()); + } + if (request.has_position()) { + mpcs.set_position(request.position()); + } + if (request.has_description()) { + mpcs.set_description(request.description()); + } -void V1_UserGet::impl(bool) { - auto server = MustServer(request); + QString err; + if (!server->setChannelStateGRPC(mpcs, err)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, u8(err)); + } - ::MurmurRPC::User rpcUser; + ::MurmurRPC::Channel rpcChannel; + ToRPC(server, channel, &rpcChannel); + end(rpcChannel); + } - if (request.has_session()) { - // Lookup user by session - auto user = MustUser(server, request); - ToRPC(server, user, &rpcUser); - end(rpcUser); - return; - } else if (request.has_name()) { - // Lookup user by name - QString qsName = u8(request.name()); - foreach(const ::ServerUser *user, server->qhUsers) { + void V1_UserQuery::impl(bool) { + auto server = MustServer(request); + + ::MurmurRPC::User_List list; + list.mutable_server()->set_id(server->iServerNum); + + foreach (const ::ServerUser *user, server->qhUsers) { if (user->sState != ServerUser::Authenticated) { continue; } - if (user->qsName == qsName) { - ToRPC(server, user, &rpcUser); - end(rpcUser); - return; - } + auto rpcUser = list.add_users(); + ToRPC(server, user, rpcUser); } - throw ::grpc::Status(::grpc::NOT_FOUND, "invalid user"); + + end(list); } - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "session or name required"); -} + void V1_UserGet::impl(bool) { + auto server = MustServer(request); -void V1_UserUpdate::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + ::MurmurRPC::User rpcUser; - auto channel = user->cChannel; - if (request.has_channel()) { - channel = MustChannel(server, request.channel()); - } - auto mute = user->bMute; - if (request.has_mute()) { - mute = request.mute(); - } - auto deaf = user->bDeaf; - if (request.has_deaf()) { - deaf = request.deaf(); - } - auto suppress = user->bSuppress; - if (request.has_suppress()) { - suppress = request.suppress(); - } - auto prioritySpeaker = user->bPrioritySpeaker; - if (request.has_priority_speaker()) { - prioritySpeaker = request.priority_speaker(); - } - auto name = user->qsName; - if (request.has_name()) { - name = u8(request.name()); - } - auto comment = user->qsComment; - if (request.has_comment()) { - comment = u8(request.comment()); + if (request.has_session()) { + // Lookup user by session + auto user = MustUser(server, request); + ToRPC(server, user, &rpcUser); + end(rpcUser); + return; + } else if (request.has_name()) { + // Lookup user by name + QString qsName = u8(request.name()); + foreach (const ::ServerUser *user, server->qhUsers) { + if (user->sState != ServerUser::Authenticated) { + continue; + } + if (user->qsName == qsName) { + ToRPC(server, user, &rpcUser); + end(rpcUser); + return; + } + } + throw ::grpc::Status(::grpc::NOT_FOUND, "invalid user"); + } + + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "session or name required"); } - server->setUserState(user, channel, mute, deaf, suppress, prioritySpeaker, name, comment); + void V1_UserUpdate::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - ::MurmurRPC::User rpcUser; - ToRPC(server, user, &rpcUser); - end(rpcUser); -} + auto channel = user->cChannel; + if (request.has_channel()) { + channel = MustChannel(server, request.channel()); + } + auto mute = user->bMute; + if (request.has_mute()) { + mute = request.mute(); + } + auto deaf = user->bDeaf; + if (request.has_deaf()) { + deaf = request.deaf(); + } + auto suppress = user->bSuppress; + if (request.has_suppress()) { + suppress = request.suppress(); + } + auto prioritySpeaker = user->bPrioritySpeaker; + if (request.has_priority_speaker()) { + prioritySpeaker = request.priority_speaker(); + } + auto name = user->qsName; + if (request.has_name()) { + name = u8(request.name()); + } + auto comment = user->qsComment; + if (request.has_comment()) { + comment = u8(request.comment()); + } -void V1_UserKick::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + server->setUserState(user, channel, mute, deaf, suppress, prioritySpeaker, name, comment); - ::MumbleProto::UserRemove mpur; - mpur.set_session(user->uiSession); - if (request.has_reason()) { - mpur.set_reason(request.reason()); + ::MurmurRPC::User rpcUser; + ToRPC(server, user, &rpcUser); + end(rpcUser); } - if (request.has_actor() && request.actor().has_session()) { - mpur.set_actor(request.actor().session()); + + void V1_UserKick::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + + ::MumbleProto::UserRemove mpur; + mpur.set_session(user->uiSession); + if (request.has_reason()) { + mpur.set_reason(request.reason()); + } + if (request.has_actor() && request.actor().has_session()) { + mpur.set_actor(request.actor().session()); + } + server->sendAll(mpur); + user->disconnectSocket(); + + end(); } - server->sendAll(mpur); - user->disconnectSocket(); - end(); -} + void V1_TreeQuery::impl(bool) { + auto server = MustServer(request); -void V1_TreeQuery::impl(bool) { - auto server = MustServer(request); + auto channel = MustChannel(server, 0); + ::MurmurRPC::Tree root; - auto channel = MustChannel(server, 0); - ::MurmurRPC::Tree root; + QQueue< QPair< const ::Channel *, ::MurmurRPC::Tree * > > qQueue; + qQueue.enqueue(qMakePair(channel, &root)); - QQueue< QPair<const ::Channel *, ::MurmurRPC::Tree *> > qQueue; - qQueue.enqueue(qMakePair(channel, &root)); + while (!qQueue.isEmpty()) { + auto current = qQueue.dequeue(); + auto currentChannel = current.first; + auto currentTree = current.second; - while (!qQueue.isEmpty()) { - auto current = qQueue.dequeue(); - auto currentChannel = current.first; - auto currentTree = current.second; + ToRPC(server, currentChannel, currentTree->mutable_channel()); - ToRPC(server, currentChannel, currentTree->mutable_channel()); + QList<::User * > users = currentChannel->qlUsers; + std::sort(users.begin(), users.end(), + [](const ::User *a, const ::User *b) -> bool { return ::User::lessThan(a, b); }); + foreach (const ::User *u, users) { + auto rpcUser = currentTree->add_users(); + ToRPC(server, u, rpcUser); + } - QList< ::User *> users = currentChannel->qlUsers; - std::sort(users.begin(), users.end(), [] (const ::User *a, const ::User *b) -> bool { - return ::User::lessThan(a, b); - }); - foreach(const ::User *u, users) { - auto rpcUser = currentTree->add_users(); - ToRPC(server, u, rpcUser); + QList<::Channel * > channels = currentChannel->qlChannels; + std::sort(channels.begin(), channels.end(), + [](const ::Channel *a, const ::Channel *b) -> bool { return ::Channel::lessThan(a, b); }); + foreach (const ::Channel *subChannel, channels) { + auto subTree = currentTree->add_children(); + qQueue.enqueue(qMakePair(subChannel, subTree)); + } } - QList< ::Channel *> channels = currentChannel->qlChannels; - std::sort(channels.begin(), channels.end(), [] (const ::Channel *a, const ::Channel *b) -> bool { - return ::Channel::lessThan(a, b); - }); - foreach(const ::Channel *subChannel, channels) { - auto subTree = currentTree->add_children(); - qQueue.enqueue(qMakePair(subChannel, subTree)); - } + end(root); } - end(root); -} + void V1_BansGet::impl(bool) { + auto server = MustServer(request); -void V1_BansGet::impl(bool) { - auto server = MustServer(request); + ::MurmurRPC::Ban_List list; + list.mutable_server()->set_id(server->iServerNum); + foreach (const ::Ban &ban, server->qlBans) { + auto rpcBan = list.add_bans(); + ToRPC(server, ban, rpcBan); + } - ::MurmurRPC::Ban_List list; - list.mutable_server()->set_id(server->iServerNum); - foreach(const ::Ban &ban, server->qlBans) { - auto rpcBan = list.add_bans(); - ToRPC(server, ban, rpcBan); + end(list); } - end(list); -} + void V1_BansSet::impl(bool) { + auto server = MustServer(request); + server->qlBans.clear(); -void V1_BansSet::impl(bool) { - auto server = MustServer(request); - server->qlBans.clear(); + for (int i = 0; i < request.bans_size(); i++) { + const auto &rpcBan = request.bans(i); + ::Ban ban; + FromRPC(server, rpcBan, ban); + server->qlBans << ban; + } + server->saveBans(); - for (int i = 0; i < request.bans_size(); i++) { - const auto &rpcBan = request.bans(i); - ::Ban ban; - FromRPC(server, rpcBan, ban); - server->qlBans << ban; + end(); } - server->saveBans(); - - end(); -} -void V1_ACLGet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + void V1_ACLGet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::MurmurRPC::ACL_List list; - list.set_inherit(channel->bInheritACL); + ::MurmurRPC::ACL_List list; + list.set_inherit(channel->bInheritACL); - QStack< ::Channel *> chans; - ChanACL *acl; - ::Channel *p = channel; - while (p) { - chans.push(p); - if ((p == channel) || p->bInheritACL) { - p = p->cParent; - } else { - p = nullptr; + QStack<::Channel * > chans; + ChanACL *acl; + ::Channel *p = channel; + while (p) { + chans.push(p); + if ((p == channel) || p->bInheritACL) { + p = p->cParent; + } else { + p = nullptr; + } } - } - while (!chans.isEmpty()) { - p = chans.pop(); - foreach(acl, p->qlACL) { - if (p == channel || acl->bApplySubs) { - auto rpcACL = list.add_acls(); - ToRPC(server, acl, rpcACL); - if (p != channel) { - rpcACL->set_inherited(true); + while (!chans.isEmpty()) { + p = chans.pop(); + foreach (acl, p->qlACL) { + if (p == channel || acl->bApplySubs) { + auto rpcACL = list.add_acls(); + ToRPC(server, acl, rpcACL); + if (p != channel) { + rpcACL->set_inherited(true); + } } } } - } - p = channel->cParent; - const QSet<QString> allnames = ::Group::groupNames(channel); - foreach(const QString &name, allnames) { - ::Group *g = channel->qhGroups.value(name); - ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; - if (!g && ! pg) { - continue; - } - auto aclGroup = list.add_groups(); - ToRPC(server, g ? g : pg, aclGroup); - QSet<int> members; - if (pg) { - members = pg->members(); - } - if (g) { - foreach(auto id, g->qsAdd) { - auto rpcUser = aclGroup->add_users_add(); - rpcUser->mutable_server()->set_id(server->iServerNum); - rpcUser->set_id(id); + p = channel->cParent; + const QSet< QString > allnames = ::Group::groupNames(channel); + foreach (const QString &name, allnames) { + ::Group *g = channel->qhGroups.value(name); + ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; + if (!g && !pg) { + continue; + } + auto aclGroup = list.add_groups(); + ToRPC(server, g ? g : pg, aclGroup); + QSet< int > members; + if (pg) { + members = pg->members(); + } + if (g) { + foreach (auto id, g->qsAdd) { + auto rpcUser = aclGroup->add_users_add(); + rpcUser->mutable_server()->set_id(server->iServerNum); + rpcUser->set_id(id); + } + foreach (auto id, g->qsRemove) { + auto rpcUser = aclGroup->add_users_remove(); + rpcUser->mutable_server()->set_id(server->iServerNum); + rpcUser->set_id(id); + } + aclGroup->set_inherited(false); + members += g->qsAdd; + members -= g->qsRemove; + } else { + aclGroup->set_inherited(true); } - foreach(auto id, g->qsRemove) { - auto rpcUser = aclGroup->add_users_remove(); + foreach (auto id, members) { + auto rpcUser = aclGroup->add_users(); rpcUser->mutable_server()->set_id(server->iServerNum); rpcUser->set_id(id); } - aclGroup->set_inherited(false); - members += g->qsAdd; - members -= g->qsRemove; - } else { - aclGroup->set_inherited(true); - } - foreach(auto id, members) { - auto rpcUser = aclGroup->add_users(); - rpcUser->mutable_server()->set_id(server->iServerNum); - rpcUser->set_id(id); } - } - end(list); -} + end(list); + } -void V1_ACLSet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + void V1_ACLSet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::Group *g; - ::ChanACL *acl; + ::Group *g; + ::ChanACL *acl; - { - QWriteLocker wl(&server->qrwlVoiceThread); + { + QWriteLocker wl(&server->qrwlVoiceThread); - QHash<QString, QSet<int> > hOldTemp; - foreach(g, channel->qhGroups) { - hOldTemp.insert(g->qsName, g->qsTemporary); - delete g; - } - foreach(acl, channel->qlACL) { - delete acl; - } + QHash< QString, QSet< int > > hOldTemp; + foreach (g, channel->qhGroups) { + hOldTemp.insert(g->qsName, g->qsTemporary); + delete g; + } + foreach (acl, channel->qlACL) { delete acl; } - channel->qhGroups.clear(); - channel->qlACL.clear(); + channel->qhGroups.clear(); + channel->qlACL.clear(); - channel->bInheritACL = request.inherit(); + channel->bInheritACL = request.inherit(); - for (int i = 0; i < request.groups_size(); i++) { - auto &rpcGroup = request.groups(i); - auto name = u8(rpcGroup.name()); - g = new ::Group(channel, name); - g->bInherit = rpcGroup.inherit(); - g->bInheritable = rpcGroup.inheritable(); - for (int j = 0; j < rpcGroup.users_add_size(); j++) { - g->qsAdd.insert(rpcGroup.users_add(j).id()); - } - for (int j = 0; j < rpcGroup.users_remove_size(); j++) { - g->qsRemove.insert(rpcGroup.users_remove(j).id()); - } - g->qsTemporary = hOldTemp.value(name); - } - for (int i = 0; i < request.acls_size(); i++) { - auto &rpcACL = request.acls(i); - acl = new ChanACL(channel); - acl->bApplyHere = rpcACL.apply_here(); - acl->bApplySubs = rpcACL.apply_subs(); - if (rpcACL.has_user()) { - acl->iUserId = rpcACL.user().id(); + for (int i = 0; i < request.groups_size(); i++) { + auto &rpcGroup = request.groups(i); + auto name = u8(rpcGroup.name()); + g = new ::Group(channel, name); + g->bInherit = rpcGroup.inherit(); + g->bInheritable = rpcGroup.inheritable(); + for (int j = 0; j < rpcGroup.users_add_size(); j++) { + g->qsAdd.insert(rpcGroup.users_add(j).id()); + } + for (int j = 0; j < rpcGroup.users_remove_size(); j++) { + g->qsRemove.insert(rpcGroup.users_remove(j).id()); + } + g->qsTemporary = hOldTemp.value(name); } - if (rpcACL.has_group() && rpcACL.group().has_name()) { - acl->qsGroup = u8(rpcACL.group().name()); + for (int i = 0; i < request.acls_size(); i++) { + auto &rpcACL = request.acls(i); + acl = new ChanACL(channel); + acl->bApplyHere = rpcACL.apply_here(); + acl->bApplySubs = rpcACL.apply_subs(); + if (rpcACL.has_user()) { + acl->iUserId = rpcACL.user().id(); + } + if (rpcACL.has_group() && rpcACL.group().has_name()) { + acl->qsGroup = u8(rpcACL.group().name()); + } + acl->pDeny = static_cast< ChanACL::Permissions >(rpcACL.deny()) & ChanACL::All; + acl->pAllow = static_cast< ChanACL::Permissions >(rpcACL.allow()) & ChanACL::All; } - acl->pDeny = static_cast<ChanACL::Permissions>(rpcACL.deny()) & ChanACL::All; - acl->pAllow = static_cast<ChanACL::Permissions>(rpcACL.allow()) & ChanACL::All; } - } - server->clearACLCache(); - server->updateChannel(channel); + server->clearACLCache(); + server->updateChannel(channel); - end(); -} - -void V1_ACLGetEffectivePermissions::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); - - auto flags = int(server->effectivePermissions(user, channel)); - - ::MurmurRPC::ACL rpcACL; - rpcACL.set_allow(::MurmurRPC::ACL_Permission(flags)); - end(rpcACL); -} + end(); + } -void V1_ACLAddTemporaryGroup::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); + void V1_ACLGetEffectivePermissions::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } + auto flags = int(server->effectivePermissions(user, channel)); - QString qsgroup = u8(request.name()); - if (qsgroup.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + ::MurmurRPC::ACL rpcACL; + rpcACL.set_allow(::MurmurRPC::ACL_Permission(flags)); + end(rpcACL); } - { - QWriteLocker wl(&server->qrwlVoiceThread); + void V1_ACLAddTemporaryGroup::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - ::Group *g = channel->qhGroups.value(qsgroup); - if (!g) { - g = new ::Group(channel, qsgroup); + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); } - g->qsTemporary.insert(-user->uiSession); - } + QString qsgroup = u8(request.name()); + if (qsgroup.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + } - server->clearACLCache(user); + { + QWriteLocker wl(&server->qrwlVoiceThread); - end(); -} + ::Group *g = channel->qhGroups.value(qsgroup); + if (!g) { + g = new ::Group(channel, qsgroup); + } -void V1_ACLRemoveTemporaryGroup::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); + g->qsTemporary.insert(-user->uiSession); + } - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } + server->clearACLCache(user); - QString qsgroup = u8(request.name()); - if (qsgroup.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + end(); } - { - QWriteLocker wl(&server->qrwlVoiceThread); + void V1_ACLRemoveTemporaryGroup::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - ::Group *g = channel->qhGroups.value(qsgroup); - if (!g) { - g = new ::Group(channel, qsgroup); + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); } - g->qsTemporary.remove(-user->uiSession); - } + QString qsgroup = u8(request.name()); + if (qsgroup.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + } - server->clearACLCache(user); + { + QWriteLocker wl(&server->qrwlVoiceThread); - end(); -} + ::Group *g = channel->qhGroups.value(qsgroup); + if (!g) { + g = new ::Group(channel, qsgroup); + } -void V1_AuthenticatorStream::impl(bool) { - auto onInitialize = [this] (V1_AuthenticatorStream *, bool ok) { - if (!ok) { - finish(ok); - return; - } - if (!request.has_initialize()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing initialize"); + g->qsTemporary.remove(-user->uiSession); } - auto server = MustServer(request.initialize()); - QMutexLocker l(&rpc->qmAuthenticatorsLock); - rpc->removeAuthenticator(server); - rpc->m_authenticators.insert(server->iServerNum, this); - }; - stream.Read(&request, callback(onInitialize)); -} -void V1_AuthenticatorStream::done(bool) { - auto i = std::find(rpc->m_authenticators.begin(), rpc->m_authenticators.end(), this); - if (i != rpc->m_authenticators.end()) { - rpc->m_authenticators.erase(i); + server->clearACLCache(user); + + end(); } - deref(); -} -void V1_DatabaseUserQuery::impl(bool) { - auto server = MustServer(request); + void V1_AuthenticatorStream::impl(bool) { + auto onInitialize = [this](V1_AuthenticatorStream *, bool ok) { + if (!ok) { + finish(ok); + return; + } + if (!request.has_initialize()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing initialize"); + } + auto server = MustServer(request.initialize()); + QMutexLocker l(&rpc->qmAuthenticatorsLock); + rpc->removeAuthenticator(server); + rpc->m_authenticators.insert(server->iServerNum, this); + }; + stream.Read(&request, callback(onInitialize)); + } - QString filter; - if (request.has_filter()) { - filter = u8(request.filter()); + void V1_AuthenticatorStream::done(bool) { + auto i = std::find(rpc->m_authenticators.begin(), rpc->m_authenticators.end(), this); + if (i != rpc->m_authenticators.end()) { + rpc->m_authenticators.erase(i); + } + deref(); } - auto users = server->getRegisteredUsers(filter); - ::MurmurRPC::DatabaseUser_List list; - list.mutable_server()->set_id(server->iServerNum); + void V1_DatabaseUserQuery::impl(bool) { + auto server = MustServer(request); - for (auto itr = users.constBegin(); itr != users.constEnd(); ++itr) { - auto user = list.add_users(); - user->mutable_server()->set_id(server->iServerNum); - user->set_id(itr.key()); - user->set_name(u8(itr.value())); - } + QString filter; + if (request.has_filter()) { + filter = u8(request.filter()); + } + auto users = server->getRegisteredUsers(filter); - end(list); -} + ::MurmurRPC::DatabaseUser_List list; + list.mutable_server()->set_id(server->iServerNum); -void V1_DatabaseUserGet::impl(bool) { - auto server = MustServer(request); + for (auto itr = users.constBegin(); itr != users.constEnd(); ++itr) { + auto user = list.add_users(); + user->mutable_server()->set_id(server->iServerNum); + user->set_id(itr.key()); + user->set_name(u8(itr.value())); + } - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - auto info = server->getRegistration(request.id()); - if (info.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + end(list); } - auto texture = server->getUserTexture(request.id()); - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - ToRPC(server, info, texture, &rpcDatabaseUser); - end(rpcDatabaseUser); -} + void V1_DatabaseUserGet::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserUpdate::impl(bool) { - auto server = MustServer(request); + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + auto info = server->getRegistration(request.id()); + if (info.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + auto texture = server->getUserTexture(request.id()); - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - if (!server->isUserId(request.id())) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + ToRPC(server, info, texture, &rpcDatabaseUser); + end(rpcDatabaseUser); } - QMap<int, QString> info; - FromRPC(request, info); + void V1_DatabaseUserUpdate::impl(bool) { + auto server = MustServer(request); - if (!server->setInfo(request.id(), info)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); - } - if (request.has_texture()) { - server->setTexture(request.id(), QByteArray(request.texture().c_str(), request.texture().size())); - } + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + if (!server->isUserId(request.id())) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } - if (info.contains(ServerDB::User_Name) || info.contains(ServerDB::User_Comment)) { - foreach(::ServerUser *u, server->qhUsers) { - if (static_cast<unsigned int>(u->iId) == request.id()) { - QString name = u->qsName; - QString comment = u->qsComment; - if (info.contains(ServerDB::User_Name)) { - name = info.value(ServerDB::User_Name); - } - if (info.contains(ServerDB::User_Comment)) { - comment = info.value(ServerDB::User_Comment); + QMap< int, QString > info; + FromRPC(request, info); + + if (!server->setInfo(request.id(), info)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + if (request.has_texture()) { + server->setTexture(request.id(), QByteArray(request.texture().c_str(), request.texture().size())); + } + + if (info.contains(ServerDB::User_Name) || info.contains(ServerDB::User_Comment)) { + foreach (::ServerUser *u, server->qhUsers) { + if (static_cast< unsigned int >(u->iId) == request.id()) { + QString name = u->qsName; + QString comment = u->qsComment; + if (info.contains(ServerDB::User_Name)) { + name = info.value(ServerDB::User_Name); + } + if (info.contains(ServerDB::User_Comment)) { + comment = info.value(ServerDB::User_Comment); + } + server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, name, + comment); + break; } - server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, name, comment); - break; } } + + end(); } - end(); -} + void V1_DatabaseUserRegister::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserRegister::impl(bool) { - auto server = MustServer(request); + QMap< int, QString > info; + FromRPC(request, info); - QMap<int, QString> info; - FromRPC(request, info); + auto userid = server->registerUser(info); + if (userid < 0) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + QByteArray texture; + if (request.has_texture()) { + texture = QByteArray(request.texture().c_str(), request.texture().size()); + server->setTexture(request.id(), texture); + } - auto userid = server->registerUser(info); - if (userid < 0) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); - } - QByteArray texture; - if (request.has_texture()) { - texture = QByteArray(request.texture().c_str(), request.texture().size()); - server->setTexture(request.id(), texture); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + rpcDatabaseUser.set_id(userid); + ToRPC(server, info, texture, &rpcDatabaseUser); + end(rpcDatabaseUser); } - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - rpcDatabaseUser.set_id(userid); - ToRPC(server, info, texture, &rpcDatabaseUser); - end(rpcDatabaseUser); -} + void V1_DatabaseUserDeregister::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserDeregister::impl(bool) { - auto server = MustServer(request); + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + if (!server->unregisterUser(request.id())) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - if (!server->unregisterUser(request.id())) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + end(); } - end(); -} - -void V1_DatabaseUserVerify::impl(bool) { - auto server = MustServer(request); + void V1_DatabaseUserVerify::impl(bool) { + auto server = MustServer(request); - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } - if (!request.has_password()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing password"); - } + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); + } + if (!request.has_password()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing password"); + } - auto name = u8(request.name()); - auto password = u8(request.password()); + auto name = u8(request.name()); + auto password = u8(request.password()); + + auto ret = server->authenticate(name, password); + switch (ret) { + case -1: + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid username and/or password"); + case -2: + throw ::grpc::Status(::grpc::NOT_FOUND, "unknown user"); + case -3: + throw ::grpc::Status(::grpc::UNAVAILABLE, "authenticator temporarily unavailable"); + } - auto ret = server->authenticate(name, password); - switch (ret) { - case -1: - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid username and/or password"); - case -2: - throw ::grpc::Status(::grpc::NOT_FOUND, "unknown user"); - case -3: - throw ::grpc::Status(::grpc::UNAVAILABLE, "authenticator temporarily unavailable"); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + rpcDatabaseUser.mutable_server()->set_id(server->iServerNum); + rpcDatabaseUser.set_id(ret); + end(rpcDatabaseUser); } - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - rpcDatabaseUser.mutable_server()->set_id(server->iServerNum); - rpcDatabaseUser.set_id(ret); - end(rpcDatabaseUser); -} + void V1_RedirectWhisperGroupAdd::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + + if (!request.source().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); + } + if (!request.target().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing target name"); + } -void V1_RedirectWhisperGroupAdd::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + QString qssource = u8(request.source().name()); + QString qstarget = u8(request.target().name()); - if (!request.source().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); - } - if (!request.target().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing target name"); - } + { + QWriteLocker wl(&server->qrwlVoiceThread); + user->qmWhisperRedirect.insert(qssource, qstarget); + } - QString qssource = u8(request.source().name()); - QString qstarget = u8(request.target().name()); + server->clearACLCache(user); - { - QWriteLocker wl(&server->qrwlVoiceThread); - user->qmWhisperRedirect.insert(qssource, qstarget); + end(); } - server->clearACLCache(user); + void V1_RedirectWhisperGroupRemove::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - end(); -} + if (!request.source().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); + } -void V1_RedirectWhisperGroupRemove::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + QString qssource = u8(request.source().name()); - if (!request.source().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); - } + { + QWriteLocker wl(&server->qrwlVoiceThread); + user->qmWhisperRedirect.remove(qssource); + } - QString qssource = u8(request.source().name()); + server->clearACLCache(user); - { - QWriteLocker wl(&server->qrwlVoiceThread); - user->qmWhisperRedirect.remove(qssource); + end(); } - server->clearACLCache(user); - - end(); -} - -} -} +} // namespace Wrapper +} // namespace MurmurRPC diff --git a/src/murmur/MurmurGRPCImpl.h b/src/murmur/MurmurGRPCImpl.h index 14b62c088..69ec36d2a 100644 --- a/src/murmur/MurmurGRPCImpl.h +++ b/src/murmur/MurmurGRPCImpl.h @@ -4,149 +4,149 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_GRPC -#ifndef MUMBLE_MURMUR_MURMURRPC_H_ -#define MUMBLE_MURMUR_MURMURRPC_H_ +# ifndef MUMBLE_MURMUR_MURMURRPC_H_ +# define MUMBLE_MURMUR_MURMURRPC_H_ -#include <QtCore/QCoreApplication> +# include <QtCore/QCoreApplication> -#include <boost/bind.hpp> +# include <boost/bind.hpp> -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" -#include "MurmurRPC.grpc.pb.h" -#pragma GCC diagnostic pop +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-parameter" +# include "MurmurRPC.grpc.pb.h" +# pragma GCC diagnostic pop -#include "Server.h" -#include "Meta.h" +# include "Meta.h" +# include "Server.h" -#include <atomic> +# include <atomic> -#include <QMultiHash> -#include <QSet> +# include <QMultiHash> +# include <QSet> -#include <grpc++/grpc++.h> -#include <grpc++/security/auth_context.h> +# include <grpc++/grpc++.h> +# include <grpc++/security/auth_context.h> class RPCCall; namespace MurmurRPC { - namespace Wrapper { - class V1_ContextActionEvents; - class V1_Events; - class V1_ServerEvents; - class V1_AuthenticatorStream; - class V1_TextMessageFilter; - } -} +namespace Wrapper { + class V1_ContextActionEvents; + class V1_Events; + class V1_ServerEvents; + class V1_AuthenticatorStream; + class V1_TextMessageFilter; +} // namespace Wrapper +} // namespace MurmurRPC class MurmurRPCAuthenticator : public ::grpc::AuthMetadataProcessor { - public: - MurmurRPCAuthenticator(); - grpc::Status Process(const InputMetadata&, ::grpc::AuthContext*, OutputMetadata*, OutputMetadata*); - bool IsBlocking() const; - protected: - QSet<QByteArray> m_gRPCUsers; +public: + MurmurRPCAuthenticator(); + grpc::Status Process(const InputMetadata &, ::grpc::AuthContext *, OutputMetadata *, OutputMetadata *); + bool IsBlocking() const; + +protected: + QSet< QByteArray > m_gRPCUsers; }; class MurmurRPCImpl : public QThread { - Q_OBJECT; - std::unique_ptr<grpc::Server> m_server; - volatile bool m_isRunning; - protected: - void customEvent(QEvent *evt); - public: - MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials> credentials); - ~MurmurRPCImpl(); - void run(); - std::unique_ptr<grpc::ServerCompletionQueue> m_completionQueue; - - // Services - MurmurRPC::V1::AsyncService m_V1Service; - - // Listeners - QHash<int, QMultiHash<QString, ::MurmurRPC::Wrapper::V1_ContextActionEvents *> > m_contextActionListeners; - - QSet<::MurmurRPC::Wrapper::V1_Events *> m_metaServiceListeners; - - QMultiHash<int, ::MurmurRPC::Wrapper::V1_ServerEvents *> m_serverServiceListeners; - - QMutex qmAuthenticatorsLock; - QHash<int, ::MurmurRPC::Wrapper::V1_AuthenticatorStream *> m_authenticators; - - QMutex qmTextMessageFilterLock; - QHash<int, ::MurmurRPC::Wrapper::V1_TextMessageFilter *> m_textMessageFilters; - - // Maps server id -> session -> context action - QMap<int, QMap<unsigned int, QSet<QString> > > m_activeContextActions; - - bool hasActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void addActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void removeActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void removeUserActiveContextActions(const ::Server *s, const ::User *u); - void removeActiveContextActions(const ::Server *s); - - void removeTextMessageFilter(const ::Server *s); - void removeAuthenticator(const ::Server *s); - void sendMetaEvent(const ::MurmurRPC::Event &e); - void sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e); - - public slots: - void started(Server *server); - void stopped(Server *server); - - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); - - void userStateChanged(const User *user); - void userTextMessage(const User *user, const TextMessage &message); - void userConnected(const User *user); - void userDisconnected(const User *user); - void channelStateChanged(const Channel *channel); - void channelCreated(const Channel *channel); - void channelRemoved(const Channel *channel); - - void textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message); - - void contextAction(const User *user, const QString &action, unsigned int session, int channel); + Q_OBJECT; + std::unique_ptr< grpc::Server > m_server; + volatile bool m_isRunning; + +protected: + void customEvent(QEvent *evt); + +public: + MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials > credentials); + ~MurmurRPCImpl(); + void run(); + std::unique_ptr< grpc::ServerCompletionQueue > m_completionQueue; + + // Services + MurmurRPC::V1::AsyncService m_V1Service; + + // Listeners + QHash< int, QMultiHash< QString, ::MurmurRPC::Wrapper::V1_ContextActionEvents * > > m_contextActionListeners; + + QSet<::MurmurRPC::Wrapper::V1_Events * > m_metaServiceListeners; + + QMultiHash< int, ::MurmurRPC::Wrapper::V1_ServerEvents * > m_serverServiceListeners; + + QMutex qmAuthenticatorsLock; + QHash< int, ::MurmurRPC::Wrapper::V1_AuthenticatorStream * > m_authenticators; + + QMutex qmTextMessageFilterLock; + QHash< int, ::MurmurRPC::Wrapper::V1_TextMessageFilter * > m_textMessageFilters; + + // Maps server id -> session -> context action + QMap< int, QMap< unsigned int, QSet< QString > > > m_activeContextActions; + + bool hasActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void addActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void removeActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void removeUserActiveContextActions(const ::Server *s, const ::User *u); + void removeActiveContextActions(const ::Server *s); + + void removeTextMessageFilter(const ::Server *s); + void removeAuthenticator(const ::Server *s); + void sendMetaEvent(const ::MurmurRPC::Event &e); + void sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e); + +public slots: + void started(Server *server); + void stopped(Server *server); + + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); + + void userStateChanged(const User *user); + void userTextMessage(const User *user, const TextMessage &message); + void userConnected(const User *user); + void userDisconnected(const User *user); + void channelStateChanged(const Channel *channel); + void channelCreated(const Channel *channel); + void channelRemoved(const Channel *channel); + + void textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message); + + void contextAction(const User *user, const QString &action, unsigned int session, int channel); }; class RPCExecEvent : public ExecEvent { Q_DISABLE_COPY(RPCExecEvent); + public: RPCCall *call; - RPCExecEvent(::boost::function<void()> fn, RPCCall *rpc_call) : ExecEvent(fn), call(rpc_call) { - } + RPCExecEvent(::boost::function< void() > fn, RPCCall *rpc_call) : ExecEvent(fn), call(rpc_call) {} }; class RPCCall { ::std::atomic_int m_refs; + public: MurmurRPCImpl *rpc; ::grpc::ServerContext context; - RPCCall(MurmurRPCImpl *rpcImpl) : m_refs(0), rpc(rpcImpl) { - ref(); - } - virtual ~RPCCall() { - } - virtual ::boost::function<void(bool)> *done() { + RPCCall(MurmurRPCImpl *rpcImpl) : m_refs(0), rpc(rpcImpl) { ref(); } + virtual ~RPCCall() {} + virtual ::boost::function< void(bool) > *done() { auto done_fn = ::boost::bind(&RPCCall::finish, this, _1); - return new ::boost::function<void(bool)>(done_fn); + return new ::boost::function< void(bool) >(done_fn); } - virtual void error(const ::grpc::Status&) = 0; + virtual void error(const ::grpc::Status &) = 0; - virtual void finish(bool) { - deref(); - } + virtual void finish(bool) { deref(); } virtual void deref() { Q_ASSERT(m_refs > 0); @@ -154,13 +154,11 @@ public: delete this; } } - virtual void ref() { - m_refs++; - } + virtual void ref() { m_refs++; } - template<class T> - class Ref { + template< class T > class Ref { T *m_object; + public: Ref(T *object) : m_object(object) { if (object) { @@ -172,31 +170,21 @@ public: m_object->deref(); } } - operator bool() const { - return m_object != nullptr && !m_object->context.IsCancelled(); - } - T *operator->() { - return m_object; - } + operator bool() const { return m_object != nullptr && !m_object->context.IsCancelled(); } + T *operator->() { return m_object; } }; }; -template <class InType, class OutType> -class RPCSingleSingleCall : public RPCCall { +template< class InType, class OutType > class RPCSingleSingleCall : public RPCCall { public: InType request; - ::grpc::ServerAsyncResponseWriter < OutType > stream; + ::grpc::ServerAsyncResponseWriter< OutType > stream; - RPCSingleSingleCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + RPCSingleSingleCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.FinishWithError(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.FinishWithError(err, done()); } - virtual void end(const OutType &msg = OutType()) { - stream.Finish(msg, ::grpc::Status::OK, done()); - } + virtual void end(const OutType &msg = OutType()) { stream.Finish(msg, ::grpc::Status::OK, done()); } }; /// Base for "single-stream" RPC methods. @@ -204,19 +192,16 @@ public: /// The helper method "write" automatically queues writes to the stream. Without /// write queuing, the grpc crashes if a stream.Write is called before a /// previous stream.Write completes. -template <class InType, class OutType> -class RPCSingleStreamCall : public RPCCall { +template< class InType, class OutType > class RPCSingleStreamCall : public RPCCall { QMutex m_writeLock; - QQueue< QPair<OutType, void *> > m_writeQueue; + QQueue< QPair< OutType, void * > > m_writeQueue; + public: InType request; - ::grpc::ServerAsyncWriter < OutType > stream; - RPCSingleStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + ::grpc::ServerAsyncWriter< OutType > stream; + RPCSingleStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.Finish(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.Finish(err, done()); } void write(const OutType &msg, void *tag) { QMutexLocker l(&m_writeLock); @@ -230,15 +215,15 @@ public: private: void *writeCB() { - auto callback = ::boost::bind(&RPCSingleStreamCall<InType, OutType>::writeCallback, this, _1); - return new ::boost::function<void(bool)>(callback); + auto callback = ::boost::bind(&RPCSingleStreamCall< InType, OutType >::writeCallback, this, _1); + return new ::boost::function< void(bool) >(callback); } void writeCallback(bool ok) { QMutexLocker l(&m_writeLock); auto processed = m_writeQueue.dequeue(); if (processed.second) { - auto cb = static_cast< ::boost::function<void(bool)> *>(processed.second); + auto cb = static_cast<::boost::function< void(bool) > * >(processed.second); (*cb)(ok); delete cb; } @@ -248,21 +233,17 @@ private: } }; -template <class InType, class OutType> -class RPCStreamStreamCall : public RPCCall { +template< class InType, class OutType > class RPCStreamStreamCall : public RPCCall { public: InType request; OutType response; ::grpc::ServerAsyncReaderWriter< OutType, InType > stream; - RPCStreamStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + RPCStreamStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.Finish(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.Finish(err, done()); } }; -#endif +# endif #endif diff --git a/src/murmur/MurmurI.h b/src/murmur/MurmurI.h index 89f20993b..ddca19fee 100644 --- a/src/murmur/MurmurI.h +++ b/src/murmur/MurmurI.h @@ -10,250 +10,181 @@ namespace Murmur { - class ServerI : virtual public Server { - public: +class ServerI : virtual public Server { +public: + virtual void isRunning_async(const ::Murmur::AMD_Server_isRunningPtr &, const Ice::Current &); - virtual void isRunning_async(const ::Murmur::AMD_Server_isRunningPtr&, - const Ice::Current&); + virtual void start_async(const ::Murmur::AMD_Server_startPtr &, const Ice::Current &); - virtual void start_async(const ::Murmur::AMD_Server_startPtr&, - const Ice::Current&); + virtual void stop_async(const ::Murmur::AMD_Server_stopPtr &, const Ice::Current &); - virtual void stop_async(const ::Murmur::AMD_Server_stopPtr&, - const Ice::Current&); + virtual void delete_async(const ::Murmur::AMD_Server_deletePtr &, const Ice::Current &); - virtual void delete_async(const ::Murmur::AMD_Server_deletePtr&, - const Ice::Current&); + virtual void addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &, const ::Murmur::ServerCallbackPrx &, + const ::Ice::Current &); + virtual void removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &, + const ::Murmur::ServerCallbackPrx &, const ::Ice::Current &); - virtual void addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr&, const ::Murmur::ServerCallbackPrx&, const ::Ice::Current&); - virtual void removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr&, const ::Murmur::ServerCallbackPrx&, const ::Ice::Current&); + virtual void setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &, + const ::Murmur::ServerAuthenticatorPrx &, const ::Ice::Current &); - virtual void setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr&, const ::Murmur::ServerAuthenticatorPrx&, const ::Ice::Current&); + virtual void id_async(const ::Murmur::AMD_Server_idPtr &, const Ice::Current &); - virtual void id_async(const ::Murmur::AMD_Server_idPtr&, - const Ice::Current&); + virtual void getConf_async(const ::Murmur::AMD_Server_getConfPtr &, const ::std::string &, const Ice::Current &); - virtual void getConf_async(const ::Murmur::AMD_Server_getConfPtr&, - const ::std::string&, - const Ice::Current&); + virtual void getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr &, const Ice::Current &); - virtual void getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr&, - const Ice::Current&); + virtual void setConf_async(const ::Murmur::AMD_Server_setConfPtr &, const ::std::string &, const ::std::string &, + const Ice::Current &); - virtual void setConf_async(const ::Murmur::AMD_Server_setConfPtr&, - const ::std::string&, - const ::std::string&, - const Ice::Current&); + virtual void setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &, const ::std::string &, + const Ice::Current &); - virtual void setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr&, - const ::std::string&, - const Ice::Current&); + virtual void getLog_async(const ::Murmur::AMD_Server_getLogPtr &, ::Ice::Int, ::Ice::Int, const Ice::Current &); - virtual void getLog_async(const ::Murmur::AMD_Server_getLogPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr &, const Ice::Current &); - virtual void getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr&, - const Ice::Current&); + virtual void getUsers_async(const ::Murmur::AMD_Server_getUsersPtr &, const Ice::Current &); - virtual void getUsers_async(const ::Murmur::AMD_Server_getUsersPtr&, - const Ice::Current&); + virtual void getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &, const Ice::Current &); - virtual void getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr&, - const Ice::Current&); + virtual void getTree_async(const ::Murmur::AMD_Server_getTreePtr &, const Ice::Current &); - virtual void getTree_async(const ::Murmur::AMD_Server_getTreePtr&, - const Ice::Current&); + virtual void getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &, ::Ice::Int, + const ::Ice::Current &); - virtual void getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr&, - ::Ice::Int, - const ::Ice::Current&); + virtual void getBans_async(const ::Murmur::AMD_Server_getBansPtr &, const Ice::Current &); - virtual void getBans_async(const ::Murmur::AMD_Server_getBansPtr&, - const Ice::Current&); + virtual void setBans_async(const ::Murmur::AMD_Server_setBansPtr &, const ::Murmur::BanList &, + const Ice::Current &); - virtual void setBans_async(const ::Murmur::AMD_Server_setBansPtr&, - const ::Murmur::BanList&, - const Ice::Current&); + virtual void kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &, ::Ice::Int, const ::std::string &, + const Ice::Current &); - virtual void kickUser_async(const ::Murmur::AMD_Server_kickUserPtr&, - ::Ice::Int, - const ::std::string&, - const Ice::Current&); + virtual void sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &, ::Ice::Int, const ::std::string &, + const Ice::Current &); - virtual void sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr&, - ::Ice::Int, - const ::std::string&, - const Ice::Current&); + virtual void hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &, ::Ice::Int, ::Ice::Int, ::Ice::Int, + const ::Ice::Current &); + virtual void effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &, ::Ice::Int, + ::Ice::Int, const ::Ice::Current &); - virtual void hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr&, ::Ice::Int, ::Ice::Int, ::Ice::Int, const ::Ice::Current&); - virtual void effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr&, ::Ice::Int, ::Ice::Int, const ::Ice::Current&); + virtual void addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &, ::Ice::Int, + const ::std::string &, const ::std::string &, + const ::Murmur::ServerContextCallbackPrx &, int, const ::Ice::Current &); + virtual void removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &, + const ::Murmur::ServerContextCallbackPrx &, const ::Ice::Current &); - virtual void addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr&, ::Ice::Int, const ::std::string&, const ::std::string&, const ::Murmur::ServerContextCallbackPrx&, int, const ::Ice::Current&); - virtual void removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr&, const ::Murmur::ServerContextCallbackPrx&, const ::Ice::Current&); + virtual void getState_async(const ::Murmur::AMD_Server_getStatePtr &, ::Ice::Int, const Ice::Current &); - virtual void getState_async(const ::Murmur::AMD_Server_getStatePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setState_async(const ::Murmur::AMD_Server_setStatePtr &, const ::Murmur::User &, const Ice::Current &); - virtual void setState_async(const ::Murmur::AMD_Server_setStatePtr&, - const ::Murmur::User&, - const Ice::Current&); + virtual void getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &, ::Ice::Int, + const Ice::Current &); - virtual void getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &, const ::Murmur::Channel &, + const Ice::Current &); - virtual void setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr&, - const ::Murmur::Channel&, - const Ice::Current&); + virtual void removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &, ::Ice::Int, const Ice::Current &); - virtual void removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &, const ::std::string &, ::Ice::Int, + const Ice::Current &); - virtual void addChannel_async(const ::Murmur::AMD_Server_addChannelPtr&, - const ::std::string&, - ::Ice::Int, - const Ice::Current&); + virtual void sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &, ::Ice::Int, bool, + const ::std::string &, const Ice::Current &); - virtual void sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr&, - ::Ice::Int, - bool, - const ::std::string&, - const Ice::Current&); + virtual void getACL_async(const ::Murmur::AMD_Server_getACLPtr &, ::Ice::Int, const Ice::Current &); - virtual void getACL_async(const ::Murmur::AMD_Server_getACLPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setACL_async(const ::Murmur::AMD_Server_setACLPtr &, ::Ice::Int, const ::Murmur::ACLList &, + const ::Murmur::GroupList &, bool, const Ice::Current &); - virtual void setACL_async(const ::Murmur::AMD_Server_setACLPtr&, - ::Ice::Int, - const ::Murmur::ACLList&, - const ::Murmur::GroupList&, - bool, - const Ice::Current&); + virtual void removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &, ::Ice::Int, ::Ice::Int, + const ::std::string &, const ::Ice::Current &); - virtual void removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr&, ::Ice::Int, ::Ice::Int, const ::std::string&, const ::Ice::Current&); + virtual void addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &, ::Ice::Int, ::Ice::Int, + const ::std::string &, const ::Ice::Current &); - virtual void addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr&, ::Ice::Int, ::Ice::Int, const ::std::string&, const ::Ice::Current&); + virtual void redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &, ::Ice::Int, + const ::std::string &, const ::std::string &, const ::Ice::Current &); - virtual void redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr&, ::Ice::Int, const ::std::string&, const ::std::string&, const ::Ice::Current&); + virtual void getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &, const ::Murmur::IdList &, + const Ice::Current &); - virtual void getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr&, - const ::Murmur::IdList&, - const Ice::Current&); + virtual void getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &, const ::Murmur::NameList &, + const Ice::Current &); - virtual void getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr&, - const ::Murmur::NameList&, - const Ice::Current&); + virtual void registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &, const Murmur::UserInfoMap &, + const Ice::Current &); - virtual void registerUser_async(const ::Murmur::AMD_Server_registerUserPtr&, - const Murmur::UserInfoMap&, - const Ice::Current&); + virtual void unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &, ::Ice::Int, const Ice::Current &); - virtual void unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &, Ice::Int, + const Murmur::UserInfoMap &, const Ice::Current &); - virtual void updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr&, - Ice::Int, - const Murmur::UserInfoMap&, - const Ice::Current&); + virtual void getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &, const ::std::string &, + const Ice::Current &); - virtual void getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr&, - const ::std::string&, - const Ice::Current&); + virtual void verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &, const ::std::string &, + const ::std::string &, const Ice::Current &); - virtual void verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr&, - const ::std::string&, - const ::std::string&, - const Ice::Current&); + virtual void getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &, ::Ice::Int, const Ice::Current &); - virtual void getTexture_async(const ::Murmur::AMD_Server_getTexturePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &, ::Ice::Int, const ::Murmur::Texture &, + const Ice::Current &); - virtual void setTexture_async(const ::Murmur::AMD_Server_setTexturePtr&, - ::Ice::Int, - const ::Murmur::Texture&, - const Ice::Current&); + virtual void getUptime_async(const ::Murmur::AMD_Server_getUptimePtr &, const Ice::Current &); - virtual void getUptime_async(const ::Murmur::AMD_Server_getUptimePtr&, - const Ice::Current&); + virtual void updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &, const std::string &, + const std::string &, const std::string &, const Ice::Current &); - virtual void updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr&, - const std::string&, - const std::string&, - const std::string&, - const Ice::Current&); + virtual void startListening_async(const ::Murmur::AMD_Server_startListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void startListening_async(const ::Murmur::AMD_Server_startListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void isListening_async(const ::Murmur::AMD_Server_isListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void isListening_async(const ::Murmur::AMD_Server_isListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void ice_ping(const Ice::Current &) const; +}; - virtual void ice_ping(const Ice::Current&) const; - }; +class MetaI : virtual public Meta { +public: + virtual void getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &, const ::Ice::Current &); - class MetaI : virtual public Meta { - public: - virtual void getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr&, - const ::Ice::Current&); + virtual void getServer_async(const ::Murmur::AMD_Meta_getServerPtr &, ::Ice::Int, const Ice::Current &); - virtual void getServer_async(const ::Murmur::AMD_Meta_getServerPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void newServer_async(const ::Murmur::AMD_Meta_newServerPtr &, const Ice::Current &); - virtual void newServer_async(const ::Murmur::AMD_Meta_newServerPtr&, - const Ice::Current&); + virtual void getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &, const Ice::Current &); - virtual void getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr&, - const Ice::Current&); + virtual void getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &, const Ice::Current &); - virtual void getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr&, - const Ice::Current&); + virtual void getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &, const Ice::Current &); - virtual void getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr&, - const Ice::Current&); + virtual void getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &, const Ice::Current &); - virtual void getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr&, - const Ice::Current&); + virtual void addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &, const ::Murmur::MetaCallbackPrx &, + const ::Ice::Current & = ::Ice::Current()); + virtual void removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &, const ::Murmur::MetaCallbackPrx &, + const ::Ice::Current & = ::Ice::Current()); - virtual void addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr&, const ::Murmur::MetaCallbackPrx&, const ::Ice::Current& = ::Ice::Current()); - virtual void removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr&, const ::Murmur::MetaCallbackPrx&, const ::Ice::Current& = ::Ice::Current()); + virtual void getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &, const Ice::Current &); - virtual void getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr&, - const Ice::Current&); + virtual void getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr &, const Ice::Current &); +}; - virtual void getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr&, - const Ice::Current&); - }; - -} +} // namespace Murmur #endif diff --git a/src/murmur/MurmurIce.cpp b/src/murmur/MurmurIce.cpp index 76211f06a..64b025ed5 100644 --- a/src/murmur/MurmurIce.cpp +++ b/src/murmur/MurmurIce.cpp @@ -5,17 +5,17 @@ #include "MurmurIce.h" +#include "Ban.h" #include "Channel.h" +#include "ChannelListener.h" #include "Group.h" #include "Meta.h" #include "MurmurI.h" #include "Server.h" -#include "ServerUser.h" #include "ServerDB.h" +#include "ServerUser.h" #include "User.h" -#include "Ban.h" #include "Utils.h" -#include "ChannelListener.h" #include <QtCore/QCoreApplication> #include <QtCore/QSettings> @@ -53,7 +53,7 @@ void IceStop() { /// Remove all NUL bytes from |s|. static std::string iceRemoveNul(std::string s) { - std::vector<char> newstr; + std::vector< char > newstr; for (size_t i = 0; i < s.size(); i++) { char c = s.at(i); if (c == 0) { @@ -82,47 +82,47 @@ static std::string iceString(const QString &s) { /// If the function is passed a string bigger than that, /// it will return an empty string. static std::string iceBase64(const std::string &s) { - if (s.size() > static_cast<size_t>(std::numeric_limits<int>::max())) { + if (s.size() > static_cast< size_t >(std::numeric_limits< int >::max())) { return std::string(); } - QByteArray ba(s.data(), static_cast<int>(s.size())); + QByteArray ba(s.data(), static_cast< int >(s.size())); QByteArray ba64 = ba.toBase64(); - return std::string(ba64.data(), static_cast<size_t>(ba.size())); + return std::string(ba64.data(), static_cast< size_t >(ba.size())); } static void logToLog(const ServerDB::LogRecord &r, Murmur::LogEntry &le) { le.timestamp = r.first; - le.txt = iceString(r.second); + le.txt = iceString(r.second); } static void userToUser(const ::User *p, Murmur::User &mp) { - mp.session = p->uiSession; - mp.userid = p->iId; - mp.name = iceString(p->qsName); - mp.mute = p->bMute; - mp.deaf = p->bDeaf; - mp.suppress = p->bSuppress; - mp.recording = p->bRecording; + mp.session = p->uiSession; + mp.userid = p->iId; + mp.name = iceString(p->qsName); + mp.mute = p->bMute; + mp.deaf = p->bDeaf; + mp.suppress = p->bSuppress; + mp.recording = p->bRecording; mp.prioritySpeaker = p->bPrioritySpeaker; - mp.selfMute = p->bSelfMute; - mp.selfDeaf = p->bSelfDeaf; - mp.channel = p->cChannel->iId; - mp.comment = iceString(p->qsComment); - - const ServerUser *u=static_cast<const ServerUser *>(p); - mp.onlinesecs = u->bwr.onlineSeconds(); - mp.bytespersec = u->bwr.bandwidth(); - mp.version = u->uiVersion; - mp.release = iceString(u->qsRelease); - mp.os = iceString(u->qsOS); - mp.osversion = iceString(u->qsOSVersion); - mp.identity = iceString(u->qsIdentity); - mp.context = iceBase64(u->ssContext); - mp.idlesecs = u->bwr.idleSeconds(); - mp.udpPing = u->dUDPPingAvg; - mp.tcpPing = u->dTCPPingAvg; + mp.selfMute = p->bSelfMute; + mp.selfDeaf = p->bSelfDeaf; + mp.channel = p->cChannel->iId; + mp.comment = iceString(p->qsComment); + + const ServerUser *u = static_cast< const ServerUser * >(p); + mp.onlinesecs = u->bwr.onlineSeconds(); + mp.bytespersec = u->bwr.bandwidth(); + mp.version = u->uiVersion; + mp.release = iceString(u->qsRelease); + mp.os = iceString(u->qsOS); + mp.osversion = iceString(u->qsOSVersion); + mp.identity = iceString(u->qsIdentity); + mp.context = iceBase64(u->ssContext); + mp.idlesecs = u->bwr.idleSeconds(); + mp.udpPing = u->dUDPPingAvg; + mp.tcpPing = u->dTCPPingAvg; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) mp.tcponly = u->aiUdpFlag.loadRelaxed() == 0; @@ -133,20 +133,20 @@ static void userToUser(const ::User *p, Murmur::User &mp) { ::Murmur::NetAddress addr(16, 0); const Q_IPV6ADDR &a = u->haAddress.qip6; - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) addr[i] = a[i]; mp.address = addr; } static void channelToChannel(const ::Channel *c, Murmur::Channel &mc) { - mc.id = c->iId; - mc.name = iceString(c->qsName); - mc.parent = c->cParent ? c->cParent->iId : -1; + mc.id = c->iId; + mc.name = iceString(c->qsName); + mc.parent = c->cParent ? c->cParent->iId : -1; mc.description = iceString(c->qsDesc); - mc.position = c->iPosition; + mc.position = c->iPosition; mc.links.clear(); - foreach(::Channel *chn, c->qsPermLinks) + foreach (::Channel *chn, c->qsPermLinks) mc.links.push_back(chn->iId); mc.temporary = c->bTemporary; } @@ -155,15 +155,15 @@ static void ACLtoACL(const ::ChanACL *acl, Murmur::ACL &ma) { ma.applyHere = acl->bApplyHere; ma.applySubs = acl->bApplySubs; ma.inherited = false; - ma.userid = acl->iUserId; - ma.group = iceString(acl->qsGroup); - ma.allow = acl->pAllow; - ma.deny = acl->pDeny; + ma.userid = acl->iUserId; + ma.group = iceString(acl->qsGroup); + ma.allow = acl->pAllow; + ma.deny = acl->pDeny; } static void groupToGroup(const ::Group *g, Murmur::Group &mg) { - mg.name = iceString(g->qsName); - mg.inherit = g->bInherit; + mg.name = iceString(g->qsName); + mg.inherit = g->bInherit; mg.inheritable = g->bInheritable; mg.add.clear(); mg.remove.clear(); @@ -173,40 +173,40 @@ static void groupToGroup(const ::Group *g, Murmur::Group &mg) { static void banToBan(const ::Ban &b, Murmur::Ban &mb) { ::Murmur::NetAddress addr(16, 0); const Q_IPV6ADDR &a = b.haAddress.qip6; - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) addr[i] = a[i]; - mb.address = addr; - mb.bits = b.iMask; - mb.name = iceString(b.qsUsername); - mb.hash = iceString(b.qsHash); - mb.reason = iceString(b.qsReason); - mb.start = b.qdtStart.toLocalTime().toTime_t(); + mb.address = addr; + mb.bits = b.iMask; + mb.name = iceString(b.qsUsername); + mb.hash = iceString(b.qsHash); + mb.reason = iceString(b.qsReason); + mb.start = b.qdtStart.toLocalTime().toTime_t(); mb.duration = b.iDuration; } static void banToBan(const ::Murmur::Ban &mb, ::Ban &b) { if (mb.address.size() != 16) - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) b.haAddress.qip6[i] = 0; else - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) b.haAddress.qip6[i] = mb.address[i]; - b.iMask = mb.bits; + b.iMask = mb.bits; b.qsUsername = u8(mb.name); - b.qsHash = u8(mb.hash); - b.qsReason = u8(mb.reason); - b.qdtStart = QDateTime::fromTime_t(static_cast<quint32>(mb.start)).toUTC(); - b.iDuration = mb.duration; + b.qsHash = u8(mb.hash); + b.qsReason = u8(mb.reason); + b.qdtStart = QDateTime::fromTime_t(static_cast< quint32 >(mb.start)).toUTC(); + b.iDuration = mb.duration; } -static void infoToInfo(const QMap<int, QString> &info, Murmur::UserInfoMap &im) { - QMap<int, QString>::const_iterator i; +static void infoToInfo(const QMap< int, QString > &info, Murmur::UserInfoMap &im) { + QMap< int, QString >::const_iterator i; for (i = info.constBegin(); i != info.constEnd(); ++i) - im[static_cast<Murmur::UserInfo>(i.key())] = iceString(i.value()); + im[static_cast< Murmur::UserInfo >(i.key())] = iceString(i.value()); } -static void infoToInfo(const Murmur::UserInfoMap &im, QMap<int, QString> &info) { +static void infoToInfo(const Murmur::UserInfoMap &im, QMap< int, QString > &info) { Murmur::UserInfoMap::const_iterator i; for (i = im.begin(); i != im.end(); ++i) info.insert((*i).first, u8((*i).second)); @@ -215,21 +215,21 @@ static void infoToInfo(const Murmur::UserInfoMap &im, QMap<int, QString> &info) static void textmessageToTextmessage(const ::TextMessage &tm, Murmur::TextMessage &tmdst) { tmdst.text = iceString(tm.qsText); - foreach(unsigned int i, tm.qlSessions) + foreach (unsigned int i, tm.qlSessions) tmdst.sessions.push_back(i); - foreach(unsigned int i, tm.qlChannels) + foreach (unsigned int i, tm.qlChannels) tmdst.channels.push_back(i); - foreach(unsigned int i, tm.qlTrees) + foreach (unsigned int i, tm.qlTrees) tmdst.trees.push_back(i); } class ServerLocator : public virtual Ice::ServantLocator { - public: - virtual Ice::ObjectPtr locate(const Ice::Current &, Ice::LocalObjectPtr &); - virtual void finished(const Ice::Current &, const Ice::ObjectPtr &, const Ice::LocalObjectPtr &) {}; - virtual void deactivate(const std::string &) {}; +public: + virtual Ice::ObjectPtr locate(const Ice::Current &, Ice::LocalObjectPtr &); + virtual void finished(const Ice::Current &, const Ice::ObjectPtr &, const Ice::LocalObjectPtr &){}; + virtual void deactivate(const std::string &){}; }; MurmurIce::MurmurIce() { @@ -241,14 +241,14 @@ MurmurIce::MurmurIce() { Ice::PropertiesPtr ipp = Ice::createProperties(); ::Meta::mp.qsSettings->beginGroup("Ice"); - foreach(const QString &v, ::Meta::mp.qsSettings->childKeys()) { + foreach (const QString &v, ::Meta::mp.qsSettings->childKeys()) { ipp->setProperty(iceString(v), iceString(::Meta::mp.qsSettings->value(v).toString())); } ::Meta::mp.qsSettings->endGroup(); Ice::PropertyDict props = ippProperties->getPropertiesForPrefix(""); Ice::PropertyDict::iterator i; - for (i=props.begin(); i != props.end(); ++i) { + for (i = props.begin(); i != props.end(); ++i) { ipp->setProperty((*i).first, (*i).second); } ipp->setProperty("Ice.ImplicitContext", "Shared"); @@ -258,12 +258,12 @@ MurmurIce::MurmurIce() { try { communicator = Ice::initialize(idd); - if (! meta->mp.qsIceSecretWrite.isEmpty()) { + if (!meta->mp.qsIceSecretWrite.isEmpty()) { ::Ice::ImplicitContextPtr impl = communicator->getImplicitContext(); if (impl) impl->put("secret", iceString(meta->mp.qsIceSecretWrite)); } - adapter = communicator->createObjectAdapterWithEndpoints("Murmur", qPrintable(meta->mp.qsIceEndpoint)); + adapter = communicator->createObjectAdapterWithEndpoints("Murmur", qPrintable(meta->mp.qsIceEndpoint)); MetaPtr m = new MetaI; #if ICE_INT_VERSION >= 30700 MetaPrx mprx = MetaPrx::uncheckedCast(adapter->add(m, Ice::stringToIdentity("Meta"))); @@ -275,7 +275,7 @@ MurmurIce::MurmurIce() { iopServer = new ServerI; adapter->activate(); - foreach(const Ice::EndpointPtr ep, mprx->ice_getEndpoints()) { + foreach (const Ice::EndpointPtr ep, mprx->ice_getEndpoints()) { qWarning("MurmurIce: Endpoint \"%s\" running", qPrintable(u8(ep->toString()))); } @@ -294,7 +294,7 @@ MurmurIce::~MurmurIce() { communicator->shutdown(); communicator->waitForShutdown(); communicator->destroy(); - communicator=nullptr; + communicator = nullptr; qWarning("MurmurIce: Shutdown complete"); } iopServer = nullptr; @@ -302,7 +302,7 @@ MurmurIce::~MurmurIce() { void MurmurIce::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) - static_cast<ExecEvent *>(evt)->execute(); + static_cast< ExecEvent * >(evt)->execute(); } void MurmurIce::badMetaProxy(const ::Murmur::MetaCallbackPrx &prx) { @@ -310,7 +310,7 @@ void MurmurIce::badMetaProxy(const ::Murmur::MetaCallbackPrx &prx) { removeMetaCallback(prx); } -void MurmurIce::badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server* server) { +void MurmurIce::badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server *server) { server->log(QString("Ice ServerCallback %1 failed").arg(QString::fromStdString(communicator->proxyToString(prx)))); removeServerCallback(server, prx); } @@ -323,91 +323,105 @@ void MurmurIce::badAuthenticator(::Server *server) { removeServerUpdatingAuthenticator(server); } -void MurmurIce::addMetaCallback(const ::Murmur::MetaCallbackPrx& prx) { +void MurmurIce::addMetaCallback(const ::Murmur::MetaCallbackPrx &prx) { if (!qlMetaCallbacks.contains(prx)) { qWarning("Added Ice MetaCallback %s", qPrintable(QString::fromStdString(communicator->proxyToString(prx)))); qlMetaCallbacks.append(prx); } } -void MurmurIce::removeMetaCallback(const ::Murmur::MetaCallbackPrx& prx) { +void MurmurIce::removeMetaCallback(const ::Murmur::MetaCallbackPrx &prx) { if (qlMetaCallbacks.removeAll(prx)) { qWarning("Removed Ice MetaCallback %s", qPrintable(QString::fromStdString(communicator->proxyToString(prx)))); } } -void MurmurIce::addServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx) { - QList< ::Murmur::ServerCallbackPrx >& cbList = qmServerCallbacks[server->iServerNum]; +void MurmurIce::addServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx) { + QList<::Murmur::ServerCallbackPrx > &cbList = qmServerCallbacks[server->iServerNum]; if (!cbList.contains(prx)) { - server->log(QString("Added Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Added Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); cbList.append(prx); } } -void MurmurIce::removeServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx) { +void MurmurIce::removeServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx) { if (qmServerCallbacks[server->iServerNum].removeAll(prx)) { - server->log(QString("Removed Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Removed Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); } } -void MurmurIce::removeServerCallbacks(const ::Server* server) { +void MurmurIce::removeServerCallbacks(const ::Server *server) { if (qmServerCallbacks.contains(server->iServerNum)) { server->log(QString("Removed all Ice ServerCallbacks")); qmServerCallbacks.remove(server->iServerNum); } } -void MurmurIce::addServerContextCallback(const ::Server* server, int session_id, const QString& action, const ::Murmur::ServerContextCallbackPrx& prx) { - QMap<QString, ::Murmur::ServerContextCallbackPrx>& callbacks = qmServerContextCallbacks[server->iServerNum][session_id]; +void MurmurIce::addServerContextCallback(const ::Server *server, int session_id, const QString &action, + const ::Murmur::ServerContextCallbackPrx &prx) { + QMap< QString, ::Murmur::ServerContextCallbackPrx > &callbacks = + qmServerContextCallbacks[server->iServerNum][session_id]; if (!callbacks.contains(action) || callbacks[action] != prx) { - server->log(QString("Added Ice ServerContextCallback %1 for session %2, action %3").arg(QString::fromStdString(communicator->proxyToString(prx))).arg(session_id).arg(action)); + server->log(QString("Added Ice ServerContextCallback %1 for session %2, action %3") + .arg(QString::fromStdString(communicator->proxyToString(prx))) + .arg(session_id) + .arg(action)); callbacks.insert(action, prx); } } -const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > MurmurIce::getServerContextCallbacks(const ::Server* server) const { +const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > + MurmurIce::getServerContextCallbacks(const ::Server *server) const { return qmServerContextCallbacks[server->iServerNum]; } -void MurmurIce::removeServerContextCallback(const ::Server* server, int session_id, const QString& action) { +void MurmurIce::removeServerContextCallback(const ::Server *server, int session_id, const QString &action) { if (qmServerContextCallbacks[server->iServerNum][session_id].remove(action)) { server->log(QString("Removed Ice ServerContextCallback for session %1, action %2").arg(session_id).arg(action)); } } -void MurmurIce::setServerAuthenticator(const ::Server* server, const ::Murmur::ServerAuthenticatorPrx& prx) { +void MurmurIce::setServerAuthenticator(const ::Server *server, const ::Murmur::ServerAuthenticatorPrx &prx) { if (prx != qmServerAuthenticator[server->iServerNum]) { - server->log(QString("Set Ice Authenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Set Ice Authenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); qmServerAuthenticator[server->iServerNum] = prx; } } -const ::Murmur::ServerAuthenticatorPrx MurmurIce::getServerAuthenticator(const ::Server* server) const { +const ::Murmur::ServerAuthenticatorPrx MurmurIce::getServerAuthenticator(const ::Server *server) const { return qmServerAuthenticator[server->iServerNum]; } -void MurmurIce::removeServerAuthenticator(const ::Server* server) { +void MurmurIce::removeServerAuthenticator(const ::Server *server) { if (qmServerAuthenticator.remove(server->iServerNum)) { - server->log(QString("Removed Ice Authenticator %1").arg(QString::fromStdString(communicator->proxyToString(getServerAuthenticator(server))))); + server->log(QString("Removed Ice Authenticator %1") + .arg(QString::fromStdString(communicator->proxyToString(getServerAuthenticator(server))))); } } -void MurmurIce::setServerUpdatingAuthenticator(const ::Server* server, const ::Murmur::ServerUpdatingAuthenticatorPrx& prx) { +void MurmurIce::setServerUpdatingAuthenticator(const ::Server *server, + const ::Murmur::ServerUpdatingAuthenticatorPrx &prx) { if (prx != qmServerUpdatingAuthenticator[server->iServerNum]) { - server->log(QString("Set Ice UpdatingAuthenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log(QString("Set Ice UpdatingAuthenticator to %1") + .arg(QString::fromStdString(communicator->proxyToString(prx)))); qmServerUpdatingAuthenticator[server->iServerNum] = prx; } } -const ::Murmur::ServerUpdatingAuthenticatorPrx MurmurIce::getServerUpdatingAuthenticator(const ::Server* server) const { +const ::Murmur::ServerUpdatingAuthenticatorPrx MurmurIce::getServerUpdatingAuthenticator(const ::Server *server) const { return qmServerUpdatingAuthenticator[server->iServerNum]; } -void MurmurIce::removeServerUpdatingAuthenticator(const ::Server* server) { +void MurmurIce::removeServerUpdatingAuthenticator(const ::Server *server) { if (qmServerUpdatingAuthenticator.contains(server->iServerNum)) { - server->log(QString("Removed Ice UpdatingAuthenticator %1").arg(QString::fromStdString(communicator->proxyToString(getServerUpdatingAuthenticator(server))))); + server->log( + QString("Removed Ice UpdatingAuthenticator %1") + .arg(QString::fromStdString(communicator->proxyToString(getServerUpdatingAuthenticator(server))))); qmServerUpdatingAuthenticator.remove(server->iServerNum); } } @@ -415,21 +429,22 @@ void MurmurIce::removeServerUpdatingAuthenticator(const ::Server* server) { static ServerPrx idToProxy(int id, const Ice::ObjectAdapterPtr &adapter) { Ice::Identity ident; ident.category = "s"; - ident.name = iceString(QString::number(id)); + ident.name = iceString(QString::number(id)); return ServerPrx::uncheckedCast(adapter->createProxy(ident)); } void MurmurIce::started(::Server *s) { s->connectListener(mi); - connect(s, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, SLOT(contextAction(const User *, const QString &, unsigned int, int))); + connect(s, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, + SLOT(contextAction(const User *, const QString &, unsigned int, int))); - const QList< ::Murmur::MetaCallbackPrx> &qlList = qlMetaCallbacks; + const QList<::Murmur::MetaCallbackPrx > &qlList = qlMetaCallbacks; if (qlList.isEmpty()) return; - foreach(const ::Murmur::MetaCallbackPrx &prx, qlList) { + foreach (const ::Murmur::MetaCallbackPrx &prx, qlList) { try { prx->started(idToProxy(s->iServerNum, adapter)); } catch (...) { @@ -443,12 +458,12 @@ void MurmurIce::stopped(::Server *s) { removeServerAuthenticator(s); removeServerUpdatingAuthenticator(s); - const QList< ::Murmur::MetaCallbackPrx> &qmList = qlMetaCallbacks; + const QList<::Murmur::MetaCallbackPrx > &qmList = qlMetaCallbacks; if (qmList.isEmpty()) return; - foreach(const ::Murmur::MetaCallbackPrx &prx, qmList) { + foreach (const ::Murmur::MetaCallbackPrx &prx, qmList) { try { prx->stopped(idToProxy(s->iServerNum, adapter)); } catch (...) { @@ -458,9 +473,9 @@ void MurmurIce::stopped(::Server *s) { } void MurmurIce::userConnected(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -468,7 +483,7 @@ void MurmurIce::userConnected(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userConnected(mp); } catch (...) { @@ -478,11 +493,11 @@ void MurmurIce::userConnected(const ::User *p) { } void MurmurIce::userDisconnected(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); qmServerContextCallbacks[s->iServerNum].remove(p->uiSession); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -490,7 +505,7 @@ void MurmurIce::userDisconnected(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userDisconnected(mp); } catch (...) { @@ -500,9 +515,9 @@ void MurmurIce::userDisconnected(const ::User *p) { } void MurmurIce::userStateChanged(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -510,7 +525,7 @@ void MurmurIce::userStateChanged(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userStateChanged(mp); } catch (...) { @@ -520,9 +535,9 @@ void MurmurIce::userStateChanged(const ::User *p) { } void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -533,7 +548,7 @@ void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { ::Murmur::TextMessage textMessage; textmessageToTextmessage(message, textMessage); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userTextMessage(mp, textMessage); } catch (...) { @@ -543,9 +558,9 @@ void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { } void MurmurIce::channelCreated(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -553,7 +568,7 @@ void MurmurIce::channelCreated(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelCreated(mc); } catch (...) { @@ -563,9 +578,9 @@ void MurmurIce::channelCreated(const ::Channel *c) { } void MurmurIce::channelRemoved(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -573,7 +588,7 @@ void MurmurIce::channelRemoved(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelRemoved(mc); } catch (...) { @@ -583,9 +598,9 @@ void MurmurIce::channelRemoved(const ::Channel *c) { } void MurmurIce::channelStateChanged(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -593,7 +608,7 @@ void MurmurIce::channelStateChanged(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelStateChanged(mc); } catch (...) { @@ -603,18 +618,18 @@ void MurmurIce::channelStateChanged(const ::Channel *c) { } void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigned int session, int iChannel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - QMap<int, QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > > &qmAll = qmServerContextCallbacks; - if (! qmAll.contains(s->iServerNum)) + QMap< int, QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > > &qmAll = qmServerContextCallbacks; + if (!qmAll.contains(s->iServerNum)) return; - QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > &qmServer = qmAll[s->iServerNum]; - if (! qmServer.contains(pSrc->uiSession)) + QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > &qmServer = qmAll[s->iServerNum]; + if (!qmServer.contains(pSrc->uiSession)) return; - QMap<QString, ::Murmur::ServerContextCallbackPrx> &qmUser = qmServer[pSrc->uiSession]; - if (! qmUser.contains(action)) + QMap< QString, ::Murmur::ServerContextCallbackPrx > &qmUser = qmServer[pSrc->uiSession]; + if (!qmUser.contains(action)) return; const ::Murmur::ServerContextCallbackPrx &prx = qmUser[action]; @@ -625,7 +640,10 @@ void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigne try { prx->contextAction(iceString(action), mp, session, iChannel); } catch (...) { - s->log(QString("Ice ServerContextCallback %1 for session %2, action %3 failed").arg(QString::fromStdString(communicator->proxyToString(prx))).arg(pSrc->uiSession).arg(action)); + s->log(QString("Ice ServerContextCallback %1 for session %2, action %3 failed") + .arg(QString::fromStdString(communicator->proxyToString(prx))) + .arg(pSrc->uiSession) + .arg(action)); removeServerContextCallback(s, pSrc->uiSession, action); // Remove clientside entry @@ -639,7 +657,7 @@ void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigne } void MurmurIce::idToNameSlot(QString &name, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { @@ -649,15 +667,15 @@ void MurmurIce::idToNameSlot(QString &name, int id) { } } void MurmurIce::idToTextureSlot(QByteArray &qba, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { const ::Murmur::Texture &tex = prx->idToTexture(id); - qba.resize(static_cast<int>(tex.size())); + qba.resize(static_cast< int >(tex.size())); char *ptr = qba.data(); - for (unsigned int i=0;i<tex.size();++i) + for (unsigned int i = 0; i < tex.size(); ++i) ptr[i] = tex[i]; } catch (...) { badAuthenticator(server); @@ -665,7 +683,7 @@ void MurmurIce::idToTextureSlot(QByteArray &qba, int id) { } void MurmurIce::nameToIdSlot(int &id, const QString &name) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { @@ -675,8 +693,9 @@ void MurmurIce::nameToIdSlot(int &id, const QString &name) { } } -void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); ::std::string newname; @@ -684,18 +703,19 @@ void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const ::Murmur::CertificateList certs; certs.resize(certlist.size()); - for (int i=0;i<certlist.size();++i) { + for (int i = 0; i < certlist.size(); ++i) { ::Murmur::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); der.resize(qba.size()); const char *ptr = qba.constData(); - for (int j=0;j<qba.size();++j) + for (int j = 0; j < qba.size(); ++j) der[j] = ptr[j]; certs[i] = der; } try { - res = prx->authenticate(iceString(uname), iceString(pw), certs, iceString(certhash), certstrong, newname, groups); + res = + prx->authenticate(iceString(uname), iceString(pw), certs, iceString(certhash), certstrong, newname, groups); } catch (...) { badAuthenticator(server); } @@ -703,19 +723,17 @@ void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const if (newname.length() > 0) uname = u8(newname); QStringList qsl; - foreach(const ::std::string &str, groups) { - qsl << u8(str); - } - if (! qsl.isEmpty()) + foreach (const ::std::string &str, groups) { qsl << u8(str); } + if (!qsl.isEmpty()) server->setTempGroups(res, sessionId, nullptr, qsl); } } -void MurmurIce::registerUserSlot(int &res, const QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::registerUserSlot(int &res, const QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::UserInfoMap im; @@ -729,10 +747,10 @@ void MurmurIce::registerUserSlot(int &res, const QMap<int, QString> &info) { } void MurmurIce::unregisterUserSlot(int &res, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; try { res = prx->unregisterUser(id); @@ -741,11 +759,11 @@ void MurmurIce::unregisterUserSlot(int &res, int id) { } } -void MurmurIce::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; Murmur::UserInfoMap im; @@ -760,11 +778,11 @@ void MurmurIce::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) } } -void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &m) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &m) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::NameMap lst; @@ -776,15 +794,15 @@ void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap<int, QString return; } ::Murmur::NameMap::const_iterator i; - for (i=lst.begin(); i != lst.end(); ++i) + for (i = lst.begin(); i != lst.end(); ++i) m.insert((*i).first, u8((*i).second)); } -void MurmurIce::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; Murmur::UserInfoMap im; @@ -798,16 +816,16 @@ void MurmurIce::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { } void MurmurIce::setTextureSlot(int &res, int id, const QByteArray &texture) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::Texture tex; tex.resize(texture.size()); const char *ptr = texture.constData(); - for (int i=0;i<texture.size();++i) + for (int i = 0; i < texture.size(); ++i) tex[i] = ptr[i]; try { @@ -821,45 +839,44 @@ Ice::ObjectPtr ServerLocator::locate(const Ice::Current &, Ice::LocalObjectPtr & return iopServer; } -#define FIND_SERVER \ - ::Server *server = meta->qhServers.value(server_id); +#define FIND_SERVER ::Server *server = meta->qhServers.value(server_id); -#define NEED_SERVER_EXISTS \ - FIND_SERVER \ - if (!server && ! ServerDB::serverExists(server_id)) { \ - cb->ice_exception(::Ice::ObjectNotExistException(__FILE__,__LINE__)); \ - return; \ +#define NEED_SERVER_EXISTS \ + FIND_SERVER \ + if (!server && !ServerDB::serverExists(server_id)) { \ + cb->ice_exception(::Ice::ObjectNotExistException(__FILE__, __LINE__)); \ + return; \ } -#define NEED_SERVER \ - NEED_SERVER_EXISTS \ - if (! server) { \ +#define NEED_SERVER \ + NEED_SERVER_EXISTS \ + if (!server) { \ cb->ice_exception(ServerBootedException()); \ - return; \ + return; \ } -#define NEED_PLAYER \ - ServerUser *user = server->qhUsers.value(session); \ - if (!user) { \ +#define NEED_PLAYER \ + ServerUser *user = server->qhUsers.value(session); \ + if (!user) { \ cb->ice_exception(::Murmur::InvalidSessionException()); \ - return; \ + return; \ } -#define NEED_CHANNEL_VAR(x,y) \ - x = server->qhChannels.value(y); \ - if (!x) { \ +#define NEED_CHANNEL_VAR(x, y) \ + x = server->qhChannels.value(y); \ + if (!x) { \ cb->ice_exception(::Murmur::InvalidChannelException()); \ - return; \ + return; \ } -#define NEED_CHANNEL \ +#define NEED_CHANNEL \ ::Channel *channel; \ NEED_CHANNEL_VAR(channel, channelid); void ServerI::ice_ping(const Ice::Current ¤t) const { // This is executed in the ice thread. int server_id = u8(current.id.name).toInt(); - if (! ServerDB::serverExists(server_id)) + if (!ServerDB::serverExists(server_id)) throw ::Ice::ObjectNotExistException(__FILE__, __LINE__); } @@ -873,7 +890,7 @@ static void impl_Server_start(const ::Murmur::AMD_Server_startPtr cb, int server NEED_SERVER_EXISTS; if (server) cb->ice_exception(ServerBootedException()); - else if (! meta->boot(server_id)) + else if (!meta->boot(server_id)) cb->ice_exception(ServerFailureException()); else cb->ice_response(); @@ -895,11 +912,13 @@ static void impl_Server_delete(const ::Murmur::AMD_Server_deletePtr cb, int serv cb->ice_response(); } -static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, int server_id, const Murmur::ServerCallbackPrx& cbptr) { +static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, int server_id, + const Murmur::ServerCallbackPrx &cbptr) { NEED_SERVER; try { - const Murmur::ServerCallbackPrx &oneway = Murmur::ServerCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)); + const Murmur::ServerCallbackPrx &oneway = + Murmur::ServerCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)); mi->addServerCallback(server, oneway); cb->ice_response(); } catch (...) { @@ -907,11 +926,13 @@ static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, } } -static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPtr cb, int server_id, const Murmur::ServerCallbackPrx& cbptr) { +static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPtr cb, int server_id, + const Murmur::ServerCallbackPrx &cbptr) { NEED_SERVER; try { - const Murmur::ServerCallbackPrx &oneway = Murmur::ServerCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)); + const Murmur::ServerCallbackPrx &oneway = + Murmur::ServerCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)); mi->removeServerCallback(server, oneway); cb->ice_response(); } catch (...) { @@ -919,7 +940,8 @@ static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPt } } -static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthenticatorPtr& cb, int server_id, const ::Murmur::ServerAuthenticatorPrx &aptr) { +static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, int server_id, + const ::Murmur::ServerAuthenticatorPrx &aptr) { NEED_SERVER; if (mi->getServerAuthenticator(server)) @@ -929,7 +951,8 @@ static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthentic try { prx = ::Murmur::ServerAuthenticatorPrx::checkedCast(aptr->ice_connectionCached(false)->ice_timeout(5000)); - const ::Murmur::ServerUpdatingAuthenticatorPrx uprx = ::Murmur::ServerUpdatingAuthenticatorPrx::checkedCast(prx); + const ::Murmur::ServerUpdatingAuthenticatorPrx uprx = + ::Murmur::ServerUpdatingAuthenticatorPrx::checkedCast(prx); mi->setServerAuthenticator(server, prx); if (uprx) @@ -952,7 +975,7 @@ static void impl_Server_id(const ::Murmur::AMD_Server_idPtr cb, int server_id) { } #define ACCESS_Server_getConf_READ -static void impl_Server_getConf(const ::Murmur::AMD_Server_getConfPtr cb, int server_id, const ::std::string& key) { +static void impl_Server_getConf(const ::Murmur::AMD_Server_getConfPtr cb, int server_id, const ::std::string &key) { NEED_SERVER_EXISTS; if (key == "key" || key == "passphrase") cb->ice_exception(WriteOnlyException()); @@ -966,9 +989,9 @@ static void impl_Server_getAllConf(const ::Murmur::AMD_Server_getAllConfPtr cb, ::Murmur::ConfigMap cm; - QMap<QString, QString> values = ServerDB::getAllConf(server_id); - QMap<QString, QString>::const_iterator i; - for (i=values.constBegin();i != values.constEnd(); ++i) { + QMap< QString, QString > values = ServerDB::getAllConf(server_id); + QMap< QString, QString >::const_iterator i; + for (i = values.constBegin(); i != values.constEnd(); ++i) { if (i.key() == "key" || i.key() == "passphrase") continue; cm[iceString(i.key())] = iceString(i.value()); @@ -976,30 +999,32 @@ static void impl_Server_getAllConf(const ::Murmur::AMD_Server_getAllConfPtr cb, cb->ice_response(cm); } -static void impl_Server_setConf(const ::Murmur::AMD_Server_setConfPtr cb, int server_id, const ::std::string& key, const ::std::string& value) { +static void impl_Server_setConf(const ::Murmur::AMD_Server_setConfPtr cb, int server_id, const ::std::string &key, + const ::std::string &value) { NEED_SERVER_EXISTS; - QString k=u8(key); - QString v=u8(value); + QString k = u8(key); + QString v = u8(value); ServerDB::setConf(server_id, k, v); if (server) server->setLiveConf(k, v); cb->ice_response(); } -static void impl_Server_setSuperuserPassword(const ::Murmur::AMD_Server_setSuperuserPasswordPtr cb, int server_id, const ::std::string& pw) { +static void impl_Server_setSuperuserPassword(const ::Murmur::AMD_Server_setSuperuserPasswordPtr cb, int server_id, + const ::std::string &pw) { NEED_SERVER_EXISTS; ServerDB::setSUPW(server_id, u8(pw)); cb->ice_response(); } #define ACCESS_Server_getLog_READ -static void impl_Server_getLog(const ::Murmur::AMD_Server_getLogPtr cb, int server_id, ::Ice::Int min, ::Ice::Int max) { +static void impl_Server_getLog(const ::Murmur::AMD_Server_getLogPtr cb, int server_id, ::Ice::Int min, ::Ice::Int max) { NEED_SERVER_EXISTS; ::Murmur::LogList ll; - QList<ServerDB::LogRecord> dblog = ServerDB::getLog(server_id, min, max); - foreach(const ServerDB::LogRecord &e, dblog) { + QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min, max); + foreach (const ServerDB::LogRecord &e, dblog) { ::Murmur::LogEntry le; logToLog(e, le); ll.push_back(le); @@ -1019,9 +1044,9 @@ static void impl_Server_getLogLen(const ::Murmur::AMD_Server_getLogLenPtr cb, in static void impl_Server_getUsers(const ::Murmur::AMD_Server_getUsersPtr cb, int server_id) { NEED_SERVER; ::Murmur::UserMap pm; - foreach(const ::User *p, server->qhUsers) { + foreach (const ::User *p, server->qhUsers) { ::Murmur::User mp; - if (static_cast<const ServerUser *>(p)->sState == ::ServerUser::Authenticated) { + if (static_cast< const ServerUser * >(p)->sState == ::ServerUser::Authenticated) { userToUser(p, mp); pm[p->uiSession] = mp; } @@ -1033,7 +1058,7 @@ static void impl_Server_getUsers(const ::Murmur::AMD_Server_getUsersPtr cb, int static void impl_Server_getChannels(const ::Murmur::AMD_Server_getChannelsPtr cb, int server_id) { NEED_SERVER; ::Murmur::ChannelMap cm; - foreach(const ::Channel *c, server->qhChannels) { + foreach (const ::Channel *c, server->qhChannels) { ::Murmur::Channel mc; channelToChannel(c, mc); cm[c->iId] = mc; @@ -1052,21 +1077,19 @@ static bool channelSort(const ::Channel *a, const ::Channel *b) { TreePtr recurseTree(const ::Channel *c) { TreePtr t = new Tree(); channelToChannel(c, t->c); - QList< ::User *> users = c->qlUsers; + QList<::User * > users = c->qlUsers; std::sort(users.begin(), users.end(), userSort); - foreach(const ::User *p, users) { + foreach (const ::User *p, users) { ::Murmur::User mp; userToUser(p, mp); t->users.push_back(mp); } - QList< ::Channel *> channels = c->qlChannels; + QList<::Channel * > channels = c->qlChannels; std::sort(channels.begin(), channels.end(), channelSort); - foreach(const ::Channel *chn, channels) { - t->children.push_back(recurseTree(chn)); - } + foreach (const ::Channel *chn, channels) { t->children.push_back(recurseTree(chn)); } return t; } @@ -1078,21 +1101,22 @@ static void impl_Server_getTree(const ::Murmur::AMD_Server_getTreePtr cb, int se } #define ACCESS_Server_getCertificateList_READ -static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertificateListPtr cb, int server_id, ::Ice::Int session) { +static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertificateListPtr cb, int server_id, + ::Ice::Int session) { NEED_SERVER; NEED_PLAYER; ::Murmur::CertificateList certs; - const QList<QSslCertificate> &certlist = user->peerCertificateChain(); + const QList< QSslCertificate > &certlist = user->peerCertificateChain(); certs.resize(certlist.size()); - for (int i=0;i<certlist.size();++i) { + for (int i = 0; i < certlist.size(); ++i) { ::Murmur::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); der.resize(qba.size()); const char *ptr = qba.constData(); - for (int j=0;j<qba.size();++j) + for (int j = 0; j < qba.size(); ++j) der[j] = ptr[j]; certs[i] = der; } @@ -1103,7 +1127,7 @@ static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertifi static void impl_Server_getBans(const ::Murmur::AMD_Server_getBansPtr cb, int server_id) { NEED_SERVER; ::Murmur::BanList bl; - foreach(const ::Ban &ban, server->qlBans) { + foreach (const ::Ban &ban, server->qlBans) { ::Murmur::Ban mb; banToBan(ban, mb); bl.push_back(mb); @@ -1111,10 +1135,11 @@ static void impl_Server_getBans(const ::Murmur::AMD_Server_getBansPtr cb, int se cb->ice_response(bl); } -static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int server_id, const ::Murmur::BanList& bans) { +static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int server_id, + const ::Murmur::BanList &bans) { NEED_SERVER; server->qlBans.clear(); - foreach(const ::Murmur::Ban &mb, bans) { + foreach (const ::Murmur::Ban &mb, bans) { ::Ban ban; banToBan(mb, ban); server->qlBans << ban; @@ -1123,7 +1148,8 @@ static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int se cb->ice_response(); } -static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int server_id, ::Ice::Int session, const ::std::string& reason) { +static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int server_id, ::Ice::Int session, + const ::std::string &reason) { NEED_SERVER; NEED_PLAYER; @@ -1135,7 +1161,8 @@ static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int cb->ice_response(); } -static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb, int server_id, ::Ice::Int session, const ::std::string &text) { +static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb, int server_id, ::Ice::Int session, + const ::std::string &text) { NEED_SERVER; NEED_PLAYER; @@ -1144,34 +1171,41 @@ static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb } #define ACCESS_Server_hasPermission_READ -static void impl_Server_hasPermission(const ::Murmur::AMD_Server_hasPermissionPtr cb, int server_id, ::Ice::Int session, ::Ice::Int channelid, ::Ice::Int perm) { +static void impl_Server_hasPermission(const ::Murmur::AMD_Server_hasPermissionPtr cb, int server_id, ::Ice::Int session, + ::Ice::Int channelid, ::Ice::Int perm) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; - cb->ice_response(server->hasPermission(user, channel, static_cast<ChanACL::Perm>(perm))); + cb->ice_response(server->hasPermission(user, channel, static_cast< ChanACL::Perm >(perm))); } #define ACCESS_Server_effectivePermissions_READ -static void impl_Server_effectivePermissions(const ::Murmur::AMD_Server_effectivePermissionsPtr cb, int server_id, ::Ice::Int session, ::Ice::Int channelid) { +static void impl_Server_effectivePermissions(const ::Murmur::AMD_Server_effectivePermissionsPtr cb, int server_id, + ::Ice::Int session, ::Ice::Int channelid) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; cb->ice_response(server->effectivePermissions(user, channel)); } -static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCallbackPtr cb, int server_id, ::Ice::Int session, const ::std::string& action, const ::std::string& text, const ::Murmur::ServerContextCallbackPrx& cbptr, int ctx) { +static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCallbackPtr cb, int server_id, + ::Ice::Int session, const ::std::string &action, const ::std::string &text, + const ::Murmur::ServerContextCallbackPrx &cbptr, int ctx) { NEED_SERVER; NEED_PLAYER; - const QMap<QString, ::Murmur::ServerContextCallbackPrx>& qmPrx = mi->getServerContextCallbacks(server)[session]; + const QMap< QString, ::Murmur::ServerContextCallbackPrx > &qmPrx = mi->getServerContextCallbacks(server)[session]; - if (!(ctx & (MumbleProto::ContextActionModify_Context_Server | MumbleProto::ContextActionModify_Context_Channel | MumbleProto::ContextActionModify_Context_User))) { + if (!(ctx + & (MumbleProto::ContextActionModify_Context_Server | MumbleProto::ContextActionModify_Context_Channel + | MumbleProto::ContextActionModify_Context_User))) { cb->ice_exception(InvalidCallbackException()); return; } try { - const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::checkedCast( + cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); if (qmPrx.contains(u8(action))) { // Since the server has no notion of the ctx part of the context action // make sure we remove them all clientside when overriding an old callback @@ -1195,18 +1229,21 @@ static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCa server->sendMessage(user, mpcam); } -static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeContextCallbackPtr cb, int server_id, const Murmur::ServerContextCallbackPrx& cbptr) { +static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeContextCallbackPtr cb, int server_id, + const Murmur::ServerContextCallbackPrx &cbptr) { NEED_SERVER; - const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> >& qmPrx = mi->getServerContextCallbacks(server); + const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > &qmPrx = + mi->getServerContextCallbacks(server); try { - const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::uncheckedCast( + cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); - foreach(int session, qmPrx.keys()) { - ServerUser *user = server->qhUsers.value(session); - const QMap<QString, ::Murmur::ServerContextCallbackPrx> &qm = qmPrx[session]; - foreach(const QString &act, qm.keys(oneway)) { + foreach (int session, qmPrx.keys()) { + ServerUser *user = server->qhUsers.value(session); + const QMap< QString, ::Murmur::ServerContextCallbackPrx > &qm = qmPrx[session]; + foreach (const QString &act, qm.keys(oneway)) { mi->removeServerContextCallback(server, session, act); // Ask clients to remove the clientside callbacks @@ -1226,7 +1263,7 @@ static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeCon } #define ACCESS_Server_getState_READ -static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int server_id, ::Ice::Int session) { +static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int server_id, ::Ice::Int session) { NEED_SERVER; NEED_PLAYER; @@ -1235,18 +1272,21 @@ static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int cb->ice_response(mp); } -static void impl_Server_setState(const ::Murmur::AMD_Server_setStatePtr cb, int server_id, const ::Murmur::User& state) { +static void impl_Server_setState(const ::Murmur::AMD_Server_setStatePtr cb, int server_id, + const ::Murmur::User &state) { int session = state.session; ::Channel *channel; NEED_SERVER; NEED_PLAYER; NEED_CHANNEL_VAR(channel, state.channel); - server->setUserState(user, channel, state.mute, state.deaf, state.suppress, state.prioritySpeaker, u8(state.name), u8(state.comment)); + server->setUserState(user, channel, state.mute, state.deaf, state.suppress, state.prioritySpeaker, u8(state.name), + u8(state.comment)); cb->ice_response(); } -static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessageChannelPtr cb, int server_id, ::Ice::Int channelid, bool tree, const ::std::string &text) { +static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessageChannelPtr cb, int server_id, + ::Ice::Int channelid, bool tree, const ::std::string &text) { NEED_SERVER; NEED_CHANNEL; @@ -1255,7 +1295,8 @@ static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessag } #define ACCESS_Server_getChannelState_READ -static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelStatePtr cb, int server_id, ::Ice::Int channelid) { +static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelStatePtr cb, int server_id, + ::Ice::Int channelid) { NEED_SERVER; NEED_CHANNEL; @@ -1264,7 +1305,8 @@ static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelSta cb->ice_response(mc); } -static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelStatePtr cb, int server_id, const ::Murmur::Channel& state) { +static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelStatePtr cb, int server_id, + const ::Murmur::Channel &state) { int channelid = state.id; NEED_SERVER; NEED_CHANNEL; @@ -1275,8 +1317,8 @@ static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelSta QString qsName = u8(state.name); - QSet< ::Channel *> newset; - foreach(int linkid, state.links) { + QSet<::Channel * > newset; + foreach (int linkid, state.links) { ::Channel *cLink; NEED_CHANNEL_VAR(cLink, linkid); newset << cLink; @@ -1287,13 +1329,14 @@ static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelSta return; } - if (! server->setChannelState(channel, np, qsName, newset, u8(state.description), state.position)) + if (!server->setChannelState(channel, np, qsName, newset, u8(state.description), state.position)) cb->ice_exception(::Murmur::InvalidChannelException()); else cb->ice_response(); } -static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPtr cb, int server_id, ::Ice::Int channelid) { +static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPtr cb, int server_id, + ::Ice::Int channelid) { NEED_SERVER; NEED_CHANNEL; @@ -1305,7 +1348,8 @@ static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPt } } -static void impl_Server_addChannel(const ::Murmur::AMD_Server_addChannelPtr cb, int server_id, const ::std::string& name, ::Ice::Int parent) { +static void impl_Server_addChannel(const ::Murmur::AMD_Server_addChannelPtr cb, int server_id, + const ::std::string &name, ::Ice::Int parent) { NEED_SERVER; ::Channel *p, *nc; NEED_CHANNEL_VAR(p, parent); @@ -1338,7 +1382,7 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv ::Murmur::ACLList acls; ::Murmur::GroupList groups; - QStack< ::Channel *> chans; + QStack<::Channel * > chans; ::Channel *p; ChanACL *acl; p = channel; @@ -1352,10 +1396,10 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv bool inherit = channel->bInheritACL; - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { - if ((p==channel) || (acl->bApplySubs)) { + foreach (acl, p->qlACL) { + if ((p == channel) || (acl->bApplySubs)) { ::Murmur::ACL ma; ACLtoACL(acl, ma); if (p != channel) @@ -1365,24 +1409,24 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv } } - p = channel->cParent; - const QSet<QString> allnames = ::Group::groupNames(channel); - foreach(const QString &name, allnames) { - ::Group *g = channel->qhGroups.value(name); + p = channel->cParent; + const QSet< QString > allnames = ::Group::groupNames(channel); + foreach (const QString &name, allnames) { + ::Group *g = channel->qhGroups.value(name); ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; - if (!g && ! pg) + if (!g && !pg) continue; ::Murmur::Group mg; groupToGroup(g ? g : pg, mg); - QSet<int> members; + QSet< int > members; if (pg) members = pg->members(); if (g) { - QVector<int> addVec = g->qsAdd.values().toVector(); - QVector<int> removeVec = g->qsRemove.values().toVector(); + QVector< int > addVec = g->qsAdd.values().toVector(); + QVector< int > removeVec = g->qsRemove.values().toVector(); - mg.add = std::vector<int>(addVec.begin(), addVec.end()); - mg.remove = std::vector<int>(removeVec.begin(), removeVec.end()); + mg.add = std::vector< int >(addVec.begin(), addVec.end()); + mg.remove = std::vector< int >(removeVec.begin(), removeVec.end()); mg.inherited = false; members += g->qsAdd; members -= g->qsRemove; @@ -1390,58 +1434,59 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv mg.inherited = true; } - QVector<int> memberVec = members.values().toVector(); - mg.members = std::vector<int>(memberVec.begin(), memberVec.end()); + QVector< int > memberVec = members.values().toVector(); + mg.members = std::vector< int >(memberVec.begin(), memberVec.end()); groups.push_back(mg); } cb->ice_response(acls, groups, inherit); } -static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int server_id, ::Ice::Int channelid, const ::Murmur::ACLList& acls, const ::Murmur::GroupList& groups, bool inherit) { +static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int server_id, ::Ice::Int channelid, + const ::Murmur::ACLList &acls, const ::Murmur::GroupList &groups, bool inherit) { NEED_SERVER; NEED_CHANNEL; ::Group *g; ChanACL *acl; - QHash<QString, QSet<int> > hOldTemp; - foreach(g, channel->qhGroups) { + QHash< QString, QSet< int > > hOldTemp; + foreach (g, channel->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } - foreach(acl, channel->qlACL) + foreach (acl, channel->qlACL) delete acl; channel->qhGroups.clear(); channel->qlACL.clear(); channel->bInheritACL = inherit; - foreach(const ::Murmur::Group &gi, groups) { - QString name = u8(gi.name); - g = new ::Group(channel, name); - g->bInherit = gi.inherit; + foreach (const ::Murmur::Group &gi, groups) { + QString name = u8(gi.name); + g = new ::Group(channel, name); + g->bInherit = gi.inherit; g->bInheritable = gi.inheritable; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QVector<int> addVec(gi.add.begin(), gi.add.end()); - QVector<int> removeVec(gi.remove.begin(), gi.remove.end()); + QVector< int > addVec(gi.add.begin(), gi.add.end()); + QVector< int > removeVec(gi.remove.begin(), gi.remove.end()); - g->qsAdd = QSet<int>(addVec.begin(), addVec.end()); - g->qsRemove = QSet<int>(removeVec.begin(), removeVec.end()); + g->qsAdd = QSet< int >(addVec.begin(), addVec.end()); + g->qsRemove = QSet< int >(removeVec.begin(), removeVec.end()); #else // Qt 5.14 prefers to use the new range-based constructor for vectors and sets - g->qsAdd = QVector<int>::fromStdVector(gi.add).toList().toSet(); - g->qsRemove = QVector<int>::fromStdVector(gi.remove).toList().toSet(); + g->qsAdd = QVector< int >::fromStdVector(gi.add).toList().toSet(); + g->qsRemove = QVector< int >::fromStdVector(gi.remove).toList().toSet(); #endif g->qsTemporary = hOldTemp.value(name); } - foreach(const ::Murmur::ACL &ai, acls) { - acl = new ChanACL(channel); + foreach (const ::Murmur::ACL &ai, acls) { + acl = new ChanACL(channel); acl->bApplyHere = ai.applyHere; acl->bApplySubs = ai.applySubs; - acl->iUserId = ai.userid; - acl->qsGroup = u8(ai.group); - acl->pDeny = static_cast<ChanACL::Permissions>(ai.deny) & ChanACL::All; - acl->pAllow = static_cast<ChanACL::Permissions>(ai.allow) & ChanACL::All; + acl->iUserId = ai.userid; + acl->qsGroup = u8(ai.group); + acl->pDeny = static_cast< ChanACL::Permissions >(ai.deny) & ChanACL::All; + acl->pAllow = static_cast< ChanACL::Permissions >(ai.allow) & ChanACL::All; } server->clearACLCache(); @@ -1450,30 +1495,31 @@ static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int serv } #define ACCESS_Server_getUserNames_READ -static void impl_Server_getUserNames(const ::Murmur::AMD_Server_getUserNamesPtr cb, int server_id, const ::Murmur::IdList& ids) { +static void impl_Server_getUserNames(const ::Murmur::AMD_Server_getUserNamesPtr cb, int server_id, + const ::Murmur::IdList &ids) { NEED_SERVER; ::Murmur::NameMap nm; - foreach(int userid, ids) { - nm[userid] = iceString(server->getUserName(userid)); - } + foreach (int userid, ids) { nm[userid] = iceString(server->getUserName(userid)); } cb->ice_response(nm); } #define ACCESS_Server_getUserIds_READ -static void impl_Server_getUserIds(const ::Murmur::AMD_Server_getUserIdsPtr cb, int server_id, const ::Murmur::NameList& names) { +static void impl_Server_getUserIds(const ::Murmur::AMD_Server_getUserIdsPtr cb, int server_id, + const ::Murmur::NameList &names) { NEED_SERVER; ::Murmur::IdMap im; - foreach(const string &n, names) { + foreach (const string &n, names) { QString name = u8(n); - im[n] = server->getUserID(name); + im[n] = server->getUserID(name); } cb->ice_response(im); } -static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb, int server_id, const ::Murmur::UserInfoMap &im) { +static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb, int server_id, + const ::Murmur::UserInfoMap &im) { NEED_SERVER; - QMap<int, QString> info; + QMap< int, QString > info; infoToInfo(im, info); int userid = server->registerUser(info); @@ -1483,34 +1529,37 @@ static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb->ice_response(userid); } -static void impl_Server_unregisterUser(const ::Murmur::AMD_Server_unregisterUserPtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_unregisterUser(const ::Murmur::AMD_Server_unregisterUserPtr cb, int server_id, + ::Ice::Int userid) { NEED_SERVER; - if (! server->unregisterUser(userid)) + if (!server->unregisterUser(userid)) cb->ice_exception(InvalidUserException()); else cb->ice_response(); } -static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegistrationPtr cb, int server_id, int id, const ::Murmur::UserInfoMap &im) { +static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegistrationPtr cb, int server_id, int id, + const ::Murmur::UserInfoMap &im) { NEED_SERVER; - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { cb->ice_exception(InvalidUserException()); return; } - QMap<int, QString> info; + QMap< int, QString > info; infoToInfo(im, info); - if (! server->setInfo(id, info)) { + if (!server->setInfo(id, info)) { cb->ice_exception(InvalidUserException()); return; } if (info.contains(ServerDB::User_Comment)) { - foreach(ServerUser *u, server->qhUsers) { + foreach (ServerUser *u, server->qhUsers) { if (u->iId == id) - server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, u->qsName, info.value(ServerDB::User_Comment)); + server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, u->qsName, + info.value(ServerDB::User_Comment)); } } @@ -1518,10 +1567,11 @@ static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegi } #define ACCESS_Server_getRegistration_READ -static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrationPtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrationPtr cb, int server_id, + ::Ice::Int userid) { NEED_SERVER; - QMap<int, QString> info = server->getRegistration(userid); + QMap< int, QString > info = server->getRegistration(userid); if (info.isEmpty()) { cb->ice_exception(InvalidUserException()); @@ -1534,12 +1584,13 @@ static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrati } #define ACCESS_Server_getRegisteredUsers_READ -static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegisteredUsersPtr cb, int server_id, const ::std::string& filter) { +static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegisteredUsersPtr cb, int server_id, + const ::std::string &filter) { NEED_SERVER; Murmur::NameMap rpl; - const QMap<int, QString> l = server->getRegisteredUsers(u8(filter)); - QMap<int, QString>::const_iterator i; + const QMap< int, QString > l = server->getRegisteredUsers(u8(filter)); + QMap< int, QString >::const_iterator i; for (i = l.constBegin(); i != l.constEnd(); ++i) { rpl[i.key()] = u8(i.value()); } @@ -1548,17 +1599,18 @@ static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegiste } #define ACCESS_Server_verifyPassword_READ -static void impl_Server_verifyPassword(const ::Murmur::AMD_Server_verifyPasswordPtr cb, int server_id, const ::std::string& name, const ::std::string& pw) { +static void impl_Server_verifyPassword(const ::Murmur::AMD_Server_verifyPasswordPtr cb, int server_id, + const ::std::string &name, const ::std::string &pw) { NEED_SERVER; QString uname = u8(name); cb->ice_response(server->authenticate(uname, u8(pw))); } #define ACCESS_Server_getTexture_READ -static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, int server_id, ::Ice::Int userid) { NEED_SERVER; - if (! server->isUserId(userid)) { + if (!server->isUserId(userid)) { cb->ice_exception(InvalidUserException()); return; } @@ -1568,25 +1620,26 @@ static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, ::Murmur::Texture tex; tex.resize(qba.size()); const char *ptr = qba.constData(); - for (int i=0;i<qba.size();++i) + for (int i = 0; i < qba.size(); ++i) tex[i] = ptr[i]; cb->ice_response(tex); } -static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, int server_id, ::Ice::Int userid, const ::Murmur::Texture& tex) { +static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, int server_id, ::Ice::Int userid, + const ::Murmur::Texture &tex) { NEED_SERVER; - if (! server->isUserId(userid)) { + if (!server->isUserId(userid)) { cb->ice_exception(InvalidUserException()); return; } - QByteArray qba(static_cast<int>(tex.size()), 0); + QByteArray qba(static_cast< int >(tex.size()), 0); char *ptr = qba.data(); - for (unsigned int i=0;i<tex.size();++i) + for (unsigned int i = 0; i < tex.size(); ++i) ptr[i] = tex[i]; - if (! server->setTexture(userid, qba)) { + if (!server->setTexture(userid, qba)) { cb->ice_exception(InvalidTextureException()); } else { ServerUser *user = server->qhUsers.value(userid); @@ -1596,7 +1649,7 @@ static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, mpus.set_texture(blob(user->qbaTexture)); server->sendAll(mpus, ~0x010202); - if (! user->qbaTextureHash.isEmpty()) { + if (!user->qbaTextureHash.isEmpty()) { mpus.clear_texture(); mpus.set_texture_hash(blob(user->qbaTextureHash)); } @@ -1610,10 +1663,12 @@ static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, #define ACCESS_Server_getUptime_READ static void impl_Server_getUptime(const ::Murmur::AMD_Server_getUptimePtr cb, int server_id) { NEED_SERVER; - cb->ice_response(static_cast<int>(server->tUptime.elapsed()/1000000LL)); + cb->ice_response(static_cast< int >(server->tUptime.elapsed() / 1000000LL)); } -static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCertificatePtr cb, int server_id, const ::std::string& certificate, const ::std::string& privateKey, const ::std::string& passphrase) { +static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCertificatePtr cb, int server_id, + const ::std::string &certificate, const ::std::string &privateKey, + const ::std::string &passphrase) { NEED_SERVER; QByteArray certPem(certificate.c_str()); @@ -1655,7 +1710,8 @@ static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCerti cb->ice_response(); } -static void impl_Server_startListening(const ::Murmur::AMD_Server_startListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_startListening(const ::Murmur::AMD_Server_startListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1665,7 +1721,8 @@ static void impl_Server_startListening(const ::Murmur::AMD_Server_startListening cb->ice_response(); } -static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1675,7 +1732,8 @@ static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPt cb->ice_response(); } -static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1683,31 +1741,34 @@ static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb cb->ice_response(ChannelListener::isListening(user, channel)); } -static void impl_Server_getListeningChannels(const ::Murmur::AMD_Server_getListeningChannelsPtr cb, int server_id, int session) { +static void impl_Server_getListeningChannels(const ::Murmur::AMD_Server_getListeningChannelsPtr cb, int server_id, + int session) { NEED_SERVER; NEED_PLAYER; ::Murmur::IntList channelIDs; - foreach(int currentChannelID, ChannelListener::getListenedChannelsForUser(user)) { + foreach (int currentChannelID, ChannelListener::getListenedChannelsForUser(user)) { channelIDs.push_back(currentChannelID); } cb->ice_response(channelIDs); } -static void impl_Server_getListeningUsers(const ::Murmur::AMD_Server_getListeningUsersPtr cb, int server_id, int channelid) { +static void impl_Server_getListeningUsers(const ::Murmur::AMD_Server_getListeningUsersPtr cb, int server_id, + int channelid) { NEED_SERVER; NEED_CHANNEL; ::Murmur::IntList userSessions; - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(channel)) { + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(channel)) { userSessions.push_back(currentSession); } cb->ice_response(userSessions); } -static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroupPtr cb, int server_id, ::Ice::Int channelid, ::Ice::Int session, const ::std::string& group) { +static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroupPtr cb, int server_id, + ::Ice::Int channelid, ::Ice::Int session, const ::std::string &group) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; @@ -1722,10 +1783,10 @@ static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroup QWriteLocker wl(&server->qrwlVoiceThread); ::Group *g = channel->qhGroups.value(qsgroup); - if (! g) + if (!g) g = new ::Group(channel, qsgroup); - g->qsTemporary.insert(- session); + g->qsTemporary.insert(-session); } server->clearACLCache(user); @@ -1733,7 +1794,8 @@ static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroup cb->ice_response(); } -static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUserFromGroupPtr cb, int server_id, ::Ice::Int channelid, ::Ice::Int session, const ::std::string& group) { +static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUserFromGroupPtr cb, int server_id, + ::Ice::Int channelid, ::Ice::Int session, const ::std::string &group) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; @@ -1759,7 +1821,9 @@ static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUse cb->ice_response(); } -static void impl_Server_redirectWhisperGroup(const ::Murmur::AMD_Server_redirectWhisperGroupPtr cb, int server_id, ::Ice::Int session, const ::std::string& source, const ::std::string& target) { +static void impl_Server_redirectWhisperGroup(const ::Murmur::AMD_Server_redirectWhisperGroupPtr cb, int server_id, + ::Ice::Int session, const ::std::string &source, + const ::std::string &target) { NEED_SERVER; NEED_PLAYER; @@ -1786,9 +1850,10 @@ static void impl_Meta_getSliceChecksums(const ::Murmur::AMD_Meta_getSliceChecksu } #define ACCESS_Meta_getServer_READ -static void impl_Meta_getServer(const ::Murmur::AMD_Meta_getServerPtr cb, const Ice::ObjectAdapterPtr adapter, ::Ice::Int id) { - QList<int> server_list = ServerDB::getAllServers(); - if (! server_list.contains(id)) +static void impl_Meta_getServer(const ::Murmur::AMD_Meta_getServerPtr cb, const Ice::ObjectAdapterPtr adapter, + ::Ice::Int id) { + QList< int > server_list = ServerDB::getAllServers(); + if (!server_list.contains(id)) cb->ice_response(nullptr); else cb->ice_response(idToProxy(id, adapter)); @@ -1802,7 +1867,7 @@ static void impl_Meta_newServer(const ::Murmur::AMD_Meta_newServerPtr cb, const static void impl_Meta_getAllServers(const ::Murmur::AMD_Meta_getAllServersPtr cb, const Ice::ObjectAdapterPtr adapter) { ::Murmur::ServerList sl; - foreach(int id, ServerDB::getAllServers()) + foreach (int id, ServerDB::getAllServers()) sl.push_back(idToProxy(id, adapter)); cb->ice_response(sl); } @@ -1810,8 +1875,8 @@ static void impl_Meta_getAllServers(const ::Murmur::AMD_Meta_getAllServersPtr cb #define ACCESS_Meta_getDefaultConf_READ static void impl_Meta_getDefaultConf(const ::Murmur::AMD_Meta_getDefaultConfPtr cb, const Ice::ObjectAdapterPtr) { ::Murmur::ConfigMap cm; - QMap<QString, QString>::const_iterator i; - for (i=meta->mp.qmConfig.constBegin();i != meta->mp.qmConfig.constEnd(); ++i) { + QMap< QString, QString >::const_iterator i; + for (i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { if (i.key() == "key" || i.key() == "passphrase") continue; cm[iceString(i.key())] = iceString(i.value()); @@ -1820,10 +1885,11 @@ static void impl_Meta_getDefaultConf(const ::Murmur::AMD_Meta_getDefaultConfPtr } #define ACCESS_Meta_getBootedServers_READ -static void impl_Meta_getBootedServers(const ::Murmur::AMD_Meta_getBootedServersPtr cb, const Ice::ObjectAdapterPtr adapter) { +static void impl_Meta_getBootedServers(const ::Murmur::AMD_Meta_getBootedServersPtr cb, + const Ice::ObjectAdapterPtr adapter) { ::Murmur::ServerList sl; - foreach(int id, meta->qhServers.keys()) + foreach (int id, meta->qhServers.keys()) sl.push_back(idToProxy(id, adapter)); cb->ice_response(sl); } @@ -1836,9 +1902,11 @@ static void impl_Meta_getVersion(const ::Murmur::AMD_Meta_getVersionPtr cb, cons cb->ice_response(major, minor, patch, iceString(txt)); } -static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, const Ice::ObjectAdapterPtr, const Murmur::MetaCallbackPrx& cbptr) { +static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, const Ice::ObjectAdapterPtr, + const Murmur::MetaCallbackPrx &cbptr) { try { - const Murmur::MetaCallbackPrx &oneway = Murmur::MetaCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::MetaCallbackPrx &oneway = + Murmur::MetaCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); mi->addMetaCallback(oneway); cb->ice_response(); } catch (...) { @@ -1846,9 +1914,11 @@ static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, cons } } -static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb, const Ice::ObjectAdapterPtr, const Murmur::MetaCallbackPrx& cbptr) { +static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb, const Ice::ObjectAdapterPtr, + const Murmur::MetaCallbackPrx &cbptr) { try { - const Murmur::MetaCallbackPrx &oneway = Murmur::MetaCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::MetaCallbackPrx &oneway = + Murmur::MetaCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); mi->removeMetaCallback(oneway); cb->ice_response(); } catch (...) { @@ -1858,7 +1928,7 @@ static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb #define ACCESS_Meta_getUptime_ALL static void impl_Meta_getUptime(const ::Murmur::AMD_Meta_getUptimePtr cb, const Ice::ObjectAdapterPtr) { - cb->ice_response(static_cast<int>(meta->tUptime.elapsed()/1000000LL)); + cb->ice_response(static_cast< int >(meta->tUptime.elapsed() / 1000000LL)); } #include "MurmurIceWrapper.cpp" diff --git a/src/murmur/MurmurIce.h b/src/murmur/MurmurIce.h index a3c135c97..a5b3675ce 100644 --- a/src/murmur/MurmurIce.h +++ b/src/murmur/MurmurIce.h @@ -4,24 +4,24 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_ICE -#ifndef MUMBLE_MURMUR_MURMURICE_H_ -#define MUMBLE_MURMUR_MURMURICE_H_ +# ifndef MUMBLE_MURMUR_MURMURICE_H_ +# define MUMBLE_MURMUR_MURMURICE_H_ -#include <QtCore/QtGlobal> +# include <QtCore/QtGlobal> -#ifdef Q_OS_WIN +# ifdef Q_OS_WIN // To prevent <windows.h> (included by Ice) from including <winsock.h>. -# define WIN32_LEAN_AND_MEAN -#endif +# define WIN32_LEAN_AND_MEAN +# endif -#include <QtCore/QList> -#include <QtCore/QMap> -#include <QtCore/QMutex> -#include <QtCore/QObject> -#include <QtCore/QWaitCondition> -#include <QtNetwork/QSslCertificate> +# include <QtCore/QList> +# include <QtCore/QMap> +# include <QtCore/QMutex> +# include <QtCore/QObject> +# include <QtCore/QWaitCondition> +# include <QtNetwork/QSslCertificate> -#include "MurmurI.h" +# include "MurmurI.h" class Channel; class Server; @@ -29,67 +29,72 @@ class User; struct TextMessage; class MurmurIce : public QObject { - friend class MurmurLocker; - Q_OBJECT; - protected: - int count; - QMutex qmEvent; - QWaitCondition qwcEvent; - void customEvent(QEvent *evt); - void badMetaProxy(const ::Murmur::MetaCallbackPrx &prx); - void badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server* server); - void badAuthenticator(::Server *); - QList< ::Murmur::MetaCallbackPrx> qlMetaCallbacks; - QMap<int, QList< ::Murmur::ServerCallbackPrx> > qmServerCallbacks; - QMap<int, QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > > qmServerContextCallbacks; - QMap<int, ::Murmur::ServerAuthenticatorPrx> qmServerAuthenticator; - QMap<int, ::Murmur::ServerUpdatingAuthenticatorPrx> qmServerUpdatingAuthenticator; - public: - Ice::CommunicatorPtr communicator; - Ice::ObjectAdapterPtr adapter; - MurmurIce(); - ~MurmurIce(); + friend class MurmurLocker; + Q_OBJECT; + +protected: + int count; + QMutex qmEvent; + QWaitCondition qwcEvent; + void customEvent(QEvent *evt); + void badMetaProxy(const ::Murmur::MetaCallbackPrx &prx); + void badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server *server); + void badAuthenticator(::Server *); + QList<::Murmur::MetaCallbackPrx > qlMetaCallbacks; + QMap< int, QList<::Murmur::ServerCallbackPrx > > qmServerCallbacks; + QMap< int, QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > > qmServerContextCallbacks; + QMap< int, ::Murmur::ServerAuthenticatorPrx > qmServerAuthenticator; + QMap< int, ::Murmur::ServerUpdatingAuthenticatorPrx > qmServerUpdatingAuthenticator; - void addMetaCallback(const ::Murmur::MetaCallbackPrx& prx); - void removeMetaCallback(const ::Murmur::MetaCallbackPrx& prx); - void addServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx); - void removeServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx); - void removeServerCallbacks(const ::Server* server); - void addServerContextCallback(const ::Server* server, int session_id, const QString& action, const ::Murmur::ServerContextCallbackPrx& prx); - const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > getServerContextCallbacks(const ::Server* server) const; - void removeServerContextCallback(const ::Server* server, int session_id, const QString& action); - void setServerAuthenticator(const ::Server* server, const ::Murmur::ServerAuthenticatorPrx& prx); - const ::Murmur::ServerAuthenticatorPrx getServerAuthenticator(const ::Server* server) const; - void removeServerAuthenticator(const ::Server* server); - void setServerUpdatingAuthenticator(const ::Server* server, const ::Murmur::ServerUpdatingAuthenticatorPrx& prx); - const ::Murmur::ServerUpdatingAuthenticatorPrx getServerUpdatingAuthenticator(const ::Server* server) const; - void removeServerUpdatingAuthenticator(const ::Server* server); +public: + Ice::CommunicatorPtr communicator; + Ice::ObjectAdapterPtr adapter; + MurmurIce(); + ~MurmurIce(); - public slots: - void started(Server *); - void stopped(Server *); + void addMetaCallback(const ::Murmur::MetaCallbackPrx &prx); + void removeMetaCallback(const ::Murmur::MetaCallbackPrx &prx); + void addServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx); + void removeServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx); + void removeServerCallbacks(const ::Server *server); + void addServerContextCallback(const ::Server *server, int session_id, const QString &action, + const ::Murmur::ServerContextCallbackPrx &prx); + const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > + getServerContextCallbacks(const ::Server *server) const; + void removeServerContextCallback(const ::Server *server, int session_id, const QString &action); + void setServerAuthenticator(const ::Server *server, const ::Murmur::ServerAuthenticatorPrx &prx); + const ::Murmur::ServerAuthenticatorPrx getServerAuthenticator(const ::Server *server) const; + void removeServerAuthenticator(const ::Server *server); + void setServerUpdatingAuthenticator(const ::Server *server, const ::Murmur::ServerUpdatingAuthenticatorPrx &prx); + const ::Murmur::ServerUpdatingAuthenticatorPrx getServerUpdatingAuthenticator(const ::Server *server) const; + void removeServerUpdatingAuthenticator(const ::Server *server); - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); +public slots: + void started(Server *); + void stopped(Server *); - void userStateChanged(const User *p); - void userTextMessage(const User *p, const TextMessage &); - void userConnected(const User *p); - void userDisconnected(const User *p); + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); - void channelStateChanged(const Channel *c); - void channelCreated(const Channel *c); - void channelRemoved(const Channel *c); + void userStateChanged(const User *p); + void userTextMessage(const User *p, const TextMessage &); + void userConnected(const User *p); + void userDisconnected(const User *p); - void contextAction(const User *, const QString &, unsigned int, int); + void channelStateChanged(const Channel *c); + void channelCreated(const Channel *c); + void channelRemoved(const Channel *c); + + void contextAction(const User *, const QString &, unsigned int, int); }; -#endif +# endif #endif diff --git a/src/murmur/MurmurIceWrapper.cpp b/src/murmur/MurmurIceWrapper.cpp index 6d735fd27..8e909529f 100644 --- a/src/murmur/MurmurIceWrapper.cpp +++ b/src/murmur/MurmurIceWrapper.cpp @@ -5,54 +5,55 @@ void ::Murmur::ServerI::isRunning_async(const ::Murmur::AMD_Server_isRunningPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "isRunning" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_isRunning_ALL -#ifdef ACCESS_Server_isRunning_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_isRunning_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_isRunning_READ +# ifdef ACCESS_Server_isRunning_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_isRunning, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_isRunning, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::start_async(const ::Murmur::AMD_Server_startPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "start" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_start_ALL -#ifdef ACCESS_Server_start_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_start_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_start_READ +# ifdef ACCESS_Server_start_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -65,24 +66,24 @@ void ::Murmur::ServerI::start_async(const ::Murmur::AMD_Server_startPtr &cb, con void ::Murmur::ServerI::stop_async(const ::Murmur::AMD_Server_stopPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "stop" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_stop_ALL -#ifdef ACCESS_Server_stop_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_stop_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_stop_READ +# ifdef ACCESS_Server_stop_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -95,54 +96,55 @@ void ::Murmur::ServerI::stop_async(const ::Murmur::AMD_Server_stopPtr &cb, const void ::Murmur::ServerI::delete_async(const ::Murmur::AMD_Server_deletePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "delete" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_delete_ALL -#ifdef ACCESS_Server_delete_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_delete_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_delete_READ +# ifdef ACCESS_Server_delete_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_delete, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_delete, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::id_async(const ::Murmur::AMD_Server_idPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "id" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_id_ALL -#ifdef ACCESS_Server_id_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_id_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_id_READ +# ifdef ACCESS_Server_id_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -152,1527 +154,1630 @@ void ::Murmur::ServerI::id_async(const ::Murmur::AMD_Server_idPtr &cb, const ::I QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &cb, const ::Murmur::ServerCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &cb, + const ::Murmur::ServerCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "addCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addCallback_ALL -#ifdef ACCESS_Server_addCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addCallback_READ +# ifdef ACCESS_Server_addCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_addCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &cb, const ::Murmur::ServerCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &cb, + const ::Murmur::ServerCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "removeCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeCallback_ALL -#ifdef ACCESS_Server_removeCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeCallback_READ +# ifdef ACCESS_Server_removeCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, const ::Murmur::ServerAuthenticatorPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, + const ::Murmur::ServerAuthenticatorPrx &p1, + const ::Ice::Current ¤t) { // qWarning() << "setAuthenticator" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setAuthenticator_ALL -#ifdef ACCESS_Server_setAuthenticator_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setAuthenticator_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setAuthenticator_READ +# ifdef ACCESS_Server_setAuthenticator_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setAuthenticator, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setAuthenticator, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getConf_async(const ::Murmur::AMD_Server_getConfPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getConf_async(const ::Murmur::AMD_Server_getConfPtr &cb, const ::std::string &p1, + const ::Ice::Current ¤t) { // qWarning() << "getConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getConf_ALL -#ifdef ACCESS_Server_getConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getConf_READ +# ifdef ACCESS_Server_getConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getConf, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getConf, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getAllConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getAllConf_ALL -#ifdef ACCESS_Server_getAllConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getAllConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getAllConf_READ +# ifdef ACCESS_Server_getAllConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getAllConf, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getAllConf, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setConf_async(const ::Murmur::AMD_Server_setConfPtr &cb, const ::std::string& p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setConf_async(const ::Murmur::AMD_Server_setConfPtr &cb, const ::std::string &p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "setConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setConf_ALL -#ifdef ACCESS_Server_setConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setConf_READ +# ifdef ACCESS_Server_setConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setConf, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setConf, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &cb, + const ::std::string &p1, const ::Ice::Current ¤t) { // qWarning() << "setSuperuserPassword" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setSuperuserPassword_ALL -#ifdef ACCESS_Server_setSuperuserPassword_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setSuperuserPassword_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setSuperuserPassword_READ +# ifdef ACCESS_Server_setSuperuserPassword_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setSuperuserPassword, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setSuperuserPassword, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getLog_async(const ::Murmur::AMD_Server_getLogPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getLog_async(const ::Murmur::AMD_Server_getLogPtr &cb, ::Ice::Int p1, ::Ice::Int p2, + const ::Ice::Current ¤t) { // qWarning() << "getLog" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getLog_ALL -#ifdef ACCESS_Server_getLog_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getLog_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getLog_READ +# ifdef ACCESS_Server_getLog_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getLog, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getLog, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getLogLen" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getLogLen_ALL -#ifdef ACCESS_Server_getLogLen_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getLogLen_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getLogLen_READ +# ifdef ACCESS_Server_getLogLen_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getLogLen, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getLogLen, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getUsers_async(const ::Murmur::AMD_Server_getUsersPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUsers_ALL -#ifdef ACCESS_Server_getUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUsers_READ +# ifdef ACCESS_Server_getUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUsers, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUsers, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getChannels" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getChannels_ALL -#ifdef ACCESS_Server_getChannels_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getChannels_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getChannels_READ +# ifdef ACCESS_Server_getChannels_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getChannels, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getChannels, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getCertificateList" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getCertificateList_ALL -#ifdef ACCESS_Server_getCertificateList_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getCertificateList_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getCertificateList_READ +# ifdef ACCESS_Server_getCertificateList_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getCertificateList, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getCertificateList, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getTree_async(const ::Murmur::AMD_Server_getTreePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getTree" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getTree_ALL -#ifdef ACCESS_Server_getTree_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getTree_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getTree_READ +# ifdef ACCESS_Server_getTree_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getTree, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getTree, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getBans_async(const ::Murmur::AMD_Server_getBansPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getBans" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getBans_ALL -#ifdef ACCESS_Server_getBans_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getBans_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getBans_READ +# ifdef ACCESS_Server_getBans_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getBans, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getBans, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setBans_async(const ::Murmur::AMD_Server_setBansPtr &cb, const ::Murmur::BanList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setBans_async(const ::Murmur::AMD_Server_setBansPtr &cb, const ::Murmur::BanList &p1, + const ::Ice::Current ¤t) { // qWarning() << "setBans" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setBans_ALL -#ifdef ACCESS_Server_setBans_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setBans_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setBans_READ +# ifdef ACCESS_Server_setBans_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setBans, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setBans, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "kickUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_kickUser_ALL -#ifdef ACCESS_Server_kickUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_kickUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_kickUser_READ +# ifdef ACCESS_Server_kickUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_kickUser, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_kickUser, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getState_async(const ::Murmur::AMD_Server_getStatePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getState_async(const ::Murmur::AMD_Server_getStatePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getState_ALL -#ifdef ACCESS_Server_getState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getState_READ +# ifdef ACCESS_Server_getState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setState_async(const ::Murmur::AMD_Server_setStatePtr &cb, const ::Murmur::User& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setState_async(const ::Murmur::AMD_Server_setStatePtr &cb, const ::Murmur::User &p1, + const ::Ice::Current ¤t) { // qWarning() << "setState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setState_ALL -#ifdef ACCESS_Server_setState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setState_READ +# ifdef ACCESS_Server_setState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "sendMessage" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_sendMessage_ALL -#ifdef ACCESS_Server_sendMessage_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_sendMessage_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_sendMessage_READ +# ifdef ACCESS_Server_sendMessage_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_sendMessage, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_sendMessage, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &cb, ::Ice::Int p1, ::Ice::Int p2, ::Ice::Int p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, ::Ice::Int p3, const ::Ice::Current ¤t) { // qWarning() << "hasPermission" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_hasPermission_ALL -#ifdef ACCESS_Server_hasPermission_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_hasPermission_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_hasPermission_READ +# ifdef ACCESS_Server_hasPermission_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_hasPermission, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_hasPermission, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &cb, + ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "effectivePermissions" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_effectivePermissions_ALL -#ifdef ACCESS_Server_effectivePermissions_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_effectivePermissions_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_effectivePermissions_READ +# ifdef ACCESS_Server_effectivePermissions_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_effectivePermissions, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_effectivePermissions, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::std::string& p3, const ::Murmur::ServerContextCallbackPrx& p4, ::Ice::Int p5, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::std::string &p3, + const ::Murmur::ServerContextCallbackPrx &p4, ::Ice::Int p5, + const ::Ice::Current ¤t) { // qWarning() << "addContextCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addContextCallback_ALL -#ifdef ACCESS_Server_addContextCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addContextCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addContextCallback_READ +# ifdef ACCESS_Server_addContextCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4, p5)); + ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addContextCallback, cb, + QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4, p5)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &cb, const ::Murmur::ServerContextCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &cb, + const ::Murmur::ServerContextCallbackPrx &p1, + const ::Ice::Current ¤t) { // qWarning() << "removeContextCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeContextCallback_ALL -#ifdef ACCESS_Server_removeContextCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeContextCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeContextCallback_READ +# ifdef ACCESS_Server_removeContextCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getChannelState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getChannelState_ALL -#ifdef ACCESS_Server_getChannelState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getChannelState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getChannelState_READ +# ifdef ACCESS_Server_getChannelState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &cb, const ::Murmur::Channel& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &cb, + const ::Murmur::Channel &p1, const ::Ice::Current ¤t) { // qWarning() << "setChannelState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setChannelState_ALL -#ifdef ACCESS_Server_setChannelState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setChannelState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setChannelState_READ +# ifdef ACCESS_Server_setChannelState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "removeChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeChannel_ALL -#ifdef ACCESS_Server_removeChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeChannel_READ +# ifdef ACCESS_Server_removeChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeChannel, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_removeChannel, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &cb, const ::std::string& p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &cb, const ::std::string &p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "addChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addChannel_ALL -#ifdef ACCESS_Server_addChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addChannel_READ +# ifdef ACCESS_Server_addChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_addChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &cb, ::Ice::Int p1, bool p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &cb, ::Ice::Int p1, + bool p2, const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "sendMessageChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_sendMessageChannel_ALL -#ifdef ACCESS_Server_sendMessageChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_sendMessageChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_sendMessageChannel_READ +# ifdef ACCESS_Server_sendMessageChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_sendMessageChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_sendMessageChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getACL_async(const ::Murmur::AMD_Server_getACLPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getACL_async(const ::Murmur::AMD_Server_getACLPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getACL" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getACL_ALL -#ifdef ACCESS_Server_getACL_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getACL_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getACL_READ +# ifdef ACCESS_Server_getACL_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getACL, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getACL, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setACL_async(const ::Murmur::AMD_Server_setACLPtr &cb, ::Ice::Int p1, const ::Murmur::ACLList& p2, const ::Murmur::GroupList& p3, bool p4, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setACL_async(const ::Murmur::AMD_Server_setACLPtr &cb, ::Ice::Int p1, + const ::Murmur::ACLList &p2, const ::Murmur::GroupList &p3, bool p4, + const ::Ice::Current ¤t) { // qWarning() << "setACL" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setACL_ALL -#ifdef ACCESS_Server_setACL_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setACL_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setACL_READ +# ifdef ACCESS_Server_setACL_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setACL, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setACL, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "addUserToGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addUserToGroup_ALL -#ifdef ACCESS_Server_addUserToGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addUserToGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addUserToGroup_READ +# ifdef ACCESS_Server_addUserToGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addUserToGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_addUserToGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::std::string &p3, + const ::Ice::Current ¤t) { // qWarning() << "removeUserFromGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeUserFromGroup_ALL -#ifdef ACCESS_Server_removeUserFromGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeUserFromGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeUserFromGroup_READ +# ifdef ACCESS_Server_removeUserFromGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeUserFromGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeUserFromGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &cb, + ::Ice::Int p1, const ::std::string &p2, const ::std::string &p3, + const ::Ice::Current ¤t) { // qWarning() << "redirectWhisperGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_redirectWhisperGroup_ALL -#ifdef ACCESS_Server_redirectWhisperGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_redirectWhisperGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_redirectWhisperGroup_READ +# ifdef ACCESS_Server_redirectWhisperGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_redirectWhisperGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_redirectWhisperGroup, cb, + QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &cb, const ::Murmur::IdList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &cb, const ::Murmur::IdList &p1, + const ::Ice::Current ¤t) { // qWarning() << "getUserNames" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUserNames_ALL -#ifdef ACCESS_Server_getUserNames_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUserNames_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUserNames_READ +# ifdef ACCESS_Server_getUserNames_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUserNames, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUserNames, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &cb, const ::Murmur::NameList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &cb, const ::Murmur::NameList &p1, + const ::Ice::Current ¤t) { // qWarning() << "getUserIds" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUserIds_ALL -#ifdef ACCESS_Server_getUserIds_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUserIds_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUserIds_READ +# ifdef ACCESS_Server_getUserIds_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUserIds, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUserIds, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &cb, const ::Murmur::UserInfoMap& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &cb, + const ::Murmur::UserInfoMap &p1, const ::Ice::Current ¤t) { // qWarning() << "registerUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_registerUser_ALL -#ifdef ACCESS_Server_registerUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_registerUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_registerUser_READ +# ifdef ACCESS_Server_registerUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_registerUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_registerUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "unregisterUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_unregisterUser_ALL -#ifdef ACCESS_Server_unregisterUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_unregisterUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_unregisterUser_READ +# ifdef ACCESS_Server_unregisterUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_unregisterUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_unregisterUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &cb, ::Ice::Int p1, const ::Murmur::UserInfoMap& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &cb, ::Ice::Int p1, + const ::Murmur::UserInfoMap &p2, const ::Ice::Current ¤t) { // qWarning() << "updateRegistration" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_updateRegistration_ALL -#ifdef ACCESS_Server_updateRegistration_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_updateRegistration_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_updateRegistration_READ +# ifdef ACCESS_Server_updateRegistration_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_updateRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_updateRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getRegistration" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getRegistration_ALL -#ifdef ACCESS_Server_getRegistration_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getRegistration_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getRegistration_READ +# ifdef ACCESS_Server_getRegistration_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &cb, + const ::std::string &p1, const ::Ice::Current ¤t) { // qWarning() << "getRegisteredUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getRegisteredUsers_ALL -#ifdef ACCESS_Server_getRegisteredUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getRegisteredUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getRegisteredUsers_READ +# ifdef ACCESS_Server_getRegisteredUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getRegisteredUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getRegisteredUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &cb, const ::std::string& p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &cb, const ::std::string &p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "verifyPassword" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_verifyPassword_ALL -#ifdef ACCESS_Server_verifyPassword_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_verifyPassword_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_verifyPassword_READ +# ifdef ACCESS_Server_verifyPassword_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_verifyPassword, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_verifyPassword, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getTexture" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getTexture_ALL -#ifdef ACCESS_Server_getTexture_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getTexture_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getTexture_READ +# ifdef ACCESS_Server_getTexture_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getTexture, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getTexture, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &cb, ::Ice::Int p1, const ::Murmur::Texture& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &cb, ::Ice::Int p1, + const ::Murmur::Texture &p2, const ::Ice::Current ¤t) { // qWarning() << "setTexture" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setTexture_ALL -#ifdef ACCESS_Server_setTexture_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setTexture_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setTexture_READ +# ifdef ACCESS_Server_setTexture_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setTexture, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setTexture, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getUptime_async(const ::Murmur::AMD_Server_getUptimePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUptime" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUptime_ALL -#ifdef ACCESS_Server_getUptime_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUptime_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUptime_READ +# ifdef ACCESS_Server_getUptime_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUptime, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUptime, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &cb, const ::std::string& p1, const ::std::string& p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &cb, + const ::std::string &p1, const ::std::string &p2, + const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "updateCertificate" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_updateCertificate_ALL -#ifdef ACCESS_Server_updateCertificate_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_updateCertificate_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_updateCertificate_READ +# ifdef ACCESS_Server_updateCertificate_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_updateCertificate, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_updateCertificate, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::startListening_async(const ::Murmur::AMD_Server_startListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::startListening_async(const ::Murmur::AMD_Server_startListeningPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "startListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_startListening_ALL -#ifdef ACCESS_Server_startListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_startListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_startListening_READ +# ifdef ACCESS_Server_startListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_startListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_startListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "stopListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_stopListening_ALL -#ifdef ACCESS_Server_stopListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_stopListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_stopListening_READ +# ifdef ACCESS_Server_stopListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_stopListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_stopListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::isListening_async(const ::Murmur::AMD_Server_isListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::isListening_async(const ::Murmur::AMD_Server_isListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, + const ::Ice::Current ¤t) { // qWarning() << "isListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_isListening_ALL -#ifdef ACCESS_Server_isListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_isListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_isListening_READ +# ifdef ACCESS_Server_isListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_isListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_isListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &cb, + ::Ice::Int p1, const ::Ice::Current ¤t) { // qWarning() << "getListeningChannels" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getListeningChannels_ALL -#ifdef ACCESS_Server_getListeningChannels_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getListeningChannels_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getListeningChannels_READ +# ifdef ACCESS_Server_getListeningChannels_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getListeningChannels, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getListeningChannels, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getListeningUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getListeningUsers_ALL -#ifdef ACCESS_Server_getListeningUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getListeningUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getListeningUsers_READ +# ifdef ACCESS_Server_getListeningUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getListeningUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getListeningUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getServer" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getServer_ALL -#ifdef ACCESS_Meta_getServer_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getServer_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getServer_READ +# ifdef ACCESS_Meta_getServer_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1685,24 +1790,24 @@ void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, void ::Murmur::MetaI::newServer_async(const ::Murmur::AMD_Meta_newServerPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "newServer" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_newServer_ALL -#ifdef ACCESS_Meta_newServer_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_newServer_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_newServer_READ +# ifdef ACCESS_Meta_newServer_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1712,27 +1817,28 @@ void ::Murmur::MetaI::newServer_async(const ::Murmur::AMD_Meta_newServerPtr &cb, QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getBootedServers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getBootedServers_ALL -#ifdef ACCESS_Meta_getBootedServers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getBootedServers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getBootedServers_READ +# ifdef ACCESS_Meta_getBootedServers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1742,27 +1848,28 @@ void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedS QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getAllServers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getAllServers_ALL -#ifdef ACCESS_Meta_getAllServers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getAllServers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getAllServers_READ +# ifdef ACCESS_Meta_getAllServers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1772,27 +1879,28 @@ void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServers QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getDefaultConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getDefaultConf_ALL -#ifdef ACCESS_Meta_getDefaultConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getDefaultConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getDefaultConf_READ +# ifdef ACCESS_Meta_getDefaultConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1805,24 +1913,24 @@ void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultCo void ::Murmur::MetaI::getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getVersion" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getVersion_ALL -#ifdef ACCESS_Meta_getVersion_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getVersion_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getVersion_READ +# ifdef ACCESS_Meta_getVersion_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1832,27 +1940,28 @@ void ::Murmur::MetaI::getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &c QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &cb, const ::Murmur::MetaCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &cb, + const ::Murmur::MetaCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "addCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_addCallback_ALL -#ifdef ACCESS_Meta_addCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_addCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_addCallback_READ +# ifdef ACCESS_Meta_addCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1862,27 +1971,28 @@ void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &cb, const ::Murmur::MetaCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &cb, + const ::Murmur::MetaCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "removeCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_removeCallback_ALL -#ifdef ACCESS_Meta_removeCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_removeCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_removeCallback_READ +# ifdef ACCESS_Meta_removeCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1895,24 +2005,24 @@ void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallba void ::Murmur::MetaI::getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUptime" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getUptime_ALL -#ifdef ACCESS_Meta_getUptime_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getUptime_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getUptime_READ +# ifdef ACCESS_Meta_getUptime_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1922,27 +2032,28 @@ void ::Murmur::MetaI::getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &cb, QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getSliceChecksums" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getSliceChecksums_ALL -#ifdef ACCESS_Meta_getSliceChecksums_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getSliceChecksums_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getSliceChecksums_READ +# ifdef ACCESS_Meta_getSliceChecksums_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1952,6 +2063,126 @@ void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceC QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr& cb, const Ice::Current&) { - cb->ice_response(std::string("// Copyright 2005-2020 The Mumble Developers. All rights reserved.\n// Use of this source code is governed by a BSD-style license\n// that can be found in the LICENSE file at the root of the\n// Mumble source tree or at <https://www.mumble.info/LICENSE>.\n#include <Ice/SliceChecksumDict.ice>\nmodule Murmur\n{\n[\"python:seq:tuple\"] sequence<byte> NetAddress;\nstruct User {\nint session;\nint userid;\nbool mute;\nbool deaf;\nbool suppress;\nbool prioritySpeaker;\nbool selfMute;\nbool selfDeaf;\nbool recording;\nint channel;\nstring name;\nint onlinesecs;\nint bytespersec;\nint version;\nstring release;\nstring os;\nstring osversion;\nstring identity;\nstring context;\nstring comment;\nNetAddress address;\nbool tcponly;\nint idlesecs;\nfloat udpPing;\nfloat tcpPing;\n};\nsequence<int> IntList;\nstruct TextMessage {\nIntList sessions;\nIntList channels;\nIntList trees;\nstring text;\n};\nstruct Channel {\nint id;\nstring name;\nint parent;\nIntList links;\nstring description;\nbool temporary;\nint position;\n};\nstruct Group {\nstring name;\nbool inherited;\nbool inherit;\nbool inheritable;\nIntList add;\nIntList remove;\nIntList members;\n};\nconst int PermissionWrite = 0x01;\nconst int PermissionTraverse = 0x02;\nconst int PermissionEnter = 0x04;\nconst int PermissionSpeak = 0x08;\nconst int PermissionWhisper = 0x100;\nconst int PermissionMuteDeafen = 0x10;\nconst int PermissionMove = 0x20;\nconst int PermissionMakeChannel = 0x40;\nconst int PermissionMakeTempChannel = 0x400;\nconst int PermissionLinkChannel = 0x80;\nconst int PermissionTextMessage = 0x200;\nconst int PermissionKick = 0x10000;\nconst int PermissionBan = 0x20000;\nconst int PermissionRegister = 0x40000;\nconst int PermissionRegisterSelf = 0x80000;\nstruct ACL {\nbool applyHere;\nbool applySubs;\nbool inherited;\nint userid;\nstring group;\nint allow;\nint deny;\n};\nstruct Ban {\nNetAddress address;\nint bits;\nstring name;\nstring hash;\nstring reason;\nint start;\nint duration;\n};\nstruct LogEntry {\nint timestamp;\nstring txt;\n};\nclass Tree;\nsequence<Tree> TreeList;\nenum ChannelInfo { ChannelDescription, ChannelPosition };\nenum UserInfo { UserName, UserEmail, UserComment, UserHash, UserPassword, UserLastActive, UserKDFIterations };\ndictionary<int, User> UserMap;\ndictionary<int, Channel> ChannelMap;\nsequence<Channel> ChannelList;\nsequence<User> UserList;\nsequence<Group> GroupList;\nsequence<ACL> ACLList;\nsequence<LogEntry> LogList;\nsequence<Ban> BanList;\nsequence<int> IdList;\nsequence<string> NameList;\ndictionary<int, string> NameMap;\ndictionary<string, int> IdMap;\nsequence<byte> Texture;\ndictionary<string, string> ConfigMap;\nsequence<string> GroupNameList;\nsequence<byte> CertificateDer;\nsequence<CertificateDer> CertificateList;\ndictionary<UserInfo, string> UserInfoMap;\nclass Tree {\nChannel c;\nTreeList children;\nUserList users;\n};\nexception MurmurException {};\nexception InvalidSessionException extends MurmurException {};\nexception InvalidChannelException extends MurmurException {};\nexception InvalidServerException extends MurmurException {};\nexception ServerBootedException extends MurmurException {};\nexception ServerFailureException extends MurmurException {};\nexception InvalidUserException extends MurmurException {};\nexception InvalidTextureException extends MurmurException {};\nexception InvalidCallbackException extends MurmurException {};\nexception InvalidSecretException extends MurmurException {};\nexception NestingLimitException extends MurmurException {};\nexception WriteOnlyException extends MurmurException {};\nexception InvalidInputDataException extends MurmurException {};\ninterface ServerCallback {\nidempotent void userConnected(User state);\nidempotent void userDisconnected(User state);\nidempotent void userStateChanged(User state);\nidempotent void userTextMessage(User state, TextMessage message);\nidempotent void channelCreated(Channel state);\nidempotent void channelRemoved(Channel state);\nidempotent void channelStateChanged(Channel state);\n};\nconst int ContextServer = 0x01;\nconst int ContextChannel = 0x02;\nconst int ContextUser = 0x04;\ninterface ServerContextCallback {\nidempotent void contextAction(string action, User usr, int session, int channelid);\n};\ninterface ServerAuthenticator {\nidempotent int authenticate(string name, string pw, CertificateList certificates, string certhash, bool certstrong, out string newname, out GroupNameList groups);\nidempotent bool getInfo(int id, out UserInfoMap info);\nidempotent int nameToId(string name);\nidempotent string idToName(int id);\nidempotent Texture idToTexture(int id);\n};\ninterface ServerUpdatingAuthenticator extends ServerAuthenticator {\nint registerUser(UserInfoMap info);\nint unregisterUser(int id);\nidempotent NameMap getRegisteredUsers(string filter);\nidempotent int setInfo(int id, UserInfoMap info);\nidempotent int setTexture(int id, Texture tex);\n};\n[\"amd\"] interface Server {\nidempotent bool isRunning() throws InvalidSecretException;\nvoid start() throws ServerBootedException, ServerFailureException, InvalidSecretException;\nvoid stop() throws ServerBootedException, InvalidSecretException;\nvoid delete() throws ServerBootedException, InvalidSecretException;\nidempotent int id() throws InvalidSecretException;\nvoid addCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid setAuthenticator(ServerAuthenticator *auth) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nidempotent string getConf(string key) throws InvalidSecretException, WriteOnlyException;\nidempotent ConfigMap getAllConf() throws InvalidSecretException;\nidempotent void setConf(string key, string value) throws InvalidSecretException;\nidempotent void setSuperuserPassword(string pw) throws InvalidSecretException;\nidempotent LogList getLog(int first, int last) throws InvalidSecretException;\nidempotent int getLogLen() throws InvalidSecretException;\nidempotent UserMap getUsers() throws ServerBootedException, InvalidSecretException;\nidempotent ChannelMap getChannels() throws ServerBootedException, InvalidSecretException;\nidempotent CertificateList getCertificateList(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent Tree getTree() throws ServerBootedException, InvalidSecretException;\nidempotent BanList getBans() throws ServerBootedException, InvalidSecretException;\nidempotent void setBans(BanList bans) throws ServerBootedException, InvalidSecretException;\nvoid kickUser(int session, string reason) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent User getState(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent void setState(User state) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid sendMessage(int session, string text) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nbool hasPermission(int session, int channelid, int perm) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nidempotent int effectivePermissions(int session, int channelid) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid addContextCallback(int session, string action, string text, ServerContextCallback *cb, int ctx) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid removeContextCallback(ServerContextCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nidempotent Channel getChannelState(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void setChannelState(Channel state) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid removeChannel(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nint addChannel(string name, int parent) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid sendMessageChannel(int channelid, bool tree, string text) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void getACL(int channelid, out ACLList acls, out GroupList groups, out bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void setACL(int channelid, ACLList acls, GroupList groups, bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void addUserToGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent void removeUserFromGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent void redirectWhisperGroup(int session, string source, string target) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent NameMap getUserNames(IdList ids) throws ServerBootedException, InvalidSecretException;\nidempotent IdMap getUserIds(NameList names) throws ServerBootedException, InvalidSecretException;\nint registerUser(UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nvoid unregisterUser(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void updateRegistration(int userid, UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent UserInfoMap getRegistration(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent NameMap getRegisteredUsers(string filter) throws ServerBootedException, InvalidSecretException;\nidempotent int verifyPassword(string name, string pw) throws ServerBootedException, InvalidSecretException;\nidempotent Texture getTexture(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void setTexture(int userid, Texture tex) throws ServerBootedException, InvalidUserException, InvalidTextureException, InvalidSecretException;\nidempotent int getUptime() throws ServerBootedException, InvalidSecretException;\n idempotent void updateCertificate(string certificate, string privateKey, string passphrase) throws ServerBootedException, InvalidSecretException, InvalidInputDataException;\n \n idempotent void startListening(int userid, int channelid);\n \n idempotent void stopListening(int userid, int channelid);\n \n idempotent bool isListening(int userid, int channelid);\n \n idempotent IntList getListeningChannels(int userid);\n \n idempotent IntList getListeningUsers(int channelid);\n};\ninterface MetaCallback {\nvoid started(Server *srv);\nvoid stopped(Server *srv);\n};\nsequence<Server *> ServerList;\n[\"amd\"] interface Meta {\nidempotent Server *getServer(int id) throws InvalidSecretException;\nServer *newServer() throws InvalidSecretException;\nidempotent ServerList getBootedServers() throws InvalidSecretException;\nidempotent ServerList getAllServers() throws InvalidSecretException;\nidempotent ConfigMap getDefaultConf() throws InvalidSecretException;\nidempotent void getVersion(out int major, out int minor, out int patch, out string text);\nvoid addCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nidempotent int getUptime();\nidempotent string getSlice();\nidempotent Ice::SliceChecksumDict getSliceChecksums();\n};\n};\n")); +void ::Murmur::MetaI::getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr &cb, const Ice::Current &) { + cb->ice_response(std::string( + "// Copyright 2005-2020 The Mumble Developers. All rights reserved.\n// Use of this source code is governed by " + "a BSD-style license\n// that can be found in the LICENSE file at the root of the\n// Mumble source tree or at " + "<https://www.mumble.info/LICENSE>.\n#include <Ice/SliceChecksumDict.ice>\nmodule " + "Murmur\n{\n[\"python:seq:tuple\"] sequence<byte> NetAddress;\nstruct User {\nint session;\nint userid;\nbool " + "mute;\nbool deaf;\nbool suppress;\nbool prioritySpeaker;\nbool selfMute;\nbool selfDeaf;\nbool " + "recording;\nint channel;\nstring name;\nint onlinesecs;\nint bytespersec;\nint version;\nstring " + "release;\nstring os;\nstring osversion;\nstring identity;\nstring context;\nstring comment;\nNetAddress " + "address;\nbool tcponly;\nint idlesecs;\nfloat udpPing;\nfloat tcpPing;\n};\nsequence<int> IntList;\nstruct " + "TextMessage {\nIntList sessions;\nIntList channels;\nIntList trees;\nstring text;\n};\nstruct Channel {\nint " + "id;\nstring name;\nint parent;\nIntList links;\nstring description;\nbool temporary;\nint " + "position;\n};\nstruct Group {\nstring name;\nbool inherited;\nbool inherit;\nbool inheritable;\nIntList " + "add;\nIntList remove;\nIntList members;\n};\nconst int PermissionWrite = 0x01;\nconst int PermissionTraverse " + "= 0x02;\nconst int PermissionEnter = 0x04;\nconst int PermissionSpeak = 0x08;\nconst int PermissionWhisper = " + "0x100;\nconst int PermissionMuteDeafen = 0x10;\nconst int PermissionMove = 0x20;\nconst int " + "PermissionMakeChannel = 0x40;\nconst int PermissionMakeTempChannel = 0x400;\nconst int PermissionLinkChannel " + "= 0x80;\nconst int PermissionTextMessage = 0x200;\nconst int PermissionKick = 0x10000;\nconst int " + "PermissionBan = 0x20000;\nconst int PermissionRegister = 0x40000;\nconst int PermissionRegisterSelf = " + "0x80000;\nstruct ACL {\nbool applyHere;\nbool applySubs;\nbool inherited;\nint userid;\nstring group;\nint " + "allow;\nint deny;\n};\nstruct Ban {\nNetAddress address;\nint bits;\nstring name;\nstring hash;\nstring " + "reason;\nint start;\nint duration;\n};\nstruct LogEntry {\nint timestamp;\nstring txt;\n};\nclass " + "Tree;\nsequence<Tree> TreeList;\nenum ChannelInfo { ChannelDescription, ChannelPosition };\nenum UserInfo { " + "UserName, UserEmail, UserComment, UserHash, UserPassword, UserLastActive, UserKDFIterations " + "};\ndictionary<int, User> UserMap;\ndictionary<int, Channel> ChannelMap;\nsequence<Channel> " + "ChannelList;\nsequence<User> UserList;\nsequence<Group> GroupList;\nsequence<ACL> " + "ACLList;\nsequence<LogEntry> LogList;\nsequence<Ban> BanList;\nsequence<int> IdList;\nsequence<string> " + "NameList;\ndictionary<int, string> NameMap;\ndictionary<string, int> IdMap;\nsequence<byte> " + "Texture;\ndictionary<string, string> ConfigMap;\nsequence<string> GroupNameList;\nsequence<byte> " + "CertificateDer;\nsequence<CertificateDer> CertificateList;\ndictionary<UserInfo, string> UserInfoMap;\nclass " + "Tree {\nChannel c;\nTreeList children;\nUserList users;\n};\nexception MurmurException {};\nexception " + "InvalidSessionException extends MurmurException {};\nexception InvalidChannelException extends " + "MurmurException {};\nexception InvalidServerException extends MurmurException {};\nexception " + "ServerBootedException extends MurmurException {};\nexception ServerFailureException extends MurmurException " + "{};\nexception InvalidUserException extends MurmurException {};\nexception InvalidTextureException extends " + "MurmurException {};\nexception InvalidCallbackException extends MurmurException {};\nexception " + "InvalidSecretException extends MurmurException {};\nexception NestingLimitException extends MurmurException " + "{};\nexception WriteOnlyException extends MurmurException {};\nexception InvalidInputDataException extends " + "MurmurException {};\ninterface ServerCallback {\nidempotent void userConnected(User state);\nidempotent void " + "userDisconnected(User state);\nidempotent void userStateChanged(User state);\nidempotent void " + "userTextMessage(User state, TextMessage message);\nidempotent void channelCreated(Channel state);\nidempotent " + "void channelRemoved(Channel state);\nidempotent void channelStateChanged(Channel state);\n};\nconst int " + "ContextServer = 0x01;\nconst int ContextChannel = 0x02;\nconst int ContextUser = 0x04;\ninterface " + "ServerContextCallback {\nidempotent void contextAction(string action, User usr, int session, int " + "channelid);\n};\ninterface ServerAuthenticator {\nidempotent int authenticate(string name, string pw, " + "CertificateList certificates, string certhash, bool certstrong, out string newname, out GroupNameList " + "groups);\nidempotent bool getInfo(int id, out UserInfoMap info);\nidempotent int nameToId(string " + "name);\nidempotent string idToName(int id);\nidempotent Texture idToTexture(int id);\n};\ninterface " + "ServerUpdatingAuthenticator extends ServerAuthenticator {\nint registerUser(UserInfoMap info);\nint " + "unregisterUser(int id);\nidempotent NameMap getRegisteredUsers(string filter);\nidempotent int setInfo(int " + "id, UserInfoMap info);\nidempotent int setTexture(int id, Texture tex);\n};\n[\"amd\"] interface Server " + "{\nidempotent bool isRunning() throws InvalidSecretException;\nvoid start() throws ServerBootedException, " + "ServerFailureException, InvalidSecretException;\nvoid stop() throws ServerBootedException, " + "InvalidSecretException;\nvoid delete() throws ServerBootedException, InvalidSecretException;\nidempotent int " + "id() throws InvalidSecretException;\nvoid addCallback(ServerCallback *cb) throws ServerBootedException, " + "InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(ServerCallback *cb) throws " + "ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid " + "setAuthenticator(ServerAuthenticator *auth) throws ServerBootedException, InvalidCallbackException, " + "InvalidSecretException;\nidempotent string getConf(string key) throws InvalidSecretException, " + "WriteOnlyException;\nidempotent ConfigMap getAllConf() throws InvalidSecretException;\nidempotent void " + "setConf(string key, string value) throws InvalidSecretException;\nidempotent void setSuperuserPassword(string " + "pw) throws InvalidSecretException;\nidempotent LogList getLog(int first, int last) throws " + "InvalidSecretException;\nidempotent int getLogLen() throws InvalidSecretException;\nidempotent UserMap " + "getUsers() throws ServerBootedException, InvalidSecretException;\nidempotent ChannelMap getChannels() throws " + "ServerBootedException, InvalidSecretException;\nidempotent CertificateList getCertificateList(int session) " + "throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent Tree getTree() " + "throws ServerBootedException, InvalidSecretException;\nidempotent BanList getBans() throws " + "ServerBootedException, InvalidSecretException;\nidempotent void setBans(BanList bans) throws " + "ServerBootedException, InvalidSecretException;\nvoid kickUser(int session, string reason) throws " + "ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent User getState(int " + "session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent void " + "setState(User state) throws ServerBootedException, InvalidSessionException, InvalidChannelException, " + "InvalidSecretException;\nvoid sendMessage(int session, string text) throws ServerBootedException, " + "InvalidSessionException, InvalidSecretException;\nbool hasPermission(int session, int channelid, int perm) " + "throws ServerBootedException, InvalidSessionException, InvalidChannelException, " + "InvalidSecretException;\nidempotent int effectivePermissions(int session, int channelid) throws " + "ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid " + "addContextCallback(int session, string action, string text, ServerContextCallback *cb, int ctx) throws " + "ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid " + "removeContextCallback(ServerContextCallback *cb) throws ServerBootedException, InvalidCallbackException, " + "InvalidSecretException;\nidempotent Channel getChannelState(int channelid) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException;\nidempotent void setChannelState(Channel state) throws " + "ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid " + "removeChannel(int channelid) throws ServerBootedException, InvalidChannelException, " + "InvalidSecretException;\nint addChannel(string name, int parent) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid sendMessageChannel(int " + "channelid, bool tree, string text) throws ServerBootedException, InvalidChannelException, " + "InvalidSecretException;\nidempotent void getACL(int channelid, out ACLList acls, out GroupList groups, out " + "bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void " + "setACL(int channelid, ACLList acls, GroupList groups, bool inherit) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException;\nidempotent void addUserToGroup(int channelid, int session, " + "string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, " + "InvalidSecretException;\nidempotent void removeUserFromGroup(int channelid, int session, string group) throws " + "ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent " + "void redirectWhisperGroup(int session, string source, string target) throws ServerBootedException, " + "InvalidSessionException, InvalidSecretException;\nidempotent NameMap getUserNames(IdList ids) throws " + "ServerBootedException, InvalidSecretException;\nidempotent IdMap getUserIds(NameList names) throws " + "ServerBootedException, InvalidSecretException;\nint registerUser(UserInfoMap info) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nvoid unregisterUser(int userid) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void updateRegistration(int " + "userid, UserInfoMap info) throws ServerBootedException, InvalidUserException, " + "InvalidSecretException;\nidempotent UserInfoMap getRegistration(int userid) throws ServerBootedException, " + "InvalidUserException, InvalidSecretException;\nidempotent NameMap getRegisteredUsers(string filter) throws " + "ServerBootedException, InvalidSecretException;\nidempotent int verifyPassword(string name, string pw) throws " + "ServerBootedException, InvalidSecretException;\nidempotent Texture getTexture(int userid) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void setTexture(int userid, " + "Texture tex) throws ServerBootedException, InvalidUserException, InvalidTextureException, " + "InvalidSecretException;\nidempotent int getUptime() throws ServerBootedException, InvalidSecretException;\n " + "idempotent void updateCertificate(string certificate, string privateKey, string passphrase) throws " + "ServerBootedException, InvalidSecretException, InvalidInputDataException;\n \n idempotent void " + "startListening(int userid, int channelid);\n \n idempotent void stopListening(int userid, int channelid);\n " + "\n idempotent bool isListening(int userid, int channelid);\n \n idempotent IntList getListeningChannels(int " + "userid);\n \n idempotent IntList getListeningUsers(int channelid);\n};\ninterface MetaCallback {\nvoid " + "started(Server *srv);\nvoid stopped(Server *srv);\n};\nsequence<Server *> ServerList;\n[\"amd\"] interface " + "Meta {\nidempotent Server *getServer(int id) throws InvalidSecretException;\nServer *newServer() throws " + "InvalidSecretException;\nidempotent ServerList getBootedServers() throws InvalidSecretException;\nidempotent " + "ServerList getAllServers() throws InvalidSecretException;\nidempotent ConfigMap getDefaultConf() throws " + "InvalidSecretException;\nidempotent void getVersion(out int major, out int minor, out int patch, out string " + "text);\nvoid addCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nvoid " + "removeCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nidempotent int " + "getUptime();\nidempotent string getSlice();\nidempotent Ice::SliceChecksumDict " + "getSliceChecksums();\n};\n};\n")); } diff --git a/src/murmur/PBKDF2.cpp b/src/murmur/PBKDF2.cpp index 905774ffe..f8fb895d2 100644 --- a/src/murmur/PBKDF2.cpp +++ b/src/murmur/PBKDF2.cpp @@ -13,13 +13,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -39,9 +39,9 @@ #ifdef Q_OS_WIN // <openssl/rand.h> includes <windows.h> without defining NOMINMAX, // which breaks our compilation because of the "max" macro. -#ifndef NOMINMAX -# define NOMINMAX -#endif +# ifndef NOMINMAX +# define NOMINMAX +# endif #endif #include "PBKDF2.h" @@ -58,28 +58,29 @@ int PBKDF2::benchmark() { const QString pseudopass(QLatin1String("aboutAvg")); const QString hexSalt = getSalt(); // Could tolerate not getting a salt here, will likely only make it harder. - + int maxIterations = -1; - + QElapsedTimer timer; timer.start(); - + for (size_t i = 0; i < BENCHMARK_N; ++i) { int iterations = BENCHMARK_MINIMUM_ITERATION_COUNT / 2; - + timer.restart(); do { iterations *= 2; - + // Store return value in a volatile to prevent optimizer // from ever removing these side-effect-free calls. I don't // think the compiler can prove they have no side-effects but // better safe than sorry. volatile QString result = getHash(hexSalt, pseudopass, iterations); Q_UNUSED(result); - - } while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS && (iterations / 2) < std::numeric_limits<int>::max()); - + + } while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS + && (iterations / 2) < std::numeric_limits< int >::max()); + if (iterations > maxIterations) { maxIterations = iterations; } @@ -89,27 +90,26 @@ int PBKDF2::benchmark() { QString PBKDF2::getHash(const QString &hexSalt, const QString &password, int iterationCount) { QByteArray hash(DERIVED_KEY_LENGTH, 0); - + const QByteArray utf8Password = password.toUtf8(); - const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1()); + const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1()); if (PKCS5_PBKDF2_HMAC(utf8Password.constData(), utf8Password.size(), - reinterpret_cast<const unsigned char*>(salt.constData()), salt.size(), - iterationCount, - EVP_sha384(), - DERIVED_KEY_LENGTH, reinterpret_cast<unsigned char*>(hash.data())) == 0) { + reinterpret_cast< const unsigned char * >(salt.constData()), salt.size(), iterationCount, + EVP_sha384(), DERIVED_KEY_LENGTH, reinterpret_cast< unsigned char * >(hash.data())) + == 0) { qFatal("PBKDF2: PKCS5_PBKDF2_HMAC failed: %s", ERR_error_string(ERR_get_error(), nullptr)); return QString(); } - + return QString::fromLatin1(hash.toHex()); } QString PBKDF2::getSalt() { QByteArray salt(SALT_LENGTH, 0); - - if (RAND_bytes(reinterpret_cast<unsigned char*>(salt.data()), salt.size()) != 1) { + + if (RAND_bytes(reinterpret_cast< unsigned char * >(salt.data()), salt.size()) != 1) { qFatal("PBKDF2: RAND_bytes for salt failed: %s", ERR_error_string(ERR_get_error(), nullptr)); return QString(); } diff --git a/src/murmur/PBKDF2.h b/src/murmur/PBKDF2.h index 1b678ef39..377e59823 100644 --- a/src/murmur/PBKDF2.h +++ b/src/murmur/PBKDF2.h @@ -13,13 +13,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -42,49 +42,46 @@ class QString; /// /// Fully static wrapper class for PBKF2 password hashing functionality used in Murmur. -/// +/// /// @note Using int all over the place because OpenSSL uses them in its C interface /// and we want to make sure not to parameterize it in unexpected ways. /// @warning Operations in this class that experience internal failure will abort /// program execution using qFatal. /// class PBKDF2 { - public: - /// - /// @return Upper bound on iterations possible in - /// BENCHMARK_DURATION_TARGET_IN_MS on this machine. - /// - static int benchmark(); - - /// Performs a PBKDF2 hash operation using EVP_sha384. - /// - /// @param hexSalt Hex encoded salt to use in operation. - /// @param password Password to hash. - /// @param iterationCount Number of PBKDF2 iterations to apply. - /// @return Hex encoded password hash of DERIVED_KEY_LENGTH octets. - /// - static QString getHash(const QString &hexSalt, - const QString &password, - int iterationCount); - - /// - /// @return SALT_LENGTH octets of hex encoded random salt. - /// - static QString getSalt(); - - /// Length of hash in octets - static const int DERIVED_KEY_LENGTH = 48; - /// Length salt in octests - static const int SALT_LENGTH = 8; - - /// Duration for hash operation the benchmark function should target - static const int BENCHMARK_DURATION_TARGET_IN_MS = 10; - /// Benchmark returns highest iteration number of N benchmark attemps - static const size_t BENCHMARK_N = 40; - /// Lower bound of iteration count returned by benchmark - /// regardless of duration (should be divisible by 2) - static const int BENCHMARK_MINIMUM_ITERATION_COUNT = 1000; +public: + /// + /// @return Upper bound on iterations possible in + /// BENCHMARK_DURATION_TARGET_IN_MS on this machine. + /// + static int benchmark(); + + /// Performs a PBKDF2 hash operation using EVP_sha384. + /// + /// @param hexSalt Hex encoded salt to use in operation. + /// @param password Password to hash. + /// @param iterationCount Number of PBKDF2 iterations to apply. + /// @return Hex encoded password hash of DERIVED_KEY_LENGTH octets. + /// + static QString getHash(const QString &hexSalt, const QString &password, int iterationCount); + + /// + /// @return SALT_LENGTH octets of hex encoded random salt. + /// + static QString getSalt(); + + /// Length of hash in octets + static const int DERIVED_KEY_LENGTH = 48; + /// Length salt in octests + static const int SALT_LENGTH = 8; + /// Duration for hash operation the benchmark function should target + static const int BENCHMARK_DURATION_TARGET_IN_MS = 10; + /// Benchmark returns highest iteration number of N benchmark attemps + static const size_t BENCHMARK_N = 40; + /// Lower bound of iteration count returned by benchmark + /// regardless of duration (should be divisible by 2) + static const int BENCHMARK_MINIMUM_ITERATION_COUNT = 1000; }; #endif // MUMBLE_MURMUR_PBKDF2_H_ diff --git a/src/murmur/RPC.cpp b/src/murmur/RPC.cpp index 2cb8deaab..0d0163744 100644 --- a/src/murmur/RPC.cpp +++ b/src/murmur/RPC.cpp @@ -6,28 +6,29 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Channel.h" +#include "ChannelListener.h" #include "Group.h" #include "Meta.h" #include "Server.h" #include "ServerDB.h" #include "ServerUser.h" #include "Version.h" -#include "ChannelListener.h" #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif -void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, const QString& name, const QString &comment) { +void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, + const QString &name, const QString &comment) { bool changed = false; if (deaf) mute = true; - if (! mute) + if (!mute) deaf = false; MumbleProto::UserState mpus; @@ -52,7 +53,7 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, changed = true; mpus.set_comment(u8(comment)); if (pUser->iId >= 0) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Comment, comment); setInfo(pUser->iId, info); } @@ -64,13 +65,13 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, { QWriteLocker wl(&qrwlVoiceThread); - pUser->bDeaf = deaf; - pUser->bMute = mute; + pUser->bDeaf = deaf; + pUser->bMute = mute; pUser->bSuppress = suppressed; } pUser->bPrioritySpeaker = prioritySpeaker; - pUser->qsName = name; + pUser->qsName = name; hashAssign(pUser->qsComment, pUser->qbaCommentHash, comment); if (cChannel != pUser->cChannel) { @@ -80,8 +81,8 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, } if (changed) { - sendAll(mpus, ~ 0x010202); - if (mpus.has_comment() && ! pUser->qbaCommentHash.isEmpty()) { + sendAll(mpus, ~0x010202); + if (mpus.has_comment() && !pUser->qbaCommentHash.isEmpty()) { mpus.clear_comment(); mpus.set_comment_hash(blob(pUser->qbaCommentHash)); } @@ -111,7 +112,7 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e // Links and parent channel are processed first, because they can return // errors. Without doing this, the server state can be changed without // notifying users. - QSet< ::Channel *> newLinksSet; + QSet<::Channel * > newLinksSet; for (int i = 0; i < cs.links_size(); i++) { Channel *link = qhChannels.value(cs.links(i)); if (!link) { @@ -165,19 +166,19 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e } } - const QSet<Channel *> &oldLinksSet = channel->qsPermLinks; + const QSet< Channel * > &oldLinksSet = channel->qsPermLinks; if (newLinksSet != oldLinksSet) { // Remove - foreach(Channel *l, oldLinksSet) { + foreach (Channel *l, oldLinksSet) { if (!newLinksSet.contains(l)) { removeLink(channel, l); mpcs.add_links_remove(l->iId); } } // Add - foreach(Channel *l, newLinksSet) { - if (! oldLinksSet.contains(l)) { + foreach (Channel *l, newLinksSet) { + if (!oldLinksSet.contains(l)) { addLink(channel, l); mpcs.add_links_add(l->iId); } @@ -209,7 +210,7 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e updateChannel(channel); } if (changed) { - sendAll(mpcs, ~ 0x010202); + sendAll(mpcs, ~0x010202); if (mpcs.has_description() && !channel->qbaDescHash.isEmpty()) { mpcs.clear_description(); mpcs.set_description_hash(blob(channel->qbaDescHash)); @@ -221,7 +222,8 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e return true; } -bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString &qsName, const QSet<Channel *> &links, const QString &desc, const int position) { +bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString &qsName, const QSet< Channel * > &links, + const QString &desc, const int position) { bool changed = false; bool updated = false; @@ -259,20 +261,20 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString changed = true; } - const QSet<Channel *> &oldset = cChannel->qsPermLinks; + const QSet< Channel * > &oldset = cChannel->qsPermLinks; if (links != oldset) { // Remove - foreach(Channel *l, oldset) { - if (! links.contains(l)) { + foreach (Channel *l, oldset) { + if (!links.contains(l)) { removeLink(cChannel, l); mpcs.add_links_remove(l->iId); } } // Add - foreach(Channel *l, links) { - if (! oldset.contains(l)) { + foreach (Channel *l, links) { + if (!oldset.contains(l)) { addLink(cChannel, l); mpcs.add_links_add(l->iId); } @@ -282,13 +284,13 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString } if (position != cChannel->iPosition) { - changed = true; - updated = true; + changed = true; + updated = true; cChannel->iPosition = position; mpcs.set_position(position); } - if (! desc.isNull() && desc != cChannel->qsDesc) { + if (!desc.isNull() && desc != cChannel->qsDesc) { updated = true; changed = true; hashAssign(cChannel->qsDesc, cChannel->qbaDescHash, desc); @@ -298,8 +300,8 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString if (updated) updateChannel(cChannel); if (changed) { - sendAll(mpcs, ~ 0x010202); - if (mpcs.has_description() && ! cChannel->qbaDescHash.isEmpty()) { + sendAll(mpcs, ~0x010202); + if (mpcs.has_description() && !cChannel->qbaDescHash.isEmpty()) { mpcs.clear_description(); mpcs.set_description_hash(blob(cChannel->qbaDescHash)); } @@ -336,7 +338,7 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { } // Channel targets - QSet<Channel *> chans; + QSet< Channel * > chans; for (int i = 0; i < tm.channel_id_size(); i++) { Channel *channel = qhChannels.value(tm.channel_id(i)); @@ -347,7 +349,7 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { mptm.add_channel_id(channel->iId); } - QQueue<Channel *> chansQ; + QQueue< Channel * > chansQ; for (int i = 0; i < tm.tree_id_size(); i++) { Channel *channel = qhChannels.value(tm.tree_id(i)); if (!channel) { @@ -359,15 +361,11 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { while (!chansQ.isEmpty()) { Channel *c = chansQ.dequeue(); chans.insert(c); - foreach(c, c->qlChannels) { - chansQ.enqueue(c); - } + foreach (c, c->qlChannels) { chansQ.enqueue(c); } } - foreach(Channel *c, chans) { - foreach(::User *p, c->qlUsers) { - sendMessage(static_cast< ::ServerUser *>(p), mptm); - } + foreach (Channel *c, chans) { + foreach (::User *p, c->qlUsers) { sendMessage(static_cast<::ServerUser * >(p), mptm); } } } @@ -384,23 +382,23 @@ void Server::sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, co else mptm.add_channel_id(cChannel->iId); - QSet<Channel *> chans; - QQueue<Channel *> q; + QSet< Channel * > chans; + QQueue< Channel * > q; q << cChannel; chans.insert(cChannel); Channel *c; if (tree) { - while (! q.isEmpty()) { + while (!q.isEmpty()) { c = q.dequeue(); chans.insert(c); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } } - foreach(c, chans) { - foreach(User *p, c->qlUsers) - sendMessage(static_cast<ServerUser *>(p), mptm); + foreach (c, chans) { + foreach (User *p, c->qlUsers) + sendMessage(static_cast< ServerUser * >(p), mptm); } } } @@ -412,28 +410,28 @@ void Server::sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, co * If userid is negative the absolute value is a session id. If it is positive it is a registration id. */ void Server::setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups) { - if (! cChannel) + if (!cChannel) cChannel = qhChannels.value(0); { QWriteLocker wl(&qrwlVoiceThread); Group *g; - foreach(g, cChannel->qhGroups) { + foreach (g, cChannel->qhGroups) { g->qsTemporary.remove(userid); if (sessionId != 0) - g->qsTemporary.remove(- sessionId); + g->qsTemporary.remove(-sessionId); } QString gname; - foreach(gname, groups) { + foreach (gname, groups) { g = cChannel->qhGroups.value(gname); - if (! g) { + if (!g) { g = new Group(cChannel, gname); } g->qsTemporary.insert(userid); if (sessionId != 0) - g->qsTemporary.insert(- sessionId); + g->qsTemporary.insert(-sessionId); } } @@ -447,8 +445,8 @@ void Server::setTempGroups(int userid, int sessionId, Channel *cChannel, const Q * If recursion is activated all temporary memberships in related channels will also be cleared. */ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { - QList<Channel*> qlChans; - if (! cChannel) + QList< Channel * > qlChans; + if (!cChannel) cChannel = qhChannels.value(0); qlChans.append(cChannel); @@ -459,9 +457,9 @@ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { while (!qlChans.isEmpty()) { Channel *chan = qlChans.takeLast(); Group *g; - foreach(g, chan->qhGroups) { + foreach (g, chan->qhGroups) { g->qsTemporary.remove(user->iId); - g->qsTemporary.remove(-static_cast<int>(user->uiSession)); + g->qsTemporary.remove(-static_cast< int >(user->uiSession)); } if (recurse) @@ -473,26 +471,46 @@ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { } void Server::connectAuthenticator(QObject *obj) { - connect(this, SIGNAL(registerUserSig(int &, const QMap<int, QString> &)), obj, SLOT(registerUserSlot(int &, const QMap<int, QString> &))); + connect(this, SIGNAL(registerUserSig(int &, const QMap< int, QString > &)), obj, + SLOT(registerUserSlot(int &, const QMap< int, QString > &))); connect(this, SIGNAL(unregisterUserSig(int &, int)), obj, SLOT(unregisterUserSlot(int &, int))); - connect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap<int, QString> &)), obj, SLOT(getRegisteredUsersSlot(const QString &, QMap<int, QString> &))); - connect(this, SIGNAL(getRegistrationSig(int &, int, QMap<int, QString> &)), obj, SLOT(getRegistrationSlot(int &, int, QMap<int, QString> &))); - connect(this, SIGNAL(authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &)), obj, SLOT(authenticateSlot(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &))); - connect(this, SIGNAL(setInfoSig(int &, int, const QMap<int, QString> &)), obj, SLOT(setInfoSlot(int &, int, const QMap<int, QString> &))); - connect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, SLOT(setTextureSlot(int &, int, const QByteArray &))); + connect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap< int, QString > &)), obj, + SLOT(getRegisteredUsersSlot(const QString &, QMap< int, QString > &))); + connect(this, SIGNAL(getRegistrationSig(int &, int, QMap< int, QString > &)), obj, + SLOT(getRegistrationSlot(int &, int, QMap< int, QString > &))); + connect(this, + SIGNAL(authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &)), + obj, + SLOT(authenticateSlot(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &))); + connect(this, SIGNAL(setInfoSig(int &, int, const QMap< int, QString > &)), obj, + SLOT(setInfoSlot(int &, int, const QMap< int, QString > &))); + connect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, + SLOT(setTextureSlot(int &, int, const QByteArray &))); connect(this, SIGNAL(idToNameSig(QString &, int)), obj, SLOT(idToNameSlot(QString &, int))); connect(this, SIGNAL(nameToIdSig(int &, const QString &)), obj, SLOT(nameToIdSlot(int &, const QString &))); connect(this, SIGNAL(idToTextureSig(QByteArray &, int)), obj, SLOT(idToTextureSlot(QByteArray &, int))); } void Server::disconnectAuthenticator(QObject *obj) { - disconnect(this, SIGNAL(registerUserSig(int &, const QMap<int, QString> &)), obj, SLOT(registerUserSlot(int &, const QMap<int, QString> &))); + disconnect(this, SIGNAL(registerUserSig(int &, const QMap< int, QString > &)), obj, + SLOT(registerUserSlot(int &, const QMap< int, QString > &))); disconnect(this, SIGNAL(unregisterUserSig(int &, int)), obj, SLOT(unregisterUserSlot(int &, int))); - disconnect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap<int, QString> &)), obj, SLOT(getRegisteredUsersSlot(const QString &, QMap<int, QString> &))); - disconnect(this, SIGNAL(getRegistrationSig(int &, int, QMap<int, QString> &)), obj, SLOT(getRegistrationSlot(int &, int, QMap<int, QString> &))); - disconnect(this, SIGNAL(authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &)), obj, SLOT(authenticateSlot(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &))); - disconnect(this, SIGNAL(setInfoSig(int &, int, const QMap<int, QString> &)), obj, SLOT(setInfoSlot(int &, int, const QMap<int, QString> &))); - disconnect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, SLOT(setTextureSlot(int &, int, const QByteArray &))); + disconnect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap< int, QString > &)), obj, + SLOT(getRegisteredUsersSlot(const QString &, QMap< int, QString > &))); + disconnect(this, SIGNAL(getRegistrationSig(int &, int, QMap< int, QString > &)), obj, + SLOT(getRegistrationSlot(int &, int, QMap< int, QString > &))); + disconnect(this, + SIGNAL(authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &)), + obj, + SLOT(authenticateSlot(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &))); + disconnect(this, SIGNAL(setInfoSig(int &, int, const QMap< int, QString > &)), obj, + SLOT(setInfoSlot(int &, int, const QMap< int, QString > &))); + disconnect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, + SLOT(setTextureSlot(int &, int, const QByteArray &))); disconnect(this, SIGNAL(idToNameSig(QString &, int)), obj, SLOT(idToNameSlot(QString &, int))); disconnect(this, SIGNAL(nameToIdSig(int &, const QString &)), obj, SLOT(nameToIdSlot(int &, const QString &))); disconnect(this, SIGNAL(idToTextureSig(QByteArray &, int)), obj, SLOT(idToTextureSlot(QByteArray &, int))); @@ -500,7 +518,8 @@ void Server::disconnectAuthenticator(QObject *obj) { void Server::connectListener(QObject *obj) { connect(this, SIGNAL(userStateChanged(const User *)), obj, SLOT(userStateChanged(const User *))); - connect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, SLOT(userTextMessage(const User *, const TextMessage &))); + connect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, + SLOT(userTextMessage(const User *, const TextMessage &))); connect(this, SIGNAL(userConnected(const User *)), obj, SLOT(userConnected(const User *))); connect(this, SIGNAL(userDisconnected(const User *)), obj, SLOT(userDisconnected(const User *))); connect(this, SIGNAL(channelStateChanged(const Channel *)), obj, SLOT(channelStateChanged(const Channel *))); @@ -510,7 +529,8 @@ void Server::connectListener(QObject *obj) { void Server::disconnectListener(QObject *obj) { disconnect(this, SIGNAL(userStateChanged(const User *)), obj, SLOT(userStateChanged(const User *))); - disconnect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, SLOT(userTextMessage(const User *, const TextMessage &))); + disconnect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, + SLOT(userTextMessage(const User *, const TextMessage &))); disconnect(this, SIGNAL(userConnected(const User *)), obj, SLOT(userConnected(const User *))); disconnect(this, SIGNAL(userDisconnected(const User *)), obj, SLOT(userDisconnected(const User *))); disconnect(this, SIGNAL(channelStateChanged(const Channel *)), obj, SLOT(channelStateChanged(const Channel *))); diff --git a/src/murmur/Register.cpp b/src/murmur/Register.cpp index 8ef6e7129..72f5c8449 100644 --- a/src/murmur/Register.cpp +++ b/src/murmur/Register.cpp @@ -3,32 +3,34 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include "Server.h" #include "Meta.h" -#include "Version.h" #include "OSInfo.h" +#include "Server.h" +#include "Version.h" #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtXml/QDomDocument> -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif void Server::initRegister() { connect(&qtTick, SIGNAL(timeout()), this, SLOT(update())); - if (! qsRegName.isEmpty()) { - if (!qsRegName.isEmpty() && !qsRegPassword.isEmpty() && qurlRegWeb.isValid() && qsPassword.isEmpty() && bAllowPing) -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - qtTick.start((60 + (QRandomGenerator::global()->generate() % 120))* 1000); + if (!qsRegName.isEmpty()) { + if (!qsRegName.isEmpty() && !qsRegPassword.isEmpty() && qurlRegWeb.isValid() && qsPassword.isEmpty() + && bAllowPing) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) + qtTick.start((60 + (QRandomGenerator::global()->generate() % 120)) * 1000); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - qtTick.start((60 + (qrand() % 120))* 1000); + qtTick.start((60 + (qrand() % 120)) * 1000); #endif else - log("Registration needs nonempty 'registername', 'registerpassword' and 'registerurl', must have an empty 'password' and allowed pings."); + log("Registration needs nonempty 'registername', 'registerpassword' and 'registerurl', must have an empty " + "'password' and allowed pings."); } else { log("Not registering server as public"); } @@ -39,10 +41,10 @@ void Server::update() { return; // When QNAM distinguishes connections by client cert, move this to Meta - if (! qnamNetwork) + if (!qnamNetwork) qnamNetwork = new QNetworkAccessManager(this); -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) qtTick.start(1000 * (60 * 60 + (QRandomGenerator::global()->generate() % 300))); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor @@ -50,7 +52,7 @@ void Server::update() { #endif QDomDocument doc; - QDomElement root=doc.createElement(QLatin1String("server")); + QDomElement root = doc.createElement(QLatin1String("server")); doc.appendChild(root); OSInfo::fillXml(doc, root, meta->qsOS, meta->qsOSVersion, qlBind); @@ -58,50 +60,50 @@ void Server::update() { QDomElement tag; QDomText t; - tag=doc.createElement(QLatin1String("name")); + tag = doc.createElement(QLatin1String("name")); root.appendChild(tag); - t=doc.createTextNode(qsRegName); + t = doc.createTextNode(qsRegName); tag.appendChild(t); - tag=doc.createElement(QLatin1String("host")); + tag = doc.createElement(QLatin1String("host")); root.appendChild(tag); - t=doc.createTextNode(qsRegHost); + t = doc.createTextNode(qsRegHost); tag.appendChild(t); - tag=doc.createElement(QLatin1String("password")); + tag = doc.createElement(QLatin1String("password")); root.appendChild(tag); - t=doc.createTextNode(qsRegPassword); + t = doc.createTextNode(qsRegPassword); tag.appendChild(t); - tag=doc.createElement(QLatin1String("port")); + tag = doc.createElement(QLatin1String("port")); root.appendChild(tag); - t=doc.createTextNode(QString::number(usPort)); + t = doc.createTextNode(QString::number(usPort)); tag.appendChild(t); - tag=doc.createElement(QLatin1String("url")); + tag = doc.createElement(QLatin1String("url")); root.appendChild(tag); - t=doc.createTextNode(qurlRegWeb.toString()); + t = doc.createTextNode(qurlRegWeb.toString()); tag.appendChild(t); - tag=doc.createElement(QLatin1String("digest")); + tag = doc.createElement(QLatin1String("digest")); root.appendChild(tag); - t=doc.createTextNode(getDigest()); + t = doc.createTextNode(getDigest()); tag.appendChild(t); - tag=doc.createElement(QLatin1String("users")); + tag = doc.createElement(QLatin1String("users")); root.appendChild(tag); - t=doc.createTextNode(QString::number(qhUsers.count())); + t = doc.createTextNode(QString::number(qhUsers.count())); tag.appendChild(t); - tag=doc.createElement(QLatin1String("channels")); + tag = doc.createElement(QLatin1String("channels")); root.appendChild(tag); - t=doc.createTextNode(QString::number(qhChannels.count())); + t = doc.createTextNode(QString::number(qhChannels.count())); tag.appendChild(t); if (!qsRegLocation.isEmpty()) { - tag=doc.createElement(QLatin1String("location")); + tag = doc.createElement(QLatin1String("location")); root.appendChild(tag); - t=doc.createTextNode(qsRegLocation); + t = doc.createTextNode(qsRegLocation); tag.appendChild(t); } @@ -113,7 +115,7 @@ void Server::update() { ssl.setPrivateKey(qskKey); /* Work around bug in QSslConfiguration */ - QList<QSslCertificate> calist = ssl.caCertificates(); + QList< QSslCertificate > calist = ssl.caCertificates(); calist << QSslConfiguration::defaultConfiguration().caCertificates(); calist << Meta::mp.qlCA; calist << Meta::mp.qlIntermediates; @@ -126,11 +128,11 @@ void Server::update() { QNetworkReply *rep = qnamNetwork->post(qnr, doc.toString().toUtf8()); connect(rep, SIGNAL(finished()), this, SLOT(finished())); - connect(rep, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(regSslError(const QList<QSslError> &))); + connect(rep, SIGNAL(sslErrors(const QList< QSslError > &)), this, SLOT(regSslError(const QList< QSslError > &))); } void Server::finished() { - QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); + QNetworkReply *rep = qobject_cast< QNetworkReply * >(sender()); if (rep->error() != QNetworkReply::NoError) { log(QString("Registration failed: %1").arg(rep->errorString())); @@ -141,7 +143,7 @@ void Server::finished() { rep->deleteLater(); } -void Server::regSslError(const QList<QSslError> &errs) { - foreach(const QSslError &e, errs) +void Server::regSslError(const QList< QSslError > &errs) { + foreach (const QSslError &e, errs) log(QString("Registration: SSL Handshake error: %1").arg(e.errorString())); } 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; } diff --git a/src/murmur/Server.h b/src/murmur/Server.h index 7383d5a96..a104a9c5e 100644 --- a/src/murmur/Server.h +++ b/src/murmur/Server.h @@ -9,40 +9,40 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "ACL.h" +#include "Ban.h" +#include "HostAddress.h" #include "Message.h" #include "Mumble.pb.h" -#include "User.h" #include "Timer.h" -#include "HostAddress.h" -#include "Ban.h" +#include "User.h" #ifndef Q_MOC_RUN -# include <boost/function.hpp> +# include <boost/function.hpp> #endif #include <QtCore/QEvent> #include <QtCore/QMutex> -#include <QtCore/QTimer> #include <QtCore/QQueue> #include <QtCore/QReadWriteLock> -#include <QtCore/QStringList> #include <QtCore/QSocketNotifier> +#include <QtCore/QStringList> #include <QtCore/QThread> +#include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtNetwork/QSslCertificate> #include <QtNetwork/QSslKey> #include <QtNetwork/QSslSocket> #include <QtNetwork/QTcpServer> #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) -# include <QtNetwork/QSslDiffieHellmanParameters> +# include <QtNetwork/QSslDiffieHellmanParameters> #endif #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif class BonjourServer; @@ -53,390 +53,405 @@ class User; class QNetworkAccessManager; struct TextMessage { - QList<unsigned int> qlSessions; - QList<unsigned int> qlChannels; - QList<unsigned int> qlTrees; + QList< unsigned int > qlSessions; + QList< unsigned int > qlChannels; + QList< unsigned int > qlTrees; QString qsText; }; class SslServer : public QTcpServer { - private: - Q_OBJECT; - Q_DISABLE_COPY(SslServer) - protected: - QList<QSslSocket *> qlSockets; - void incomingConnection(qintptr) Q_DECL_OVERRIDE; - public: - QSslSocket *nextPendingSSLConnection(); - SslServer(QObject *parent = nullptr); - - /// Checks whether the AF_INET6 socket on this system has dual-stack support. - static bool hasDualStackSupport(); +private: + Q_OBJECT; + Q_DISABLE_COPY(SslServer) +protected: + QList< QSslSocket * > qlSockets; + void incomingConnection(qintptr) Q_DECL_OVERRIDE; + +public: + QSslSocket *nextPendingSSLConnection(); + SslServer(QObject *parent = nullptr); + + /// Checks whether the AF_INET6 socket on this system has dual-stack support. + static bool hasDualStackSupport(); }; #define EXEC_QEVENT (QEvent::User + 959) class ExecEvent : public QEvent { - Q_DISABLE_COPY(ExecEvent); - protected: - boost::function<void ()> func; - public: - ExecEvent(boost::function<void ()>); - void execute(); + Q_DISABLE_COPY(ExecEvent); + +protected: + boost::function< void() > func; + +public: + ExecEvent(boost::function< void() >); + void execute(); }; class Server : public QThread { - private: - Q_OBJECT; - Q_DISABLE_COPY(Server); - protected: - bool bRunning; +private: + Q_OBJECT; + Q_DISABLE_COPY(Server); + +protected: + bool bRunning; - QNetworkAccessManager *qnamNetwork; + QNetworkAccessManager *qnamNetwork; #ifdef USE_BONJOUR - BonjourServer *bsRegistration; + BonjourServer *bsRegistration; #endif - void startThread(); - void stopThread(); - - void customEvent(QEvent *evt); - // Former ServerParams - public: - QList<QHostAddress> qlBind; - unsigned short usPort; - int iTimeout; - int iMaxBandwidth; - int iMaxUsers; - int iMaxUsersPerChannel; - int iDefaultChan; - bool bRememberChan; - int iRememberChanDuration; - int iMaxTextMessageLength; - int iMaxImageMessageLength; - int iOpusThreshold; - bool bAllowHTML; - QString qsPassword; - QString qsWelcomeText; - QString qsWelcomeTextFile; - bool bCertRequired; - bool bForceExternalAuth; - - QString qsRegName; - QString qsRegPassword; - QString qsRegHost; - QString qsRegLocation; - QUrl qurlRegWeb; - bool bBonjour; - bool bAllowPing; - - QRegExp qrUserName; - QRegExp qrChannelName; - - unsigned int iMessageLimit; - unsigned int iMessageBurst; - - QVariant qvSuggestVersion; - QVariant qvSuggestPositional; - QVariant qvSuggestPushToTalk; - - bool bUsingMetaCert; - QSslCertificate qscCert; - QSslKey qskKey; - - /// qlIntermediates contains the certificates - /// from this virtual server's certificate PEM - // bundle that do not match the virtual server's - // private key. - /// - /// Simply put: it contains any certificates - /// that aren't the main certificate, or "leaf" - /// certificate. - QList<QSslCertificate> qlIntermediates; + void startThread(); + void stopThread(); + + void customEvent(QEvent *evt); + // Former ServerParams +public: + QList< QHostAddress > qlBind; + unsigned short usPort; + int iTimeout; + int iMaxBandwidth; + int iMaxUsers; + int iMaxUsersPerChannel; + int iDefaultChan; + bool bRememberChan; + int iRememberChanDuration; + int iMaxTextMessageLength; + int iMaxImageMessageLength; + int iOpusThreshold; + bool bAllowHTML; + QString qsPassword; + QString qsWelcomeText; + QString qsWelcomeTextFile; + bool bCertRequired; + bool bForceExternalAuth; + + QString qsRegName; + QString qsRegPassword; + QString qsRegHost; + QString qsRegLocation; + QUrl qurlRegWeb; + bool bBonjour; + bool bAllowPing; + + QRegExp qrUserName; + QRegExp qrChannelName; + + unsigned int iMessageLimit; + unsigned int iMessageBurst; + + QVariant qvSuggestVersion; + QVariant qvSuggestPositional; + QVariant qvSuggestPushToTalk; + + bool bUsingMetaCert; + QSslCertificate qscCert; + QSslKey qskKey; + + /// qlIntermediates contains the certificates + /// from this virtual server's certificate PEM + // bundle that do not match the virtual server's + // private key. + /// + /// Simply put: it contains any certificates + /// that aren't the main certificate, or "leaf" + /// certificate. + QList< QSslCertificate > qlIntermediates; #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - QSslDiffieHellmanParameters qsdhpDHParams; + QSslDiffieHellmanParameters qsdhpDHParams; #endif - Timer tUptime; + Timer tUptime; - bool bValid; + bool bValid; - void readParams(); + void readParams(); - int iCodecAlpha; - int iCodecBeta; - bool bPreferAlpha; - bool bOpus; - void recheckCodecVersions(ServerUser *connectingUser = 0); + int iCodecAlpha; + int iCodecBeta; + bool bPreferAlpha; + bool bOpus; + void recheckCodecVersions(ServerUser *connectingUser = 0); #ifdef USE_BONJOUR - void initBonjour(); - void removeBonjour(); + void initBonjour(); + void removeBonjour(); #endif - // Registration, implementation in Register.cpp - QTimer qtTick; - void initRegister(); - - private: - int iChannelNestingLimit; - int iChannelCountLimit; - - public slots: - void regSslError(const QList<QSslError> &); - void finished(); - void update(); - - // Certificate stuff, implemented partially in Cert.cpp - public: - static bool isKeyForCert(const QSslKey &key, const QSslCertificate &cert); - /// Attempt to load a private key in PEM format from |buf|. - /// If |passphrase| is non-empty, it will be used for decrypting the private key in |buf|. - /// If a valid RSA, DSA or EC key is found, it is returned. - /// If no valid private key is found, a null QSslKey is returned. - static QSslKey privateKeyFromPEM(const QByteArray &buf, const QByteArray &pass = QByteArray()); - void initializeCert(); - const QString getDigest() const; - - public slots: - void newClient(); - void connectionClosed(QAbstractSocket::SocketError, const QString &); - void sslError(const QList<QSslError> &); - void message(unsigned int, const QByteArray &, ServerUser *cCon = nullptr); - void checkTimeout(); - void tcpTransmitData(QByteArray, unsigned int); - void doSync(unsigned int); - void encrypted(); - void udpActivated(int); - signals: - void reqSync(unsigned int); - void tcpTransmit(QByteArray, unsigned int id); - public: - int iServerNum; - QQueue<int> qqIds; - QList<SslServer *> qlServer; - QTimer *qtTimeout; + // Registration, implementation in Register.cpp + QTimer qtTick; + void initRegister(); + +private: + int iChannelNestingLimit; + int iChannelCountLimit; + +public slots: + void regSslError(const QList< QSslError > &); + void finished(); + void update(); + + // Certificate stuff, implemented partially in Cert.cpp +public: + static bool isKeyForCert(const QSslKey &key, const QSslCertificate &cert); + /// Attempt to load a private key in PEM format from |buf|. + /// If |passphrase| is non-empty, it will be used for decrypting the private key in |buf|. + /// If a valid RSA, DSA or EC key is found, it is returned. + /// If no valid private key is found, a null QSslKey is returned. + static QSslKey privateKeyFromPEM(const QByteArray &buf, const QByteArray &pass = QByteArray()); + void initializeCert(); + const QString getDigest() const; + +public slots: + void newClient(); + void connectionClosed(QAbstractSocket::SocketError, const QString &); + void sslError(const QList< QSslError > &); + void message(unsigned int, const QByteArray &, ServerUser *cCon = nullptr); + void checkTimeout(); + void tcpTransmitData(QByteArray, unsigned int); + void doSync(unsigned int); + void encrypted(); + void udpActivated(int); +signals: + void reqSync(unsigned int); + void tcpTransmit(QByteArray, unsigned int id); + +public: + int iServerNum; + QQueue< int > qqIds; + QList< SslServer * > qlServer; + QTimer *qtTimeout; #ifdef Q_OS_UNIX - int aiNotify[2]; - QList<int> qlUdpSocket; + int aiNotify[2]; + QList< int > qlUdpSocket; #else - HANDLE hNotify; - QList<SOCKET> qlUdpSocket; + HANDLE hNotify; + QList< SOCKET > qlUdpSocket; #endif - quint32 uiVersionBlob; - QList<QSocketNotifier *> qlUdpNotifier; - - /// This lock provides synchronization between the - /// main thread (where control channel messages and - /// RPC happens), and the Server's voice thread. - /// - /// These are the only two threads in Murmur that - /// access a Server's data. - /// - /// The easiest way to understand the locking strategy - /// and synchronization between the main thread and the - /// Server's voice thread is by using the concept of - /// ownership. - /// - /// A thread owning an object means that it is the only - /// thread that is allowed to write to that object. To - /// make changes to it. - /// - /// Most data in the Server class is owned by the main - /// thread. That means that the main thread is the only - /// thread that writes/updates those structures. - /// - /// When processing incoming voice data (and re- - /// broadcasting) that voice data), the Server's voice - /// thread needs to access various parts of Server's data, - /// such as qhUsers, qhChannels, User->cChannel, etc. - /// However, these are owned by the main thread. - /// - /// To ensure correct synchronization between the two - /// threads, the contract for using qrwlVoiceThread is - /// as follows: - /// - /// - When the Server's voice thread needs to read data - /// owned by the main thread, it must hold a read lock - /// on qrwlVoiceThread. - /// - /// - The Server's voice thread does not write to any data - /// that is owned by the main thread. - /// - /// - When the main thread needs to write to data owned by - /// itself that is accessed by the voice thread, it must - /// hold a write lock on qrwlVoiceThread. - /// - /// - When the main thread needs to read data that is owned - /// by itself, it DOES NOT hold a lock on qrwlVoiceThread. - /// That is because ownership of data guarantees that no - /// other thread can write to that data. - QReadWriteLock qrwlVoiceThread; - QHash<unsigned int, ServerUser *> qhUsers; - QHash<QPair<HostAddress, quint16>, ServerUser *> qhPeerUsers; - QHash<HostAddress, QSet<ServerUser *> > qhHostUsers; - QHash<unsigned int, Channel *> qhChannels; - - QMutex qmCache; - ChanACL::ACLCache acCache; - - QHash<int, QString> qhUserNameCache; - QHash<QString, int> qhUserIDCache; - - QList<Ban> qlBans; - - void processMsg(ServerUser *u, const char *data, int len); - void sendMessage(ServerUser *u, const char *data, int len, QByteArray &cache, bool force = false); - void run(); - - bool validateChannelName(const QString &name); - bool validateUserName(const QString &name); - - bool checkDecrypt(ServerUser *u, const char *encrypted, char *plain, unsigned int cryptlen); - - bool hasPermission(ServerUser *p, Channel *c, QFlags<ChanACL::Perm> perm); - QFlags<ChanACL::Perm> effectivePermissions(ServerUser *p, Channel *c); - void sendClientPermission(ServerUser *u, Channel *c, bool updatelast = false); - void flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mpqq); - void clearACLCache(User *p = nullptr); - void clearWhisperTargetCache(); - - void sendProtoAll(const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); - void sendProtoExcept(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); - void sendProtoMessage(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType); - - // sendAll sends a protobuf message to all users on the server whose version is either bigger than v or - // lower than ~v. If v == 0 the message is sent to everyone. -#define MUMBLE_MH_MSG(x) \ - void sendAll(const MumbleProto:: x &msg, unsigned int v = 0) { sendProtoAll(msg, MessageHandler:: x, v); } \ - void sendExcept(ServerUser *u, const MumbleProto:: x &msg, unsigned int v = 0) { sendProtoExcept(u, msg, MessageHandler:: x, v); } \ - void sendMessage(ServerUser *u, const MumbleProto:: x &msg) { sendProtoMessage(u, msg, MessageHandler:: x); } - - MUMBLE_MH_ALL + quint32 uiVersionBlob; + QList< QSocketNotifier * > qlUdpNotifier; + + /// This lock provides synchronization between the + /// main thread (where control channel messages and + /// RPC happens), and the Server's voice thread. + /// + /// These are the only two threads in Murmur that + /// access a Server's data. + /// + /// The easiest way to understand the locking strategy + /// and synchronization between the main thread and the + /// Server's voice thread is by using the concept of + /// ownership. + /// + /// A thread owning an object means that it is the only + /// thread that is allowed to write to that object. To + /// make changes to it. + /// + /// Most data in the Server class is owned by the main + /// thread. That means that the main thread is the only + /// thread that writes/updates those structures. + /// + /// When processing incoming voice data (and re- + /// broadcasting) that voice data), the Server's voice + /// thread needs to access various parts of Server's data, + /// such as qhUsers, qhChannels, User->cChannel, etc. + /// However, these are owned by the main thread. + /// + /// To ensure correct synchronization between the two + /// threads, the contract for using qrwlVoiceThread is + /// as follows: + /// + /// - When the Server's voice thread needs to read data + /// owned by the main thread, it must hold a read lock + /// on qrwlVoiceThread. + /// + /// - The Server's voice thread does not write to any data + /// that is owned by the main thread. + /// + /// - When the main thread needs to write to data owned by + /// itself that is accessed by the voice thread, it must + /// hold a write lock on qrwlVoiceThread. + /// + /// - When the main thread needs to read data that is owned + /// by itself, it DOES NOT hold a lock on qrwlVoiceThread. + /// That is because ownership of data guarantees that no + /// other thread can write to that data. + QReadWriteLock qrwlVoiceThread; + QHash< unsigned int, ServerUser * > qhUsers; + QHash< QPair< HostAddress, quint16 >, ServerUser * > qhPeerUsers; + QHash< HostAddress, QSet< ServerUser * > > qhHostUsers; + QHash< unsigned int, Channel * > qhChannels; + + QMutex qmCache; + ChanACL::ACLCache acCache; + + QHash< int, QString > qhUserNameCache; + QHash< QString, int > qhUserIDCache; + + QList< Ban > qlBans; + + void processMsg(ServerUser *u, const char *data, int len); + void sendMessage(ServerUser *u, const char *data, int len, QByteArray &cache, bool force = false); + void run(); + + bool validateChannelName(const QString &name); + bool validateUserName(const QString &name); + + bool checkDecrypt(ServerUser *u, const char *encrypted, char *plain, unsigned int cryptlen); + + bool hasPermission(ServerUser *p, Channel *c, QFlags< ChanACL::Perm > perm); + QFlags< ChanACL::Perm > effectivePermissions(ServerUser *p, Channel *c); + void sendClientPermission(ServerUser *u, Channel *c, bool updatelast = false); + void flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mpqq); + void clearACLCache(User *p = nullptr); + void clearWhisperTargetCache(); + + void sendProtoAll(const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); + void sendProtoExcept(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType, + unsigned int minversion); + void sendProtoMessage(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType); + + // sendAll sends a protobuf message to all users on the server whose version is either bigger than v or + // lower than ~v. If v == 0 the message is sent to everyone. +#define MUMBLE_MH_MSG(x) \ + void sendAll(const MumbleProto::x &msg, unsigned int v = 0) { sendProtoAll(msg, MessageHandler::x, v); } \ + void sendExcept(ServerUser *u, const MumbleProto::x &msg, unsigned int v = 0) { \ + sendProtoExcept(u, msg, MessageHandler::x, v); \ + } \ + void sendMessage(ServerUser *u, const MumbleProto::x &msg) { sendProtoMessage(u, msg, MessageHandler::x); } + + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG - static void hashAssign(QString &destination, QByteArray &hash, const QString &str); - static void hashAssign(QByteArray &destination, QByteArray &hash, const QByteArray &source); - bool isTextAllowed(QString &str, bool &changed); - - void setLiveConf(const QString &key, const QString &value); - - QString addressToString(const QHostAddress &, unsigned short port); - - void log(const QString &) const; - void log(ServerUser *u, const QString &) const; - - void removeChannel(int id); - void removeChannel(Channel *c, Channel *dest = nullptr); - void userEnterChannel(User *u, Channel *c, MumbleProto::UserState &mpus); - bool unregisterUser(int id); - - Server(int snum, QObject *parent = nullptr); - ~Server(); - - bool canNest(Channel *newParent, Channel *channel = nullptr) const; - - // RPC functions. Implementation in RPC.cpp - void connectAuthenticator(QObject *p); - void disconnectAuthenticator(QObject *p); - void connectListener(QObject *p); - void disconnectListener(QObject *p); - void setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups); - void clearTempGroups(User *user, Channel *cChannel = nullptr, bool recurse = true); - void startListeningToChannel(ServerUser *user, Channel *cChannel); - void stopListeningToChannel(ServerUser *user, Channel *cChannel); - signals: - void registerUserSig(int &, const QMap<int, QString> &); - void unregisterUserSig(int &, int); - void getRegisteredUsersSig(const QString &, QMap<int, QString > &); - void getRegistrationSig(int &, int, QMap<int, QString> &); - void authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &); - void setInfoSig(int &, int, const QMap<int, QString> &); - void setTextureSig(int &, int, const QByteArray &); - void idToNameSig(QString &, int); - void nameToIdSig(int &, const QString &); - void idToTextureSig(QByteArray &, int); - - void userStateChanged(const User *); - void userTextMessage(const User *, const TextMessage &); - void userConnected(const User *); - void userDisconnected(const User *); - void channelStateChanged(const Channel *); - void channelCreated(const Channel *); - void channelRemoved(const Channel *); - - void textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &); - - void contextAction(const User *, const QString &, unsigned int, int); - public: - void setUserState(User *p, Channel *parent, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, const QString& name = QString(), const QString &comment = QString()); - - /// Update a channel's state using the ChannelState protobuf message and - /// broadcast the changes appropriately to the server. On return, if - /// err is non-empty, the operation failed, and err contains a description - /// of the error. - /// - /// This method is equivalent to the logic that happens in - /// Server::msgChannelState when a ChannelState message is recieved from - /// a user. However, this method doesn't do permissions checking. - /// - /// This method is used by the gRPC implementation to perform channel - /// state changes. - bool setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &err); - - bool setChannelState(Channel *c, Channel *parent, const QString &qsName, const QSet<Channel *> &links, const QString &desc = QString(), const int position = 0); - - /// Send a text message using the TextMessage protobuf message - /// as a template. - /// This is equivalent to the logic that happens in Server::msgTextMessage - /// when sending a receieved TextMessage, with the exception that this - /// method does not perform any permission checks. - /// It is used by our gRPC implementation to send text messages. - void sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm); - - void sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, const QString &text); - - /// Returns true if a channel is full. If a user is provided, false will always - /// be returned if the user has write permission in the channel. - bool isChannelFull(Channel *c, ServerUser *u = 0); - - // Database / DBus functions. Implementation in ServerDB.cpp - void initialize(); - int authenticate(QString &name, const QString &pw, int sessionId = 0, const QStringList &emails = QStringList(), const QString &certhash = QString(), bool bStrongCert = false, const QList<QSslCertificate> & = QList<QSslCertificate>()); - Channel *addChannel(Channel *c, const QString &name, bool temporary = false, int position = 0, unsigned int maxUsers = 0); - void removeChannelDB(const Channel *c); - void readChannels(Channel *p = nullptr); - void readLinks(); - void updateChannel(const Channel *c); - void readChannelPrivs(Channel *c); - void setLastChannel(const User *u); - int readLastChannel(int id); - - /// Set last_disconnect of a registered user to the current time - void setLastDisconnect(const User *u); - void dumpChannel(const Channel *c); - int getUserID(const QString &name); - QString getUserName(int id); - QByteArray getUserTexture(int id); - QMap<int, QString> getRegistration(int id); - int registerUser(const QMap<int, QString> &info); - bool unregisterUserDB(int id); - QList<UserInfo> getRegisteredUsersEx(); - QMap<int, QString > getRegisteredUsers(const QString &filter = QString()); - bool setInfo(int id, const QMap<int, QString> &info); - bool setTexture(int id, const QByteArray &texture); - bool isUserId(int id); - void addLink(Channel *c, Channel *l); - void removeLink(Channel *c, Channel *l); - void getBans(); - void saveBans(); - QVariant getConf(const QString &key, QVariant def); - void setConf(const QString &key, const QVariant &value); - void dblog(const QString &str) const; - - // From msgHandler. Implementation in Messages.cpp -#define MUMBLE_MH_MSG(x) void msg##x(ServerUser *, MumbleProto:: x &); - MUMBLE_MH_ALL + static void hashAssign(QString &destination, QByteArray &hash, const QString &str); + static void hashAssign(QByteArray &destination, QByteArray &hash, const QByteArray &source); + bool isTextAllowed(QString &str, bool &changed); + + void setLiveConf(const QString &key, const QString &value); + + QString addressToString(const QHostAddress &, unsigned short port); + + void log(const QString &) const; + void log(ServerUser *u, const QString &) const; + + void removeChannel(int id); + void removeChannel(Channel *c, Channel *dest = nullptr); + void userEnterChannel(User *u, Channel *c, MumbleProto::UserState &mpus); + bool unregisterUser(int id); + + Server(int snum, QObject *parent = nullptr); + ~Server(); + + bool canNest(Channel *newParent, Channel *channel = nullptr) const; + + // RPC functions. Implementation in RPC.cpp + void connectAuthenticator(QObject *p); + void disconnectAuthenticator(QObject *p); + void connectListener(QObject *p); + void disconnectListener(QObject *p); + void setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups); + void clearTempGroups(User *user, Channel *cChannel = nullptr, bool recurse = true); + void startListeningToChannel(ServerUser *user, Channel *cChannel); + void stopListeningToChannel(ServerUser *user, Channel *cChannel); +signals: + void registerUserSig(int &, const QMap< int, QString > &); + void unregisterUserSig(int &, int); + void getRegisteredUsersSig(const QString &, QMap< int, QString > &); + void getRegistrationSig(int &, int, QMap< int, QString > &); + void authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &); + void setInfoSig(int &, int, const QMap< int, QString > &); + void setTextureSig(int &, int, const QByteArray &); + void idToNameSig(QString &, int); + void nameToIdSig(int &, const QString &); + void idToTextureSig(QByteArray &, int); + + void userStateChanged(const User *); + void userTextMessage(const User *, const TextMessage &); + void userConnected(const User *); + void userDisconnected(const User *); + void channelStateChanged(const Channel *); + void channelCreated(const Channel *); + void channelRemoved(const Channel *); + + void textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &); + + void contextAction(const User *, const QString &, unsigned int, int); + +public: + void setUserState(User *p, Channel *parent, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, + const QString &name = QString(), const QString &comment = QString()); + + /// Update a channel's state using the ChannelState protobuf message and + /// broadcast the changes appropriately to the server. On return, if + /// err is non-empty, the operation failed, and err contains a description + /// of the error. + /// + /// This method is equivalent to the logic that happens in + /// Server::msgChannelState when a ChannelState message is recieved from + /// a user. However, this method doesn't do permissions checking. + /// + /// This method is used by the gRPC implementation to perform channel + /// state changes. + bool setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &err); + + bool setChannelState(Channel *c, Channel *parent, const QString &qsName, const QSet< Channel * > &links, + const QString &desc = QString(), const int position = 0); + + /// Send a text message using the TextMessage protobuf message + /// as a template. + /// This is equivalent to the logic that happens in Server::msgTextMessage + /// when sending a receieved TextMessage, with the exception that this + /// method does not perform any permission checks. + /// It is used by our gRPC implementation to send text messages. + void sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm); + + void sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, const QString &text); + + /// Returns true if a channel is full. If a user is provided, false will always + /// be returned if the user has write permission in the channel. + bool isChannelFull(Channel *c, ServerUser *u = 0); + + // Database / DBus functions. Implementation in ServerDB.cpp + void initialize(); + int authenticate(QString &name, const QString &pw, int sessionId = 0, const QStringList &emails = QStringList(), + const QString &certhash = QString(), bool bStrongCert = false, + const QList< QSslCertificate > & = QList< QSslCertificate >()); + Channel *addChannel(Channel *c, const QString &name, bool temporary = false, int position = 0, + unsigned int maxUsers = 0); + void removeChannelDB(const Channel *c); + void readChannels(Channel *p = nullptr); + void readLinks(); + void updateChannel(const Channel *c); + void readChannelPrivs(Channel *c); + void setLastChannel(const User *u); + int readLastChannel(int id); + + /// Set last_disconnect of a registered user to the current time + void setLastDisconnect(const User *u); + void dumpChannel(const Channel *c); + int getUserID(const QString &name); + QString getUserName(int id); + QByteArray getUserTexture(int id); + QMap< int, QString > getRegistration(int id); + int registerUser(const QMap< int, QString > &info); + bool unregisterUserDB(int id); + QList< UserInfo > getRegisteredUsersEx(); + QMap< int, QString > getRegisteredUsers(const QString &filter = QString()); + bool setInfo(int id, const QMap< int, QString > &info); + bool setTexture(int id, const QByteArray &texture); + bool isUserId(int id); + void addLink(Channel *c, Channel *l); + void removeLink(Channel *c, Channel *l); + void getBans(); + void saveBans(); + QVariant getConf(const QString &key, QVariant def); + void setConf(const QString &key, const QVariant &value); + void dblog(const QString &str) const; + + // From msgHandler. Implementation in Messages.cpp +#define MUMBLE_MH_MSG(x) void msg##x(ServerUser *, MumbleProto::x &); + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG }; diff --git a/src/murmur/ServerDB.cpp b/src/murmur/ServerDB.cpp index 460db00cb..58316d699 100644 --- a/src/murmur/ServerDB.cpp +++ b/src/murmur/ServerDB.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "ServerDB.h" @@ -17,20 +17,20 @@ #include "DBus.h" #include "Group.h" #include "Meta.h" +#include "PBKDF2.h" +#include "PasswordGenerator.h" #include "Server.h" #include "ServerUser.h" #include "User.h" -#include "PBKDF2.h" -#include "PasswordGenerator.h" #include <QtCore/QCoreApplication> #include <QtSql/QSqlError> #include <QtSql/QSqlQuery> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <arpa/inet.h> +# include <arpa/inet.h> #endif #define SQLQUERY(x) ServerDB::query(query, QLatin1String(x), true) @@ -44,22 +44,22 @@ class TransactionHolder { - public: - QSqlQuery *qsqQuery; - TransactionHolder() { - ServerDB::db->transaction(); - qsqQuery = new QSqlQuery(); - } +public: + QSqlQuery *qsqQuery; + TransactionHolder() { + ServerDB::db->transaction(); + qsqQuery = new QSqlQuery(); + } - ~TransactionHolder() { - qsqQuery->clear(); - delete qsqQuery; - ServerDB::db->commit(); - } - TransactionHolder(const TransactionHolder & other) { - ServerDB::db->transaction(); - qsqQuery = other.qsqQuery ? new QSqlQuery(*other.qsqQuery) : 0; - } + ~TransactionHolder() { + qsqQuery->clear(); + delete qsqQuery; + ServerDB::db->commit(); + } + TransactionHolder(const TransactionHolder &other) { + ServerDB::db->transaction(); + qsqQuery = other.qsqQuery ? new QSqlQuery(*other.qsqQuery) : 0; + } }; QSqlDatabase *ServerDB::db = nullptr; @@ -80,7 +80,8 @@ void ServerDB::loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query) { // Didn't get a valid iteration count from DB, overwrite Meta::mp.kdfIterations = PBKDF2::benchmark(); - qWarning() << "Performed initial PBKDF2 benchmark. Will use" << Meta::mp.kdfIterations << "iterations as default"; + qWarning() << "Performed initial PBKDF2 benchmark. Will use" << Meta::mp.kdfIterations + << "iterations as default"; SQLPREP("INSERT INTO `%1meta` (`keystring`, `value`) VALUES('pbkdf2_iterations',?)"); query.addBindValue(Meta::mp.kdfIterations); @@ -89,16 +90,20 @@ void ServerDB::loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query) { } if (Meta::mp.kdfIterations < PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT) { - qWarning() << "Configured default PBKDF2 iteration count of" << Meta::mp.kdfIterations << "is below minimum recommended value of" << PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT << "and could be insecure."; + qWarning() << "Configured default PBKDF2 iteration count of" << Meta::mp.kdfIterations + << "is below minimum recommended value of" << PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT + << "and could be insecure."; } } } ServerDB::ServerDB() { - if (Meta::mp.qsDBDriver != QLatin1String("QMYSQL") && Meta::mp.qsDBDriver != QLatin1String("QSQLITE") && Meta::mp.qsDBDriver != QLatin1String("QPSQL")) { - qFatal("ServerDB: invalid DB driver specified: '%s'. Murmur only supports QSQLITE, QMYSQL, and QPSQL.", qPrintable(Meta::mp.qsDBDriver)); + if (Meta::mp.qsDBDriver != QLatin1String("QMYSQL") && Meta::mp.qsDBDriver != QLatin1String("QSQLITE") + && Meta::mp.qsDBDriver != QLatin1String("QPSQL")) { + qFatal("ServerDB: invalid DB driver specified: '%s'. Murmur only supports QSQLITE, QMYSQL, and QPSQL.", + qPrintable(Meta::mp.qsDBDriver)); } - if (! QSqlDatabase::isDriverAvailable(Meta::mp.qsDBDriver)) { + if (!QSqlDatabase::isDriverAvailable(Meta::mp.qsDBDriver)) { qFatal("ServerDB: Database driver %s not available", qPrintable(Meta::mp.qsDBDriver)); } if (db) { @@ -112,7 +117,7 @@ ServerDB::ServerDB() { bool found = false; if (Meta::mp.qsDBDriver == "QSQLITE") { - if (! Meta::mp.qsDatabase.isEmpty()) { + if (!Meta::mp.qsDatabase.isEmpty()) { db->setDatabaseName(Meta::mp.qsDatabase); found = db->open(); } else { @@ -124,7 +129,7 @@ ServerDB::ServerDB() { datapaths << QCoreApplication::instance()->applicationDirPath(); datapaths << QDir::homePath(); - for (i = 0; (i < datapaths.size()) && ! found; i++) { + for (i = 0; (i < datapaths.size()) && !found; i++) { if (!datapaths[i].isEmpty()) { QFile f(datapaths[i] + "/murmur.sqlite"); if (f.exists()) { @@ -134,8 +139,8 @@ ServerDB::ServerDB() { } } - if (! found) { - for (i = 0; (i < datapaths.size()) && ! found; i++) { + if (!found) { + for (i = 0; (i < datapaths.size()) && !found; i++) { if (!datapaths[i].isEmpty()) { QFile f(datapaths[i] + "/murmur.sqlite"); db->setDatabaseName(f.fileName()); @@ -147,7 +152,7 @@ ServerDB::ServerDB() { if (found) { QFileInfo fi(db->databaseName()); qWarning("ServerDB: Opened SQLite database %s", qPrintable(fi.absoluteFilePath())); - if (! fi.isWritable()) + if (!fi.isWritable()) qFatal("ServerDB: Database is not writable"); } } else { @@ -160,9 +165,9 @@ ServerDB::ServerDB() { found = db->open(); } - if (! found) { + if (!found) { QSqlError e = db->lastError(); - qFatal("ServerDB: Failed initialization: %s",qPrintable(e.text())); + qFatal("ServerDB: Failed initialization: %s", qPrintable(e.text())); } // Use SQLite in WAL mode if possible. @@ -173,7 +178,7 @@ ServerDB::ServerDB() { QSqlQuery query; bool hasversion = false; - bool okversion = false; + bool okversion = false; QString version; SQLDO("SELECT sqlite_version();"); if (query.next()) { @@ -183,8 +188,8 @@ ServerDB::ServerDB() { QStringList splitVersion = version.split(QLatin1String(".")); int major = 0, minor = 0; if (splitVersion.count() >= 3) { - major = splitVersion.at(0).toInt(); - minor = splitVersion.at(1).toInt(); + major = splitVersion.at(0).toInt(); + minor = splitVersion.at(1).toInt(); hasversion = true; } if (major > 3 || (major == 3 && minor >= 7)) { @@ -201,12 +206,16 @@ ServerDB::ServerDB() { qWarning("ServerDB: Configured SQLite for journal_mode=WAL, synchronous=FULL"); } } else if (hasversion) { - qWarning("ServerDB: Unable to use SQLite in WAL mode due to incompatible SQLite version %i.%i", major, minor); + qWarning("ServerDB: Unable to use SQLite in WAL mode due to incompatible SQLite version %i.%i", major, + minor); } else { - qWarning("ServerDB: Unable to use SQLite in WAL mode because the SQLite version could not be determined."); + qWarning( + "ServerDB: Unable to use SQLite in WAL mode because the SQLite version could not be determined."); } } else { - qFatal("ServerDB: Invalid value '%i' for sqlite_wal. Please use 0 (no wal), 1 (wal), 2 (wal with synchronous=full)", Meta::mp.iSQLiteWAL); + qFatal("ServerDB: Invalid value '%i' for sqlite_wal. Please use 0 (no wal), 1 (wal), 2 (wal with " + "synchronous=full)", + Meta::mp.iSQLiteWAL); } } @@ -216,19 +225,24 @@ ServerDB::ServerDB() { // Ensure that a proper encoding is used for the DB if (Meta::mp.qsDBDriver == "QMYSQL") { - query.exec(QString::fromLatin1("SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '%1'").arg(Meta::mp.qsDatabase)); + query.exec(QString::fromLatin1( + "SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '%1'") + .arg(Meta::mp.qsDatabase)); if (query.next()) { QString encoding = query.value(0).toString(); - // Because MySQL's utf8 implementation is not actually utf8, we have to use a different name to access the actual - // utf8 implementation. (See https://mathiasbynens.be/notes/mysql-utf8mb4) + // Because MySQL's utf8 implementation is not actually utf8, we have to use a different name to access the + // actual utf8 implementation. (See https://mathiasbynens.be/notes/mysql-utf8mb4) if (encoding.toLower() != QLatin1String("utf8mb4")) { // Change the database's encoding qWarning("Changing database encoding to utf8mb4..."); - if (!query.exec(QString::fromLatin1("ALTER DATABASE `%1` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci").arg(Meta::mp.qsDatabase))) { - qFatal("ServerDB: Failed to set default encoding & collation to UTF-8: %s", qPrintable(query.lastError().text())); + if (!query.exec( + QString::fromLatin1("ALTER DATABASE `%1` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci") + .arg(Meta::mp.qsDatabase))) { + qFatal("ServerDB: Failed to set default encoding & collation to UTF-8: %s", + qPrintable(query.lastError().text())); } } } else { @@ -280,7 +294,8 @@ ServerDB::ServerDB() { SQLQUERY("CREATE TABLE IF NOT EXISTS `%1meta` (`keystring` varchar(255) PRIMARY KEY, `value` varchar(255))"); else // MySQL - SQLDO("CREATE TABLE IF NOT EXISTS `%1meta`(`keystring` varchar(255) PRIMARY KEY, `value` varchar(255)) ENGINE=InnoDB"); + SQLDO("CREATE TABLE IF NOT EXISTS `%1meta`(`keystring` varchar(255) PRIMARY KEY, `value` varchar(255)) " + "ENGINE=InnoDB"); // Query the database structure version the existing database conforms to SQLDO("SELECT `value` FROM `%1meta` WHERE `keystring` = 'version'"); @@ -368,80 +383,122 @@ ServerDB::ServerDB() { SQLDO("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` DATE)"); SQLDO("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLDO("CREATE TRIGGER `%1slog_timestamp` AFTER INSERT ON `%1slog` FOR EACH ROW BEGIN UPDATE `%1slog` SET `msgtime` = datetime('now') WHERE rowid = new.rowid; END;"); - SQLDO("CREATE TRIGGER `%1slog_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1slog` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1slog_timestamp` AFTER INSERT ON `%1slog` FOR EACH ROW BEGIN UPDATE `%1slog` SET " + "`msgtime` = datetime('now') WHERE rowid = new.rowid; END;"); + SQLDO("CREATE TRIGGER `%1slog_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1slog` WHERE `server_id` = old.`server_id`; END;"); SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` TEXT, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1config_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1config` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1config_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1config` WHERE `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` TEXT, `inheritacl` INTEGER)"); + SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` " + "INTEGER, `name` TEXT, `inheritacl` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLDO("CREATE TRIGGER `%1channels_parent_del` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channels` WHERE `parent_id` = old.`channel_id` AND `server_id` = old.`server_id`; UPDATE `%1users` SET `lastchannel`=0 WHERE `lastchannel` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1channels_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1channels` WHERE `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLDO( + "CREATE TRIGGER `%1channels_parent_del` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1channels` WHERE `parent_id` = old.`channel_id` AND `server_id` = old.`server_id`; UPDATE `%1users` " + "SET `lastchannel`=0 WHERE `lastchannel` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1channels_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1channels` WHERE `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO( + "CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE " + "FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `pw` TEXT, `salt` TEXT, `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BLOB, `last_active` DATE, `last_disconnect` DATE)"); + SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT " + "NULL, `pw` TEXT, `salt` TEXT, `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BLOB, " + "`last_active` DATE, `last_disconnect` DATE)"); SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1users` WHERE `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1users_update_timestamp` AFTER UPDATE OF `lastchannel` ON `%1users` FOR EACH ROW BEGIN UPDATE `%1users` SET `last_active` = datetime('now') WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1users` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1users_update_timestamp` AFTER UPDATE OF `lastchannel` ON `%1users` FOR EACH ROW " + "BEGIN UPDATE `%1users` SET `last_active` = datetime('now') WHERE `user_id` = old.`user_id` AND " + "`server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1user_info_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM `%1user_info` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1user_info_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM " + "`%1user_info` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_id` INTEGER NOT NULL, `name` TEXT, `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); + SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_id` INTEGER NOT " + "NULL, `name` TEXT, `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLDO("CREATE TRIGGER `%1groups_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1groups` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER)"); - SQLDO("CREATE TRIGGER `%1groups_members_del_group` AFTER DELETE ON `%1groups` FOR EACH ROW BEGIN DELETE FROM `%1group_members` WHERE `group_id` = old.`group_id`; END;"); - SQLDO("CREATE TRIGGER `%1groups_members_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM `%1group_members` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` TEXT, `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); + SQLDO("CREATE TRIGGER `%1groups_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1groups` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER)"); + SQLDO("CREATE TRIGGER `%1groups_members_del_group` AFTER DELETE ON `%1groups` FOR EACH ROW BEGIN DELETE " + "FROM `%1group_members` WHERE `group_id` = old.`group_id`; END;"); + SQLDO("CREATE TRIGGER `%1groups_members_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM " + "`%1group_members` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` TEXT, `apply_here` INTEGER, `apply_sub` INTEGER, " + "`grantpriv` INTEGER, `revokepriv` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); - SQLDO("CREATE TRIGGER `%1acl_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1acl` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1acl_del_user` AFTER DELETE ON `%1users` FOR EACH ROW BEGIN DELETE FROM `%1acl` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL)"); - SQLDO("CREATE TRIGGER `%1channel_links_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_links` WHERE `server_id` = old.`server_id` AND (`channel_id` = old.`channel_id` OR `link_id` = old.`channel_id`); END;"); + SQLDO("CREATE TRIGGER `%1acl_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1acl` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1acl_del_user` AFTER DELETE ON `%1users` FOR EACH ROW BEGIN DELETE FROM `%1acl` " + "WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL)"); + SQLDO("CREATE TRIGGER `%1channel_links_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE " + "FROM `%1channel_links` WHERE `server_id` = old.`server_id` AND (`channel_id` = old.`channel_id` OR " + "`link_id` = old.`channel_id`); END;"); SQLDO("DELETE FROM `%1channel_links`"); - SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BLOB, `mask` INTEGER, `name` TEXT, `hash` TEXT, `reason` TEXT, `start` DATE, `duration` INTEGER)"); - SQLDO("CREATE TRIGGER `%1bans_del_server` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1bans` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BLOB, `mask` INTEGER, `name` TEXT, " + "`hash` TEXT, `reason` TEXT, `start` DATE, `duration` INTEGER)"); + SQLDO("CREATE TRIGGER `%1bans_del_server` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1bans` WHERE `server_id` = old.`server_id`; END;"); } else if (Meta::mp.qsDBDriver == "QPSQL") { if (version > 0) { - typedef QPair<QString, QString> qsp; - QList<qsp> qlForeignKeys; - QList<qsp> qlIndexes; + typedef QPair< QString, QString > qsp; + QList< qsp > qlForeignKeys; + QList< qsp > qlIndexes; - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlForeignKeys << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlForeignKeys) { + foreach (const qsp &key, qlForeignKeys) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT FOREIGN KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT FOREIGN KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } - - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='PRIMARY KEY'"); + + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='PRIMARY KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlIndexes << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlIndexes) { + foreach (const qsp &key, qlIndexes) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT PRIMARY KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT PRIMARY KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } - - + + SQLQUERY("DROP INDEX IF EXISTS `%1slog_time` CASCADE"); SQLQUERY("DROP INDEX IF EXISTS `%1config_key` CASCADE"); SQLQUERY("DROP INDEX IF EXISTS `%1channel_id` CASCADE"); @@ -459,122 +516,181 @@ ServerDB::ServerDB() { } SQLQUERY("CREATE TABLE `%1servers`(`server_id` SERIAL PRIMARY KEY)"); - SQLQUERY("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP DEFAULT now())"); + SQLQUERY( + "CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP DEFAULT now())"); SQLQUERY("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLQUERY("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); SQLQUERY("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER)"); + SQLQUERY("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, `parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, " + "`parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) " + "REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLQUERY("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`key` INTEGER, `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY " + "(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BYTEA, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP)"); + SQLQUERY("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` " + "varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` " + "INTEGER, `texture` BYTEA, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP)"); SQLQUERY("CREATE INDEX `%1users_channel` ON `%1users`(`server_id`, `lastchannel`)"); SQLQUERY("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLQUERY("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLQUERY("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1groups` (`group_id` SERIAL PRIMARY KEY, `server_id` INTEGER NOT NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); + SQLQUERY("CREATE TABLE `%1groups` (`group_id` SERIAL PRIMARY KEY, `server_id` INTEGER NOT NULL, `name` " + "varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLQUERY("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER)"); + SQLQUERY("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER)"); SQLQUERY("CREATE INDEX `%1group_members_users` ON `%1group_members`(`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - - SQLQUERY("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); + SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY " + "(`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY " + "(`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + + SQLQUERY("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` " + "INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); SQLQUERY("CREATE INDEX `%1acl_user` ON `%1acl`(`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); - - SQLQUERY("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL)"); - SQLQUERY("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) " + "REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) " + "REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); + + SQLQUERY("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL)"); + SQLQUERY( + "ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); SQLQUERY("DELETE FROM `%1channel_links`"); - SQLQUERY("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BYTEA, `mask` INTEGER, `name` varchar(255), `hash` CHAR(40), `reason` TEXT, `start` TIMESTAMP, `duration` INTEGER)"); - SQLQUERY("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BYTEA, `mask` INTEGER, `name` " + "varchar(255), `hash` CHAR(40), `reason` TEXT, `start` TIMESTAMP, `duration` INTEGER)"); + SQLQUERY("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); } else { // MySQL if (version > 0) { - typedef QPair<QString, QString> qsp; - QList<qsp> qlForeignKeys; - QList<qsp> qlIndexes; + typedef QPair< QString, QString > qsp; + QList< qsp > qlForeignKeys; + QList< qsp > qlIndexes; - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlForeignKeys << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlForeignKeys) { + foreach (const qsp &key, qlForeignKeys) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP FOREIGN KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP FOREIGN KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } } SQLDO("CREATE TABLE `%1servers`(`server_id` INTEGER PRIMARY KEY AUTO_INCREMENT) ENGINE=InnoDB"); SQLDO("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLDO("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT) " + "ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLDO("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` " + "INTEGER, `name` varchar(255), `inheritacl` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, `parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, " + "`parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) " + "REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLDO("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` LONGBLOB, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` " + "varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` " + "INTEGER, `texture` LONGBLOB, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1users_channel` ON `%1users`(`server_id`, `lastchannel`)"); SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLDO("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTO_INCREMENT, `server_id` INTEGER NOT NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTO_INCREMENT, `server_id` INTEGER NOT " + "NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER) " + "ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLDO("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1group_members_users` ON `%1group_members`(`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - - SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) " + "REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + + SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, " + "`grantpriv` INTEGER, `revokepriv` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); SQLDO("CREATE INDEX `%1acl_user` ON `%1acl`(`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); - - SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL) ENGINE=InnoDB"); - SQLDO("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) " + "REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES " + "`%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); + + SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); SQLDO("DELETE FROM `%1channel_links`"); - SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BINARY(16), `mask` INTEGER, `name` varchar(255), `hash` CHAR(40), `reason` TEXT, `start` DATETIME, `duration` INTEGER) ENGINE=InnoDB"); - SQLDO("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BINARY(16), `mask` INTEGER, `name` " + "varchar(255), `hash` CHAR(40), `reason` TEXT, `start` DATETIME, `duration` INTEGER) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); } if (version == 0) { @@ -583,63 +699,84 @@ ServerDB::ServerDB() { // server) as well as the version info about the database structure version. SQLDO("INSERT INTO `%1servers` (`server_id`) VALUES(1)"); // Calling this function is the same as using the SQLDO macro - SQLDO_NO_CONVERSION(QLatin1String("INSERT INTO `%1meta` (`keystring`, `value`) ") - + QString::fromLatin1("VALUES('version','%1')").arg(QString::number(DB_STRUCTURE_VERSION))); + SQLDO_NO_CONVERSION( + QLatin1String("INSERT INTO `%1meta` (`keystring`, `value`) ") + + QString::fromLatin1("VALUES('version','%1')").arg(QString::number(DB_STRUCTURE_VERSION))); } else { qWarning("Importing old data..."); if (Meta::mp.qsDBDriver == "QMYSQL") SQLDO("SET FOREIGN_KEY_CHECKS = 0;"); SQLDO("INSERT INTO `%1servers` (`server_id`) SELECT `server_id` FROM `%1servers%2`"); - SQLDO("INSERT INTO `%1slog` (`server_id`, `msg`, `msgtime`) SELECT `server_id`, `msg`, `msgtime` FROM `%1slog%2`"); + SQLDO("INSERT INTO `%1slog` (`server_id`, `msg`, `msgtime`) SELECT `server_id`, `msg`, `msgtime` FROM " + "`%1slog%2`"); if (version < 4) - SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `keystring`, `value` FROM `%1config%2`"); + SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `keystring`, `value` " + "FROM `%1config%2`"); else - SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `key`, `value` FROM `%1config%2`"); + SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `key`, `value` FROM " + "`%1config%2`"); - SQLDO("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl`) SELECT `server_id`, `channel_id`, `parent_id`, `name`, `inheritacl` FROM `%1channels%2` ORDER BY `parent_id`, `channel_id`"); + SQLDO("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl`) SELECT " + "`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl` FROM `%1channels%2` ORDER BY " + "`parent_id`, `channel_id`"); if (version < 4) - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `player_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active` FROM `%1players%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `player_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active` FROM `%1players%2`"); else if (version < 8) - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active` FROM `%1users%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active` FROM `%1users%2`"); else - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`, `last_disconnect` FROM `%1users%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`, `last_disconnect` FROM `%1users%2`"); - SQLDO("INSERT INTO `%1groups` (`group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable`) SELECT `group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable` FROM `%1groups%2`"); + SQLDO("INSERT INTO `%1groups` (`group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable`) " + "SELECT `group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable` FROM `%1groups%2`"); if (version < 4) - SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, `server_id`, `player_id`, `addit` FROM `%1group_members%2`"); + SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, " + "`server_id`, `player_id`, `addit` FROM `%1group_members%2`"); else - SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, `server_id`, `user_id`, `addit` FROM `%1group_members%2`"); + SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, " + "`server_id`, `user_id`, `addit` FROM `%1group_members%2`"); if (version < 4) - SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, `priority`, `player_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl%2`"); + SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, " + "`apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, " + "`priority`, `player_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` " + "FROM `%1acl%2`"); else - SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl%2`"); + SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, " + "`apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, " + "`priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM " + "`%1acl%2`"); - SQLDO("INSERT INTO `%1channel_links` (`server_id`, `channel_id`, `link_id`) SELECT `server_id`, `channel_id`, `link_id` FROM `%1channel_links%2`"); + SQLDO("INSERT INTO `%1channel_links` (`server_id`, `channel_id`, `link_id`) SELECT `server_id`, " + "`channel_id`, `link_id` FROM `%1channel_links%2`"); if (version < 4) { - QList<QList<QVariant> > ql; + QList< QList< QVariant > > ql; SQLPREP("SELECT `server_id`, `base`, `mask` FROM `%1bans%2`"); SQLEXEC(); while (query.next()) { - QList<QVariant> l; + QList< QVariant > l; l << query.value(0); l << query.value(1); l << query.value(2); ql << l; } SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) VALUES (?, ?, ?)"); - foreach(const QList<QVariant> &l, ql) { - - quint32 addr = htonl(l.at(1).toUInt()); - const char *ptr = reinterpret_cast<const char *>(&addr); + foreach (const QList< QVariant > &l, ql) { + quint32 addr = htonl(l.at(1).toUInt()); + const char *ptr = reinterpret_cast< const char * >(&addr); QByteArray qba(16, 0); - qba[10] = static_cast<char>(-1); - qba[11] = static_cast<char>(-1); + qba[10] = static_cast< char >(-1); + qba[11] = static_cast< char >(-1); qba[12] = ptr[0]; qba[13] = ptr[1]; qba[14] = ptr[2]; @@ -651,14 +788,17 @@ ServerDB::ServerDB() { SQLEXEC(); } } else { - SQLDO("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) SELECT `server_id`, `base`, `mask` FROM `%1bans%2`"); + SQLDO("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) SELECT `server_id`, `base`, `mask` FROM " + "`%1bans%2`"); } if (version < 4) - SQLDO("INSERT INTO `%1user_info` SELECT `server_id`,`player_id`,1,`email` FROM `%1players%2` WHERE `email` IS NOT NULL"); + SQLDO("INSERT INTO `%1user_info` SELECT `server_id`,`player_id`,1,`email` FROM `%1players%2` WHERE " + "`email` IS NOT NULL"); if (version == 3) { - SQLDO("INSERT INTO `%1channel_info` SELECT `server_id`,`channel_id`,0,`description` FROM `%1channels%2` WHERE `description` IS NOT NULL"); + SQLDO("INSERT INTO `%1channel_info` SELECT `server_id`,`channel_id`,0,`description` FROM " + "`%1channels%2` WHERE `description` IS NOT NULL"); } if (version >= 4) { @@ -685,7 +825,7 @@ ServerDB::ServerDB() { SQLQUERY("DROP TABLE IF EXISTS `%1servers%2`"); SQLDO_NO_CONVERSION(QLatin1String("UPDATE `%1meta` SET `value` = ") - + QString::fromLatin1("'%1' WHERE `keystring` = 'version'").arg(DB_STRUCTURE_VERSION)); + + QString::fromLatin1("'%1' WHERE `keystring` = 'version'").arg(DB_STRUCTURE_VERSION)); } } query.clear(); @@ -698,7 +838,7 @@ ServerDB::~ServerDB() { } bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! db->isValid()) { + if (!db->isValid()) { qWarning("SQL [%s] rejected: Database is gone", qPrintable(str)); return false; } @@ -715,12 +855,12 @@ bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool wa if (Meta::mp.qsDBDriver == "QPSQL") { q.replace("`", "\""); } - + if (query.prepare(q)) { return true; } else { db->close(); - if (! db->open()) { + if (!db->open()) { qFatal("Lost connection to SQL Database: Reconnect: %s", qPrintable(db->lastError().text())); } query = QSqlQuery(); @@ -740,8 +880,8 @@ bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool wa } bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! str.isEmpty()) { - if (! db->isValid()) { + if (!str.isEmpty()) { + if (!db->isValid()) { qWarning("SQL [%s] rejected: Database is gone", qPrintable(str)); return false; } @@ -758,7 +898,7 @@ bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn if (Meta::mp.qsDBDriver == "QPSQL") { q.replace("`", "\""); } - + if (query.exec(q)) { return true; } else { @@ -776,12 +916,11 @@ bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn } bool ServerDB::exec(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! str.isEmpty()) + if (!str.isEmpty()) prepare(query, str, fatal, warn); if (query.exec()) { return true; } else { - if (fatal) { *db = QSqlDatabase(); qFatal("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); @@ -793,12 +932,11 @@ bool ServerDB::exec(QSqlQuery &query, const QString &str, bool fatal, bool warn) } bool ServerDB::execBatch(QSqlQuery &query, const QString &str, bool fatal) { - if (! str.isEmpty()) + if (!str.isEmpty()) prepare(query, str, fatal); if (query.execBatch()) { return true; } else { - if (fatal) { *db = QSqlDatabase(); qFatal("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); @@ -816,14 +954,15 @@ void Server::initialize() { SQLPREP("SELECT `channel_id` FROM `%1channels` WHERE `server_id` = ? AND `channel_id` = 0"); query.addBindValue(iServerNum); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`) VALUES (?, ?, ?, ?)"); query.addBindValue(iServerNum); query.addBindValue(0); query.addBindValue(QVariant()); query.addBindValue(QLatin1String("Root")); SQLEXEC(); - SQLPREP("UPDATE `%1channels` SET `channel_id` = 0 WHERE `server_id` = ? AND `name` = ? AND `parent_id` IS NULL"); + SQLPREP( + "UPDATE `%1channels` SET `channel_id` = 0 WHERE `server_id` = ? AND `name` = ? AND `parent_id` IS NULL"); query.addBindValue(iServerNum); query.addBindValue(QLatin1String("Root")); SQLEXEC(); @@ -832,7 +971,7 @@ void Server::initialize() { SQLPREP("SELECT `user_id` FROM `%1users` WHERE `server_id` = ? AND `user_id` = 0"); query.addBindValue(iServerNum); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (?, ?, ?)"); query.addBindValue(iServerNum); query.addBindValue(0); @@ -844,7 +983,7 @@ void Server::initialize() { SQLEXEC(); const int passwordLength = 12; - QString pw = PasswordGenerator::generatePassword(passwordLength); + QString pw = PasswordGenerator::generatePassword(passwordLength); ServerDB::setSUPW(iServerNum, pw); log(QString("Password for 'SuperUser' set to '%2'").arg(pw)); } @@ -855,7 +994,8 @@ void Server::initialize() { if (query.next()) { int c = query.value(0).toInt(); if (c == 0) { - SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`) VALUES (?,?,?,?,?,?,?)"); + SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `group_name`, `apply_here`, " + "`apply_sub`, `grantpriv`) VALUES (?,?,?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(0); @@ -863,7 +1003,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("admin")); query.addBindValue(1); query.addBindValue(1); - query.addBindValue(static_cast<int>(ChanACL::Write)); + query.addBindValue(static_cast< int >(ChanACL::Write)); SQLEXEC(); query.addBindValue(iServerNum); @@ -872,7 +1012,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("auth")); query.addBindValue(1); query.addBindValue(1); - query.addBindValue(static_cast<int>(ChanACL::MakeTempChannel)); + query.addBindValue(static_cast< int >(ChanACL::MakeTempChannel)); SQLEXEC(); query.addBindValue(iServerNum); @@ -881,7 +1021,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("all")); query.addBindValue(1); query.addBindValue(0); - query.addBindValue(static_cast<int>(ChanACL::SelfRegister)); + query.addBindValue(static_cast< int >(ChanACL::SelfRegister)); SQLEXEC(); } } @@ -893,7 +1033,8 @@ void Server::initialize() { if (query.next()) { int c = query.value(0).toInt(); if (c == 0) { - SQLPREP("INSERT INTO `%1groups`(`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?)"); + SQLPREP("INSERT INTO `%1groups`(`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(0); query.addBindValue(QLatin1String("admin")); @@ -905,13 +1046,13 @@ void Server::initialize() { query.clear(); } -int Server::registerUser(const QMap<int, QString> &info) { +int Server::registerUser(const QMap< int, QString > &info) { const QString &name = info.value(ServerDB::User_Name); if (name.isEmpty()) return -1; - if (! validateUserName(name)) + if (!validateUserName(name)) return -1; if (getUserID(name) >= 0) @@ -933,7 +1074,7 @@ int Server::registerUser(const QMap<int, QString> &info) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - + if (res < 0) { SQLPREP("SELECT MAX(`user_id`)+1 AS id FROM `%1users` WHERE `server_id`=? AND `user_id` < 1000000000"); @@ -946,7 +1087,9 @@ int Server::registerUser(const QMap<int, QString> &info) { } if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (:server_id,:user_id,:name) ON CONFLICT (`server_id`, `name`) DO UPDATE SET `user_id` = :u_user_id WHERE `%1users`.`server_id` = :u_server_id AND `%1users`.`name` = :u_name"); + SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (:server_id,:user_id,:name) ON " + "CONFLICT (`server_id`, `name`) DO UPDATE SET `user_id` = :u_user_id WHERE `%1users`.`server_id` = " + ":u_server_id AND `%1users`.`name` = :u_name"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", id); query.bindValue(":name", name); @@ -962,7 +1105,7 @@ int Server::registerUser(const QMap<int, QString> &info) { SQLEXEC(); } } - + qhUserNameCache.remove(id); setInfo(id, info); @@ -974,7 +1117,7 @@ bool Server::unregisterUserDB(int id) { if (id <= 0) return false; - QMap<int, QString> info = getRegistration(id); + QMap< int, QString > info = getRegistration(id); if (info.isEmpty()) return false; @@ -1004,15 +1147,13 @@ bool Server::unregisterUserDB(int id) { return true; } -QList<UserInfo> Server::getRegisteredUsersEx() { - - QMap<int, QString> rpcUsers; +QList< UserInfo > Server::getRegisteredUsersEx() { + QMap< int, QString > rpcUsers; emit getRegisteredUsersSig(QString(), rpcUsers); - QList<UserInfo> users; - QMap<int, QString>::iterator it = rpcUsers.begin(); - for (; it != rpcUsers.end(); ++it) - { + QList< UserInfo > users; + QMap< int, QString >::iterator it = rpcUsers.begin(); + for (; it != rpcUsers.end(); ++it) { users.insert(it.key(), UserInfo(it.key(), it.value())); } @@ -1025,10 +1166,10 @@ QList<UserInfo> Server::getRegisteredUsersEx() { while (query.next()) { UserInfo userinfo; - userinfo.user_id = query.value(0).toInt(); - userinfo.name = query.value(1).toString(); + userinfo.user_id = query.value(0).toInt(); + userinfo.name = query.value(1).toString(); userinfo.last_channel = query.value(2).toInt(); - userinfo.last_active = QDateTime::fromString(query.value(3).toString(), Qt::ISODate); + userinfo.last_active = QDateTime::fromString(query.value(3).toString(), Qt::ISODate); userinfo.last_active.setTimeSpec(Qt::UTC); users << userinfo; @@ -1037,8 +1178,8 @@ QList<UserInfo> Server::getRegisteredUsersEx() { return users; } -QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { - QMap<int, QString > m; +QMap< int, QString > Server::getRegisteredUsers(const QString &filter) { + QMap< int, QString > m; emit getRegisteredUsersSig(filter, m); @@ -1056,7 +1197,7 @@ QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { SQLEXEC(); while (query.next()) { - int id = query.value(0).toInt(); + int id = query.value(0).toInt(); QString name = query.value(1).toString(); m.insert(id, name); } @@ -1064,7 +1205,7 @@ QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { } bool Server::isUserId(int id) { - QMap<int, QString> info; + QMap< int, QString > info; int res = -2; emit getRegistrationSig(res, id, info); if (res >= 0) @@ -1083,8 +1224,8 @@ bool Server::isUserId(int id) { return false; } -QMap<int, QString> Server::getRegistration(int id) { - QMap<int, QString> info; +QMap< int, QString > Server::getRegistration(int id) { + QMap< int, QString > info; int res = -2; emit getRegistrationSig(res, id, info); if (res >= 0) @@ -1116,7 +1257,8 @@ QMap<int, QString> Server::getRegistration(int id) { /// @return UserID of authenticated user, -1 for authentication failures, -2 for unknown user (fallthrough), /// -3 for authentication failures where the data could (temporarily) not be verified. -int Server::authenticate(QString &name, const QString &password, int sessionId, const QStringList &emails, const QString &certhash, bool bStrongCert, const QList<QSslCertificate> &certs) { +int Server::authenticate(QString &name, const QString &password, int sessionId, const QStringList &emails, + const QString &certhash, bool bStrongCert, const QList< QSslCertificate > &certs) { int res = bForceExternalAuth ? -3 : -2; emit authenticateSig(res, name, sessionId, certs, certhash, bStrongCert, password); @@ -1127,12 +1269,15 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - int lchan=readLastChannel(res); + int lchan = readLastChannel(res); if (lchan < 0) lchan = 0; if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES (:server_id,:user_id,:name,:lastchannel) ON CONFLICT (`server_id`, `user_id`) DO UPDATE SET `name` = :u_name, `lastchannel` = :u_lastchannel WHERE `%1users`.`server_id` = :u_server_id AND `%1users`.`user_id` = :u_user_id"); + SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES " + "(:server_id,:user_id,:name,:lastchannel) ON CONFLICT (`server_id`, `user_id`) DO UPDATE SET " + "`name` = :u_name, `lastchannel` = :u_lastchannel WHERE `%1users`.`server_id` = :u_server_id " + "AND `%1users`.`user_id` = :u_user_id"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); query.bindValue(":name", name); @@ -1161,33 +1306,34 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - SQLPREP("SELECT `user_id`,`name`,`pw`, `salt`, `kdfiterations` FROM `%1users` WHERE `server_id` = ? AND LOWER(`name`) = LOWER(?)"); + SQLPREP("SELECT `user_id`,`name`,`pw`, `salt`, `kdfiterations` FROM `%1users` WHERE `server_id` = ? AND " + "LOWER(`name`) = LOWER(?)"); query.addBindValue(iServerNum); query.addBindValue(name); SQLEXEC(); if (query.next()) { - const int userId = query.value(0).toInt(); + const int userId = query.value(0).toInt(); const QString storedPasswordHash = query.value(2).toString(); - const QString storedSalt = query.value(3).toString(); - const int storedKdfIterations = query.value(4).toInt(); - res = -1; + const QString storedSalt = query.value(3).toString(); + const int storedKdfIterations = query.value(4).toInt(); + res = -1; if (!storedPasswordHash.isEmpty()) { // A user has password authentication enabled if there is a password hash. - + if (storedKdfIterations <= 0) { // If storedKdfIterations is <=0 this means this is an old-style SHA1 hash // that hasn't been converted yet. Or we are operating in legacy mode. if (ServerDB::getLegacySHA1Hash(password) == storedPasswordHash) { name = query.value(1).toString(); - res = query.value(0).toInt(); - - if (! Meta::mp.legacyPasswordHash) { + res = query.value(0).toInt(); + + if (!Meta::mp.legacyPasswordHash) { // Unless disabled upgrade the user password hash - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); info.insert(ServerDB::User_KDFIterations, QString::number(Meta::mp.kdfIterations)); - + if (!setInfo(userId, info)) { qWarning("ServerDB: Failed to upgrade user account to PBKDF2 hash, rejecting login."); return -1; @@ -1197,11 +1343,11 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, } else { if (PBKDF2::getHash(storedSalt, password, storedKdfIterations) == storedPasswordHash) { name = query.value(1).toString(); - res = query.value(0).toInt(); - + res = query.value(0).toInt(); + if (Meta::mp.legacyPasswordHash) { // Downgrade the password to the legacy hash - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); if (!setInfo(userId, info)) { @@ -1210,19 +1356,20 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, } } else if (storedKdfIterations != Meta::mp.kdfIterations) { // User kdfiterations not equal to the global one. Update it. - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); info.insert(ServerDB::User_KDFIterations, QString::number(Meta::mp.kdfIterations)); if (!setInfo(userId, info)) { - qWarning() << "ServerDB: Failed to update user PBKDF2 to new iteration count" << Meta::mp.kdfIterations << ", rejecting login."; + qWarning() << "ServerDB: Failed to update user PBKDF2 to new iteration count" + << Meta::mp.kdfIterations << ", rejecting login."; return -1; } } } } } - + if (userId == 0 && res < 0) { // For SuperUser only password based authentication is allowed. // If we couldn't verify the password don't proceed to cert auth @@ -1241,8 +1388,8 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, if (query.next()) { res = query.value(0).toInt(); } else if (bStrongCert) { - foreach(const QString &email, emails) { - if (! email.isEmpty()) { + foreach (const QString &email, emails) { + if (!email.isEmpty()) { query.addBindValue(iServerNum); query.addBindValue(ServerDB::User_Email); query.addBindValue(email); @@ -1259,16 +1406,19 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, query.addBindValue(iServerNum); query.addBindValue(res); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { res = -1; } else { name = query.value(0).toString(); } } } - if (! certhash.isEmpty() && (res > 0)) { + if (!certhash.isEmpty() && (res > 0)) { if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, :key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND `%1user_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, " + ":key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE " + "`%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND " + "`%1user_info`.`key` = :u_key"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); query.bindValue(":key", ServerDB::User_Hash); @@ -1286,8 +1436,8 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, query.addBindValue(certhash); SQLEXEC(); } - - if (! emails.isEmpty()) { + + if (!emails.isEmpty()) { if (Meta::mp.qsDBDriver == "QPSQL") { query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); @@ -1314,10 +1464,10 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, return res; } -bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { +bool Server::setInfo(int id, const QMap< int, QString > &setinfo) { int res = -2; - QMap<int, QString> info = setinfo; + QMap< int, QString > info = setinfo; if (info.contains(ServerDB::User_Name)) { const QString &uname = info.value(ServerDB::User_Name); @@ -1357,7 +1507,7 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { } } - salt = PBKDF2::getSalt(); + salt = PBKDF2::getSalt(); passwordHash = PBKDF2::getHash(salt, password, kdfIterations); } @@ -1379,8 +1529,8 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { SQLEXEC(); info.remove(ServerDB::User_Name); } - if (! info.isEmpty()) { - QMap<int, QString>::const_iterator i; + if (!info.isEmpty()) { + QMap< int, QString >::const_iterator i; QVariantList serverids, userids, keys, values; for (i = info.constBegin(); i != info.constEnd(); ++i) { @@ -1390,7 +1540,10 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { values << i.value(); } if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, :key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND `%1user_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, " + ":key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE " + "`%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND " + "`%1user_info`.`key` = :u_key"); query.bindValue(":server_id", serverids); query.bindValue(":user_id", userids); query.bindValue(":key", keys); @@ -1423,7 +1576,7 @@ bool Server::setTexture(int id, const QByteArray &texture) { else tex = texture; - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->iId == id) hashAssign(u->qbaTexture, u->qbaTextureHash, tex); } @@ -1453,7 +1606,7 @@ void ServerDB::writeSUPW(int srvnum, const QString &pwHash, const QString &saltH query.addBindValue(srvnum); query.addBindValue(0); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (?, ?, ?)"); query.addBindValue(srvnum); query.addBindValue(0); @@ -1476,7 +1629,7 @@ void ServerDB::setSUPW(int srvnum, const QString &pw) { if (!Meta::mp.legacyPasswordHash) { saltHash = PBKDF2::getSalt(); - pwHash = PBKDF2::getHash(saltHash, pw, Meta::mp.kdfIterations); + pwHash = PBKDF2::getHash(saltHash, pw, Meta::mp.kdfIterations); } else { pwHash = getLegacySHA1Hash(pw); } @@ -1485,7 +1638,7 @@ void ServerDB::setSUPW(int srvnum, const QString &pw) { } void ServerDB::disableSU(int srvnum) { - writeSUPW(srvnum, QString(), QString(), QVariant()); // nullptr, nullptr, nullptr + writeSUPW(srvnum, QString(), QString(), QVariant()); // nullptr, nullptr, nullptr } QString ServerDB::getLegacySHA1Hash(const QString &password) { @@ -1498,7 +1651,7 @@ QString Server::getUserName(int id) { return qhUserNameCache.value(id); QString name; emit idToNameSig(name, id); - if (! name.isEmpty()) { + if (!name.isEmpty()) { qhUserIDCache.insert(name, id); qhUserNameCache.insert(id, name); return name; @@ -1551,7 +1704,7 @@ int Server::getUserID(const QString &name) { QByteArray Server::getUserTexture(int id) { QByteArray qba; emit idToTextureSig(qba, id); - if (! qba.isNull()) { + if (!qba.isNull()) { return qba; } @@ -1564,7 +1717,7 @@ QByteArray Server::getUserTexture(int id) { SQLEXEC(); if (query.next()) { qba = query.value(0).toByteArray(); - if (! qba.isEmpty()) + if (!qba.isEmpty()) if (qba.size() == 600 * 60 * 4) qba = qCompress(qba); } @@ -1634,7 +1787,7 @@ Channel *Server::addChannel(Channel *p, const QString &name, bool temporary, int while (qhChannels.contains(id)) ++id; - if (! temporary) { + if (!temporary) { SQLPREP("INSERT INTO `%1channels` (`server_id`, `parent_id`, `channel_id`, `name`) VALUES (?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(p->iId); @@ -1664,16 +1817,16 @@ Channel *Server::addChannel(Channel *p, const QString &name, bool temporary, int SQLEXEC(); } - Channel *c = new Channel(id, name, p); + Channel *c = new Channel(id, name, p); c->bTemporary = temporary; - c->iPosition = position; + c->iPosition = position; c->uiMaxUsers = maxUsers; qhChannels.insert(id, c); return c; } void Server::removeChannelDB(const Channel *c) { - if (! c->bTemporary) { + if (!c->bTemporary) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; @@ -1693,7 +1846,8 @@ void Server::updateChannel(const Channel *c) { ChanACL *acl; QSqlQuery &query = *th.qsqQuery; - SQLPREP("UPDATE `%1channels` SET `name` = ?, `parent_id` = ?, `inheritacl` = ? WHERE `server_id` = ? AND `channel_id` = ?"); + SQLPREP("UPDATE `%1channels` SET `name` = ?, `parent_id` = ?, `inheritacl` = ? WHERE `server_id` = ? AND " + "`channel_id` = ?"); query.addBindValue(c->qsName); query.addBindValue(c->cParent ? c->cParent->iId : QVariant()); query.addBindValue(c->bInheritACL ? 1 : 0); @@ -1703,7 +1857,10 @@ void Server::updateChannel(const Channel *c) { // Update channel description information if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1channel_info` (`server_id`, `channel_id`, `key`, `value`) VALUES (:server_id, :channel_id, :key, :value) ON CONFLICT (`server_id`, `channel_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1channel_info`.`server_id` = :u_server_id AND `%1channel_info`.`channel_id` = :u_channel_id AND `%1channel_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1channel_info` (`server_id`, `channel_id`, `key`, `value`) VALUES (:server_id, " + ":channel_id, :key, :value) ON CONFLICT (`server_id`, `channel_id`, `key`) DO UPDATE SET `value` = " + ":u_value WHERE `%1channel_info`.`server_id` = :u_server_id AND `%1channel_info`.`channel_id` = " + ":u_channel_id AND `%1channel_info`.`key` = :u_key"); query.bindValue(":server_id", iServerNum); query.bindValue(":channel_id", c->iId); query.bindValue(":key", ServerDB::Channel_Description); @@ -1768,37 +1925,40 @@ void Server::updateChannel(const Channel *c) { query.addBindValue(c->iId); SQLEXEC(); - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { int id = 0; int pid; - + if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?) RETURNING group_id"); + SQLPREP("INSERT INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?) RETURNING group_id"); query.addBindValue(iServerNum); query.addBindValue(g->c->iId); query.addBindValue(g->qsName); query.addBindValue(g->bInherit ? 1 : 0); query.addBindValue(g->bInheritable ? 1 : 0); SQLEXEC(); - + if (query.next()) { id = query.value(0).toInt(); } else { - qFatal("ServerDB: internal query failure: PostgreSQL query did not return the inserted group's group_id"); + qFatal( + "ServerDB: internal query failure: PostgreSQL query did not return the inserted group's group_id"); } } else { - SQLPREP("REPLACE INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?)"); + SQLPREP("REPLACE INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(g->c->iId); query.addBindValue(g->qsName); query.addBindValue(g->bInherit ? 1 : 0); query.addBindValue(g->bInheritable ? 1 : 0); SQLEXEC(); - + id = query.lastInsertId().toInt(); } - foreach(pid, g->qsAdd) { + foreach (pid, g->qsAdd) { SQLPREP("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) VALUES (?, ?, ?, ?)"); query.addBindValue(id); query.addBindValue(iServerNum); @@ -1806,7 +1966,7 @@ void Server::updateChannel(const Channel *c) { query.addBindValue(1); SQLEXEC(); } - foreach(pid, g->qsRemove) { + foreach (pid, g->qsRemove) { SQLPREP("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) VALUES (?, ?, ?, ?)"); query.addBindValue(id); query.addBindValue(iServerNum); @@ -1818,8 +1978,9 @@ void Server::updateChannel(const Channel *c) { int pri = 5; - foreach(acl, c->qlACL) { - SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) VALUES (?,?,?,?,?,?,?,?,?)"); + foreach (acl, c->qlACL) { + SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, " + "`apply_sub`, `grantpriv`, `revokepriv`) VALUES (?,?,?,?,?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(acl->c->iId); query.addBindValue(pri++); @@ -1828,8 +1989,8 @@ void Server::updateChannel(const Channel *c) { query.addBindValue((acl->qsGroup.isEmpty()) ? QVariant() : acl->qsGroup); query.addBindValue(acl->bApplyHere ? 1 : 0); query.addBindValue(acl->bApplySubs ? 1 : 0); - query.addBindValue(static_cast<int>(acl->pAllow)); - query.addBindValue(static_cast<int>(acl->pDeny)); + query.addBindValue(static_cast< int >(acl->pAllow)); + query.addBindValue(static_cast< int >(acl->pDeny)); SQLEXEC(); } } @@ -1849,7 +2010,7 @@ void Server::readChannelPrivs(Channel *c) { query.addBindValue(cid); SQLEXEC(); while (query.next()) { - int key = query.value(0).toInt(); + int key = query.value(0).toInt(); const QString &value = query.value(1).toString(); if (key == ServerDB::Channel_Description) { hashAssign(c->qsDesc, c->qbaDescHash, value); @@ -1860,19 +2021,21 @@ void Server::readChannelPrivs(Channel *c) { } } - SQLPREP("SELECT `group_id`, `name`, `inherit`, `inheritable` FROM `%1groups` WHERE `server_id` = ? AND `channel_id` = ?"); + SQLPREP("SELECT `group_id`, `name`, `inherit`, `inheritable` FROM `%1groups` WHERE `server_id` = ? AND " + "`channel_id` = ?"); query.addBindValue(iServerNum); query.addBindValue(cid); SQLEXEC(); while (query.next()) { - int gid = query.value(0).toInt(); - QString name = query.value(1).toString(); - Group *g = new Group(c, name); - g->bInherit = query.value(2).toBool(); + int gid = query.value(0).toInt(); + QString name = query.value(1).toString(); + Group *g = new Group(c, name); + g->bInherit = query.value(2).toBool(); g->bInheritable = query.value(3).toBool(); QSqlQuery mem; - mem.prepare(QString::fromLatin1("SELECT user_id, addit FROM %1group_members WHERE group_id = ?").arg(Meta::mp.qsDBPrefix)); + mem.prepare(QString::fromLatin1("SELECT user_id, addit FROM %1group_members WHERE group_id = ?") + .arg(Meta::mp.qsDBPrefix)); mem.addBindValue(gid); mem.exec(); while (mem.next()) { @@ -1884,23 +2047,24 @@ void Server::readChannelPrivs(Channel *c) { } } - SQLPREP("SELECT `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl` WHERE `server_id` = ? AND `channel_id` = ? ORDER BY `priority`"); + SQLPREP("SELECT `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl` WHERE " + "`server_id` = ? AND `channel_id` = ? ORDER BY `priority`"); query.addBindValue(iServerNum); query.addBindValue(cid); SQLEXEC(); while (query.next()) { - ChanACL *acl = new ChanACL(c); - acl->iUserId = query.value(0).isNull() ? -1 : query.value(0).toInt(); - acl->qsGroup = query.value(1).toString(); + ChanACL *acl = new ChanACL(c); + acl->iUserId = query.value(0).isNull() ? -1 : query.value(0).toInt(); + acl->qsGroup = query.value(1).toString(); acl->bApplyHere = query.value(2).toBool(); acl->bApplySubs = query.value(3).toBool(); - acl->pAllow = static_cast<ChanACL::Permissions>(query.value(4).toInt()); - acl->pDeny = static_cast<ChanACL::Permissions>(query.value(5).toInt()); + acl->pAllow = static_cast< ChanACL::Permissions >(query.value(4).toInt()); + acl->pDeny = static_cast< ChanACL::Permissions >(query.value(5).toInt()); } } void Server::readChannels(Channel *p) { - QList<Channel *> kids; + QList< Channel * > kids; Channel *c; QSqlQuery query; int parentid = -1; @@ -1913,10 +2077,12 @@ void Server::readChannels(Channel *p) { { TransactionHolder th; if (parentid == -1) { - SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id` IS NULL ORDER BY `name`"); + SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id` " + "IS NULL ORDER BY `name`"); query.addBindValue(iServerNum); } else { - SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id`=? ORDER BY `name`"); + SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND " + "`parent_id`=? ORDER BY `name`"); query.addBindValue(iServerNum); query.addBindValue(parentid); } @@ -1924,7 +2090,7 @@ void Server::readChannels(Channel *p) { while (query.next()) { c = new Channel(query.value(0).toInt(), query.value(1).toString(), p); - if (! p) + if (!p) c->setParent(this); qhChannels.insert(c->iId, c); c->bInheritACL = query.value(2).toBool(); @@ -1934,7 +2100,7 @@ void Server::readChannels(Channel *p) { query.clear(); - foreach(c, kids) + foreach (c, kids) readChannels(c); } @@ -2003,7 +2169,7 @@ int Server::readLastChannel(int id) { QDateTime last_disconnect = QDateTime::fromString(query.value(1).toString(), Qt::ISODate); last_disconnect.setTimeSpec(Qt::UTC); QDateTime now = QDateTime::currentDateTime(); - now = now.toTimeSpec(Qt::UTC); + now = now.toTimeSpec(Qt::UTC); int duration = Meta::mp.iRememberChanDuration; if (duration <= 0 || last_disconnect.secsTo(now) <= duration) { @@ -2044,23 +2210,22 @@ void Server::dumpChannel(const Channel *c) { qWarning("Channel %s (ACLInherit %d)", qPrintable(c->qsName), c->bInheritACL); qWarning("Description: %s", qPrintable(c->qsDesc)); - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { qWarning("Group %s (Inh %d Able %d)", qPrintable(g->qsName), g->bInherit, g->bInheritable); - foreach(pid, g->qsAdd) + foreach (pid, g->qsAdd) qWarning("Add %d", pid); - foreach(pid, g->qsRemove) + foreach (pid, g->qsRemove) qWarning("Remove %d", pid); } - foreach(acl, c->qlACL) { - int allow = static_cast<int>(acl->pAllow); - int deny = static_cast<int>(acl->pDeny); - qWarning("ChanACL Here %d Sub %d Allow %04x Deny %04x ID %d Group %s", acl->bApplyHere, acl->bApplySubs, allow, deny, acl->iUserId, qPrintable(acl->qsGroup)); + foreach (acl, c->qlACL) { + int allow = static_cast< int >(acl->pAllow); + int deny = static_cast< int >(acl->pDeny); + qWarning("ChanACL Here %d Sub %d Allow %04x Deny %04x ID %d Group %s", acl->bApplyHere, acl->bApplySubs, allow, + deny, acl->iUserId, qPrintable(acl->qsGroup)); } qWarning(" "); - foreach(c, c->qlChannels) { - dumpChannel(c); - } + foreach (c, c->qlChannels) { dumpChannel(c); } } void Server::getBans() { @@ -2073,15 +2238,14 @@ void Server::getBans() { query.addBindValue(iServerNum); SQLEXEC(); while (query.next()) { - Ban ban; ban.haAddress = query.value(0).toByteArray(); - ban.iMask = query.value(1).toInt(); + ban.iMask = query.value(1).toInt(); ban.qsUsername = query.value(2).toString(); - ban.qsHash = query.value(3).toString(); - ban.qsReason = query.value(4).toString(); - ban.qdtStart = query.value(5).toDateTime(); + ban.qsHash = query.value(3).toString(); + ban.qsReason = query.value(4).toString(); + ban.qdtStart = query.value(5).toDateTime(); ban.qdtStart.setTimeSpec(Qt::UTC); ban.iDuration = query.value(6).toInt(); @@ -2098,8 +2262,9 @@ void Server::saveBans() { query.addBindValue(iServerNum); SQLEXEC(); - SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`,`mask`,`name`,`hash`,`reason`,`start`,`duration`) VALUES (?,?,?,?,?,?,?,?)"); - foreach(const Ban &ban, qlBans) { + SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`,`mask`,`name`,`hash`,`reason`,`start`,`duration`) VALUES " + "(?,?,?,?,?,?,?,?)"); + foreach (const Ban &ban, qlBans) { query.addBindValue(iServerNum); query.addBindValue(ban.haAddress.toByteArray()); query.addBindValue(ban.iMask); @@ -2130,10 +2295,10 @@ QVariant ServerDB::getConf(int server_id, const QString &key, QVariant def) { return def; } -QMap<QString, QString> ServerDB::getAllConf(int server_id) { +QMap< QString, QString > ServerDB::getAllConf(int server_id) { TransactionHolder th; - QMap<QString, QString> map; + QMap< QString, QString > map; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `key`, `value` FROM `%1config` WHERE `server_id` = ?"); @@ -2186,10 +2351,10 @@ void ServerDB::wipeLogs() { SQLDO("DELETE FROM %1slog"); } -QList<QPair<unsigned int, QString> > ServerDB::getLog(int server_id, unsigned int offs_min, unsigned int offs_max) { +QList< QPair< unsigned int, QString > > ServerDB::getLog(int server_id, unsigned int offs_min, unsigned int offs_max) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - + if (Meta::mp.qsDBDriver == "QPSQL") { SQLPREP("SELECT `msgtime`, `msg` FROM `%1slog` WHERE `server_id` = ? ORDER BY `msgtime` DESC LIMIT ? OFFSET ?"); query.addBindValue(server_id); @@ -2204,11 +2369,11 @@ QList<QPair<unsigned int, QString> > ServerDB::getLog(int server_id, unsigned in SQLEXEC(); } - QList<QPair<unsigned int, QString> > ql; + QList< QPair< unsigned int, QString > > ql; while (query.next()) { QDateTime qdt = query.value(0).toDateTime(); - QString msg = query.value(1).toString(); - ql << QPair<unsigned int, QString>(qdt.toLocalTime().toTime_t(), msg); + QString msg = query.value(1).toString(); + ql << QPair< unsigned int, QString >(qdt.toLocalTime().toTime_t(), msg); } return ql; } @@ -2240,7 +2405,9 @@ void ServerDB::setConf(int server_id, const QString &k, const QVariant &value) { query.addBindValue(key); } else { if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1config` (`server_id`, `key`, `value`) VALUES (:server_id, :key, :value) ON CONFLICT (`server_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1config`.`server_id` = :u_server_id AND `%1config`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1config` (`server_id`, `key`, `value`) VALUES (:server_id, :key, :value) ON " + "CONFLICT (`server_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1config`.`server_id` = " + ":u_server_id AND `%1config`.`key` = :u_key"); query.bindValue(":server_id", server_id); query.bindValue(":key", key); query.bindValue(":value", value.toString()); @@ -2258,31 +2425,31 @@ void ServerDB::setConf(int server_id, const QString &k, const QVariant &value) { } -QList<int> ServerDB::getAllServers() { +QList< int > ServerDB::getAllServers() { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `server_id` FROM `%1servers`"); SQLEXEC(); - QList<int> ql; + QList< int > ql; while (query.next()) ql << query.value(0).toInt(); return ql; } -QList<int> ServerDB::getBootServers() { - QList<int> ql = getAllServers(); +QList< int > ServerDB::getBootServers() { + QList< int > ql = getAllServers(); TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - QList<int> bootlist; - foreach(int i, ql) { + QList< int > bootlist; + foreach (int i, ql) { SQLPREP("SELECT `value` FROM `%1config` WHERE `server_id` = ? AND `key` = ?"); query.addBindValue(i); query.addBindValue(QLatin1String("boot")); SQLEXEC(); - if (! query.next() || query.value(0).toBool()) + if (!query.next() || query.value(0).toBool()) bootlist << i; } return bootlist; diff --git a/src/murmur/ServerDB.h b/src/murmur/ServerDB.h index 4c7df0038..2b05b0324 100644 --- a/src/murmur/ServerDB.h +++ b/src/murmur/ServerDB.h @@ -19,51 +19,59 @@ class QSqlQuery; class ServerDB : public QObject { Q_OBJECT; - public: - /// A version number that allows us to keep track of changes we make to the DB architecture - /// in order to provide backwards compatibility and perform automatic updates of older DBs. - /// Whenever you change the DB structure (add a new table, added a new column in a table, etc.) - /// you have to increase this version number by one and add the respective "backwards compatibility - /// code" into the ServerDB code. - static const int DB_STRUCTURE_VERSION = 8; - enum ChannelInfo { Channel_Description, Channel_Position, Channel_Max_Users }; - enum UserInfo { User_Name, User_Email, User_Comment, User_Hash, User_Password, User_LastActive, User_KDFIterations }; - ServerDB(); - ~ServerDB(); - typedef QPair<unsigned int, QString> LogRecord; - static Timer tLogClean; - static QSqlDatabase *db; - static QString qsUpgradeSuffix; - static void setSUPW(int iServNum, const QString &pw); - static void disableSU(int srvnum); - static QList<int> getBootServers(); - static QList<int> getAllServers(); - static int addServer(); - static void deleteServer(int server_id); - static bool serverExists(int num); - static QMap<QString, QString> getAllConf(int server_id); - static QVariant getConf(int server_id, const QString &key, QVariant def = QVariant()); - static void setConf(int server_id, const QString &key, const QVariant &value = QVariant()); - static QList<LogRecord> getLog(int server_id, unsigned int offs_min, unsigned int offs_max); - static QString getLegacySHA1Hash(const QString &password); - static int getLogLen(int server_id); - static void wipeLogs(); - static bool prepare(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); - static bool query(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); - static bool exec(QSqlQuery &, const QString &str = QString(), bool fatal= true, bool warn = true); - static bool execBatch(QSqlQuery &, const QString &str = QString(), bool fatal= true); - // No copy; private declaration without implementation - ServerDB(const ServerDB &); - - private: - static void loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query); - static void writeSUPW(int srvnum, const QString &pwHash, const QString &saltHash, const QVariant &kdfIterations); +public: + /// A version number that allows us to keep track of changes we make to the DB architecture + /// in order to provide backwards compatibility and perform automatic updates of older DBs. + /// Whenever you change the DB structure (add a new table, added a new column in a table, etc.) + /// you have to increase this version number by one and add the respective "backwards compatibility + /// code" into the ServerDB code. + static const int DB_STRUCTURE_VERSION = 8; - public slots: - /// Clear last_disconnect date of every user of the server - void clearLastDisconnect(Server *); + enum ChannelInfo { Channel_Description, Channel_Position, Channel_Max_Users }; + enum UserInfo { + User_Name, + User_Email, + User_Comment, + User_Hash, + User_Password, + User_LastActive, + User_KDFIterations + }; + ServerDB(); + ~ServerDB(); + typedef QPair< unsigned int, QString > LogRecord; + static Timer tLogClean; + static QSqlDatabase *db; + static QString qsUpgradeSuffix; + static void setSUPW(int iServNum, const QString &pw); + static void disableSU(int srvnum); + static QList< int > getBootServers(); + static QList< int > getAllServers(); + static int addServer(); + static void deleteServer(int server_id); + static bool serverExists(int num); + static QMap< QString, QString > getAllConf(int server_id); + static QVariant getConf(int server_id, const QString &key, QVariant def = QVariant()); + static void setConf(int server_id, const QString &key, const QVariant &value = QVariant()); + static QList< LogRecord > getLog(int server_id, unsigned int offs_min, unsigned int offs_max); + static QString getLegacySHA1Hash(const QString &password); + static int getLogLen(int server_id); + static void wipeLogs(); + static bool prepare(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); + static bool query(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); + static bool exec(QSqlQuery &, const QString &str = QString(), bool fatal = true, bool warn = true); + static bool execBatch(QSqlQuery &, const QString &str = QString(), bool fatal = true); + // No copy; private declaration without implementation + ServerDB(const ServerDB &); +private: + static void loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query); + static void writeSUPW(int srvnum, const QString &pwHash, const QString &saltHash, const QVariant &kdfIterations); + +public slots: + /// Clear last_disconnect date of every user of the server + void clearLastDisconnect(Server *); }; #endif diff --git a/src/murmur/ServerUser.cpp b/src/murmur/ServerUser.cpp index d55845166..42a9782d2 100644 --- a/src/murmur/ServerUser.cpp +++ b/src/murmur/ServerUser.cpp @@ -9,11 +9,12 @@ #include "Server.h" #ifdef Q_OS_UNIX -# include "Utils.h" +# include "Utils.h" #endif -ServerUser::ServerUser(Server *p, QSslSocket *socket) : Connection(p, socket), User(), s(nullptr), leakyBucket(p->iMessageLimit, p->iMessageBurst) { - sState = ServerUser::Connected; +ServerUser::ServerUser(Server *p, QSslSocket *socket) + : Connection(p, socket), User(), s(nullptr), leakyBucket(p->iMessageLimit, p->iMessageBurst) { + sState = ServerUser::Connected; sUdpSocket = INVALID_SOCKET; memset(&saiUdpAddress, 0, sizeof(saiUdpAddress)); @@ -23,11 +24,11 @@ ServerUser::ServerUser(Server *p, QSslSocket *socket) : Connection(p, socket), U dTCPPingAvg = dTCPPingVar = 0.0f; uiUDPPackets = uiTCPPackets = 0; - aiUdpFlag = 1; - uiVersion = 0; - bVerified = true; + aiUdpFlag = 1; + uiVersion = 0; + bVerified = true; iLastPermissionCheck = -1; - + bOpus = false; } @@ -37,8 +38,8 @@ ServerUser::operator QString() const { } BandwidthRecord::BandwidthRecord() { iRecNum = 0; - iSum = 0; - for (int i=0;i<N_BANDWIDTH_SLOTS;i++) + iSum = 0; + for (int i = 0; i < N_BANDWIDTH_SLOTS; i++) a_iBW[i] = 0; } @@ -50,13 +51,13 @@ bool BandwidthRecord::addFrame(int size, int maxpersec) { if (elapsed == 0) return false; - int nsum = iSum-a_iBW[iRecNum]+size; - int bw = static_cast<int>((nsum * 1000000LL) / elapsed); + int nsum = iSum - a_iBW[iRecNum] + size; + int bw = static_cast< int >((nsum * 1000000LL) / elapsed); if (bw > maxpersec) return false; - a_iBW[iRecNum] = static_cast<unsigned short>(size); + a_iBW[iRecNum] = static_cast< unsigned short >(size); a_qtWhen[iRecNum].restart(); iSum = nsum; @@ -71,7 +72,7 @@ bool BandwidthRecord::addFrame(int size, int maxpersec) { int BandwidthRecord::onlineSeconds() const { QMutexLocker ml(&qmMutex); - return static_cast<int>(tFirst.elapsed() / 1000000LL); + return static_cast< int >(tFirst.elapsed() / 1000000LL); } int BandwidthRecord::idleSeconds() const { @@ -81,7 +82,7 @@ int BandwidthRecord::idleSeconds() const { if (tIdleControl.elapsed() < iIdle) iIdle = tIdleControl.elapsed(); - return static_cast<int>(iIdle / 1000000LL); + return static_cast< int >(iIdle / 1000000LL); } void BandwidthRecord::resetIdleSeconds() { @@ -93,11 +94,11 @@ void BandwidthRecord::resetIdleSeconds() { int BandwidthRecord::bandwidth() const { QMutexLocker ml(&qmMutex); - int sum = 0; + int sum = 0; quint64 elapsed = 0ULL; - for (int i=1;i<N_BANDWIDTH_SLOTS;++i) { - int idx = (iRecNum + N_BANDWIDTH_SLOTS - i) % N_BANDWIDTH_SLOTS; + for (int i = 1; i < N_BANDWIDTH_SLOTS; ++i) { + int idx = (iRecNum + N_BANDWIDTH_SLOTS - i) % N_BANDWIDTH_SLOTS; quint64 e = a_qtWhen[idx].elapsed(); if (e > 1000000ULL) { break; @@ -110,21 +111,18 @@ int BandwidthRecord::bandwidth() const { if (elapsed < 250000ULL) return 0; - return static_cast<int>((sum * 1000000ULL) / elapsed); + return static_cast< int >((sum * 1000000ULL) / elapsed); } LeakyBucket::LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens) - : m_tokensPerSec(tokensPerSec), - m_maxTokens(maxTokens), - m_currentTokens(0), - m_timer() { - m_timer.start(); - - if (!QElapsedTimer::isMonotonic()) { - qFatal("Non-monotonic clocks are not reliable enough and lead to issues as " - "https://github.com/mumble-voip/mumble/issues/3985. " - "This is a serious issue and should be reported!"); - } + : m_tokensPerSec(tokensPerSec), m_maxTokens(maxTokens), m_currentTokens(0), m_timer() { + m_timer.start(); + + if (!QElapsedTimer::isMonotonic()) { + qFatal("Non-monotonic clocks are not reliable enough and lead to issues as " + "https://github.com/mumble-voip/mumble/issues/3985. " + "This is a serious issue and should be reported!"); + } } bool LeakyBucket::ratelimit(int tokens) { @@ -172,7 +170,7 @@ bool LeakyBucket::ratelimit(int tokens) { } // Make sure that m_currentTokens never gets less than 0 by draining - if (static_cast<qint64>(m_currentTokens) < drainTokens) { + if (static_cast< qint64 >(m_currentTokens) < drainTokens) { m_currentTokens = 0; } else { m_currentTokens -= drainTokens; @@ -182,7 +180,7 @@ bool LeakyBucket::ratelimit(int tokens) { // the imaginary leaking bucket, we can check whether the given amount of tokens // still fit in this imaginary bucket (and thus the corresponding message may pass) // or if it doesn't (and thus the message will be limited (rejected)) - bool limit = m_currentTokens > ((static_cast<long>(m_maxTokens)) - tokens); + bool limit = m_currentTokens > ((static_cast< long >(m_maxTokens)) - tokens); // If the bucket is not overflowed, allow message and add tokens if (!limit) { diff --git a/src/murmur/ServerUser.h b/src/murmur/ServerUser.h index e89eaea62..c5ab6dda1 100644 --- a/src/murmur/ServerUser.h +++ b/src/murmur/ServerUser.h @@ -9,21 +9,21 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Connection.h" +#include "HostAddress.h" #include "Timer.h" #include "User.h" -#include "HostAddress.h" -#include <QtCore/QStringList> #include <QtCore/QElapsedTimer> +#include <QtCore/QStringList> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <sys/socket.h> +# include <sys/socket.h> #endif // Unfortunately, this needs to be "large enough" to hold @@ -56,16 +56,16 @@ struct WhisperTarget { bool bLinks; QString qsGroup; }; - QList<unsigned int> qlSessions; - QList<WhisperTarget::Channel> qlChannels; + QList< unsigned int > qlSessions; + QList< WhisperTarget::Channel > qlChannels; }; class ServerUser; struct WhisperTargetCache { - QSet<ServerUser *> channelTargets; - QSet<ServerUser *> directTargets; - QSet<ServerUser *> listeningTargets; + QSet< ServerUser * > channelTargets; + QSet< ServerUser * > directTargets; + QSet< ServerUser * > listeningTargets; }; class Server; @@ -73,91 +73,92 @@ class Server; /// A simple implementation for rate-limiting. /// See https://en.wikipedia.org/wiki/Leaky_bucket class LeakyBucket { - private: - /// The amount of tokens that are drained per second. - /// (The sze of the whole in the bucket) - unsigned int m_tokensPerSec; - /// The maximum amount of tokens that may be encountered. - /// (The capacity of the bucket) - unsigned int m_maxTokens; - /// The amount of tokens currently stored - /// (The amount of whater currently in the bucket) - long m_currentTokens; - /// A timer that is used to measure time intervals. It is essential - /// that this timer uses a monotonic clock (which is why QElapsedTimer is - /// used instead of QTime or QDateTime). - QElapsedTimer m_timer; - - public: - /// @param tokens The amount of tokens that should be added. - /// @returns Whether adding this amount of tokens triggers rate - /// limiting (true means the corresponding packet has to be - /// discared and false means the packet may be processed) - bool ratelimit(int tokens); - - LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens); +private: + /// The amount of tokens that are drained per second. + /// (The sze of the whole in the bucket) + unsigned int m_tokensPerSec; + /// The maximum amount of tokens that may be encountered. + /// (The capacity of the bucket) + unsigned int m_maxTokens; + /// The amount of tokens currently stored + /// (The amount of whater currently in the bucket) + long m_currentTokens; + /// A timer that is used to measure time intervals. It is essential + /// that this timer uses a monotonic clock (which is why QElapsedTimer is + /// used instead of QTime or QDateTime). + QElapsedTimer m_timer; + +public: + /// @param tokens The amount of tokens that should be added. + /// @returns Whether adding this amount of tokens triggers rate + /// limiting (true means the corresponding packet has to be + /// discared and false means the packet may be processed) + bool ratelimit(int tokens); + + LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens); }; class ServerUser : public Connection, public User { - private: - Q_OBJECT - Q_DISABLE_COPY(ServerUser) - protected: - Server *s; - public: - enum State { Connected, Authenticated }; - State sState; - operator QString() const; - - float dUDPPingAvg, dUDPPingVar; - float dTCPPingAvg, dTCPPingVar; - quint32 uiUDPPackets, uiTCPPackets; - - unsigned int uiVersion; - QString qsRelease; - QString qsOS; - QString qsOSVersion; - - std::string ssContext; - QString qsIdentity; - - bool bVerified; - QStringList qslEmail; - - HostAddress haAddress; - - /// Holds whether the user is using TCP - /// or UDP for voice packets. - /// - /// If the flag is 0, the user is using - /// TCP. - /// - /// If the flag is 1, the user is using - /// UDP. - QAtomicInt aiUdpFlag; - - QList<int> qlCodecs; - bool bOpus; - - QStringList qslAccessTokens; - - QMap<int, WhisperTarget> qmTargets; - QMap<int, WhisperTargetCache> qmTargetCache; - QMap<QString, QString> qmWhisperRedirect; - - LeakyBucket leakyBucket; - - int iLastPermissionCheck; - QMap<int, unsigned int> qmPermissionSent; +private: + Q_OBJECT + Q_DISABLE_COPY(ServerUser) +protected: + Server *s; + +public: + enum State { Connected, Authenticated }; + State sState; + operator QString() const; + + float dUDPPingAvg, dUDPPingVar; + float dTCPPingAvg, dTCPPingVar; + quint32 uiUDPPackets, uiTCPPackets; + + unsigned int uiVersion; + QString qsRelease; + QString qsOS; + QString qsOSVersion; + + std::string ssContext; + QString qsIdentity; + + bool bVerified; + QStringList qslEmail; + + HostAddress haAddress; + + /// Holds whether the user is using TCP + /// or UDP for voice packets. + /// + /// If the flag is 0, the user is using + /// TCP. + /// + /// If the flag is 1, the user is using + /// UDP. + QAtomicInt aiUdpFlag; + + QList< int > qlCodecs; + bool bOpus; + + QStringList qslAccessTokens; + + QMap< int, WhisperTarget > qmTargets; + QMap< int, WhisperTargetCache > qmTargetCache; + QMap< QString, QString > qmWhisperRedirect; + + LeakyBucket leakyBucket; + + int iLastPermissionCheck; + QMap< int, unsigned int > qmPermissionSent; #ifdef Q_OS_UNIX - int sUdpSocket; + int sUdpSocket; #else - SOCKET sUdpSocket; + SOCKET sUdpSocket; #endif - BandwidthRecord bwr; - struct sockaddr_storage saiUdpAddress; - struct sockaddr_storage saiTcpLocalAddress; - ServerUser(Server *parent, QSslSocket *socket); + BandwidthRecord bwr; + struct sockaddr_storage saiUdpAddress; + struct sockaddr_storage saiTcpLocalAddress; + ServerUser(Server *parent, QSslSocket *socket); }; #endif diff --git a/src/murmur/Tray.cpp b/src/murmur/Tray.cpp index 6c5a876a8..8fed8a85e 100644 --- a/src/murmur/Tray.cpp +++ b/src/murmur/Tray.cpp @@ -6,10 +6,10 @@ #include "Tray.h" #include "About.h" +#include "LogEmitter.h" #include "Meta.h" #include "Server.h" #include "Version.h" -#include "LogEmitter.h" #include <QtWidgets/QAction> #include <QtWidgets/QApplication> @@ -54,12 +54,15 @@ Tray::Tray(QObject *p, LogEmitter *logger) : QObject(p) { void Tray::on_Tray_activated(QSystemTrayIcon::ActivationReason r) { if (r == QSystemTrayIcon::Trigger) { - qsti->showMessage(tr("Murmur"), tr("%1 server running.").arg(meta->qhServers.count()), QSystemTrayIcon::Information, 5000); + qsti->showMessage(tr("Murmur"), tr("%1 server running.").arg(meta->qhServers.count()), + QSystemTrayIcon::Information, 5000); } } void Tray::on_Quit_triggered() { - if (QMessageBox::question(nullptr, tr("Murmur"), tr("Are you sure you want to quit Murmur?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { + if (QMessageBox::question(nullptr, tr("Murmur"), tr("Are you sure you want to quit Murmur?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) + == QMessageBox::Yes) { qApp->quit(); } } @@ -79,7 +82,7 @@ void Tray::on_ShowLog_triggered() { connect(le, SIGNAL(newLogEntry(const QString &)), tb, SLOT(append(const QString &))); - foreach(const QString &m, qlLog) + foreach (const QString &m, qlLog) tb->append(m); mw->show(); diff --git a/src/murmur/Tray.h b/src/murmur/Tray.h index fec537411..43dc5881a 100644 --- a/src/murmur/Tray.h +++ b/src/murmur/Tray.h @@ -6,33 +6,35 @@ #ifndef MUMBLE_MURMUR_TRAY_H_ #define MUMBLE_MURMUR_TRAY_H_ -#include <QtCore/QStringList> #include <QtCore/QObject> +#include <QtCore/QStringList> #include <QtWidgets/QSystemTrayIcon> class LogEmitter; class QAction; class Tray : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(Tray); - protected: - QSystemTrayIcon *qsti; - QMenu *qm; - QAction *qaQuit; - QAction *qaAbout; - QAction *qaShowLog; - QStringList qlLog; - LogEmitter *le; - public slots: - void on_Tray_activated(QSystemTrayIcon::ActivationReason); - void on_About_triggered(); - void on_Quit_triggered(); - void on_ShowLog_triggered(); - void addLogMessage(const QString &); - public: - Tray(QObject *parent, LogEmitter *le); +private: + Q_OBJECT + Q_DISABLE_COPY(Tray); + +protected: + QSystemTrayIcon *qsti; + QMenu *qm; + QAction *qaQuit; + QAction *qaAbout; + QAction *qaShowLog; + QStringList qlLog; + LogEmitter *le; +public slots: + void on_Tray_activated(QSystemTrayIcon::ActivationReason); + void on_About_triggered(); + void on_Quit_triggered(); + void on_ShowLog_triggered(); + void addLogMessage(const QString &); + +public: + Tray(QObject *parent, LogEmitter *le); }; #endif diff --git a/src/murmur/UnixMurmur.cpp b/src/murmur/UnixMurmur.cpp index 2b2abd0ec..68159177e 100644 --- a/src/murmur/UnixMurmur.cpp +++ b/src/murmur/UnixMurmur.cpp @@ -5,8 +5,8 @@ #include "UnixMurmur.h" -#include "Meta.h" #include "EnvUtils.h" +#include "Meta.h" #include <QtCore/QAbstractEventDispatcher> #include <QtCore/QCoreApplication> @@ -18,9 +18,9 @@ #include <signal.h> #ifdef Q_OS_LINUX -# include <sys/capability.h> -# include <sys/prctl.h> -# include <sys/resource.h> +# include <sys/capability.h> +# include <sys/prctl.h> +# include <sys/resource.h> #endif #include <sys/socket.h> @@ -45,11 +45,13 @@ void LimitTest::run() { void LimitTest::testLimits(QCoreApplication &a) { QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(); if (QLatin1String(ed->metaObject()->className()) != QLatin1String("QEventDispatcherGlib")) - qWarning("Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", FD_SETSIZE); + qWarning( + "Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", + FD_SETSIZE); qWarning("Running descriptor test."); int count; - QList<QFile *> ql; - for (count=0;count < 524288; ++count) { + QList< QFile * > ql; + for (count = 0; count < 524288; ++count) { QFile *qf = new QFile(a.applicationFilePath()); if (qf->open(QIODevice::ReadOnly)) ql.prepend(qf); @@ -58,13 +60,13 @@ void LimitTest::testLimits(QCoreApplication &a) { if ((count & 1023) == 0) qWarning("%d descriptors...", count); } - foreach(QFile *qf, ql) + foreach (QFile *qf, ql) delete qf; ql.clear(); qCritical("Managed to open %d descriptors", count); - qm = new QMutex(); - qw = new QWaitCondition(); + qm = new QMutex(); + qw = new QWaitCondition(); qstartw = new QWaitCondition(); int fdcount = count / 8; @@ -72,16 +74,16 @@ void LimitTest::testLimits(QCoreApplication &a) { if (fdcount > 1024) fdcount = 1024; - QList<LimitTest *> qtl; - for (count=0;count < fdcount; ++count) { + QList< LimitTest * > qtl; + for (count = 0; count < fdcount; ++count) { LimitTest *t = new LimitTest(); - t->tid = count; + t->tid = count; qtl << t; qm->lock(); t->start(); qstartw->wait(qm); qm->unlock(); - if (! t->isRunning()) + if (!t->isRunning()) break; if ((count & 511) == 0) qWarning("%d threads...", count); @@ -90,8 +92,8 @@ void LimitTest::testLimits(QCoreApplication &a) { qw->wakeAll(); qm->unlock(); - foreach(LimitTest *qt, qtl) { - if (! qt->wait(1000)) { + foreach (LimitTest *qt, qtl) { + if (!qt->wait(1000)) { qWarning("Thread %d failed to terminate...", qt->tid); qt->terminate(); } @@ -106,7 +108,7 @@ int UnixMurmur::iTermFd[2]; int UnixMurmur::iUsr1Fd[2]; UnixMurmur::UnixMurmur() { - bRoot = true; + bRoot = true; logToSyslog = false; if (geteuid() != 0 && getuid() != 0) { @@ -121,7 +123,7 @@ UnixMurmur::UnixMurmur() { if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iUsr1Fd)) qFatal("Couldn't create USR1 socketpair"); - qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); + qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); qsnTerm = new QSocketNotifier(iTermFd[1], QSocketNotifier::Read, this); qsnUsr1 = new QSocketNotifier(iUsr1Fd[1], QSocketNotifier::Read, this); @@ -160,7 +162,7 @@ UnixMurmur::~UnixMurmur() { delete qsnTerm; delete qsnUsr1; - qsnHup = nullptr; + qsnHup = nullptr; qsnTerm = nullptr; qsnUsr1 = nullptr; @@ -173,19 +175,19 @@ UnixMurmur::~UnixMurmur() { } void UnixMurmur::hupSignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iHupFd[0], &a, sizeof(a)); Q_UNUSED(len); } void UnixMurmur::termSignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iTermFd[0], &a, sizeof(a)); Q_UNUSED(len); } void UnixMurmur::usr1SignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iUsr1Fd[0], &a, sizeof(a)); Q_UNUSED(len); } @@ -201,17 +203,17 @@ void UnixMurmur::handleSigHup() { if (logToSyslog) { qWarning("Caught SIGHUP, but logging to syslog"); - } else if (! qfLog) { + } else if (!qfLog) { qWarning("Caught SIGHUP, but logfile not in use"); - } else if (! qfLog->isOpen()) { + } else if (!qfLog->isOpen()) { qWarning("Caught SIGHUP, but logfile not in use -- interpreting as hint to quit"); QCoreApplication::instance()->quit(); } else { qWarning("Caught SIGHUP, will reopen %s", qPrintable(Meta::mp.qsLogfile)); QFile *newlog = new QFile(Meta::mp.qsLogfile); - bool result = newlog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); - if (! result) { + bool result = newlog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); + if (!result) { delete newlog; qCritical("Failed to reopen logfile for writing, keeping old log"); } else { @@ -252,7 +254,8 @@ void UnixMurmur::handleSigUsr1() { if (ok) { qWarning("UnixMurmur: Done reloading SSL settings."); } else { - qWarning("UnixMurmur: Failed to reload SSL settings. Server state is intact and fully operational. No configuration changes were made."); + qWarning("UnixMurmur: Failed to reload SSL settings. Server state is intact and fully operational. No " + "configuration changes were made."); } } @@ -263,7 +266,7 @@ void UnixMurmur::setuid() { if (Meta::mp.uiUid != 0) { #ifdef Q_OS_DARWIN qCritical("WARNING: You are launching murmurd as root on Mac OS X or Darwin. Murmur does not need " - "special privileges to set itself up on these systems, so this behavior is highly discouraged."); + "special privileges to set itself up on these systems, so this behavior is highly discouraged."); if (::setgid(Meta::mp.uiGid) != 0) qFatal("Failed to switch to gid %d", Meta::mp.uiGid); @@ -272,8 +275,7 @@ void UnixMurmur::setuid() { uid_t uid = getuid(), euid = geteuid(); gid_t gid = getgid(), egid = getegid(); - if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid - && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { + if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); } else qFatal("Couldn't switch uid/gid."); @@ -296,18 +298,19 @@ void UnixMurmur::setuid() { } #endif } else if (bRoot) { - qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a security risk."); + qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a " + "security risk."); } } void UnixMurmur::initialcap() { #ifdef Q_OS_LINUX - cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; + cap_value_t caps[] = { CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; - if (! bRoot) + if (!bRoot) return; - int ncap = sizeof(caps)/sizeof(cap_value_t); + int ncap = sizeof(caps) / sizeof(cap_value_t); if (geteuid() != 0) ncap--; @@ -328,10 +331,10 @@ void UnixMurmur::initialcap() { void UnixMurmur::finalcap() { #ifdef Q_OS_LINUX - cap_value_t caps[] = {CAP_SYS_RESOURCE}; + cap_value_t caps[] = { CAP_SYS_RESOURCE }; struct rlimit r; - if (! bRoot) + if (!bRoot) return; if (getrlimit(RLIMIT_RTPRIO, &r) != 0) { @@ -344,7 +347,7 @@ void UnixMurmur::finalcap() { } } - int ncap = sizeof(caps)/sizeof(cap_value_t); + int ncap = sizeof(caps) / sizeof(cap_value_t); cap_t c = cap_init(); cap_clear(c); @@ -359,7 +362,7 @@ void UnixMurmur::finalcap() { #endif } -const QString UnixMurmur::trySystemIniFiles(const QString& fname) { +const QString UnixMurmur::trySystemIniFiles(const QString &fname) { QString file = fname; if (!file.isEmpty()) return file; @@ -374,7 +377,7 @@ const QString UnixMurmur::trySystemIniFiles(const QString& fname) { inipaths << QLatin1String("/etc/mumble-server.ini"); inipaths << QLatin1String("/etc/murmur.ini"); - foreach(const QString &f, inipaths) { + foreach (const QString &f, inipaths) { QFileInfo fi(f); if (fi.exists() && fi.isReadable()) { file = fi.absoluteFilePath(); diff --git a/src/murmur/UnixMurmur.h b/src/murmur/UnixMurmur.h index 86950d7d8..faf63d318 100644 --- a/src/murmur/UnixMurmur.h +++ b/src/murmur/UnixMurmur.h @@ -15,43 +15,45 @@ class QSocketNotifier; class QWaitCondition; class LimitTest : public QThread { - Q_OBJECT - Q_DISABLE_COPY(LimitTest) - protected: - static QMutex *qm; - static QWaitCondition *qw, *qstartw; - LimitTest(); - public: - int tid; - void run(); - static void testLimits(QCoreApplication &); + Q_OBJECT + Q_DISABLE_COPY(LimitTest) +protected: + static QMutex *qm; + static QWaitCondition *qw, *qstartw; + LimitTest(); + +public: + int tid; + void run(); + static void testLimits(QCoreApplication &); }; class UnixMurmur : public QObject { - Q_OBJECT - Q_DISABLE_COPY(UnixMurmur) - protected: - bool bRoot; - static int iHupFd[2], iTermFd[2], iUsr1Fd[2]; - QSocketNotifier *qsnHup, *qsnTerm, *qsnUsr1; - - static void hupSignalHandler(int); - static void termSignalHandler(int); - static void usr1SignalHandler(int); - public slots: - void handleSigHup(); - void handleSigTerm(); - void handleSigUsr1(); - public: - bool logToSyslog; - - void setuid(); - void initialcap(); - void finalcap(); - const QString trySystemIniFiles(const QString& fname); - - UnixMurmur(); - ~UnixMurmur(); + Q_OBJECT + Q_DISABLE_COPY(UnixMurmur) +protected: + bool bRoot; + static int iHupFd[2], iTermFd[2], iUsr1Fd[2]; + QSocketNotifier *qsnHup, *qsnTerm, *qsnUsr1; + + static void hupSignalHandler(int); + static void termSignalHandler(int); + static void usr1SignalHandler(int); +public slots: + void handleSigHup(); + void handleSigTerm(); + void handleSigUsr1(); + +public: + bool logToSyslog; + + void setuid(); + void initialcap(); + void finalcap(); + const QString trySystemIniFiles(const QString &fname); + + UnixMurmur(); + ~UnixMurmur(); }; #endif diff --git a/src/murmur/main.cpp b/src/murmur/main.cpp index e194991df..1aff85a40 100644 --- a/src/murmur/main.cpp +++ b/src/murmur/main.cpp @@ -4,43 +4,43 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_DBUS -# include "DBus.h" +# include "DBus.h" #endif +#include "EnvUtils.h" +#include "License.h" +#include "LogEmitter.h" +#include "Meta.h" +#include "SSL.h" #include "Server.h" #include "ServerDB.h" -#include "Meta.h" #include "Version.h" -#include "SSL.h" -#include "License.h" -#include "LogEmitter.h" -#include "EnvUtils.h" #ifdef Q_OS_WIN -# include "About.h" -# include "Tray.h" +# include "About.h" +# include "Tray.h" -# include <QtWidgets/QApplication> +# include <QtWidgets/QApplication> #else -# include "UnixMurmur.h" +# include "UnixMurmur.h" -# include <QtCore/QCoreApplication> +# include <QtCore/QCoreApplication> #endif #include <QtCore/QTextCodec> #ifdef USE_DBUS -# include <QtDBus/QDBusError> -# include <QtDBus/QDBusServer> +# include <QtDBus/QDBusError> +# include <QtDBus/QDBusServer> #endif #include <openssl/crypto.h> #ifdef Q_OS_WIN -# include <intrin.h> +# include <intrin.h> #else -# include <fcntl.h> -# include <sys/syslog.h> +# include <fcntl.h> +# include <sys/syslog.h> #endif QFile *qfLog = nullptr; @@ -67,19 +67,19 @@ static void murmurMessageOutputQString(QtMsgType type, const QString &msg) { if (unixMurmur->logToSyslog) { int level; switch (type) { - case QtDebugMsg: - level = LOG_DEBUG; - break; - case QtWarningMsg: - level = LOG_WARNING; - break; - case QtCriticalMsg: - level = LOG_CRIT; - break; - case QtFatalMsg: - default: - level = LOG_ALERT; - break; + case QtDebugMsg: + level = LOG_DEBUG; + break; + case QtWarningMsg: + level = LOG_WARNING; + break; + case QtCriticalMsg: + level = LOG_CRIT; + break; + case QtFatalMsg: + default: + level = LOG_ALERT; + break; } syslog(level, "%s", qPrintable(msg)); if (type == QtFatalMsg) { @@ -92,39 +92,42 @@ static void murmurMessageOutputQString(QtMsgType type, const QString &msg) { char c; switch (type) { case QtDebugMsg: - if (! bVerbose) + if (!bVerbose) return; - c='D'; + c = 'D'; break; case QtWarningMsg: - c='W'; + c = 'W'; break; case QtCriticalMsg: - c='C'; + c = 'C'; break; case QtFatalMsg: - c='F'; + c = 'F'; break; default: - c='X'; + c = 'X'; } - QString m= QString::fromLatin1("<%1>%2 %3").arg(QChar::fromLatin1(c)).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(msg); + QString m = QString::fromLatin1("<%1>%2 %3") + .arg(QChar::fromLatin1(c)) + .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")) + .arg(msg); - if (! qfLog || ! qfLog->isOpen()) { + if (!qfLog || !qfLog->isOpen()) { #ifdef Q_OS_UNIX - if (! detach) + if (!detach) fprintf(stderr, "%s\n", qPrintable(m)); else qlErrors << m; #else qlErrors << m; -#ifndef QT_NO_DEBUG +# ifndef QT_NO_DEBUG fprintf(stderr, "%s\n", qPrintable(m)); -#endif +# endif #endif } else { - if (! qlErrors.isEmpty()) { - foreach(const QString &e, qlErrors) { + if (!qlErrors.isEmpty()) { + foreach (const QString &e, qlErrors) { qfLog->write(e.toUtf8()); qfLog->write("\n"); } @@ -174,9 +177,10 @@ int main(int argc, char **argv) { int cpuinfo[4]; __cpuid(cpuinfo, 1); -#define MMXSSE 0x02800000 +# define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { - ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); + ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", + MB_OK | MB_ICONERROR); exit(0); } @@ -199,9 +203,9 @@ int main(int argc, char **argv) { icon.addFile(QLatin1String(":/murmur.64x64.png")); a.setWindowIcon(icon); #else -#ifndef Q_OS_MAC +# ifndef Q_OS_MAC EnvUtils::setenv(QLatin1String("AVAHI_COMPAT_NOWARN"), QLatin1String("1")); -#endif +# endif QCoreApplication a(argc, argv); UnixMurmur unixhandler; unixMurmur = &unixhandler; @@ -224,7 +228,8 @@ int main(int argc, char **argv) { if (path.isEmpty()) { qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; } else { - QString newPath = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(path); + QString newPath = + QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(path); if (!EnvUtils::setenv(QLatin1String("PATH"), newPath)) { qWarning() << "Failed to set PATH. DBus bindings may not work."; } @@ -235,16 +240,16 @@ int main(int argc, char **argv) { QString inifile; QString supw; bool disableSu = false; - bool wipeSsl = false; - bool wipeLogs = false; - int sunum = 1; + bool wipeSsl = false; + bool wipeLogs = false; + int sunum = 1; #ifdef Q_OS_UNIX bool readPw = false; #endif bool logGroups = false; - bool logACL = false; + bool logACL = false; -#if QT_VERSION < QT_VERSION_CHECK(5,10,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // For Qt >= 5.10 we use QRandomNumberGenerator that is seeded automatically qsrand(QDateTime::currentDateTime().toTime_t()); #endif @@ -257,14 +262,14 @@ int main(int argc, char **argv) { QStringList args = a.arguments(); for (int i = 1; i < args.size(); i++) { - bool bLast = false; + bool bLast = false; QString arg = args.at(i).toLower(); if ((arg == "-supw")) { detach = false; - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; supw = args.at(i); - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; sunum = args.at(i).toInt(); } @@ -280,21 +285,21 @@ int main(int argc, char **argv) { } else if ((arg == "-readsupw")) { detach = false; readPw = true; - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; sunum = args.at(i).toInt(); } bLast = true; #endif } else if ((arg == "-disablesu")) { - detach = false; - disableSu = true; - if (i+1 < args.size()) { - i++; - sunum = args.at(i).toInt(); - } - bLast = true; - } else if ((arg == "-ini") && (i+1 < args.size())) { + detach = false; + disableSu = true; + if (i + 1 < args.size()) { + i++; + sunum = args.at(i).toInt(); + } + bLast = true; + } else if ((arg == "-ini") && (i + 1 < args.size())) { i++; inifile = args.at(i); } else if ((arg == "-wipessl")) { @@ -327,7 +332,8 @@ int main(int argc, char **argv) { qInfo("%s\n", qPrintable(License::authors())); return 0; #endif - } else if (args.at(i) == QLatin1String("-third-party-licenses") || args.at(i) == QLatin1String("--third-party-licenses")) { + } else if (args.at(i) == QLatin1String("-third-party-licenses") + || args.at(i) == QLatin1String("--third-party-licenses")) { #ifdef Q_OS_WIN AboutDialog ad(nullptr, AboutDialogOptionsShowThirdPartyLicenses); ad.exec(); @@ -339,35 +345,36 @@ int main(int argc, char **argv) { } else if ((arg == "-h") || (arg == "-help") || (arg == "--help")) { detach = false; qInfo("Usage: %s [-ini <inifile>] [-supw <password>]\n" - " -ini <inifile> Specify ini file to use.\n" - " -supw <pw> [srv] Set password for 'SuperUser' account on server srv.\n" + " -ini <inifile> Specify ini file to use.\n" + " -supw <pw> [srv] Set password for 'SuperUser' account on server srv.\n" #ifdef Q_OS_UNIX - " -readsupw [srv] Reads password for server srv from standard input.\n" + " -readsupw [srv] Reads password for server srv from standard input.\n" #endif - " -disablesu [srv] Disable password for 'SuperUser' account on server srv.\n" + " -disablesu [srv] Disable password for 'SuperUser' account on server srv.\n" #ifdef Q_OS_UNIX - " -limits Tests and shows how many file descriptors and threads can be created.\n" - " The purpose of this option is to test how many clients Murmur can handle.\n" - " Murmur will exit after this test.\n" + " -limits Tests and shows how many file descriptors and threads can be created.\n" + " The purpose of this option is to test how many clients Murmur can handle.\n" + " Murmur will exit after this test.\n" #endif - " -v Use verbose logging (include debug-logs).\n" + " -v Use verbose logging (include debug-logs).\n" #ifdef Q_OS_UNIX - " -fg Don't detach from console.\n" + " -fg Don't detach from console.\n" #else - " -fg Don't write to the log file.\n" -#endif - " -wipessl Remove SSL certificates from database.\n" - " -wipelogs Remove all log entries from database.\n" - " -loggroups Turns on logging for group changes for all servers." - " -logacls Turns on logging for ACL changes for all servers." - " -version Show version information.\n" - "\n" - " -license Show Murmur's license.\n" - " -authors Show Murmur's authors.\n" - " -third-party-licenses Show licenses for third-party software used by Murmur.\n" - "\n" - "If no inifile is provided, murmur will search for one in \n" - "default locations.", qPrintable(args.at(0))); + " -fg Don't write to the log file.\n" +#endif + " -wipessl Remove SSL certificates from database.\n" + " -wipelogs Remove all log entries from database.\n" + " -loggroups Turns on logging for group changes for all servers." + " -logacls Turns on logging for ACL changes for all servers." + " -version Show version information.\n" + "\n" + " -license Show Murmur's license.\n" + " -authors Show Murmur's authors.\n" + " -third-party-licenses Show licenses for third-party software used by Murmur.\n" + "\n" + "If no inifile is provided, murmur will search for one in \n" + "default locations.", + qPrintable(args.at(0))); return 0; #ifdef Q_OS_UNIX } else if (arg == "-limits") { @@ -385,7 +392,7 @@ int main(int argc, char **argv) { detach = false; qFatal("Unknown argument %s", qPrintable(args.at(i))); } - if (bLast && (i+1 != args.size())) { + if (bLast && (i + 1 != args.size())) { detach = false; qFatal("Password arguments must be last."); } @@ -415,16 +422,17 @@ int main(int argc, char **argv) { // http://article.gmane.org/gmane.comp.security.oss.general/4404 #ifdef Q_OS_UNIX unixhandler.logToSyslog = Meta::mp.qsLogfile == QLatin1String("syslog"); - if (detach && ! Meta::mp.qsLogfile.isEmpty() && !unixhandler.logToSyslog) { + if (detach && !Meta::mp.qsLogfile.isEmpty() && !unixhandler.logToSyslog) { #else - if (detach && ! Meta::mp.qsLogfile.isEmpty()) { + if (detach && !Meta::mp.qsLogfile.isEmpty()) { #endif qfLog = new QFile(Meta::mp.qsLogfile); - if (! qfLog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { + if (!qfLog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { delete qfLog; qfLog = nullptr; #ifdef Q_OS_UNIX - fprintf(stderr, "murmurd: failed to open logfile %s: no logging will be done\n", qPrintable(Meta::mp.qsLogfile)); + fprintf(stderr, "murmurd: failed to open logfile %s: no logging will be done\n", + qPrintable(Meta::mp.qsLogfile)); #else qWarning("Failed to open logfile %s. No logging will be performed.", qPrintable(Meta::mp.qsLogfile)); #endif @@ -434,7 +442,8 @@ int main(int argc, char **argv) { Meta::mp.qsLogfile = qfi.absoluteFilePath(); #ifdef Q_OS_UNIX if (Meta::mp.uiUid != 0 && fchown(qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid) == -1) { - qFatal("can't change log file owner to %d %d:%d - %s", qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid, strerror(errno)); + qFatal("can't change log file owner to %d %d:%d - %s", qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid, + strerror(errno)); } #endif } @@ -489,14 +498,14 @@ int main(int argc, char **argv) { } if (disableSu) { - ServerDB::disableSU(sunum); - qInfo("SuperUser password disabled on server %d", sunum); - return 0; + ServerDB::disableSU(sunum); + qInfo("SuperUser password disabled on server %d", sunum); + return 0; } if (wipeSsl) { qWarning("Removing all per-server SSL certificates from the database."); - foreach(int sid, ServerDB::getAllServers()) { + foreach (int sid, ServerDB::getAllServers()) { ServerDB::setConf(sid, "key"); ServerDB::setConf(sid, "certificate"); ServerDB::setConf(sid, "passphrase"); @@ -519,7 +528,7 @@ int main(int argc, char **argv) { _exit(0); } - if (! Meta::mp.qsPid.isEmpty()) { + if (!Meta::mp.qsPid.isEmpty()) { QFile pid(Meta::mp.qsPid); if (pid.open(QIODevice::WriteOnly)) { QFileInfo fi(pid); @@ -553,7 +562,7 @@ int main(int argc, char **argv) { #ifdef USE_DBUS MurmurDBus::registerTypes(); - if (! Meta::mp.qsDBus.isEmpty()) { + if (!Meta::mp.qsDBus.isEmpty()) { if (Meta::mp.qsDBus == "session") MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::sessionBus()); else if (Meta::mp.qsDBus == "system") @@ -562,21 +571,22 @@ int main(int argc, char **argv) { // QtDBus is not quite finished yet. qWarning("Warning: Peer-to-peer session support is currently nonworking."); MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::connectToBus(Meta::mp.qsDBus, "mainbus")); - if (! MurmurDBus::qdbc->isConnected()) { + if (!MurmurDBus::qdbc->isConnected()) { QDBusServer *qdbs = new QDBusServer(Meta::mp.qsDBus, &a); - qWarning("%s",qPrintable(qdbs->lastError().name())); - qWarning("%d",qdbs->isConnected()); - qWarning("%s",qPrintable(qdbs->address())); + qWarning("%s", qPrintable(qdbs->lastError().name())); + qWarning("%d", qdbs->isConnected()); + qWarning("%s", qPrintable(qdbs->address())); MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::connectToBus(Meta::mp.qsDBus, "mainbus")); } } - if (! MurmurDBus::qdbc->isConnected()) { - qWarning("Failed to connect to D-Bus %s",qPrintable(Meta::mp.qsDBus)); + if (!MurmurDBus::qdbc->isConnected()) { + qWarning("Failed to connect to D-Bus %s", qPrintable(Meta::mp.qsDBus)); } else { new MetaDBus(meta); if (MurmurDBus::qdbc->isConnected()) { - if (! MurmurDBus::qdbc->registerObject("/", meta) || ! MurmurDBus::qdbc->registerService(Meta::mp.qsDBusService)) { - QDBusError e=MurmurDBus::qdbc->lastError(); + if (!MurmurDBus::qdbc->registerObject("/", meta) + || !MurmurDBus::qdbc->registerService(Meta::mp.qsDBusService)) { + QDBusError e = MurmurDBus::qdbc->lastError(); qWarning("Failed to register on DBus: %s %s", qPrintable(e.name()), qPrintable(e.message())); } else { qWarning("DBus registration succeeded"); @@ -594,7 +604,8 @@ int main(int argc, char **argv) { GRPCStart(); #else if (!meta->mp.qsGRPCAddress.isEmpty() || !meta->mp.qsGRPCCert.isEmpty() || !meta->mp.qsGRPCKey.isEmpty()) { - qWarning("This version of Murmur was built without gRPC support. Ignoring 'grpc' option from configuration file."); + qWarning( + "This version of Murmur was built without gRPC support. Ignoring 'grpc' option from configuration file."); } #endif @@ -604,11 +615,12 @@ int main(int argc, char **argv) { QString strver; meta->getVersion(major, minor, patch, strver); - qWarning("Murmur %d.%d.%d (%s) running on %s: %s: Booting servers", major, minor, patch, qPrintable(strver), qPrintable(meta->qsOS), qPrintable(meta->qsOSVersion)); + qWarning("Murmur %d.%d.%d (%s) running on %s: %s: Booting servers", major, minor, patch, qPrintable(strver), + qPrintable(meta->qsOS), qPrintable(meta->qsOSVersion)); meta->bootAll(); - res=a.exec(); + res = a.exec(); qWarning("Killing running servers"); @@ -637,7 +649,7 @@ int main(int argc, char **argv) { qInstallMessageHandler(nullptr); #ifdef Q_OS_UNIX - if (! Meta::mp.qsPid.isEmpty()) { + if (!Meta::mp.qsPid.isEmpty()) { QFile pid(Meta::mp.qsPid); pid.remove(); } diff --git a/src/murmur/murmur_pch.h b/src/murmur/murmur_pch.h index 3224728d8..d6f5ca8dd 100644 --- a/src/murmur/murmur_pch.h +++ b/src/murmur/murmur_pch.h @@ -4,101 +4,100 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef Q_MOC_RUN -#ifndef MUMBLE_MURMUR_MURMUR_PCH_H_ -#define MUMBLE_MURMUR_MURMUR_PCH_H_ +# ifndef MUMBLE_MURMUR_MURMUR_PCH_H_ +# define MUMBLE_MURMUR_MURMUR_PCH_H_ -#ifdef _MSC_VER -# define _USE_MATH_DEFINES -#endif +# ifdef _MSC_VER +# define _USE_MATH_DEFINES +# endif -#include <QtCore/QtGlobal> +# include <QtCore/QtGlobal> -#ifdef Q_OS_WIN -# include "win.h" -#endif +# ifdef Q_OS_WIN +# include "win.h" +# endif -#ifdef __APPLE__ -# include <CoreFoundation/CoreFoundation.h> -# include <CoreServices/CoreServices.h> -# undef check -# undef TYPE_BOOL -#endif +# ifdef __APPLE__ +# include <CoreFoundation/CoreFoundation.h> +# include <CoreServices/CoreServices.h> +# undef check +# undef TYPE_BOOL +# endif -#include <QtCore/QtCore> -#include <QtNetwork/QtNetwork> -#include <QtSql/QtSql> -#include <QtXml/QtXml> -#ifdef USE_DBUS -# include <QtDBus/QtDBus> -#endif +# include <QtCore/QtCore> +# include <QtNetwork/QtNetwork> +# include <QtSql/QtSql> +# include <QtXml/QtXml> +# ifdef USE_DBUS +# include <QtDBus/QtDBus> +# endif -#ifdef Q_OS_WIN -# include <QtGui/QtGui> +# ifdef Q_OS_WIN +# include <QtGui/QtGui> -# include <ws2tcpip.h> -# include <qos2.h> -# include <shellapi.h> -# include <delayimp.h> +# include <delayimp.h> +# include <qos2.h> +# include <shellapi.h> +# include <ws2tcpip.h> extern "C" { - void __cpuid(int a[4], int b); +void __cpuid(int a[4], int b); }; -#endif +# endif -#ifdef Q_OS_UNIX -# include <stdio.h> -# include <stdlib.h> -# include <unistd.h> -# include <sys/types.h> -# include <sys/stat.h> -# include <fcntl.h> -# include <sys/types.h> -# include <sys/socket.h> -# include <sys/time.h> -# include <sys/resource.h> -# include <syslog.h> -# ifdef Q_OS_LINUX -# include <linux/types.h> // needed to work around evil magic stuff in capability.h -# include <sys/capability.h> -# include <sys/prctl.h> -# endif -# include <pwd.h> -# include <grp.h> -# if defined __FreeBSD__ || defined __OpenBSD__ -# include <netinet/in_systm.h> -# endif -# include <netinet/in.h> -# include <netinet/ip.h> -# include <errno.h> -# include <signal.h> -# include <poll.h> -# ifdef Q_OS_DARWIN -# include <poll.h> -# endif -#endif +# ifdef Q_OS_UNIX +# include <fcntl.h> +# include <stdio.h> +# include <stdlib.h> +# include <sys/resource.h> +# include <sys/socket.h> +# include <sys/stat.h> +# include <sys/time.h> +# include <sys/types.h> +# include <syslog.h> +# include <unistd.h> +# ifdef Q_OS_LINUX +# include <linux/types.h> // needed to work around evil magic stuff in capability.h +# include <sys/capability.h> +# include <sys/prctl.h> +# endif +# include <grp.h> +# include <pwd.h> +# if defined __FreeBSD__ || defined __OpenBSD__ +# include <netinet/in_systm.h> +# endif +# include <errno.h> +# include <netinet/in.h> +# include <netinet/ip.h> +# include <poll.h> +# include <signal.h> +# ifdef Q_OS_DARWIN +# include <poll.h> +# endif +# endif -#include <cmath> +# include <cmath> -#include <boost/function.hpp> -#include <boost/bind.hpp> -#include <boost/shared_ptr.hpp> -#include <boost/weak_ptr.hpp> +# include <boost/bind.hpp> +# include <boost/function.hpp> +# include <boost/shared_ptr.hpp> +# include <boost/weak_ptr.hpp> -#ifdef USE_BONJOUR -# include <dns_sd.h> -#endif +# ifdef USE_BONJOUR +# include <dns_sd.h> +# endif -#include <openssl/opensslv.h> -#include <openssl/bn.h> -#include <openssl/aes.h> -#include <openssl/rand.h> -#include <openssl/pem.h> -#include <openssl/conf.h> -#include <openssl/x509v3.h> -#include <openssl/err.h> -#include <openssl/ssl.h> +# include <openssl/aes.h> +# include <openssl/bn.h> +# include <openssl/conf.h> +# include <openssl/err.h> +# include <openssl/opensslv.h> +# include <openssl/pem.h> +# include <openssl/rand.h> +# include <openssl/ssl.h> +# include <openssl/x509v3.h> /* OpenSSL defines set_key. This breaks our protobuf-generated setters. */ -#undef set_key +# undef set_key -#endif +# endif #endif |