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::instanceptr = 0;
71 Core *Core::instance()
73 if (instanceptr) return instanceptr;
74 instanceptr = new Core();
89 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
91 Quassel::loadTranslation(QLocale::system());
93 // check settings version
94 // so far, we only have 1
96 if (s.version() != 1) {
97 qCritical() << "Invalid core settings version, terminating!";
101 // Set up storage and authentication backends
102 registerStorageBackends();
103 registerAuthenticators();
105 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
106 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
112 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
113 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
116 QVariantMap db_connectionProperties;
118 QString auth_authenticator;
119 QVariantMap auth_properties;
121 bool writeError = false;
123 if (config_from_environment) {
124 db_backend = environment.value("DB_BACKEND");
125 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
129 QVariantMap dbsettings = cs.storageSettings().toMap();
130 db_backend = dbsettings.value("Backend").toString();
131 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
133 QVariantMap authSettings = cs.authSettings().toMap();
134 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
135 auth_properties = authSettings.value("AuthProperties").toMap();
137 writeError = !cs.isWritable();
141 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
143 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
145 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
148 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
149 if (Quassel::isOptionSet("select-backend")) {
150 selectBackend(Quassel::optionValue("select-backend"));
152 if (Quassel::isOptionSet("select-authenticator")) {
153 selectAuthenticator(Quassel::optionValue("select-authenticator"));
159 if (config_from_environment) {
160 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
161 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
164 qWarning() << "Cannot configure from environment";
168 if (_registeredStorageBackends.empty()) {
169 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
171 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
172 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
174 exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
176 quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
179 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
185 if (Quassel::isOptionSet("add-user")) {
186 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
190 if (Quassel::isOptionSet("change-userpass")) {
191 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
192 EXIT_SUCCESS : EXIT_FAILURE);
195 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
196 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
197 if (!startListening()) exit(1); // TODO make this less brutal
199 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
200 if (_strictIdentEnabled) {
204 if (Quassel::isOptionSet("oidentd")) {
205 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
212 // FIXME do we need more cleanup for handlers?
213 foreach(CoreAuthHandler *handler, _connectingClients) {
214 handler->deleteLater(); // disconnect non authed clients
216 qDeleteAll(_sessions);
220 /*** Session Restore ***/
222 void Core::saveState()
224 QVariantList activeSessions;
225 foreach(UserId user, instance()->_sessions.keys())
226 activeSessions << QVariant::fromValue<UserId>(user);
227 instance()->_storage->setCoreState(activeSessions);
231 void Core::restoreState()
233 if (!instance()->_configured) {
234 // quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
237 if (instance()->_sessions.count()) {
238 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
242 /* We don't check, since we are at the first version since switching to Git
243 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
245 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
250 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
251 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
253 if (activeSessions.count() > 0) {
254 quInfo() << "Restoring previous core state...";
255 foreach(QVariant v, activeSessions) {
256 UserId user = v.value<UserId>();
257 instance()->sessionForUser(user, true);
265 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
267 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
271 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
274 return tr("Core is already configured! Not configuring again...");
276 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
277 return tr("Admin user or password not set.");
279 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
280 return tr("Could not setup storage!");
283 quInfo() << "Selected authenticator:" << authenticator;
284 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
286 return tr("Could not setup authenticator!");
289 if (!saveBackendSettings(backend, setupData)) {
290 return tr("Could not save backend settings, probably a permission problem.");
292 saveAuthenticatorSettings(authenticator, authSetupData);
294 quInfo() << qPrintable(tr("Creating admin user..."));
295 _storage->addUser(adminUser, adminPassword);
297 startListening(); // TODO check when we need this
302 QString Core::setupCoreForInternalUsage()
304 Q_ASSERT(!_registeredStorageBackends.empty());
306 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
308 for (int i = 0; i < 10; i++) {
310 pass += qrand() % 10;
313 // mono client currently needs sqlite
314 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
318 /*** Storage Handling ***/
320 template<typename Storage>
321 void Core::registerStorageBackend()
323 auto backend = makeDeferredShared<Storage>(this);
324 if (backend->isAvailable())
325 _registeredStorageBackends.emplace_back(std::move(backend));
327 backend->deleteLater();
331 void Core::registerStorageBackends()
333 if (_registeredStorageBackends.empty()) {
334 registerStorageBackend<SqliteStorage>();
335 registerStorageBackend<PostgreSqlStorage>();
340 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
342 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
343 [backendId](const DeferredSharedPtr<Storage> &backend) {
344 return backend->displayName() == backendId;
346 return it != _registeredStorageBackends.end() ? *it : nullptr;
350 // "Type" => "sqlite"
351 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
352 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
354 if (backend.isEmpty()) {
355 quWarning() << "No storage backend selected!";
359 auto storage = storageBackend(backend);
361 qCritical() << "Selected storage backend is not available:" << backend;
365 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
366 switch (storageState) {
367 case Storage::NeedsSetup:
369 return false; // trigger setup process
370 if (storage->setup(settings, environment, loadFromEnvironment))
371 return initStorage(backend, settings, environment, loadFromEnvironment, false);
374 // if initialization wasn't successful, we quit to keep from coming up unconfigured
375 case Storage::NotAvailable:
376 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
381 case Storage::IsReady:
382 // delete all other backends
383 _registeredStorageBackends.clear();
384 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
385 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
388 _storage = std::move(storage);
393 void Core::syncStorage()
400 /*** Storage Access ***/
401 bool Core::createNetwork(UserId user, NetworkInfo &info)
403 NetworkId networkId = instance()->_storage->createNetwork(user, info);
404 if (!networkId.isValid())
407 info.networkId = networkId;
412 /*** Authenticators ***/
414 // Authentication handling, now independent from storage.
415 template<typename Authenticator>
416 void Core::registerAuthenticator()
418 auto authenticator = makeDeferredShared<Authenticator>(this);
419 if (authenticator->isAvailable())
420 _registeredAuthenticators.emplace_back(std::move(authenticator));
422 authenticator->deleteLater();
426 void Core::registerAuthenticators()
428 if (_registeredAuthenticators.empty()) {
429 registerAuthenticator<SqlAuthenticator>();
431 registerAuthenticator<LdapAuthenticator>();
437 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
439 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
440 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
441 return authenticator->backendId() == backendId;
443 return it != _registeredAuthenticators.end() ? *it : nullptr;
447 // FIXME: Apparently, this is the legacy way of initting storage backends?
448 // If there's a not-legacy way, it should be used here
449 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
450 const QProcessEnvironment &environment, bool loadFromEnvironment,
453 if (backend.isEmpty()) {
454 quWarning() << "No authenticator selected!";
458 auto auth = authenticator(backend);
460 qCritical() << "Selected auth backend is not available:" << backend;
464 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
466 case Authenticator::NeedsSetup:
468 return false; // trigger setup process
469 if (auth->setup(settings, environment, loadFromEnvironment))
470 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
473 // if initialization wasn't successful, we quit to keep from coming up unconfigured
474 case Authenticator::NotAvailable:
475 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
480 case Authenticator::IsReady:
481 // delete all other backends
482 _registeredAuthenticators.clear();
485 _authenticator = std::move(auth);
490 /*** Network Management ***/
492 bool Core::sslSupported()
495 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
496 return sslServer && sslServer->isCertValid();
503 bool Core::reloadCerts()
506 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
507 bool retv4 = sslServerv4->reloadCerts();
509 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
510 bool retv6 = sslServerv6->reloadCerts();
512 return retv4 && retv6;
514 // SSL not supported, don't mark configuration reload as failed
520 void Core::cacheSysIdent()
522 if (isConfigured()) {
523 instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
528 QString Core::strictSysIdent(UserId user) const
530 if (_authUserNames.contains(user)) {
531 return _authUserNames[user];
534 // A new user got added since we last pulled our cache from the database.
535 // There's no way to avoid a database hit - we don't even know the authname!
538 if (_authUserNames.contains(user)) {
539 return _authUserNames[user];
542 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
543 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
544 return "unknown"; // Should we just terminate the program instead?
548 bool Core::startListening()
550 // in mono mode we only start a local port if a port is specified in the cli call
551 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
554 bool success = false;
555 uint port = Quassel::optionValue("port").toUInt();
557 const QString listen = Quassel::optionValue("listen");
558 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
559 if (listen_list.size() > 0) {
560 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
562 if (!addr.setAddress(listen_term)) {
563 qCritical() << qPrintable(
564 tr("Invalid listen address %1")
569 switch (addr.protocol()) {
570 case QAbstractSocket::IPv6Protocol:
571 if (_v6server.listen(addr, port)) {
572 quInfo() << qPrintable(
573 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
574 .arg(addr.toString())
575 .arg(_v6server.serverPort())
576 .arg(Quassel::buildInfo().protocolVersion)
581 quWarning() << qPrintable(
582 tr("Could not open IPv6 interface %1:%2: %3")
583 .arg(addr.toString())
585 .arg(_v6server.errorString()));
587 case QAbstractSocket::IPv4Protocol:
588 if (_server.listen(addr, port)) {
589 quInfo() << qPrintable(
590 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
591 .arg(addr.toString())
592 .arg(_server.serverPort())
593 .arg(Quassel::buildInfo().protocolVersion)
598 // if v6 succeeded on Any, the port will be already in use - don't display the error then
599 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
600 quWarning() << qPrintable(
601 tr("Could not open IPv4 interface %1:%2: %3")
602 .arg(addr.toString())
604 .arg(_server.errorString()));
608 qCritical() << qPrintable(
609 tr("Invalid listen address %1, unknown network protocol")
618 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
624 void Core::stopListening(const QString &reason)
626 bool wasListening = false;
627 if (_server.isListening()) {
631 if (_v6server.isListening()) {
636 if (reason.isEmpty())
637 quInfo() << "No longer listening for GUI clients.";
639 quInfo() << qPrintable(reason);
644 void Core::incomingConnection()
646 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
648 while (server->hasPendingConnections()) {
649 QTcpSocket *socket = server->nextPendingConnection();
651 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
652 _connectingClients.insert(handler);
654 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
655 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
656 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
658 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
661 stopListening(tr("Closing server for basic setup."));
667 // Potentially called during the initialization phase (before handing the connection off to the session)
668 void Core::clientDisconnected()
670 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
673 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
674 _connectingClients.remove(handler);
675 handler->deleteLater();
677 // make server listen again if still not configured
682 // TODO remove unneeded sessions - if necessary/possible...
683 // Suggestion: kill sessions if they are not connected to any network and client.
687 void Core::setupClientSession(RemotePeer *peer, UserId uid)
689 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
692 // From now on everything is handled by the client session
693 disconnect(handler, 0, this, 0);
694 _connectingClients.remove(handler);
695 handler->deleteLater();
697 // Find or create session for validated user
700 // as we are currently handling an event triggered by incoming data on this socket
701 // it is unsafe to directly move the socket to the client thread.
702 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
706 void Core::customEvent(QEvent *event)
708 if (event->type() == AddClientEventId) {
709 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
710 addClientHelper(addClientEvent->peer, addClientEvent->userId);
716 void Core::addClientHelper(RemotePeer *peer, UserId uid)
718 // Find or create session for validated user
719 SessionThread *session = sessionForUser(uid);
720 session->addClient(peer);
724 void Core::setupInternalClientSession(InternalPeer *clientPeer)
728 setupCoreForInternalUsage();
733 uid = _storage->internalUser();
736 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
740 InternalPeer *corePeer = new InternalPeer(this);
741 corePeer->setPeer(clientPeer);
742 clientPeer->setPeer(corePeer);
744 // Find or create session for validated user
745 SessionThread *sessionThread = sessionForUser(uid);
746 sessionThread->addClient(corePeer);
750 SessionThread *Core::sessionForUser(UserId uid, bool restore)
752 if (_sessions.contains(uid))
753 return _sessions[uid];
755 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
756 _sessions[uid] = session;
762 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
764 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
768 QVariantList Core::backendInfo()
770 instance()->registerStorageBackends();
772 QVariantList backendInfos;
773 for (auto &&backend : instance()->_registeredStorageBackends) {
775 v["BackendId"] = backend->backendId();
776 v["DisplayName"] = backend->displayName();
777 v["Description"] = backend->description();
778 v["SetupData"] = backend->setupData(); // ignored by legacy clients
780 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
781 const auto &setupData = backend->setupData();
782 QStringList setupKeys;
783 QVariantMap setupDefaults;
784 for (int i = 0; i + 2 < setupData.size(); i += 3) {
785 setupKeys << setupData[i].toString();
786 setupDefaults[setupData[i].toString()] = setupData[i + 2];
788 v["SetupKeys"] = setupKeys;
789 v["SetupDefaults"] = setupDefaults;
790 // TODO Protocol Break: Remove
791 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
799 QVariantList Core::authenticatorInfo()
801 instance()->registerAuthenticators();
803 QVariantList authInfos;
804 for(auto &&backend : instance()->_registeredAuthenticators) {
806 v["BackendId"] = backend->backendId();
807 v["DisplayName"] = backend->displayName();
808 v["Description"] = backend->description();
809 v["SetupData"] = backend->setupData();
815 // migration / backend selection
816 bool Core::selectBackend(const QString &backend)
818 // reregister all storage backends
819 registerStorageBackends();
820 auto storage = storageBackend(backend);
822 QStringList backends;
823 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
824 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
825 return backend->displayName();
827 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
828 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
832 QVariantMap settings = promptForSettings(storage.get());
834 Storage::State storageState = storage->init(settings);
835 switch (storageState) {
836 case Storage::IsReady:
837 if (!saveBackendSettings(backend, settings)) {
838 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
840 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
841 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
843 case Storage::NotAvailable:
844 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
846 case Storage::NeedsSetup:
847 if (!storage->setup(settings)) {
848 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
852 if (storage->init(settings) != Storage::IsReady) {
853 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
857 if (!saveBackendSettings(backend, settings)) {
858 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
860 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
864 // let's see if we have a current storage object we can migrate from
865 auto reader = getMigrationReader(_storage.get());
866 auto writer = getMigrationWriter(storage.get());
867 if (reader && writer) {
868 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
871 if (reader->migrateTo(writer.get())) {
872 qDebug() << "Migration finished!";
873 qDebug() << qPrintable(tr("Migration finished!"));
874 if (!saveBackendSettings(backend, settings)) {
875 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
880 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
884 // inform the user why we cannot merge
886 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
889 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
892 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
895 // so we were unable to merge, but let's create a user \o/
896 _storage = std::move(storage);
901 // TODO: I am not sure if this function is implemented correctly.
902 // There is currently no concept of migraiton between auth backends.
903 bool Core::selectAuthenticator(const QString &backend)
905 // Register all authentication backends.
906 registerAuthenticators();
907 auto auther = authenticator(backend);
909 QStringList authenticators;
910 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
911 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
912 return authenticator->displayName();
914 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
915 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
919 QVariantMap settings = promptForSettings(auther.get());
921 Authenticator::State state = auther->init(settings);
923 case Authenticator::IsReady:
924 saveAuthenticatorSettings(backend, settings);
925 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
927 case Authenticator::NotAvailable:
928 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
930 case Authenticator::NeedsSetup:
931 if (!auther->setup(settings)) {
932 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
936 if (auther->init(settings) != Authenticator::IsReady) {
937 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
941 saveAuthenticatorSettings(backend, settings);
942 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
945 _authenticator = std::move(auther);
950 bool Core::createUser()
952 QTextStream out(stdout);
953 QTextStream in(stdin);
954 out << "Add a new user:" << endl;
957 QString username = in.readLine().trimmed();
962 QString password = in.readLine().trimmed();
964 out << "Repeat Password: ";
966 QString password2 = in.readLine().trimmed();
970 if (password != password2) {
971 quWarning() << "Passwords don't match!";
974 if (password.isEmpty()) {
975 quWarning() << "Password is empty!";
979 if (_configured && _storage->addUser(username, password).isValid()) {
980 out << "Added user " << username << " successfully!" << endl;
984 quWarning() << "Unable to add user:" << qPrintable(username);
990 bool Core::changeUserPass(const QString &username)
992 QTextStream out(stdout);
993 QTextStream in(stdin);
994 UserId userId = _storage->getUserId(username);
995 if (!userId.isValid()) {
996 out << "User " << username << " does not exist." << endl;
1000 if (!canChangeUserPassword(userId)) {
1001 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1005 out << "Change password for user: " << username << endl;
1008 out << "New Password: ";
1010 QString password = in.readLine().trimmed();
1012 out << "Repeat Password: ";
1014 QString password2 = in.readLine().trimmed();
1018 if (password != password2) {
1019 quWarning() << "Passwords don't match!";
1022 if (password.isEmpty()) {
1023 quWarning() << "Password is empty!";
1027 if (_configured && _storage->updateUser(userId, password)) {
1028 out << "Password changed successfully!" << endl;
1032 quWarning() << "Failed to change password!";
1038 bool Core::changeUserPassword(UserId userId, const QString &password)
1040 if (!isConfigured() || !userId.isValid())
1043 if (!canChangeUserPassword(userId))
1046 return instance()->_storage->updateUser(userId, password);
1049 // TODO: this code isn't currently 100% optimal because the core
1050 // doesn't know it can have multiple auth providers configured (there aren't
1051 // multiple auth providers at the moment anyway) and we have hardcoded the
1052 // Database provider to be always allowed.
1053 bool Core::canChangeUserPassword(UserId userId)
1055 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1056 if (authProvider != "Database") {
1057 if (authProvider != instance()->_authenticator->backendId()) {
1060 else if (instance()->_authenticator->canChangePassword()) {
1068 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1073 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1075 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1079 return sqlStorage->createMigrationReader();
1083 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1088 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1090 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1094 return sqlStorage->createMigrationWriter();
1098 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1100 QVariantMap dbsettings;
1101 dbsettings["Backend"] = backend;
1102 dbsettings["ConnectionProperties"] = settings;
1103 CoreSettings s = CoreSettings();
1104 s.setStorageSettings(dbsettings);
1109 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1111 QVariantMap dbsettings;
1112 dbsettings["Authenticator"] = backend;
1113 dbsettings["AuthProperties"] = settings;
1114 CoreSettings().setAuthSettings(dbsettings);
1117 // Generic version of promptForSettings that doesn't care what *type* of
1118 // backend it runs over.
1119 template<typename Backend>
1120 QVariantMap Core::promptForSettings(const Backend *backend)
1122 QVariantMap settings;
1123 const QVariantList& setupData = backend->setupData();
1125 if (setupData.isEmpty())
1128 QTextStream out(stdout);
1129 QTextStream in(stdin);
1130 out << "Default values are in brackets" << endl;
1132 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1133 QString key = setupData[i].toString();
1134 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1136 bool noEcho = key.toLower().contains("password");
1140 QString input = in.readLine().trimmed();
1146 QVariant value{setupData[i+2]};
1147 if (!input.isEmpty()) {
1148 switch (value.type()) {
1150 value = input.toInt();
1156 settings[key] = value;
1163 void Core::stdInEcho(bool on)
1165 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1167 GetConsoleMode(hStdin, &mode);
1169 mode |= ENABLE_ECHO_INPUT;
1171 mode &= ~ENABLE_ECHO_INPUT;
1172 SetConsoleMode(hStdin, mode);
1176 void Core::stdInEcho(bool on)
1179 tcgetattr(STDIN_FILENO, &t);
1184 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1187 #endif /* Q_OS_WIN */