1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
23 #include <QCoreApplication>
26 #include "coreauthhandler.h"
27 #include "coresession.h"
28 #include "coresettings.h"
30 #include "internalpeer.h"
32 #include "postgresqlstorage.h"
34 #include "sqlauthenticator.h"
35 #include "sqlitestorage.h"
38 // Currently building with LDAP bindings is optional.
40 #include "ldapauthenticator.h"
52 // ==============================
54 // ==============================
55 const int Core::AddClientEventId = QEvent::registerEventType();
57 class AddClientEvent : public QEvent
60 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
66 // ==============================
68 // ==============================
69 Core *Core::_instance{nullptr};
71 Core *Core::instance()
80 qWarning() << "Recreating core instance!";
85 // Parent all QObject-derived attributes, so when the Core instance gets moved into another
86 // thread, they get moved with it
87 _server.setParent(this);
88 _v6server.setParent(this);
89 _storageSyncTimer.setParent(this);
96 qDeleteAll(_connectingClients);
97 qDeleteAll(_sessions);
105 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
107 if (Quassel::runMode() == Quassel::RunMode::CoreOnly) {
108 Quassel::loadTranslation(QLocale::system());
111 // check settings version
112 // so far, we only have 1
114 if (s.version() != 1) {
115 qCritical() << "Invalid core settings version, terminating!";
116 QCoreApplication::exit(EXIT_FAILURE);
120 // Set up storage and authentication backends
121 registerStorageBackends();
122 registerAuthenticators();
124 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
125 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
128 QVariantMap db_connectionProperties;
130 QString auth_authenticator;
131 QVariantMap auth_properties;
133 bool writeError = false;
135 if (config_from_environment) {
136 db_backend = environment.value("DB_BACKEND");
137 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
141 QVariantMap dbsettings = cs.storageSettings().toMap();
142 db_backend = dbsettings.value("Backend").toString();
143 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
145 QVariantMap authSettings = cs.authSettings().toMap();
146 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
147 auth_properties = authSettings.value("AuthProperties").toMap();
149 writeError = !cs.isWritable();
153 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
155 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
157 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
160 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
162 if (Quassel::isOptionSet("select-backend")) {
163 success &= selectBackend(Quassel::optionValue("select-backend"));
165 if (Quassel::isOptionSet("select-authenticator")) {
166 success &= selectAuthenticator(Quassel::optionValue("select-authenticator"));
168 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
173 if (config_from_environment) {
174 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
175 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
178 qWarning() << "Cannot configure from environment";
179 QCoreApplication::exit(EXIT_FAILURE);
184 if (_registeredStorageBackends.empty()) {
185 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
187 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
188 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
190 QCoreApplication::exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
195 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
196 QCoreApplication::exit(EXIT_FAILURE);
200 quInfo() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
204 if (Quassel::isOptionSet("add-user")) {
205 bool success = createUser();
206 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
210 if (Quassel::isOptionSet("change-userpass")) {
211 bool success = changeUserPass(Quassel::optionValue("change-userpass"));
212 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
216 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
217 if (_strictIdentEnabled) {
221 if (Quassel::isOptionSet("oidentd")) {
222 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
225 Quassel::registerReloadHandler([]() {
226 // Currently, only reloading SSL certificates and the sysident cache is supported
227 if (Core::instance()) {
228 Core::instance()->cacheSysIdent();
229 Core::instance()->reloadCerts();
235 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
236 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
239 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
240 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
242 if (!startListening()) {
243 QCoreApplication::exit(EXIT_FAILURE); // TODO make this less brutal
247 if (_configured && !Quassel::isOptionSet("norestore")) {
248 Core::restoreState();
253 if (_pendingInternalConnection) {
254 connectInternalPeer(_pendingInternalConnection);
255 _pendingInternalConnection = {};
261 /*** Session Restore ***/
263 void Core::saveState()
266 QVariantList activeSessions;
267 for (auto &&user : instance()->_sessions.keys())
268 activeSessions << QVariant::fromValue<UserId>(user);
269 _storage->setCoreState(activeSessions);
274 void Core::restoreState()
277 quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
280 if (_sessions.count()) {
281 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
286 /* We don't check, since we are at the first version since switching to Git
287 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
289 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
294 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
295 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
297 if (activeSessions.count() > 0) {
298 quInfo() << "Restoring previous core state...";
299 for(auto &&v : activeSessions) {
300 UserId user = v.value<UserId>();
301 sessionForUser(user, true);
309 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
311 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
315 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
318 return tr("Core is already configured! Not configuring again...");
320 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
321 return tr("Admin user or password not set.");
323 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
324 return tr("Could not setup storage!");
327 quInfo() << "Selected authenticator:" << authenticator;
328 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
330 return tr("Could not setup authenticator!");
333 if (!saveBackendSettings(backend, setupData)) {
334 return tr("Could not save backend settings, probably a permission problem.");
336 saveAuthenticatorSettings(authenticator, authSetupData);
338 quInfo() << qPrintable(tr("Creating admin user..."));
339 _storage->addUser(adminUser, adminPassword);
341 startListening(); // TODO check when we need this
346 QString Core::setupCoreForInternalUsage()
348 Q_ASSERT(!_registeredStorageBackends.empty());
350 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
352 for (int i = 0; i < 10; i++) {
354 pass += qrand() % 10;
357 // mono client currently needs sqlite
358 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
362 /*** Storage Handling ***/
364 template<typename Storage>
365 void Core::registerStorageBackend()
367 auto backend = makeDeferredShared<Storage>(this);
368 if (backend->isAvailable())
369 _registeredStorageBackends.emplace_back(std::move(backend));
371 backend->deleteLater();
375 void Core::registerStorageBackends()
377 if (_registeredStorageBackends.empty()) {
378 registerStorageBackend<SqliteStorage>();
379 registerStorageBackend<PostgreSqlStorage>();
384 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
386 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
387 [backendId](const DeferredSharedPtr<Storage> &backend) {
388 return backend->displayName() == backendId;
390 return it != _registeredStorageBackends.end() ? *it : nullptr;
394 // "Type" => "sqlite"
395 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
396 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
398 if (backend.isEmpty()) {
399 quWarning() << "No storage backend selected!";
403 auto storage = storageBackend(backend);
405 qCritical() << "Selected storage backend is not available:" << backend;
409 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
410 switch (storageState) {
411 case Storage::NeedsSetup:
413 return false; // trigger setup process
414 if (storage->setup(settings, environment, loadFromEnvironment))
415 return initStorage(backend, settings, environment, loadFromEnvironment, false);
418 // if initialization wasn't successful, we quit to keep from coming up unconfigured
419 case Storage::NotAvailable:
420 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
422 QCoreApplication::exit(EXIT_FAILURE);
426 case Storage::IsReady:
427 // delete all other backends
428 _registeredStorageBackends.clear();
429 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
430 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
433 _storage = std::move(storage);
438 void Core::syncStorage()
445 /*** Storage Access ***/
446 bool Core::createNetwork(UserId user, NetworkInfo &info)
448 NetworkId networkId = instance()->_storage->createNetwork(user, info);
449 if (!networkId.isValid())
452 info.networkId = networkId;
457 /*** Authenticators ***/
459 // Authentication handling, now independent from storage.
460 template<typename Authenticator>
461 void Core::registerAuthenticator()
463 auto authenticator = makeDeferredShared<Authenticator>(this);
464 if (authenticator->isAvailable())
465 _registeredAuthenticators.emplace_back(std::move(authenticator));
467 authenticator->deleteLater();
471 void Core::registerAuthenticators()
473 if (_registeredAuthenticators.empty()) {
474 registerAuthenticator<SqlAuthenticator>();
476 registerAuthenticator<LdapAuthenticator>();
482 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
484 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
485 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
486 return authenticator->backendId() == backendId;
488 return it != _registeredAuthenticators.end() ? *it : nullptr;
492 // FIXME: Apparently, this is the legacy way of initting storage backends?
493 // If there's a not-legacy way, it should be used here
494 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
495 const QProcessEnvironment &environment, bool loadFromEnvironment,
498 if (backend.isEmpty()) {
499 quWarning() << "No authenticator selected!";
503 auto auth = authenticator(backend);
505 qCritical() << "Selected auth backend is not available:" << backend;
509 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
511 case Authenticator::NeedsSetup:
513 return false; // trigger setup process
514 if (auth->setup(settings, environment, loadFromEnvironment))
515 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
518 // if initialization wasn't successful, we quit to keep from coming up unconfigured
519 case Authenticator::NotAvailable:
520 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
522 QCoreApplication::exit(EXIT_FAILURE);
526 case Authenticator::IsReady:
527 // delete all other backends
528 _registeredAuthenticators.clear();
531 _authenticator = std::move(auth);
536 /*** Network Management ***/
538 bool Core::sslSupported()
541 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
542 return sslServer && sslServer->isCertValid();
549 bool Core::reloadCerts()
552 SslServer *sslServerv4 = qobject_cast<SslServer *>(&_server);
553 bool retv4 = sslServerv4->reloadCerts();
555 SslServer *sslServerv6 = qobject_cast<SslServer *>(&_v6server);
556 bool retv6 = sslServerv6->reloadCerts();
558 return retv4 && retv6;
560 // SSL not supported, don't mark configuration reload as failed
566 void Core::cacheSysIdent()
568 if (isConfigured()) {
569 _authUserNames = _storage->getAllAuthUserNames();
574 QString Core::strictSysIdent(UserId user) const
576 if (_authUserNames.contains(user)) {
577 return _authUserNames[user];
580 // A new user got added since we last pulled our cache from the database.
581 // There's no way to avoid a database hit - we don't even know the authname!
582 instance()->cacheSysIdent();
584 if (_authUserNames.contains(user)) {
585 return _authUserNames[user];
588 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
589 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
590 return "unknown"; // Should we just terminate the program instead?
594 bool Core::startListening()
596 // in mono mode we only start a local port if a port is specified in the cli call
597 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
600 bool success = false;
601 uint port = Quassel::optionValue("port").toUInt();
603 const QString listen = Quassel::optionValue("listen");
604 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
605 if (listen_list.size() > 0) {
606 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
608 if (!addr.setAddress(listen_term)) {
609 qCritical() << qPrintable(
610 tr("Invalid listen address %1")
615 switch (addr.protocol()) {
616 case QAbstractSocket::IPv6Protocol:
617 if (_v6server.listen(addr, port)) {
618 quInfo() << qPrintable(
619 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
620 .arg(addr.toString())
621 .arg(_v6server.serverPort())
622 .arg(Quassel::buildInfo().protocolVersion)
627 quWarning() << qPrintable(
628 tr("Could not open IPv6 interface %1:%2: %3")
629 .arg(addr.toString())
631 .arg(_v6server.errorString()));
633 case QAbstractSocket::IPv4Protocol:
634 if (_server.listen(addr, port)) {
635 quInfo() << qPrintable(
636 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
637 .arg(addr.toString())
638 .arg(_server.serverPort())
639 .arg(Quassel::buildInfo().protocolVersion)
644 // if v6 succeeded on Any, the port will be already in use - don't display the error then
645 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
646 quWarning() << qPrintable(
647 tr("Could not open IPv4 interface %1:%2: %3")
648 .arg(addr.toString())
650 .arg(_server.errorString()));
654 qCritical() << qPrintable(
655 tr("Invalid listen address %1, unknown network protocol")
664 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
670 void Core::stopListening(const QString &reason)
672 bool wasListening = false;
673 if (_server.isListening()) {
677 if (_v6server.isListening()) {
682 if (reason.isEmpty())
683 quInfo() << "No longer listening for GUI clients.";
685 quInfo() << qPrintable(reason);
690 void Core::incomingConnection()
692 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
694 while (server->hasPendingConnections()) {
695 QTcpSocket *socket = server->nextPendingConnection();
697 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
698 _connectingClients.insert(handler);
700 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
701 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
702 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
704 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
707 stopListening(tr("Closing server for basic setup."));
713 // Potentially called during the initialization phase (before handing the connection off to the session)
714 void Core::clientDisconnected()
716 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
719 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
720 _connectingClients.remove(handler);
721 handler->deleteLater();
723 // make server listen again if still not configured
728 // TODO remove unneeded sessions - if necessary/possible...
729 // Suggestion: kill sessions if they are not connected to any network and client.
733 void Core::setupClientSession(RemotePeer *peer, UserId uid)
735 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
738 // From now on everything is handled by the client session
739 disconnect(handler, 0, this, 0);
740 _connectingClients.remove(handler);
741 handler->deleteLater();
743 // Find or create session for validated user
746 // as we are currently handling an event triggered by incoming data on this socket
747 // it is unsafe to directly move the socket to the client thread.
748 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
752 void Core::customEvent(QEvent *event)
754 if (event->type() == AddClientEventId) {
755 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
756 addClientHelper(addClientEvent->peer, addClientEvent->userId);
762 void Core::addClientHelper(RemotePeer *peer, UserId uid)
764 // Find or create session for validated user
765 SessionThread *session = sessionForUser(uid);
766 session->addClient(peer);
770 void Core::connectInternalPeer(QPointer<InternalPeer> peer)
772 if (_initialized && peer) {
773 setupInternalClientSession(peer);
776 _pendingInternalConnection = peer;
781 void Core::setupInternalClientSession(QPointer<InternalPeer> clientPeer)
785 setupCoreForInternalUsage();
790 uid = _storage->internalUser();
793 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
794 QCoreApplication::exit(EXIT_FAILURE);
799 quWarning() << "Client peer went away, not starting a session";
803 InternalPeer *corePeer = new InternalPeer(this);
804 corePeer->setPeer(clientPeer);
805 clientPeer->setPeer(corePeer);
807 // Find or create session for validated user
808 SessionThread *sessionThread = sessionForUser(uid);
809 sessionThread->addClient(corePeer);
813 SessionThread *Core::sessionForUser(UserId uid, bool restore)
815 if (_sessions.contains(uid))
816 return _sessions[uid];
818 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
819 _sessions[uid] = session;
825 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
827 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
831 QVariantList Core::backendInfo()
833 instance()->registerStorageBackends();
835 QVariantList backendInfos;
836 for (auto &&backend : instance()->_registeredStorageBackends) {
838 v["BackendId"] = backend->backendId();
839 v["DisplayName"] = backend->displayName();
840 v["Description"] = backend->description();
841 v["SetupData"] = backend->setupData(); // ignored by legacy clients
843 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
844 const auto &setupData = backend->setupData();
845 QStringList setupKeys;
846 QVariantMap setupDefaults;
847 for (int i = 0; i + 2 < setupData.size(); i += 3) {
848 setupKeys << setupData[i].toString();
849 setupDefaults[setupData[i].toString()] = setupData[i + 2];
851 v["SetupKeys"] = setupKeys;
852 v["SetupDefaults"] = setupDefaults;
853 // TODO Protocol Break: Remove
854 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
862 QVariantList Core::authenticatorInfo()
864 instance()->registerAuthenticators();
866 QVariantList authInfos;
867 for(auto &&backend : instance()->_registeredAuthenticators) {
869 v["BackendId"] = backend->backendId();
870 v["DisplayName"] = backend->displayName();
871 v["Description"] = backend->description();
872 v["SetupData"] = backend->setupData();
878 // migration / backend selection
879 bool Core::selectBackend(const QString &backend)
881 // reregister all storage backends
882 registerStorageBackends();
883 auto storage = storageBackend(backend);
885 QStringList backends;
886 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
887 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
888 return backend->displayName();
890 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
891 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
895 QVariantMap settings = promptForSettings(storage.get());
897 Storage::State storageState = storage->init(settings);
898 switch (storageState) {
899 case Storage::IsReady:
900 if (!saveBackendSettings(backend, settings)) {
901 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
903 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
904 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
906 case Storage::NotAvailable:
907 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
909 case Storage::NeedsSetup:
910 if (!storage->setup(settings)) {
911 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
915 if (storage->init(settings) != Storage::IsReady) {
916 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
920 if (!saveBackendSettings(backend, settings)) {
921 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
923 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
927 // let's see if we have a current storage object we can migrate from
928 auto reader = getMigrationReader(_storage.get());
929 auto writer = getMigrationWriter(storage.get());
930 if (reader && writer) {
931 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
934 if (reader->migrateTo(writer.get())) {
935 qDebug() << "Migration finished!";
936 qDebug() << qPrintable(tr("Migration finished!"));
937 if (!saveBackendSettings(backend, settings)) {
938 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
943 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
947 // inform the user why we cannot merge
949 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
952 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
955 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
958 // so we were unable to merge, but let's create a user \o/
959 _storage = std::move(storage);
964 // TODO: I am not sure if this function is implemented correctly.
965 // There is currently no concept of migraiton between auth backends.
966 bool Core::selectAuthenticator(const QString &backend)
968 // Register all authentication backends.
969 registerAuthenticators();
970 auto auther = authenticator(backend);
972 QStringList authenticators;
973 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
974 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
975 return authenticator->displayName();
977 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
978 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
982 QVariantMap settings = promptForSettings(auther.get());
984 Authenticator::State state = auther->init(settings);
986 case Authenticator::IsReady:
987 saveAuthenticatorSettings(backend, settings);
988 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
990 case Authenticator::NotAvailable:
991 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
993 case Authenticator::NeedsSetup:
994 if (!auther->setup(settings)) {
995 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
999 if (auther->init(settings) != Authenticator::IsReady) {
1000 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
1004 saveAuthenticatorSettings(backend, settings);
1005 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1008 _authenticator = std::move(auther);
1013 bool Core::createUser()
1015 QTextStream out(stdout);
1016 QTextStream in(stdin);
1017 out << "Add a new user:" << endl;
1018 out << "Username: ";
1020 QString username = in.readLine().trimmed();
1023 out << "Password: ";
1025 QString password = in.readLine().trimmed();
1027 out << "Repeat Password: ";
1029 QString password2 = in.readLine().trimmed();
1033 if (password != password2) {
1034 quWarning() << "Passwords don't match!";
1037 if (password.isEmpty()) {
1038 quWarning() << "Password is empty!";
1042 if (_configured && _storage->addUser(username, password).isValid()) {
1043 out << "Added user " << username << " successfully!" << endl;
1047 quWarning() << "Unable to add user:" << qPrintable(username);
1053 bool Core::changeUserPass(const QString &username)
1055 QTextStream out(stdout);
1056 QTextStream in(stdin);
1057 UserId userId = _storage->getUserId(username);
1058 if (!userId.isValid()) {
1059 out << "User " << username << " does not exist." << endl;
1063 if (!canChangeUserPassword(userId)) {
1064 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1068 out << "Change password for user: " << username << endl;
1071 out << "New Password: ";
1073 QString password = in.readLine().trimmed();
1075 out << "Repeat Password: ";
1077 QString password2 = in.readLine().trimmed();
1081 if (password != password2) {
1082 quWarning() << "Passwords don't match!";
1085 if (password.isEmpty()) {
1086 quWarning() << "Password is empty!";
1090 if (_configured && _storage->updateUser(userId, password)) {
1091 out << "Password changed successfully!" << endl;
1095 quWarning() << "Failed to change password!";
1101 bool Core::changeUserPassword(UserId userId, const QString &password)
1103 if (!isConfigured() || !userId.isValid())
1106 if (!canChangeUserPassword(userId))
1109 return instance()->_storage->updateUser(userId, password);
1112 // TODO: this code isn't currently 100% optimal because the core
1113 // doesn't know it can have multiple auth providers configured (there aren't
1114 // multiple auth providers at the moment anyway) and we have hardcoded the
1115 // Database provider to be always allowed.
1116 bool Core::canChangeUserPassword(UserId userId)
1118 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1119 if (authProvider != "Database") {
1120 if (authProvider != instance()->_authenticator->backendId()) {
1123 else if (instance()->_authenticator->canChangePassword()) {
1131 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1136 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1138 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1142 return sqlStorage->createMigrationReader();
1146 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1151 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1153 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1157 return sqlStorage->createMigrationWriter();
1161 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1163 QVariantMap dbsettings;
1164 dbsettings["Backend"] = backend;
1165 dbsettings["ConnectionProperties"] = settings;
1166 CoreSettings s = CoreSettings();
1167 s.setStorageSettings(dbsettings);
1172 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1174 QVariantMap dbsettings;
1175 dbsettings["Authenticator"] = backend;
1176 dbsettings["AuthProperties"] = settings;
1177 CoreSettings().setAuthSettings(dbsettings);
1180 // Generic version of promptForSettings that doesn't care what *type* of
1181 // backend it runs over.
1182 template<typename Backend>
1183 QVariantMap Core::promptForSettings(const Backend *backend)
1185 QVariantMap settings;
1186 const QVariantList& setupData = backend->setupData();
1188 if (setupData.isEmpty())
1191 QTextStream out(stdout);
1192 QTextStream in(stdin);
1193 out << "Default values are in brackets" << endl;
1195 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1196 QString key = setupData[i].toString();
1197 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1199 bool noEcho = key.toLower().contains("password");
1203 QString input = in.readLine().trimmed();
1209 QVariant value{setupData[i+2]};
1210 if (!input.isEmpty()) {
1211 switch (value.type()) {
1213 value = input.toInt();
1219 settings[key] = value;
1226 void Core::stdInEcho(bool on)
1228 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1230 GetConsoleMode(hStdin, &mode);
1232 mode |= ENABLE_ECHO_INPUT;
1234 mode &= ~ENABLE_ECHO_INPUT;
1235 SetConsoleMode(hStdin, mode);
1239 void Core::stdInEcho(bool on)
1242 tcgetattr(STDIN_FILENO, &t);
1247 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1250 #endif /* Q_OS_WIN */