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 Quassel::loadTranslation(QLocale::system());
109 // check settings version
110 // so far, we only have 1
112 if (s.version() != 1) {
113 qCritical() << "Invalid core settings version, terminating!";
114 QCoreApplication::exit(EXIT_FAILURE);
118 // Set up storage and authentication backends
119 registerStorageBackends();
120 registerAuthenticators();
122 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
123 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
126 QVariantMap db_connectionProperties;
128 QString auth_authenticator;
129 QVariantMap auth_properties;
131 bool writeError = false;
133 if (config_from_environment) {
134 db_backend = environment.value("DB_BACKEND");
135 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
139 QVariantMap dbsettings = cs.storageSettings().toMap();
140 db_backend = dbsettings.value("Backend").toString();
141 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
143 QVariantMap authSettings = cs.authSettings().toMap();
144 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
145 auth_properties = authSettings.value("AuthProperties").toMap();
147 writeError = !cs.isWritable();
151 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
153 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
155 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
158 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
160 if (Quassel::isOptionSet("select-backend")) {
161 success &= selectBackend(Quassel::optionValue("select-backend"));
163 if (Quassel::isOptionSet("select-authenticator")) {
164 success &= selectAuthenticator(Quassel::optionValue("select-authenticator"));
166 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
171 if (config_from_environment) {
172 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
173 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
176 qWarning() << "Cannot configure from environment";
177 QCoreApplication::exit(EXIT_FAILURE);
182 if (_registeredStorageBackends.empty()) {
183 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
185 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
186 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
188 QCoreApplication::exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
193 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
194 QCoreApplication::exit(EXIT_FAILURE);
198 quInfo() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
202 if (Quassel::isOptionSet("add-user")) {
203 bool success = createUser();
204 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
208 if (Quassel::isOptionSet("change-userpass")) {
209 bool success = changeUserPass(Quassel::optionValue("change-userpass"));
210 QCoreApplication::exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
214 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
215 if (_strictIdentEnabled) {
219 if (Quassel::isOptionSet("oidentd")) {
220 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
223 Quassel::registerReloadHandler([]() {
224 // Currently, only reloading SSL certificates and the sysident cache is supported
225 if (Core::instance()) {
226 Core::instance()->cacheSysIdent();
227 Core::instance()->reloadCerts();
233 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
234 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
237 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
238 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
240 if (!startListening()) {
241 QCoreApplication::exit(EXIT_FAILURE); // TODO make this less brutal
245 if (_configured && !Quassel::isOptionSet("norestore")) {
246 Core::restoreState();
252 /*** Session Restore ***/
254 void Core::saveState()
257 QVariantList activeSessions;
258 for (auto &&user : instance()->_sessions.keys())
259 activeSessions << QVariant::fromValue<UserId>(user);
260 _storage->setCoreState(activeSessions);
265 void Core::restoreState()
268 quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
271 if (_sessions.count()) {
272 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
277 /* We don't check, since we are at the first version since switching to Git
278 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
280 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
285 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
286 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
288 if (activeSessions.count() > 0) {
289 quInfo() << "Restoring previous core state...";
290 for(auto &&v : activeSessions) {
291 UserId user = v.value<UserId>();
292 sessionForUser(user, true);
300 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
302 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
306 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
309 return tr("Core is already configured! Not configuring again...");
311 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
312 return tr("Admin user or password not set.");
314 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
315 return tr("Could not setup storage!");
318 quInfo() << "Selected authenticator:" << authenticator;
319 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
321 return tr("Could not setup authenticator!");
324 if (!saveBackendSettings(backend, setupData)) {
325 return tr("Could not save backend settings, probably a permission problem.");
327 saveAuthenticatorSettings(authenticator, authSetupData);
329 quInfo() << qPrintable(tr("Creating admin user..."));
330 _storage->addUser(adminUser, adminPassword);
332 startListening(); // TODO check when we need this
337 QString Core::setupCoreForInternalUsage()
339 Q_ASSERT(!_registeredStorageBackends.empty());
341 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
343 for (int i = 0; i < 10; i++) {
345 pass += qrand() % 10;
348 // mono client currently needs sqlite
349 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
353 /*** Storage Handling ***/
355 template<typename Storage>
356 void Core::registerStorageBackend()
358 auto backend = makeDeferredShared<Storage>(this);
359 if (backend->isAvailable())
360 _registeredStorageBackends.emplace_back(std::move(backend));
362 backend->deleteLater();
366 void Core::registerStorageBackends()
368 if (_registeredStorageBackends.empty()) {
369 registerStorageBackend<SqliteStorage>();
370 registerStorageBackend<PostgreSqlStorage>();
375 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
377 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
378 [backendId](const DeferredSharedPtr<Storage> &backend) {
379 return backend->displayName() == backendId;
381 return it != _registeredStorageBackends.end() ? *it : nullptr;
385 // "Type" => "sqlite"
386 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
387 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
389 if (backend.isEmpty()) {
390 quWarning() << "No storage backend selected!";
394 auto storage = storageBackend(backend);
396 qCritical() << "Selected storage backend is not available:" << backend;
400 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
401 switch (storageState) {
402 case Storage::NeedsSetup:
404 return false; // trigger setup process
405 if (storage->setup(settings, environment, loadFromEnvironment))
406 return initStorage(backend, settings, environment, loadFromEnvironment, false);
409 // if initialization wasn't successful, we quit to keep from coming up unconfigured
410 case Storage::NotAvailable:
411 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
413 QCoreApplication::exit(EXIT_FAILURE);
417 case Storage::IsReady:
418 // delete all other backends
419 _registeredStorageBackends.clear();
420 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
421 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
424 _storage = std::move(storage);
429 void Core::syncStorage()
436 /*** Storage Access ***/
437 bool Core::createNetwork(UserId user, NetworkInfo &info)
439 NetworkId networkId = instance()->_storage->createNetwork(user, info);
440 if (!networkId.isValid())
443 info.networkId = networkId;
448 /*** Authenticators ***/
450 // Authentication handling, now independent from storage.
451 template<typename Authenticator>
452 void Core::registerAuthenticator()
454 auto authenticator = makeDeferredShared<Authenticator>(this);
455 if (authenticator->isAvailable())
456 _registeredAuthenticators.emplace_back(std::move(authenticator));
458 authenticator->deleteLater();
462 void Core::registerAuthenticators()
464 if (_registeredAuthenticators.empty()) {
465 registerAuthenticator<SqlAuthenticator>();
467 registerAuthenticator<LdapAuthenticator>();
473 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
475 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
476 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
477 return authenticator->backendId() == backendId;
479 return it != _registeredAuthenticators.end() ? *it : nullptr;
483 // FIXME: Apparently, this is the legacy way of initting storage backends?
484 // If there's a not-legacy way, it should be used here
485 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
486 const QProcessEnvironment &environment, bool loadFromEnvironment,
489 if (backend.isEmpty()) {
490 quWarning() << "No authenticator selected!";
494 auto auth = authenticator(backend);
496 qCritical() << "Selected auth backend is not available:" << backend;
500 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
502 case Authenticator::NeedsSetup:
504 return false; // trigger setup process
505 if (auth->setup(settings, environment, loadFromEnvironment))
506 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
509 // if initialization wasn't successful, we quit to keep from coming up unconfigured
510 case Authenticator::NotAvailable:
511 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
513 QCoreApplication::exit(EXIT_FAILURE);
517 case Authenticator::IsReady:
518 // delete all other backends
519 _registeredAuthenticators.clear();
522 _authenticator = std::move(auth);
527 /*** Network Management ***/
529 bool Core::sslSupported()
532 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
533 return sslServer && sslServer->isCertValid();
540 bool Core::reloadCerts()
543 SslServer *sslServerv4 = qobject_cast<SslServer *>(&_server);
544 bool retv4 = sslServerv4->reloadCerts();
546 SslServer *sslServerv6 = qobject_cast<SslServer *>(&_v6server);
547 bool retv6 = sslServerv6->reloadCerts();
549 return retv4 && retv6;
551 // SSL not supported, don't mark configuration reload as failed
557 void Core::cacheSysIdent()
559 if (isConfigured()) {
560 _authUserNames = _storage->getAllAuthUserNames();
565 QString Core::strictSysIdent(UserId user) const
567 if (_authUserNames.contains(user)) {
568 return _authUserNames[user];
571 // A new user got added since we last pulled our cache from the database.
572 // There's no way to avoid a database hit - we don't even know the authname!
573 instance()->cacheSysIdent();
575 if (_authUserNames.contains(user)) {
576 return _authUserNames[user];
579 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
580 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
581 return "unknown"; // Should we just terminate the program instead?
585 bool Core::startListening()
587 // in mono mode we only start a local port if a port is specified in the cli call
588 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
591 bool success = false;
592 uint port = Quassel::optionValue("port").toUInt();
594 const QString listen = Quassel::optionValue("listen");
595 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
596 if (listen_list.size() > 0) {
597 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
599 if (!addr.setAddress(listen_term)) {
600 qCritical() << qPrintable(
601 tr("Invalid listen address %1")
606 switch (addr.protocol()) {
607 case QAbstractSocket::IPv6Protocol:
608 if (_v6server.listen(addr, port)) {
609 quInfo() << qPrintable(
610 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
611 .arg(addr.toString())
612 .arg(_v6server.serverPort())
613 .arg(Quassel::buildInfo().protocolVersion)
618 quWarning() << qPrintable(
619 tr("Could not open IPv6 interface %1:%2: %3")
620 .arg(addr.toString())
622 .arg(_v6server.errorString()));
624 case QAbstractSocket::IPv4Protocol:
625 if (_server.listen(addr, port)) {
626 quInfo() << qPrintable(
627 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
628 .arg(addr.toString())
629 .arg(_server.serverPort())
630 .arg(Quassel::buildInfo().protocolVersion)
635 // if v6 succeeded on Any, the port will be already in use - don't display the error then
636 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
637 quWarning() << qPrintable(
638 tr("Could not open IPv4 interface %1:%2: %3")
639 .arg(addr.toString())
641 .arg(_server.errorString()));
645 qCritical() << qPrintable(
646 tr("Invalid listen address %1, unknown network protocol")
655 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
661 void Core::stopListening(const QString &reason)
663 bool wasListening = false;
664 if (_server.isListening()) {
668 if (_v6server.isListening()) {
673 if (reason.isEmpty())
674 quInfo() << "No longer listening for GUI clients.";
676 quInfo() << qPrintable(reason);
681 void Core::incomingConnection()
683 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
685 while (server->hasPendingConnections()) {
686 QTcpSocket *socket = server->nextPendingConnection();
688 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
689 _connectingClients.insert(handler);
691 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
692 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
693 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
695 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
698 stopListening(tr("Closing server for basic setup."));
704 // Potentially called during the initialization phase (before handing the connection off to the session)
705 void Core::clientDisconnected()
707 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
710 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
711 _connectingClients.remove(handler);
712 handler->deleteLater();
714 // make server listen again if still not configured
719 // TODO remove unneeded sessions - if necessary/possible...
720 // Suggestion: kill sessions if they are not connected to any network and client.
724 void Core::setupClientSession(RemotePeer *peer, UserId uid)
726 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
729 // From now on everything is handled by the client session
730 disconnect(handler, 0, this, 0);
731 _connectingClients.remove(handler);
732 handler->deleteLater();
734 // Find or create session for validated user
737 // as we are currently handling an event triggered by incoming data on this socket
738 // it is unsafe to directly move the socket to the client thread.
739 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
743 void Core::customEvent(QEvent *event)
745 if (event->type() == AddClientEventId) {
746 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
747 addClientHelper(addClientEvent->peer, addClientEvent->userId);
753 void Core::addClientHelper(RemotePeer *peer, UserId uid)
755 // Find or create session for validated user
756 SessionThread *session = sessionForUser(uid);
757 session->addClient(peer);
761 void Core::setupInternalClientSession(InternalPeer *clientPeer)
765 setupCoreForInternalUsage();
770 uid = _storage->internalUser();
773 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
777 InternalPeer *corePeer = new InternalPeer(this);
778 corePeer->setPeer(clientPeer);
779 clientPeer->setPeer(corePeer);
781 // Find or create session for validated user
782 SessionThread *sessionThread = sessionForUser(uid);
783 sessionThread->addClient(corePeer);
787 SessionThread *Core::sessionForUser(UserId uid, bool restore)
789 if (_sessions.contains(uid))
790 return _sessions[uid];
792 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
793 _sessions[uid] = session;
799 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
801 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
805 QVariantList Core::backendInfo()
807 instance()->registerStorageBackends();
809 QVariantList backendInfos;
810 for (auto &&backend : instance()->_registeredStorageBackends) {
812 v["BackendId"] = backend->backendId();
813 v["DisplayName"] = backend->displayName();
814 v["Description"] = backend->description();
815 v["SetupData"] = backend->setupData(); // ignored by legacy clients
817 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
818 const auto &setupData = backend->setupData();
819 QStringList setupKeys;
820 QVariantMap setupDefaults;
821 for (int i = 0; i + 2 < setupData.size(); i += 3) {
822 setupKeys << setupData[i].toString();
823 setupDefaults[setupData[i].toString()] = setupData[i + 2];
825 v["SetupKeys"] = setupKeys;
826 v["SetupDefaults"] = setupDefaults;
827 // TODO Protocol Break: Remove
828 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
836 QVariantList Core::authenticatorInfo()
838 instance()->registerAuthenticators();
840 QVariantList authInfos;
841 for(auto &&backend : instance()->_registeredAuthenticators) {
843 v["BackendId"] = backend->backendId();
844 v["DisplayName"] = backend->displayName();
845 v["Description"] = backend->description();
846 v["SetupData"] = backend->setupData();
852 // migration / backend selection
853 bool Core::selectBackend(const QString &backend)
855 // reregister all storage backends
856 registerStorageBackends();
857 auto storage = storageBackend(backend);
859 QStringList backends;
860 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
861 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
862 return backend->displayName();
864 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
865 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
869 QVariantMap settings = promptForSettings(storage.get());
871 Storage::State storageState = storage->init(settings);
872 switch (storageState) {
873 case Storage::IsReady:
874 if (!saveBackendSettings(backend, settings)) {
875 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
877 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
878 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
880 case Storage::NotAvailable:
881 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
883 case Storage::NeedsSetup:
884 if (!storage->setup(settings)) {
885 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
889 if (storage->init(settings) != Storage::IsReady) {
890 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
894 if (!saveBackendSettings(backend, settings)) {
895 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
897 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
901 // let's see if we have a current storage object we can migrate from
902 auto reader = getMigrationReader(_storage.get());
903 auto writer = getMigrationWriter(storage.get());
904 if (reader && writer) {
905 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
908 if (reader->migrateTo(writer.get())) {
909 qDebug() << "Migration finished!";
910 qDebug() << qPrintable(tr("Migration finished!"));
911 if (!saveBackendSettings(backend, settings)) {
912 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
917 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
921 // inform the user why we cannot merge
923 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
926 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
929 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
932 // so we were unable to merge, but let's create a user \o/
933 _storage = std::move(storage);
938 // TODO: I am not sure if this function is implemented correctly.
939 // There is currently no concept of migraiton between auth backends.
940 bool Core::selectAuthenticator(const QString &backend)
942 // Register all authentication backends.
943 registerAuthenticators();
944 auto auther = authenticator(backend);
946 QStringList authenticators;
947 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
948 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
949 return authenticator->displayName();
951 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
952 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
956 QVariantMap settings = promptForSettings(auther.get());
958 Authenticator::State state = auther->init(settings);
960 case Authenticator::IsReady:
961 saveAuthenticatorSettings(backend, settings);
962 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
964 case Authenticator::NotAvailable:
965 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
967 case Authenticator::NeedsSetup:
968 if (!auther->setup(settings)) {
969 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
973 if (auther->init(settings) != Authenticator::IsReady) {
974 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
978 saveAuthenticatorSettings(backend, settings);
979 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
982 _authenticator = std::move(auther);
987 bool Core::createUser()
989 QTextStream out(stdout);
990 QTextStream in(stdin);
991 out << "Add a new user:" << endl;
994 QString username = in.readLine().trimmed();
999 QString password = in.readLine().trimmed();
1001 out << "Repeat Password: ";
1003 QString password2 = in.readLine().trimmed();
1007 if (password != password2) {
1008 quWarning() << "Passwords don't match!";
1011 if (password.isEmpty()) {
1012 quWarning() << "Password is empty!";
1016 if (_configured && _storage->addUser(username, password).isValid()) {
1017 out << "Added user " << username << " successfully!" << endl;
1021 quWarning() << "Unable to add user:" << qPrintable(username);
1027 bool Core::changeUserPass(const QString &username)
1029 QTextStream out(stdout);
1030 QTextStream in(stdin);
1031 UserId userId = _storage->getUserId(username);
1032 if (!userId.isValid()) {
1033 out << "User " << username << " does not exist." << endl;
1037 if (!canChangeUserPassword(userId)) {
1038 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1042 out << "Change password for user: " << username << endl;
1045 out << "New Password: ";
1047 QString password = in.readLine().trimmed();
1049 out << "Repeat Password: ";
1051 QString password2 = in.readLine().trimmed();
1055 if (password != password2) {
1056 quWarning() << "Passwords don't match!";
1059 if (password.isEmpty()) {
1060 quWarning() << "Password is empty!";
1064 if (_configured && _storage->updateUser(userId, password)) {
1065 out << "Password changed successfully!" << endl;
1069 quWarning() << "Failed to change password!";
1075 bool Core::changeUserPassword(UserId userId, const QString &password)
1077 if (!isConfigured() || !userId.isValid())
1080 if (!canChangeUserPassword(userId))
1083 return instance()->_storage->updateUser(userId, password);
1086 // TODO: this code isn't currently 100% optimal because the core
1087 // doesn't know it can have multiple auth providers configured (there aren't
1088 // multiple auth providers at the moment anyway) and we have hardcoded the
1089 // Database provider to be always allowed.
1090 bool Core::canChangeUserPassword(UserId userId)
1092 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1093 if (authProvider != "Database") {
1094 if (authProvider != instance()->_authenticator->backendId()) {
1097 else if (instance()->_authenticator->canChangePassword()) {
1105 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1110 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1112 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1116 return sqlStorage->createMigrationReader();
1120 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1125 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1127 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1131 return sqlStorage->createMigrationWriter();
1135 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1137 QVariantMap dbsettings;
1138 dbsettings["Backend"] = backend;
1139 dbsettings["ConnectionProperties"] = settings;
1140 CoreSettings s = CoreSettings();
1141 s.setStorageSettings(dbsettings);
1146 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1148 QVariantMap dbsettings;
1149 dbsettings["Authenticator"] = backend;
1150 dbsettings["AuthProperties"] = settings;
1151 CoreSettings().setAuthSettings(dbsettings);
1154 // Generic version of promptForSettings that doesn't care what *type* of
1155 // backend it runs over.
1156 template<typename Backend>
1157 QVariantMap Core::promptForSettings(const Backend *backend)
1159 QVariantMap settings;
1160 const QVariantList& setupData = backend->setupData();
1162 if (setupData.isEmpty())
1165 QTextStream out(stdout);
1166 QTextStream in(stdin);
1167 out << "Default values are in brackets" << endl;
1169 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1170 QString key = setupData[i].toString();
1171 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1173 bool noEcho = key.toLower().contains("password");
1177 QString input = in.readLine().trimmed();
1183 QVariant value{setupData[i+2]};
1184 if (!input.isEmpty()) {
1185 switch (value.type()) {
1187 value = input.toInt();
1193 settings[key] = value;
1200 void Core::stdInEcho(bool on)
1202 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1204 GetConsoleMode(hStdin, &mode);
1206 mode |= ENABLE_ECHO_INPUT;
1208 mode &= ~ENABLE_ECHO_INPUT;
1209 SetConsoleMode(hStdin, mode);
1213 void Core::stdInEcho(bool on)
1216 tcgetattr(STDIN_FILENO, &t);
1221 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1224 #endif /* Q_OS_WIN */