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"
53 # include <sys/types.h>
54 # include <sys/stat.h>
55 #endif /* HAVE_UMASK */
57 // ==============================
59 // ==============================
60 const int Core::AddClientEventId = QEvent::registerEventType();
62 class AddClientEvent : public QEvent
65 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
71 // ==============================
73 // ==============================
74 Core *Core::instanceptr = 0;
76 Core *Core::instance()
78 if (instanceptr) return instanceptr;
79 instanceptr = new Core();
95 umask(S_IRWXG | S_IRWXO);
97 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
99 Quassel::loadTranslation(QLocale::system());
101 // check settings version
102 // so far, we only have 1
104 if (s.version() != 1) {
105 qCritical() << "Invalid core settings version, terminating!";
109 // Set up storage and authentication backends
110 registerStorageBackends();
111 registerAuthenticators();
113 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
114 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
120 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
121 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
124 QVariantMap db_connectionProperties;
126 QString auth_authenticator;
127 QVariantMap auth_properties;
129 bool writeError = false;
131 if (config_from_environment) {
132 db_backend = environment.value("DB_BACKEND");
133 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
137 QVariantMap dbsettings = cs.storageSettings().toMap();
138 db_backend = dbsettings.value("Backend").toString();
139 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
141 QVariantMap authSettings = cs.authSettings().toMap();
142 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
143 auth_properties = authSettings.value("AuthProperties").toMap();
145 writeError = !cs.isWritable();
149 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
151 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
153 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
156 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
157 if (Quassel::isOptionSet("select-backend")) {
158 selectBackend(Quassel::optionValue("select-backend"));
160 if (Quassel::isOptionSet("select-authenticator")) {
161 selectAuthenticator(Quassel::optionValue("select-authenticator"));
167 if (config_from_environment) {
168 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
169 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
172 qWarning() << "Cannot configure from environment";
176 if (_registeredStorageBackends.empty()) {
177 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
179 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
180 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
182 exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
184 quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
187 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
193 if (Quassel::isOptionSet("add-user")) {
194 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
198 if (Quassel::isOptionSet("change-userpass")) {
199 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
200 EXIT_SUCCESS : EXIT_FAILURE);
203 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
204 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
205 if (!startListening()) exit(1); // TODO make this less brutal
207 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
208 if (_strictIdentEnabled) {
212 if (Quassel::isOptionSet("oidentd")) {
213 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
220 // FIXME do we need more cleanup for handlers?
221 foreach(CoreAuthHandler *handler, _connectingClients) {
222 handler->deleteLater(); // disconnect non authed clients
224 qDeleteAll(_sessions);
228 /*** Session Restore ***/
230 void Core::saveState()
232 QVariantList activeSessions;
233 foreach(UserId user, instance()->_sessions.keys())
234 activeSessions << QVariant::fromValue<UserId>(user);
235 instance()->_storage->setCoreState(activeSessions);
239 void Core::restoreState()
241 if (!instance()->_configured) {
242 // quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
245 if (instance()->_sessions.count()) {
246 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
250 /* We don't check, since we are at the first version since switching to Git
251 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
253 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
258 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
259 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
261 if (activeSessions.count() > 0) {
262 quInfo() << "Restoring previous core state...";
263 foreach(QVariant v, activeSessions) {
264 UserId user = v.value<UserId>();
265 instance()->sessionForUser(user, true);
273 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
275 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
279 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
282 return tr("Core is already configured! Not configuring again...");
284 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
285 return tr("Admin user or password not set.");
287 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
288 return tr("Could not setup storage!");
291 quInfo() << "Selected authenticator:" << authenticator;
292 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
294 return tr("Could not setup authenticator!");
297 if (!saveBackendSettings(backend, setupData)) {
298 return tr("Could not save backend settings, probably a permission problem.");
300 saveAuthenticatorSettings(authenticator, authSetupData);
302 quInfo() << qPrintable(tr("Creating admin user..."));
303 _storage->addUser(adminUser, adminPassword);
305 startListening(); // TODO check when we need this
310 QString Core::setupCoreForInternalUsage()
312 Q_ASSERT(!_registeredStorageBackends.empty());
314 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
316 for (int i = 0; i < 10; i++) {
318 pass += qrand() % 10;
321 // mono client currently needs sqlite
322 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
326 /*** Storage Handling ***/
328 template<typename Storage>
329 void Core::registerStorageBackend()
331 auto backend = makeDeferredShared<Storage>(this);
332 if (backend->isAvailable())
333 _registeredStorageBackends.emplace_back(std::move(backend));
335 backend->deleteLater();
339 void Core::registerStorageBackends()
341 if (_registeredStorageBackends.empty()) {
342 registerStorageBackend<SqliteStorage>();
343 registerStorageBackend<PostgreSqlStorage>();
348 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
350 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
351 [backendId](const DeferredSharedPtr<Storage> &backend) {
352 return backend->displayName() == backendId;
354 return it != _registeredStorageBackends.end() ? *it : nullptr;
358 // "Type" => "sqlite"
359 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
360 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
362 if (backend.isEmpty()) {
363 quWarning() << "No storage backend selected!";
367 auto storage = storageBackend(backend);
369 qCritical() << "Selected storage backend is not available:" << backend;
373 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
374 switch (storageState) {
375 case Storage::NeedsSetup:
377 return false; // trigger setup process
378 if (storage->setup(settings, environment, loadFromEnvironment))
379 return initStorage(backend, settings, environment, loadFromEnvironment, false);
382 // if initialization wasn't successful, we quit to keep from coming up unconfigured
383 case Storage::NotAvailable:
384 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
389 case Storage::IsReady:
390 // delete all other backends
391 _registeredStorageBackends.clear();
392 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
393 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
396 _storage = std::move(storage);
401 void Core::syncStorage()
408 /*** Storage Access ***/
409 bool Core::createNetwork(UserId user, NetworkInfo &info)
411 NetworkId networkId = instance()->_storage->createNetwork(user, info);
412 if (!networkId.isValid())
415 info.networkId = networkId;
420 /*** Authenticators ***/
422 // Authentication handling, now independent from storage.
423 template<typename Authenticator>
424 void Core::registerAuthenticator()
426 auto authenticator = makeDeferredShared<Authenticator>(this);
427 if (authenticator->isAvailable())
428 _registeredAuthenticators.emplace_back(std::move(authenticator));
430 authenticator->deleteLater();
434 void Core::registerAuthenticators()
436 if (_registeredAuthenticators.empty()) {
437 registerAuthenticator<SqlAuthenticator>();
439 registerAuthenticator<LdapAuthenticator>();
445 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
447 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
448 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
449 return authenticator->backendId() == backendId;
451 return it != _registeredAuthenticators.end() ? *it : nullptr;
455 // FIXME: Apparently, this is the legacy way of initting storage backends?
456 // If there's a not-legacy way, it should be used here
457 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
458 const QProcessEnvironment &environment, bool loadFromEnvironment,
461 if (backend.isEmpty()) {
462 quWarning() << "No authenticator selected!";
466 auto auth = authenticator(backend);
468 qCritical() << "Selected auth backend is not available:" << backend;
472 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
474 case Authenticator::NeedsSetup:
476 return false; // trigger setup process
477 if (auth->setup(settings, environment, loadFromEnvironment))
478 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
481 // if initialization wasn't successful, we quit to keep from coming up unconfigured
482 case Authenticator::NotAvailable:
483 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
488 case Authenticator::IsReady:
489 // delete all other backends
490 _registeredAuthenticators.clear();
493 _authenticator = std::move(auth);
498 /*** Network Management ***/
500 bool Core::sslSupported()
503 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
504 return sslServer && sslServer->isCertValid();
511 bool Core::reloadCerts()
514 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
515 bool retv4 = sslServerv4->reloadCerts();
517 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
518 bool retv6 = sslServerv6->reloadCerts();
520 return retv4 && retv6;
522 // SSL not supported, don't mark configuration reload as failed
528 void Core::cacheSysIdent()
530 if (isConfigured()) {
531 instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
536 QString Core::strictSysIdent(UserId user) const
538 if (_authUserNames.contains(user)) {
539 return _authUserNames[user];
542 // A new user got added since we last pulled our cache from the database.
543 // There's no way to avoid a database hit - we don't even know the authname!
546 if (_authUserNames.contains(user)) {
547 return _authUserNames[user];
550 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
551 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
552 return "unknown"; // Should we just terminate the program instead?
556 bool Core::startListening()
558 // in mono mode we only start a local port if a port is specified in the cli call
559 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
562 bool success = false;
563 uint port = Quassel::optionValue("port").toUInt();
565 const QString listen = Quassel::optionValue("listen");
566 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
567 if (listen_list.size() > 0) {
568 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
570 if (!addr.setAddress(listen_term)) {
571 qCritical() << qPrintable(
572 tr("Invalid listen address %1")
577 switch (addr.protocol()) {
578 case QAbstractSocket::IPv6Protocol:
579 if (_v6server.listen(addr, port)) {
580 quInfo() << qPrintable(
581 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
582 .arg(addr.toString())
583 .arg(_v6server.serverPort())
584 .arg(Quassel::buildInfo().protocolVersion)
589 quWarning() << qPrintable(
590 tr("Could not open IPv6 interface %1:%2: %3")
591 .arg(addr.toString())
593 .arg(_v6server.errorString()));
595 case QAbstractSocket::IPv4Protocol:
596 if (_server.listen(addr, port)) {
597 quInfo() << qPrintable(
598 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
599 .arg(addr.toString())
600 .arg(_server.serverPort())
601 .arg(Quassel::buildInfo().protocolVersion)
606 // if v6 succeeded on Any, the port will be already in use - don't display the error then
607 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
608 quWarning() << qPrintable(
609 tr("Could not open IPv4 interface %1:%2: %3")
610 .arg(addr.toString())
612 .arg(_server.errorString()));
616 qCritical() << qPrintable(
617 tr("Invalid listen address %1, unknown network protocol")
626 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
632 void Core::stopListening(const QString &reason)
634 bool wasListening = false;
635 if (_server.isListening()) {
639 if (_v6server.isListening()) {
644 if (reason.isEmpty())
645 quInfo() << "No longer listening for GUI clients.";
647 quInfo() << qPrintable(reason);
652 void Core::incomingConnection()
654 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
656 while (server->hasPendingConnections()) {
657 QTcpSocket *socket = server->nextPendingConnection();
659 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
660 _connectingClients.insert(handler);
662 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
663 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
664 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
666 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
669 stopListening(tr("Closing server for basic setup."));
675 // Potentially called during the initialization phase (before handing the connection off to the session)
676 void Core::clientDisconnected()
678 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
681 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
682 _connectingClients.remove(handler);
683 handler->deleteLater();
685 // make server listen again if still not configured
690 // TODO remove unneeded sessions - if necessary/possible...
691 // Suggestion: kill sessions if they are not connected to any network and client.
695 void Core::setupClientSession(RemotePeer *peer, UserId uid)
697 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
700 // From now on everything is handled by the client session
701 disconnect(handler, 0, this, 0);
702 _connectingClients.remove(handler);
703 handler->deleteLater();
705 // Find or create session for validated user
708 // as we are currently handling an event triggered by incoming data on this socket
709 // it is unsafe to directly move the socket to the client thread.
710 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
714 void Core::customEvent(QEvent *event)
716 if (event->type() == AddClientEventId) {
717 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
718 addClientHelper(addClientEvent->peer, addClientEvent->userId);
724 void Core::addClientHelper(RemotePeer *peer, UserId uid)
726 // Find or create session for validated user
727 SessionThread *session = sessionForUser(uid);
728 session->addClient(peer);
732 void Core::setupInternalClientSession(InternalPeer *clientPeer)
736 setupCoreForInternalUsage();
741 uid = _storage->internalUser();
744 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
748 InternalPeer *corePeer = new InternalPeer(this);
749 corePeer->setPeer(clientPeer);
750 clientPeer->setPeer(corePeer);
752 // Find or create session for validated user
753 SessionThread *sessionThread = sessionForUser(uid);
754 sessionThread->addClient(corePeer);
758 SessionThread *Core::sessionForUser(UserId uid, bool restore)
760 if (_sessions.contains(uid))
761 return _sessions[uid];
763 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
764 _sessions[uid] = session;
770 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
772 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
776 QVariantList Core::backendInfo()
778 instance()->registerStorageBackends();
780 QVariantList backendInfos;
781 for (auto &&backend : instance()->_registeredStorageBackends) {
783 v["BackendId"] = backend->backendId();
784 v["DisplayName"] = backend->displayName();
785 v["Description"] = backend->description();
786 v["SetupData"] = backend->setupData(); // ignored by legacy clients
788 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
789 const auto &setupData = backend->setupData();
790 QStringList setupKeys;
791 QVariantMap setupDefaults;
792 for (int i = 0; i + 2 < setupData.size(); i += 3) {
793 setupKeys << setupData[i].toString();
794 setupDefaults[setupData[i].toString()] = setupData[i + 2];
796 v["SetupKeys"] = setupKeys;
797 v["SetupDefaults"] = setupDefaults;
798 // TODO Protocol Break: Remove
799 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
807 QVariantList Core::authenticatorInfo()
809 instance()->registerAuthenticators();
811 QVariantList authInfos;
812 for(auto &&backend : instance()->_registeredAuthenticators) {
814 v["BackendId"] = backend->backendId();
815 v["DisplayName"] = backend->displayName();
816 v["Description"] = backend->description();
817 v["SetupData"] = backend->setupData();
823 // migration / backend selection
824 bool Core::selectBackend(const QString &backend)
826 // reregister all storage backends
827 registerStorageBackends();
828 auto storage = storageBackend(backend);
830 QStringList backends;
831 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
832 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
833 return backend->displayName();
835 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
836 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
840 QVariantMap settings = promptForSettings(storage.get());
842 Storage::State storageState = storage->init(settings);
843 switch (storageState) {
844 case Storage::IsReady:
845 if (!saveBackendSettings(backend, settings)) {
846 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
848 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
849 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
851 case Storage::NotAvailable:
852 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
854 case Storage::NeedsSetup:
855 if (!storage->setup(settings)) {
856 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
860 if (storage->init(settings) != Storage::IsReady) {
861 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
865 if (!saveBackendSettings(backend, settings)) {
866 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
868 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
872 // let's see if we have a current storage object we can migrate from
873 auto reader = getMigrationReader(_storage.get());
874 auto writer = getMigrationWriter(storage.get());
875 if (reader && writer) {
876 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
879 if (reader->migrateTo(writer.get())) {
880 qDebug() << "Migration finished!";
881 qDebug() << qPrintable(tr("Migration finished!"));
882 if (!saveBackendSettings(backend, settings)) {
883 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
888 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
892 // inform the user why we cannot merge
894 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
897 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
900 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
903 // so we were unable to merge, but let's create a user \o/
904 _storage = std::move(storage);
909 // TODO: I am not sure if this function is implemented correctly.
910 // There is currently no concept of migraiton between auth backends.
911 bool Core::selectAuthenticator(const QString &backend)
913 // Register all authentication backends.
914 registerAuthenticators();
915 auto auther = authenticator(backend);
917 QStringList authenticators;
918 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
919 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
920 return authenticator->displayName();
922 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
923 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
927 QVariantMap settings = promptForSettings(auther.get());
929 Authenticator::State state = auther->init(settings);
931 case Authenticator::IsReady:
932 saveAuthenticatorSettings(backend, settings);
933 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
935 case Authenticator::NotAvailable:
936 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
938 case Authenticator::NeedsSetup:
939 if (!auther->setup(settings)) {
940 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
944 if (auther->init(settings) != Authenticator::IsReady) {
945 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
949 saveAuthenticatorSettings(backend, settings);
950 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
953 _authenticator = std::move(auther);
958 bool Core::createUser()
960 QTextStream out(stdout);
961 QTextStream in(stdin);
962 out << "Add a new user:" << endl;
965 QString username = in.readLine().trimmed();
970 QString password = in.readLine().trimmed();
972 out << "Repeat Password: ";
974 QString password2 = in.readLine().trimmed();
978 if (password != password2) {
979 quWarning() << "Passwords don't match!";
982 if (password.isEmpty()) {
983 quWarning() << "Password is empty!";
987 if (_configured && _storage->addUser(username, password).isValid()) {
988 out << "Added user " << username << " successfully!" << endl;
992 quWarning() << "Unable to add user:" << qPrintable(username);
998 bool Core::changeUserPass(const QString &username)
1000 QTextStream out(stdout);
1001 QTextStream in(stdin);
1002 UserId userId = _storage->getUserId(username);
1003 if (!userId.isValid()) {
1004 out << "User " << username << " does not exist." << endl;
1008 if (!canChangeUserPassword(userId)) {
1009 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1013 out << "Change password for user: " << username << endl;
1016 out << "New Password: ";
1018 QString password = in.readLine().trimmed();
1020 out << "Repeat Password: ";
1022 QString password2 = in.readLine().trimmed();
1026 if (password != password2) {
1027 quWarning() << "Passwords don't match!";
1030 if (password.isEmpty()) {
1031 quWarning() << "Password is empty!";
1035 if (_configured && _storage->updateUser(userId, password)) {
1036 out << "Password changed successfully!" << endl;
1040 quWarning() << "Failed to change password!";
1046 bool Core::changeUserPassword(UserId userId, const QString &password)
1048 if (!isConfigured() || !userId.isValid())
1051 if (!canChangeUserPassword(userId))
1054 return instance()->_storage->updateUser(userId, password);
1057 // TODO: this code isn't currently 100% optimal because the core
1058 // doesn't know it can have multiple auth providers configured (there aren't
1059 // multiple auth providers at the moment anyway) and we have hardcoded the
1060 // Database provider to be always allowed.
1061 bool Core::canChangeUserPassword(UserId userId)
1063 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1064 if (authProvider != "Database") {
1065 if (authProvider != instance()->_authenticator->backendId()) {
1068 else if (instance()->_authenticator->canChangePassword()) {
1076 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1081 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1083 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1087 return sqlStorage->createMigrationReader();
1091 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1096 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1098 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1102 return sqlStorage->createMigrationWriter();
1106 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1108 QVariantMap dbsettings;
1109 dbsettings["Backend"] = backend;
1110 dbsettings["ConnectionProperties"] = settings;
1111 CoreSettings s = CoreSettings();
1112 s.setStorageSettings(dbsettings);
1117 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1119 QVariantMap dbsettings;
1120 dbsettings["Authenticator"] = backend;
1121 dbsettings["AuthProperties"] = settings;
1122 CoreSettings().setAuthSettings(dbsettings);
1125 // Generic version of promptForSettings that doesn't care what *type* of
1126 // backend it runs over.
1127 template<typename Backend>
1128 QVariantMap Core::promptForSettings(const Backend *backend)
1130 QVariantMap settings;
1131 const QVariantList& setupData = backend->setupData();
1133 if (setupData.isEmpty())
1136 QTextStream out(stdout);
1137 QTextStream in(stdin);
1138 out << "Default values are in brackets" << endl;
1140 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1141 QString key = setupData[i].toString();
1142 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1144 bool noEcho = key.toLower().contains("password");
1148 QString input = in.readLine().trimmed();
1154 QVariant value{setupData[i+2]};
1155 if (!input.isEmpty()) {
1156 switch (value.type()) {
1158 value = input.toInt();
1164 settings[key] = value;
1171 void Core::stdInEcho(bool on)
1173 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1175 GetConsoleMode(hStdin, &mode);
1177 mode |= ENABLE_ECHO_INPUT;
1179 mode &= ~ENABLE_ECHO_INPUT;
1180 SetConsoleMode(hStdin, mode);
1184 void Core::stdInEcho(bool on)
1187 tcgetattr(STDIN_FILENO, &t);
1192 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1195 #endif /* Q_OS_WIN */