X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fcore%2Fcore.cpp;h=7068f84ec28b67bf30bff7a7437fbde5acd3194f;hp=e7c56e5537c80e2d2b82468670a3d33a2afa6c2a;hb=8166d1701686588630cae9b44310790d084f8fd7;hpb=4a5065255e652dd0c301bac0db41b7afb777ef49 diff --git a/src/core/core.cpp b/src/core/core.cpp index e7c56e55..7068f84e 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright (C) 2005-2013 by the Quassel Project * + * Copyright (C) 2005-2014 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * @@ -21,28 +21,25 @@ #include #include "core.h" +#include "coreauthhandler.h" #include "coresession.h" #include "coresettings.h" -#include "internalconnection.h" +#include "logger.h" +#include "internalpeer.h" +#include "network.h" #include "postgresqlstorage.h" #include "quassel.h" -#include "signalproxy.h" #include "sqlitestorage.h" -#include "network.h" -#include "logger.h" - #include "util.h" -#include "protocols/legacy/legacyconnection.h" - // migration related #include -#ifdef Q_OS_WIN32 +#ifdef Q_OS_WIN # include #else # include # include -#endif /* Q_OS_WIN32 */ +#endif /* Q_OS_WIN */ #ifdef HAVE_UMASK # include @@ -57,8 +54,8 @@ const int Core::AddClientEventId = QEvent::registerEventType(); class AddClientEvent : public QEvent { public: - AddClientEvent(RemoteConnection *connection, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), connection(connection), userId(uid) {} - RemoteConnection *connection; + AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {} + RemotePeer *peer; UserId userId; }; @@ -85,7 +82,8 @@ void Core::destroy() Core::Core() - : _storage(0) + : QObject(), + _storage(0) { #ifdef HAVE_UMASK umask(S_IRWXG | S_IRWXO); @@ -96,11 +94,11 @@ Core::Core() // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location // Move settings, note this does not delete the old files -#ifdef Q_WS_MAC +#ifdef Q_OS_MAC QSettings newSettings("quassel-irc.org", "quasselcore"); #else -# ifdef Q_WS_WIN +# ifdef Q_OS_WIN QSettings::Format format = QSettings::IniFormat; # else QSettings::Format format = QSettings::NativeFormat; @@ -108,10 +106,10 @@ Core::Core() QString newFilePath = Quassel::configDirPath() + "quasselcore" + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini")); QSettings newSettings(newFilePath, format); -#endif /* Q_WS_MAC */ +#endif /* Q_OS_MAC */ if (newSettings.value("Config/Version").toUInt() == 0) { -# ifdef Q_WS_MAC +# ifdef Q_OS_MAC QString org = "quassel-irc.org"; # else QString org = "Quassel Project"; @@ -124,10 +122,10 @@ Core::Core() newSettings.setValue("Config/Version", 1); qWarning() << "* Your core settings have been migrated to" << newSettings.fileName(); -#ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */ -#ifdef Q_OS_WIN32 +#ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */ +#ifdef Q_OS_WIN QString quasselDir = qgetenv("APPDATA") + "/quassel/"; -#elif defined Q_WS_MAC +#elif defined Q_OS_MAC QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/"; #else QString quasselDir = QDir::homePath() + "/.quassel/"; @@ -155,7 +153,7 @@ Core::Core() else qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath(); } -#endif /* !Q_WS_MAC */ +#endif /* !Q_OS_MAC */ qWarning() << "*** Migration completed.\n\n"; } } @@ -179,7 +177,9 @@ Core::Core() void Core::init() { CoreSettings cs; - _configured = initStorage(cs.storageSettings().toMap()); + // legacy + QVariantMap dbsettings = cs.storageSettings().toMap(); + _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap()); if (Quassel::isOptionSet("select-backend")) { selectBackend(Quassel::optionValue("select-backend")); @@ -218,8 +218,9 @@ void Core::init() Core::~Core() { - foreach(RemoteConnection *connection, clientInfo.keys()) { - connection->close(); // disconnect non authed clients + // FIXME do we need more cleanup for handlers? + foreach(CoreAuthHandler *handler, _connectingClients) { + handler->deleteLater(); // disconnect non authed clients } qDeleteAll(sessions); qDeleteAll(_storageBackends); @@ -271,42 +272,50 @@ void Core::restoreState() /*** Core Setup ***/ -QString Core::setupCoreForInternalUsage() + +QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData) { - Q_ASSERT(!_storageBackends.isEmpty()); - QVariantMap setupData; - qsrand(QDateTime::currentDateTime().toTime_t()); - int pass = 0; - for (int i = 0; i < 10; i++) { - pass *= 10; - pass += qrand() % 10; - } - setupData["AdminUser"] = "AdminUser"; - setupData["AdminPasswd"] = QString::number(pass); - setupData["Backend"] = QString("SQLite"); // mono client currently needs sqlite - return setupCore(setupData); + return instance()->setupCore(adminUser, adminPassword, backend, setupData); } -QString Core::setupCore(QVariantMap setupData) +QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData) { - QString user = setupData.take("AdminUser").toString(); - QString password = setupData.take("AdminPasswd").toString(); - if (user.isEmpty() || password.isEmpty()) { + if (_configured) + return tr("Core is already configured! Not configuring again..."); + + if (adminUser.isEmpty() || adminPassword.isEmpty()) { return tr("Admin user or password not set."); } - if (_configured || !(_configured = initStorage(setupData, true))) { + if (!(_configured = initStorage(backend, setupData, true))) { return tr("Could not setup storage!"); } - CoreSettings s; - s.setStorageSettings(setupData); + + saveBackendSettings(backend, setupData); + quInfo() << qPrintable(tr("Creating admin user...")); - _storage->addUser(user, password); + _storage->addUser(adminUser, adminPassword); startListening(); // TODO check when we need this return QString(); } +QString Core::setupCoreForInternalUsage() +{ + Q_ASSERT(!_storageBackends.isEmpty()); + + qsrand(QDateTime::currentDateTime().toTime_t()); + int pass = 0; + for (int i = 0; i < 10; i++) { + pass *= 10; + pass += qrand() % 10; + } + + // mono client currently needs sqlite + return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap()); +} + + /*** Storage Handling ***/ void Core::registerStorageBackends() { @@ -347,7 +356,7 @@ void Core::unregisterStorageBackend(Storage *backend) // old db settings: // "Type" => "sqlite" -bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup) +bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup) { _storage = 0; @@ -371,13 +380,10 @@ bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup) return false; // trigger setup process if (storage->setup(settings)) return initStorage(backend, settings, false); - // if setup wasn't successfull we mark the backend as unavailable + // if initialization wasn't successful, we quit to keep from coming up unconfigured case Storage::NotAvailable: - qCritical() << "Selected storage backend is not available:" << backend; - storage->deleteLater(); - _storageBackends.remove(backend); - storage = 0; - return false; + qCritical() << "FATAL: Selected storage backend is not available:" << backend; + exit(EXIT_FAILURE); case Storage::IsReady: // delete all other backends _storageBackends.remove(backend); @@ -389,12 +395,6 @@ bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup) } -bool Core::initStorage(QVariantMap dbSettings, bool setup) -{ - return initStorage(dbSettings["Backend"].toString(), dbSettings["ConnectionProperties"].toMap(), setup); -} - - void Core::syncStorage() { if (_storage) @@ -416,6 +416,17 @@ bool Core::createNetwork(UserId user, NetworkInfo &info) /*** Network Management ***/ +bool Core::sslSupported() +{ +#ifdef HAVE_SSL + SslServer *sslServer = qobject_cast(&instance()->_server); + return sslServer && sslServer->isCertValid(); +#else + return false; +#endif +} + + bool Core::startListening() { // in mono mode we only start a local port if a port is specified in the cli call @@ -518,13 +529,14 @@ void Core::incomingConnection() Q_ASSERT(server); while (server->hasPendingConnections()) { QTcpSocket *socket = server->nextPendingConnection(); - RemoteConnection *connection = new LegacyConnection(socket, this); - connect(connection, SIGNAL(disconnected()), SLOT(clientDisconnected())); - connect(connection, SIGNAL(dataReceived(QVariant)), SLOT(processClientMessage(QVariant))); - connect(connection, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError))); + CoreAuthHandler *handler = new CoreAuthHandler(socket, this); + _connectingClients.insert(handler); + + connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected())); + connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString))); + connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId))); - clientInfo.insert(connection, QVariantMap()); quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString()); if (!_configured) { @@ -534,168 +546,15 @@ void Core::incomingConnection() } -void Core::processClientMessage(const QVariant &data) -{ - RemoteConnection *connection = qobject_cast(sender()); - if (!connection) { - qWarning() << Q_FUNC_INFO << "Message not sent by RemoteConnection!"; - return; - } - - QVariantMap msg = data.toMap(); - if (!msg.contains("MsgType")) { - // Client is way too old, does not even use the current init format - qWarning() << qPrintable(tr("Antique client trying to connect... refusing.")); - connection->close(); - return; - } - - // OK, so we have at least an init message format we can understand - if (msg["MsgType"] == "ClientInit") { - QVariantMap reply; - - // Just version information -- check it! - uint ver = msg["ProtocolVersion"].toUInt(); - if (ver < Quassel::buildInfo().coreNeedsProtocol) { - reply["MsgType"] = "ClientInitReject"; - reply["Error"] = tr("Your Quassel Client is too old!
" - "This core needs at least client/core protocol version %1.
" - "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol); - connection->writeSocketData(reply); - qWarning() << qPrintable(tr("Client")) << connection->description() << qPrintable(tr("too old, rejecting.")); - connection->close(); - return; - } - - reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion; - reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString; - reply["CoreDate"] = Quassel::buildInfo().buildDate; - reply["CoreStartTime"] = startTime(); // v10 clients don't necessarily parse this, see below - - // FIXME: newer clients no longer use the hardcoded CoreInfo (for now), since it gets the - // time zone wrong. With the next protocol bump (10 -> 11), we should remove this - // or make it properly configurable. - - int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC()); - int updays = uptime / 86400; uptime %= 86400; - int uphours = uptime / 3600; uptime %= 3600; - int upmins = uptime / 60; - reply["CoreInfo"] = tr("Quassel Core Version %1
" - "Built: %2
" - "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString) - .arg(Quassel::buildInfo().buildDate) - .arg(updays).arg(uphours, 2, 10, QChar('0')).arg(upmins, 2, 10, QChar('0')).arg(startTime().toString(Qt::TextDate)); - - reply["CoreFeatures"] = (int)Quassel::features(); - -#ifdef HAVE_SSL - SslServer *sslServer = qobject_cast(&_server); - QSslSocket *sslSocket = qobject_cast(connection->socket()); - bool supportSsl = sslServer && sslSocket && sslServer->isCertValid(); -#else - bool supportSsl = false; -#endif - -#ifndef QT_NO_COMPRESS - bool supportsCompression = true; -#else - bool supportsCompression = false; -#endif - - reply["SupportSsl"] = supportSsl; - reply["SupportsCompression"] = supportsCompression; - // switch to ssl/compression after client has been informed about our capabilities (see below) - - reply["LoginEnabled"] = true; - - // check if we are configured, start wizard otherwise - if (!_configured) { - reply["Configured"] = false; - QList backends; - foreach(Storage *backend, _storageBackends.values()) { - QVariantMap v; - v["DisplayName"] = backend->displayName(); - v["Description"] = backend->description(); - v["SetupKeys"] = backend->setupKeys(); - v["SetupDefaults"] = backend->setupDefaults(); - backends.append(v); - } - reply["StorageBackends"] = backends; - reply["LoginEnabled"] = false; - } - else { - reply["Configured"] = true; - } - clientInfo[connection] = msg; // store for future reference - reply["MsgType"] = "ClientInitAck"; - connection->writeSocketData(reply); - connection->socket()->flush(); // ensure that the write cache is flushed before we switch to ssl - -#ifdef HAVE_SSL - // after we told the client that we are ssl capable we switch to ssl mode - if (supportSsl && msg["UseSsl"].toBool()) { - qDebug() << qPrintable(tr("Starting TLS for Client:")) << connection->description(); - connect(sslSocket, SIGNAL(sslErrors(const QList &)), SLOT(sslErrors(const QList &))); - sslSocket->startServerEncryption(); - } -#endif - -#ifndef QT_NO_COMPRESS - if (supportsCompression && msg["UseCompression"].toBool()) { - connection->socket()->setProperty("UseCompression", true); - qDebug() << "Using compression for Client:" << qPrintable(connection->socket()->peerAddress().toString()); - } -#endif - } - else { - // for the rest, we need an initialized connection - if (!clientInfo.contains(connection)) { - QVariantMap reply; - reply["MsgType"] = "ClientLoginReject"; - reply["Error"] = tr("Client not initialized!
You need to send an init message before trying to login."); - connection->writeSocketData(reply); - qWarning() << qPrintable(tr("Client")) << qPrintable(connection->socket()->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting.")); - connection->close(); return; - } - if (msg["MsgType"] == "CoreSetupData") { - QVariantMap reply; - QString result = setupCore(msg["SetupData"].toMap()); - if (!result.isEmpty()) { - reply["MsgType"] = "CoreSetupReject"; - reply["Error"] = result; - } - else { - reply["MsgType"] = "CoreSetupAck"; - } - connection->writeSocketData(reply); - } - else if (msg["MsgType"] == "ClientLogin") { - QVariantMap reply; - UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString()); - if (uid == 0) { - reply["MsgType"] = "ClientLoginReject"; - reply["Error"] = tr("Invalid username or password!
The username/password combination you supplied could not be found in the database."); - connection->writeSocketData(reply); - return; - } - reply["MsgType"] = "ClientLoginAck"; - connection->writeSocketData(reply); - quInfo() << qPrintable(tr("Client")) << qPrintable(connection->socket()->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt())); - setupClientSession(connection, uid); - } - } -} - - // Potentially called during the initialization phase (before handing the connection off to the session) void Core::clientDisconnected() { - RemoteConnection *connection = qobject_cast(sender()); - Q_ASSERT(connection); + CoreAuthHandler *handler = qobject_cast(sender()); + Q_ASSERT(handler); - quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(connection->socket()->peerAddress().toString()); - clientInfo.remove(connection); - connection->deleteLater(); + quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString()); + _connectingClients.remove(handler); + handler->deleteLater(); // make server listen again if still not configured if (!_configured) { @@ -707,12 +566,15 @@ void Core::clientDisconnected() } -void Core::setupClientSession(RemoteConnection *connection, UserId uid) +void Core::setupClientSession(RemotePeer *peer, UserId uid) { + CoreAuthHandler *handler = qobject_cast(sender()); + Q_ASSERT(handler); + // From now on everything is handled by the client session - disconnect(connection, 0, this, 0); - connection->socket()->flush(); - clientInfo.remove(connection); + disconnect(handler, 0, this, 0); + _connectingClients.remove(handler); + handler->deleteLater(); // Find or create session for validated user SessionThread *session; @@ -722,15 +584,16 @@ void Core::setupClientSession(RemoteConnection *connection, UserId uid) else { session = createSession(uid); if (!session) { - qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(connection->socket()->peerAddress().toString()); - connection->close(); + qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(peer->description()); + peer->close(); + peer->deleteLater(); return; } } // as we are currently handling an event triggered by incoming data on this socket // it is unsafe to directly move the socket to the client thread. - QCoreApplication::postEvent(this, new AddClientEvent(connection, uid)); + QCoreApplication::postEvent(this, new AddClientEvent(peer, uid)); } @@ -738,27 +601,28 @@ void Core::customEvent(QEvent *event) { if (event->type() == AddClientEventId) { AddClientEvent *addClientEvent = static_cast(event); - addClientHelper(addClientEvent->connection, addClientEvent->userId); + addClientHelper(addClientEvent->peer, addClientEvent->userId); return; } } -void Core::addClientHelper(RemoteConnection *connection, UserId uid) +void Core::addClientHelper(RemotePeer *peer, UserId uid) { // Find or create session for validated user if (!sessions.contains(uid)) { - qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(connection->socket()->peerAddress().toString()); - connection->close(); + qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(peer->description()); + peer->close(); + peer->deleteLater(); return; } SessionThread *session = sessions[uid]; - session->addClient(connection); + session->addClient(peer); } -void Core::setupInternalClientSession(InternalConnection *clientConnection) +void Core::setupInternalClientSession(InternalPeer *clientPeer) { if (!_configured) { stopListening(); @@ -774,9 +638,9 @@ void Core::setupInternalClientSession(InternalConnection *clientConnection) return; } - InternalConnection *coreConnection = new InternalConnection(this); - coreConnection->setPeer(clientConnection); - clientConnection->setPeer(coreConnection); + InternalPeer *corePeer = new InternalPeer(this); + corePeer->setPeer(clientPeer); + clientPeer->setPeer(corePeer); // Find or create session for validated user SessionThread *sessionThread; @@ -785,7 +649,7 @@ void Core::setupInternalClientSession(InternalConnection *clientConnection) else sessionThread = createSession(uid); - sessionThread->addClient(coreConnection); + sessionThread->addClient(corePeer); } @@ -802,23 +666,24 @@ SessionThread *Core::createSession(UserId uid, bool restore) } -#ifdef HAVE_SSL -void Core::sslErrors(const QList &errors) +void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString) { - Q_UNUSED(errors); - QSslSocket *socket = qobject_cast(sender()); - if (socket) - socket->ignoreSslErrors(); + qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString); } -#endif - -void Core::socketError(QAbstractSocket::SocketError err) +QVariantList Core::backendInfo() { - RemoteConnection *connection = qobject_cast(sender()); - if (connection && err != QAbstractSocket::RemoteHostClosedError) - qWarning() << "Core::socketError()" << connection->socket() << err << connection->socket()->errorString(); + QVariantList backends; + foreach(const Storage *backend, instance()->_storageBackends.values()) { + QVariantMap v; + v["DisplayName"] = backend->displayName(); + v["Description"] = backend->description(); + v["SetupKeys"] = backend->setupKeys(); + v["SetupDefaults"] = backend->setupDefaults(); + backends.append(v); + } + return backends; } @@ -1067,7 +932,7 @@ QVariantMap Core::promptForSettings(const Storage *storage) } -#ifdef Q_OS_WIN32 +#ifdef Q_OS_WIN void Core::stdInEcho(bool on) { HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); @@ -1094,4 +959,4 @@ void Core::stdInEcho(bool on) } -#endif /* Q_OS_WIN32 */ +#endif /* Q_OS_WIN */