X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fcore%2Fcore.cpp;h=c145f5b3957d94022962aa1c61f9fd3110f6156c;hp=4413211e1e6334016e95a54c66588850d5208760;hb=61aac1868f15babb7086d8bc6bbcff530346f438;hpb=76db8cdfbeffaaba359c8e80cf2146da9e9e7f8a diff --git a/src/core/core.cpp b/src/core/core.cpp index 4413211e..c145f5b3 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-2016 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * @@ -21,27 +21,26 @@ #include #include "core.h" +#include "coreauthhandler.h" #include "coresession.h" #include "coresettings.h" +#include "logger.h" #include "internalpeer.h" +#include "network.h" #include "postgresqlstorage.h" #include "quassel.h" +#include "sqlauthenticator.h" #include "sqlitestorage.h" -#include "network.h" -#include "logger.h" - #include "util.h" -#include "protocols/legacy/legacypeer.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 @@ -84,7 +83,9 @@ void Core::destroy() Core::Core() - : _storage(0) + : QObject(), + _storage(0), + _authenticator(0) { #ifdef HAVE_UMASK umask(S_IRWXG | S_IRWXO); @@ -95,11 +96,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; @@ -107,10 +108,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"; @@ -123,10 +124,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/"; @@ -154,7 +155,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"; } } @@ -169,7 +170,8 @@ Core::Core() } registerStorageBackends(); - + registerAuthenticatorBackends(); + connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage())); _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes } @@ -178,12 +180,20 @@ 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()); + + // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work! + QVariantMap authSettings = cs.authSettings().toMap(); + initAuthenticator(authSettings.value("AuthBackend").toString(), authSettings.value("ConnectionProperties").toMap()); + if (Quassel::isOptionSet("select-backend")) { selectBackend(Quassel::optionValue("select-backend")); exit(0); } + + // TODO: add --select-authenticator command line option and code. if (!_configured) { if (!_storageBackends.count()) { @@ -193,17 +203,24 @@ void Core::init() "to work.")); exit(1); // TODO make this less brutal (especially for mono client -> popup) } + qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup."; + + if (!cs.isWritable()) { + qWarning() << "Cannot write quasselcore configuration; probably a permission problem."; + exit(EXIT_FAILURE); + } + } if (Quassel::isOptionSet("add-user")) { - createUser(); - exit(0); + exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE); + } if (Quassel::isOptionSet("change-userpass")) { - changeUserPass(Quassel::optionValue("change-userpass")); - exit(0); + exit(changeUserPass(Quassel::optionValue("change-userpass")) ? + EXIT_SUCCESS : EXIT_FAILURE); } connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection())); @@ -217,10 +234,11 @@ void Core::init() Core::~Core() { - foreach(RemotePeer *peer, clientInfo.keys()) { - peer->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(_sessions); qDeleteAll(_storageBackends); } @@ -232,7 +250,8 @@ void Core::saveState() CoreSettings s; QVariantMap state; QVariantList activeSessions; - foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue(user); + foreach(UserId user, instance()->_sessions.keys()) + activeSessions << QVariant::fromValue(user); state["CoreStateVersion"] = 1; state["ActiveSessions"] = activeSessions; s.setCoreState(state); @@ -245,7 +264,7 @@ void Core::restoreState() // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!")); return; } - if (instance()->sessions.count()) { + if (instance()->_sessions.count()) { qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!")); return; } @@ -263,49 +282,60 @@ void Core::restoreState() quInfo() << "Restoring previous core state..."; foreach(QVariant v, activeSessions) { UserId user = v.value(); - instance()->createSession(user, true); + instance()->sessionForUser(user, true); } } } /*** Core Setup ***/ -QString Core::setupCoreForInternalUsage() + +QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData) { - 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, authBackend, authSetupData); } -QString Core::setupCore(QVariantMap setupData) +QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData) { - 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); + + if (!saveBackendSettings(backend, setupData)) { + return tr("Could not save backend settings, probably a permission problem."); + } + saveAuthBackendSettings(authBackend, authSetupData); + 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(), "StorageAuth", QVariantMap()); +} + + /*** Storage Handling ***/ void Core::registerStorageBackends() { @@ -327,7 +357,6 @@ bool Core::registerStorageBackend(Storage *backend) } } - void Core::unregisterStorageBackends() { foreach(Storage *s, _storageBackends.values()) { @@ -343,10 +372,47 @@ void Core::unregisterStorageBackend(Storage *backend) backend->deleteLater(); } +// Authentication handling, now independent from storage. +// Register and unregister authenticators. + +void Core::registerAuthenticatorBackends() +{ + // Register new authentication backends here! + //registerAuthenticatorBackend(new LdapAuthenticator(this)); + registerAuthenticatorBackend(new SqlAuthenticator(this)); + +} + +bool Core::registerAuthenticatorBackend(Authenticator *authenticator) +{ + if (authenticator->isAvailable()) + { + _authenticatorBackends[authenticator->displayName()] = authenticator; + return true; + } else { + authenticator->deleteLater(); + return false; + } +} + +void Core::unregisterAuthenticatorBackends() +{ + foreach(Authenticator* a, _authenticatorBackends.values()) + { + a->deleteLater(); + } + _authenticatorBackends.clear(); +} + +void Core::unregisterAuthenticatorBackend(Authenticator *backend) +{ + _authenticatorBackends.remove(backend->displayName()); + backend->deleteLater(); +} // 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; @@ -370,13 +436,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); @@ -387,12 +450,43 @@ bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup) return true; } - -bool Core::initStorage(QVariantMap dbSettings, bool setup) +// XXX: TODO: Apparently, this is legacy? +bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup) { - return initStorage(dbSettings["Backend"].toString(), dbSettings["ConnectionProperties"].toMap(), setup); -} + _authenticator = 0; + + if (backend.isEmpty()) { + return false; + } + + Authenticator *authenticator = 0; + if (_authenticatorBackends.contains(backend)) { + authenticator = _authenticatorBackends[backend]; + } + else { + qCritical() << "Selected auth backend is not available:" << backend; + return false; + } + Authenticator::State authState = authenticator->init(settings); + switch (authState) { + case Authenticator::NeedsSetup: + if (!setup) + return false; // trigger setup process + if (authenticator->setup(settings)) + return initAuthenticator(backend, settings, false); + // if initialization wasn't successful, we quit to keep from coming up unconfigured + case Authenticator::NotAvailable: + qCritical() << "FATAL: Selected auth backend is not available:" << backend; + exit(EXIT_FAILURE); + case Authenticator::IsReady: + // delete all other backends + _authenticatorBackends.remove(backend); + unregisterAuthenticatorBackends(); + } + _authenticator = authenticator; + return true; +} void Core::syncStorage() { @@ -415,6 +509,34 @@ 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::reloadCerts() +{ +#ifdef HAVE_SSL + SslServer *sslServerv4 = qobject_cast(&instance()->_server); + bool retv4 = sslServerv4->reloadCerts(); + + SslServer *sslServerv6 = qobject_cast(&instance()->_v6server); + bool retv6 = sslServerv6->reloadCerts(); + + return retv4 && retv6; +#else + // SSL not supported, don't mark configuration reload as failed + return true; +#endif +} + + bool Core::startListening() { // in mono mode we only start a local port if a port is specified in the cli call @@ -517,13 +639,14 @@ void Core::incomingConnection() Q_ASSERT(server); while (server->hasPendingConnections()) { QTcpSocket *socket = server->nextPendingConnection(); - RemotePeer *peer = new LegacyPeer(socket, this); - connect(peer, SIGNAL(disconnected()), SLOT(clientDisconnected())); - connect(peer, SIGNAL(dataReceived(QVariant)), SLOT(processClientMessage(QVariant))); - connect(peer, 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(peer, QVariantMap()); quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString()); if (!_configured) { @@ -533,168 +656,15 @@ void Core::incomingConnection() } -void Core::processClientMessage(const QVariant &data) -{ - RemotePeer *peer = qobject_cast(sender()); - if (!peer) { - 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.")); - peer->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); - peer->writeSocketData(reply); - qWarning() << qPrintable(tr("Client")) << peer->description() << qPrintable(tr("too old, rejecting.")); - peer->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(peer->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[peer] = msg; // store for future reference - reply["MsgType"] = "ClientInitAck"; - peer->writeSocketData(reply); - peer->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:")) << peer->description(); - connect(sslSocket, SIGNAL(sslErrors(const QList &)), SLOT(sslErrors(const QList &))); - sslSocket->startServerEncryption(); - } -#endif - -#ifndef QT_NO_COMPRESS - if (supportsCompression && msg["UseCompression"].toBool()) { - peer->socket()->setProperty("UseCompression", true); - qDebug() << "Using compression for Client:" << qPrintable(peer->socket()->peerAddress().toString()); - } -#endif - } - else { - // for the rest, we need an initialized connection - if (!clientInfo.contains(peer)) { - QVariantMap reply; - reply["MsgType"] = "ClientLoginReject"; - reply["Error"] = tr("Client not initialized!
You need to send an init message before trying to login."); - peer->writeSocketData(reply); - qWarning() << qPrintable(tr("Client")) << qPrintable(peer->socket()->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting.")); - peer->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"; - } - peer->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."); - peer->writeSocketData(reply); - return; - } - reply["MsgType"] = "ClientLoginAck"; - peer->writeSocketData(reply); - quInfo() << qPrintable(tr("Client")) << qPrintable(peer->socket()->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt())); - setupClientSession(peer, uid); - } - } -} - - // Potentially called during the initialization phase (before handing the connection off to the session) void Core::clientDisconnected() { - RemotePeer *peer = qobject_cast(sender()); - Q_ASSERT(peer); + CoreAuthHandler *handler = qobject_cast(sender()); + Q_ASSERT(handler); - quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(peer->socket()->peerAddress().toString()); - clientInfo.remove(peer); - peer->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) { @@ -708,24 +678,16 @@ void Core::clientDisconnected() 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(peer, 0, this, 0); - peer->socket()->flush(); - clientInfo.remove(peer); + disconnect(handler, 0, this, 0); + _connectingClients.remove(handler); + handler->deleteLater(); // Find or create session for validated user - SessionThread *session; - if (sessions.contains(uid)) { - session = sessions[uid]; - } - else { - session = createSession(uid); - if (!session) { - qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(peer->socket()->peerAddress().toString()); - peer->close(); - return; - } - } + sessionForUser(uid); // 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. @@ -746,13 +708,7 @@ void Core::customEvent(QEvent *event) 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(peer->socket()->peerAddress().toString()); - peer->close(); - return; - } - - SessionThread *session = sessions[uid]; + SessionThread *session = sessionForUser(uid); session->addClient(peer); } @@ -778,48 +734,57 @@ void Core::setupInternalClientSession(InternalPeer *clientPeer) clientPeer->setPeer(corePeer); // Find or create session for validated user - SessionThread *sessionThread; - if (sessions.contains(uid)) - sessionThread = sessions[uid]; - else - sessionThread = createSession(uid); - + SessionThread *sessionThread = sessionForUser(uid); sessionThread->addClient(corePeer); } -SessionThread *Core::createSession(UserId uid, bool restore) +SessionThread *Core::sessionForUser(UserId uid, bool restore) { - if (sessions.contains(uid)) { - qWarning() << "Calling createSession() when a session for the user already exists!"; - return 0; - } - SessionThread *sess = new SessionThread(uid, restore, this); - sessions[uid] = sess; - sess->start(); - return sess; + if (_sessions.contains(uid)) + return _sessions[uid]; + + SessionThread *session = new SessionThread(uid, restore, this); + _sessions[uid] = session; + session->start(); + return session; } -#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() { - RemotePeer *peer = qobject_cast(sender()); - if (peer && err != QAbstractSocket::RemoteHostClosedError) - qWarning() << "Core::socketError()" << peer->socket() << err << peer->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(); + v["IsDefault"] = isStorageBackendDefault(backend); + backends.append(v); + } + return backends; } +QVariantList Core::authenticatorInfo() +{ + QVariantList backends; + foreach(const Authenticator *backend, instance()->_authenticatorBackends.values()) { + QVariantMap v; + v["DisplayName"] = backend->displayName(); + v["Description"] = backend->description(); + v["SetupKeys"] = backend->setupKeys(); + v["SetupDefaults"] = backend->setupDefaults(); + backends.append(v); + } + return backends; +} // migration / backend selection bool Core::selectBackend(const QString &backend) @@ -838,7 +803,9 @@ bool Core::selectBackend(const QString &backend) Storage::State storageState = storage->init(settings); switch (storageState) { case Storage::IsReady: - saveBackendSettings(backend, settings); + if (!saveBackendSettings(backend, settings)) { + qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem.")); + } qWarning() << "Switched backend to:" << qPrintable(backend); qWarning() << "Backend already initialized. Skipping Migration"; return true; @@ -856,7 +823,9 @@ bool Core::selectBackend(const QString &backend) return false; } - saveBackendSettings(backend, settings); + if (!saveBackendSettings(backend, settings)) { + qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem.")); + } qWarning() << "Switched backend to:" << qPrintable(backend); break; } @@ -872,7 +841,10 @@ bool Core::selectBackend(const QString &backend) storage = 0; if (reader->migrateTo(writer)) { qDebug() << "Migration finished!"; - saveBackendSettings(backend, settings); + if (!saveBackendSettings(backend, settings)) { + qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem.")); + return false; + } return true; } return false; @@ -897,7 +869,7 @@ bool Core::selectBackend(const QString &backend) } -void Core::createUser() +bool Core::createUser() { QTextStream out(stdout); QTextStream in(stdin); @@ -919,30 +891,32 @@ void Core::createUser() if (password != password2) { qWarning() << "Passwords don't match!"; - return; + return false; } if (password.isEmpty()) { qWarning() << "Password is empty!"; - return; + return false; } if (_configured && _storage->addUser(username, password).isValid()) { out << "Added user " << username << " successfully!" << endl; + return true; } else { qWarning() << "Unable to add user:" << qPrintable(username); + return false; } } -void Core::changeUserPass(const QString &username) +bool Core::changeUserPass(const QString &username) { QTextStream out(stdout); QTextStream in(stdin); UserId userId = _storage->getUserId(username); if (!userId.isValid()) { out << "User " << username << " does not exist." << endl; - return; + return false; } out << "Change password for user: " << username << endl; @@ -960,22 +934,33 @@ void Core::changeUserPass(const QString &username) if (password != password2) { qWarning() << "Passwords don't match!"; - return; + return false; } if (password.isEmpty()) { qWarning() << "Password is empty!"; - return; + return false; } if (_configured && _storage->updateUser(userId, password)) { out << "Password changed successfully!" << endl; + return true; } else { qWarning() << "Failed to change password!"; + return false; } } +bool Core::changeUserPassword(UserId userId, const QString &password) +{ + if (!isConfigured() || !userId.isValid()) + return false; + + return instance()->_storage->updateUser(userId, password); +} + + AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage) { if (!storage) @@ -1006,12 +991,22 @@ AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage) } -void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings) +bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings) { QVariantMap dbsettings; dbsettings["Backend"] = backend; dbsettings["ConnectionProperties"] = settings; - CoreSettings().setStorageSettings(dbsettings); + CoreSettings s = CoreSettings(); + s.setStorageSettings(dbsettings); + return s.sync(); +} + +void Core::saveAuthBackendSettings(const QString &backend, const QVariantMap &settings) +{ + QVariantMap dbsettings; + dbsettings["AuthBackend"] = backend; + dbsettings["ConnectionProperties"] = settings; + CoreSettings().setAuthSettings(dbsettings); } @@ -1066,7 +1061,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); @@ -1093,4 +1088,4 @@ void Core::stdInEcho(bool on) } -#endif /* Q_OS_WIN32 */ +#endif /* Q_OS_WIN */