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);
226 if (Quassel::isOptionSet("ident-daemon")) {
227 _identServer = new IdentServer(_strictIdentEnabled, this);
230 Quassel::registerReloadHandler([]() {
231 // Currently, only reloading SSL certificates and the sysident cache is supported
232 if (Core::instance()) {
233 Core::instance()->cacheSysIdent();
234 Core::instance()->reloadCerts();
240 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
241 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
244 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
245 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
247 if (!startListening()) {
248 QCoreApplication::exit(EXIT_FAILURE); // TODO make this less brutal
252 if (_configured && !Quassel::isOptionSet("norestore")) {
253 Core::restoreState();
258 if (_pendingInternalConnection) {
259 connectInternalPeer(_pendingInternalConnection);
260 _pendingInternalConnection = {};
266 /*** Session Restore ***/
268 void Core::saveState()
271 QVariantList activeSessions;
272 for (auto &&user : instance()->_sessions.keys())
273 activeSessions << QVariant::fromValue<UserId>(user);
274 _storage->setCoreState(activeSessions);
279 void Core::restoreState()
282 quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
285 if (_sessions.count()) {
286 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
291 /* We don't check, since we are at the first version since switching to Git
292 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
294 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
299 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
300 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
302 if (activeSessions.count() > 0) {
303 quInfo() << "Restoring previous core state...";
304 for(auto &&v : activeSessions) {
305 UserId user = v.value<UserId>();
306 sessionForUser(user, true);
314 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
316 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
320 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
323 return tr("Core is already configured! Not configuring again...");
325 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
326 return tr("Admin user or password not set.");
328 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
329 return tr("Could not setup storage!");
332 quInfo() << "Selected authenticator:" << authenticator;
333 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
335 return tr("Could not setup authenticator!");
338 if (!saveBackendSettings(backend, setupData)) {
339 return tr("Could not save backend settings, probably a permission problem.");
341 saveAuthenticatorSettings(authenticator, authSetupData);
343 quInfo() << qPrintable(tr("Creating admin user..."));
344 _storage->addUser(adminUser, adminPassword);
346 startListening(); // TODO check when we need this
351 QString Core::setupCoreForInternalUsage()
353 Q_ASSERT(!_registeredStorageBackends.empty());
355 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
357 for (int i = 0; i < 10; i++) {
359 pass += qrand() % 10;
362 // mono client currently needs sqlite
363 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
367 /*** Storage Handling ***/
369 template<typename Storage>
370 void Core::registerStorageBackend()
372 auto backend = makeDeferredShared<Storage>(this);
373 if (backend->isAvailable())
374 _registeredStorageBackends.emplace_back(std::move(backend));
376 backend->deleteLater();
380 void Core::registerStorageBackends()
382 if (_registeredStorageBackends.empty()) {
383 registerStorageBackend<SqliteStorage>();
384 registerStorageBackend<PostgreSqlStorage>();
389 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
391 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
392 [backendId](const DeferredSharedPtr<Storage> &backend) {
393 return backend->displayName() == backendId;
395 return it != _registeredStorageBackends.end() ? *it : nullptr;
399 // "Type" => "sqlite"
400 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
401 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
403 if (backend.isEmpty()) {
404 quWarning() << "No storage backend selected!";
408 auto storage = storageBackend(backend);
410 qCritical() << "Selected storage backend is not available:" << backend;
414 connect(storage.get(), SIGNAL(dbUpgradeInProgress(bool)), this, SIGNAL(dbUpgradeInProgress(bool)));
416 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
417 switch (storageState) {
418 case Storage::NeedsSetup:
420 return false; // trigger setup process
421 if (storage->setup(settings, environment, loadFromEnvironment))
422 return initStorage(backend, settings, environment, loadFromEnvironment, false);
425 // if initialization wasn't successful, we quit to keep from coming up unconfigured
426 case Storage::NotAvailable:
427 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
429 QCoreApplication::exit(EXIT_FAILURE);
433 case Storage::IsReady:
434 // delete all other backends
435 _registeredStorageBackends.clear();
436 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
437 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
440 _storage = std::move(storage);
445 void Core::syncStorage()
452 /*** Storage Access ***/
453 bool Core::createNetwork(UserId user, NetworkInfo &info)
455 NetworkId networkId = instance()->_storage->createNetwork(user, info);
456 if (!networkId.isValid())
459 info.networkId = networkId;
464 /*** Authenticators ***/
466 // Authentication handling, now independent from storage.
467 template<typename Authenticator>
468 void Core::registerAuthenticator()
470 auto authenticator = makeDeferredShared<Authenticator>(this);
471 if (authenticator->isAvailable())
472 _registeredAuthenticators.emplace_back(std::move(authenticator));
474 authenticator->deleteLater();
478 void Core::registerAuthenticators()
480 if (_registeredAuthenticators.empty()) {
481 registerAuthenticator<SqlAuthenticator>();
483 registerAuthenticator<LdapAuthenticator>();
489 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
491 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
492 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
493 return authenticator->backendId() == backendId;
495 return it != _registeredAuthenticators.end() ? *it : nullptr;
499 // FIXME: Apparently, this is the legacy way of initting storage backends?
500 // If there's a not-legacy way, it should be used here
501 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
502 const QProcessEnvironment &environment, bool loadFromEnvironment,
505 if (backend.isEmpty()) {
506 quWarning() << "No authenticator selected!";
510 auto auth = authenticator(backend);
512 qCritical() << "Selected auth backend is not available:" << backend;
516 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
518 case Authenticator::NeedsSetup:
520 return false; // trigger setup process
521 if (auth->setup(settings, environment, loadFromEnvironment))
522 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
525 // if initialization wasn't successful, we quit to keep from coming up unconfigured
526 case Authenticator::NotAvailable:
527 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
529 QCoreApplication::exit(EXIT_FAILURE);
533 case Authenticator::IsReady:
534 // delete all other backends
535 _registeredAuthenticators.clear();
538 _authenticator = std::move(auth);
543 /*** Network Management ***/
545 bool Core::sslSupported()
548 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
549 return sslServer && sslServer->isCertValid();
556 bool Core::reloadCerts()
559 SslServer *sslServerv4 = qobject_cast<SslServer *>(&_server);
560 bool retv4 = sslServerv4->reloadCerts();
562 SslServer *sslServerv6 = qobject_cast<SslServer *>(&_v6server);
563 bool retv6 = sslServerv6->reloadCerts();
565 return retv4 && retv6;
567 // SSL not supported, don't mark configuration reload as failed
573 void Core::cacheSysIdent()
575 if (isConfigured()) {
576 _authUserNames = _storage->getAllAuthUserNames();
581 QString Core::strictSysIdent(UserId user) const
583 if (_authUserNames.contains(user)) {
584 return _authUserNames[user];
587 // A new user got added since we last pulled our cache from the database.
588 // There's no way to avoid a database hit - we don't even know the authname!
589 instance()->cacheSysIdent();
591 if (_authUserNames.contains(user)) {
592 return _authUserNames[user];
595 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
596 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
597 return "unknown"; // Should we just terminate the program instead?
601 bool Core::startListening()
603 // in mono mode we only start a local port if a port is specified in the cli call
604 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
607 bool success = false;
608 uint port = Quassel::optionValue("port").toUInt();
610 const QString listen = Quassel::optionValue("listen");
611 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
612 if (listen_list.size() > 0) {
613 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
615 if (!addr.setAddress(listen_term)) {
616 qCritical() << qPrintable(
617 tr("Invalid listen address %1")
622 switch (addr.protocol()) {
623 case QAbstractSocket::IPv6Protocol:
624 if (_v6server.listen(addr, port)) {
625 quInfo() << qPrintable(
626 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
627 .arg(addr.toString())
628 .arg(_v6server.serverPort())
629 .arg(Quassel::buildInfo().protocolVersion)
634 quWarning() << qPrintable(
635 tr("Could not open IPv6 interface %1:%2: %3")
636 .arg(addr.toString())
638 .arg(_v6server.errorString()));
640 case QAbstractSocket::IPv4Protocol:
641 if (_server.listen(addr, port)) {
642 quInfo() << qPrintable(
643 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
644 .arg(addr.toString())
645 .arg(_server.serverPort())
646 .arg(Quassel::buildInfo().protocolVersion)
651 // if v6 succeeded on Any, the port will be already in use - don't display the error then
652 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
653 quWarning() << qPrintable(
654 tr("Could not open IPv4 interface %1:%2: %3")
655 .arg(addr.toString())
657 .arg(_server.errorString()));
661 qCritical() << qPrintable(
662 tr("Invalid listen address %1, unknown network protocol")
671 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
673 if (_identServer != nullptr) _identServer->startListening();
679 void Core::stopListening(const QString &reason)
681 if (_identServer != nullptr) _identServer->stopListening(reason);
683 bool wasListening = false;
684 if (_server.isListening()) {
688 if (_v6server.isListening()) {
693 if (reason.isEmpty())
694 quInfo() << "No longer listening for GUI clients.";
696 quInfo() << qPrintable(reason);
701 void Core::incomingConnection()
703 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
705 while (server->hasPendingConnections()) {
706 QTcpSocket *socket = server->nextPendingConnection();
708 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
709 _connectingClients.insert(handler);
711 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
712 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
713 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
715 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
718 stopListening(tr("Closing server for basic setup."));
724 // Potentially called during the initialization phase (before handing the connection off to the session)
725 void Core::clientDisconnected()
727 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
730 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
731 _connectingClients.remove(handler);
732 handler->deleteLater();
734 // make server listen again if still not configured
739 // TODO remove unneeded sessions - if necessary/possible...
740 // Suggestion: kill sessions if they are not connected to any network and client.
744 void Core::setupClientSession(RemotePeer *peer, UserId uid)
746 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
749 // From now on everything is handled by the client session
750 disconnect(handler, 0, this, 0);
751 _connectingClients.remove(handler);
752 handler->deleteLater();
754 // Find or create session for validated user
757 // as we are currently handling an event triggered by incoming data on this socket
758 // it is unsafe to directly move the socket to the client thread.
759 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
763 void Core::customEvent(QEvent *event)
765 if (event->type() == AddClientEventId) {
766 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
767 addClientHelper(addClientEvent->peer, addClientEvent->userId);
773 void Core::addClientHelper(RemotePeer *peer, UserId uid)
775 // Find or create session for validated user
776 SessionThread *session = sessionForUser(uid);
777 session->addClient(peer);
781 void Core::connectInternalPeer(QPointer<InternalPeer> peer)
783 if (_initialized && peer) {
784 setupInternalClientSession(peer);
787 _pendingInternalConnection = peer;
792 void Core::setupInternalClientSession(QPointer<InternalPeer> clientPeer)
796 setupCoreForInternalUsage();
801 uid = _storage->internalUser();
804 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
805 QCoreApplication::exit(EXIT_FAILURE);
810 quWarning() << "Client peer went away, not starting a session";
814 InternalPeer *corePeer = new InternalPeer(this);
815 corePeer->setPeer(clientPeer);
816 clientPeer->setPeer(corePeer);
818 // Find or create session for validated user
819 SessionThread *sessionThread = sessionForUser(uid);
820 sessionThread->addClient(corePeer);
824 SessionThread *Core::sessionForUser(UserId uid, bool restore)
826 if (_sessions.contains(uid))
827 return _sessions[uid];
829 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
830 _sessions[uid] = session;
836 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
838 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
842 QVariantList Core::backendInfo()
844 instance()->registerStorageBackends();
846 QVariantList backendInfos;
847 for (auto &&backend : instance()->_registeredStorageBackends) {
849 v["BackendId"] = backend->backendId();
850 v["DisplayName"] = backend->displayName();
851 v["Description"] = backend->description();
852 v["SetupData"] = backend->setupData(); // ignored by legacy clients
854 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
855 const auto &setupData = backend->setupData();
856 QStringList setupKeys;
857 QVariantMap setupDefaults;
858 for (int i = 0; i + 2 < setupData.size(); i += 3) {
859 setupKeys << setupData[i].toString();
860 setupDefaults[setupData[i].toString()] = setupData[i + 2];
862 v["SetupKeys"] = setupKeys;
863 v["SetupDefaults"] = setupDefaults;
864 // TODO Protocol Break: Remove
865 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
873 QVariantList Core::authenticatorInfo()
875 instance()->registerAuthenticators();
877 QVariantList authInfos;
878 for(auto &&backend : instance()->_registeredAuthenticators) {
880 v["BackendId"] = backend->backendId();
881 v["DisplayName"] = backend->displayName();
882 v["Description"] = backend->description();
883 v["SetupData"] = backend->setupData();
889 // migration / backend selection
890 bool Core::selectBackend(const QString &backend)
892 // reregister all storage backends
893 registerStorageBackends();
894 auto storage = storageBackend(backend);
896 QStringList backends;
897 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
898 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
899 return backend->displayName();
901 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
902 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
906 QVariantMap settings = promptForSettings(storage.get());
908 Storage::State storageState = storage->init(settings);
909 switch (storageState) {
910 case Storage::IsReady:
911 if (!saveBackendSettings(backend, settings)) {
912 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
914 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
915 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
917 case Storage::NotAvailable:
918 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
920 case Storage::NeedsSetup:
921 if (!storage->setup(settings)) {
922 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
926 if (storage->init(settings) != Storage::IsReady) {
927 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
931 if (!saveBackendSettings(backend, settings)) {
932 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
934 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
938 // let's see if we have a current storage object we can migrate from
939 auto reader = getMigrationReader(_storage.get());
940 auto writer = getMigrationWriter(storage.get());
941 if (reader && writer) {
942 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
945 if (reader->migrateTo(writer.get())) {
946 qDebug() << "Migration finished!";
947 qDebug() << qPrintable(tr("Migration finished!"));
948 if (!saveBackendSettings(backend, settings)) {
949 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
954 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
958 // inform the user why we cannot merge
960 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
963 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
966 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
969 // so we were unable to merge, but let's create a user \o/
970 _storage = std::move(storage);
975 // TODO: I am not sure if this function is implemented correctly.
976 // There is currently no concept of migraiton between auth backends.
977 bool Core::selectAuthenticator(const QString &backend)
979 // Register all authentication backends.
980 registerAuthenticators();
981 auto auther = authenticator(backend);
983 QStringList authenticators;
984 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
985 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
986 return authenticator->displayName();
988 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
989 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
993 QVariantMap settings = promptForSettings(auther.get());
995 Authenticator::State state = auther->init(settings);
997 case Authenticator::IsReady:
998 saveAuthenticatorSettings(backend, settings);
999 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1001 case Authenticator::NotAvailable:
1002 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
1004 case Authenticator::NeedsSetup:
1005 if (!auther->setup(settings)) {
1006 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
1010 if (auther->init(settings) != Authenticator::IsReady) {
1011 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
1015 saveAuthenticatorSettings(backend, settings);
1016 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1019 _authenticator = std::move(auther);
1024 bool Core::createUser()
1026 QTextStream out(stdout);
1027 QTextStream in(stdin);
1028 out << "Add a new user:" << endl;
1029 out << "Username: ";
1031 QString username = in.readLine().trimmed();
1034 out << "Password: ";
1036 QString password = in.readLine().trimmed();
1038 out << "Repeat Password: ";
1040 QString password2 = in.readLine().trimmed();
1044 if (password != password2) {
1045 quWarning() << "Passwords don't match!";
1048 if (password.isEmpty()) {
1049 quWarning() << "Password is empty!";
1053 if (_configured && _storage->addUser(username, password).isValid()) {
1054 out << "Added user " << username << " successfully!" << endl;
1058 quWarning() << "Unable to add user:" << qPrintable(username);
1064 bool Core::changeUserPass(const QString &username)
1066 QTextStream out(stdout);
1067 QTextStream in(stdin);
1068 UserId userId = _storage->getUserId(username);
1069 if (!userId.isValid()) {
1070 out << "User " << username << " does not exist." << endl;
1074 if (!canChangeUserPassword(userId)) {
1075 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1079 out << "Change password for user: " << username << endl;
1082 out << "New Password: ";
1084 QString password = in.readLine().trimmed();
1086 out << "Repeat Password: ";
1088 QString password2 = in.readLine().trimmed();
1092 if (password != password2) {
1093 quWarning() << "Passwords don't match!";
1096 if (password.isEmpty()) {
1097 quWarning() << "Password is empty!";
1101 if (_configured && _storage->updateUser(userId, password)) {
1102 out << "Password changed successfully!" << endl;
1106 quWarning() << "Failed to change password!";
1112 bool Core::changeUserPassword(UserId userId, const QString &password)
1114 if (!isConfigured() || !userId.isValid())
1117 if (!canChangeUserPassword(userId))
1120 return instance()->_storage->updateUser(userId, password);
1123 // TODO: this code isn't currently 100% optimal because the core
1124 // doesn't know it can have multiple auth providers configured (there aren't
1125 // multiple auth providers at the moment anyway) and we have hardcoded the
1126 // Database provider to be always allowed.
1127 bool Core::canChangeUserPassword(UserId userId)
1129 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1130 if (authProvider != "Database") {
1131 if (authProvider != instance()->_authenticator->backendId()) {
1134 else if (instance()->_authenticator->canChangePassword()) {
1142 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1147 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1149 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1153 return sqlStorage->createMigrationReader();
1157 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1162 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1164 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1168 return sqlStorage->createMigrationWriter();
1172 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1174 QVariantMap dbsettings;
1175 dbsettings["Backend"] = backend;
1176 dbsettings["ConnectionProperties"] = settings;
1177 CoreSettings s = CoreSettings();
1178 s.setStorageSettings(dbsettings);
1183 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1185 QVariantMap dbsettings;
1186 dbsettings["Authenticator"] = backend;
1187 dbsettings["AuthProperties"] = settings;
1188 CoreSettings().setAuthSettings(dbsettings);
1191 // Generic version of promptForSettings that doesn't care what *type* of
1192 // backend it runs over.
1193 template<typename Backend>
1194 QVariantMap Core::promptForSettings(const Backend *backend)
1196 QVariantMap settings;
1197 const QVariantList& setupData = backend->setupData();
1199 if (setupData.isEmpty())
1202 QTextStream out(stdout);
1203 QTextStream in(stdin);
1204 out << "Default values are in brackets" << endl;
1206 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1207 QString key = setupData[i].toString();
1208 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1210 bool noEcho = key.toLower().contains("password");
1214 QString input = in.readLine().trimmed();
1220 QVariant value{setupData[i+2]};
1221 if (!input.isEmpty()) {
1222 switch (value.type()) {
1224 value = input.toInt();
1230 settings[key] = value;
1237 void Core::stdInEcho(bool on)
1239 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1241 GetConsoleMode(hStdin, &mode);
1243 mode |= ENABLE_ECHO_INPUT;
1245 mode &= ~ENABLE_ECHO_INPUT;
1246 SetConsoleMode(hStdin, mode);
1250 void Core::stdInEcho(bool on)
1253 tcgetattr(STDIN_FILENO, &t);
1258 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1261 #endif /* Q_OS_WIN */