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 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
102 // Move settings, note this does not delete the old files
104 QSettings newSettings("quassel-irc.org", "quasselcore");
108 QSettings::Format format = QSettings::IniFormat;
110 QSettings::Format format = QSettings::NativeFormat;
112 QString newFilePath = Quassel::configDirPath() + "quasselcore"
113 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
114 QSettings newSettings(newFilePath, format);
115 #endif /* Q_OS_MAC */
117 if (newSettings.value("Config/Version").toUInt() == 0) {
119 QString org = "quassel-irc.org";
121 QString org = "Quassel Project";
123 QSettings oldSettings(org, "Quassel Core");
124 if (oldSettings.allKeys().count()) {
125 quWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
126 foreach(QString key, oldSettings.allKeys())
127 newSettings.setValue(key, oldSettings.value(key));
128 newSettings.setValue("Config/Version", 1);
129 quWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
131 #ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
133 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
134 #elif defined Q_OS_MAC
135 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
137 QString quasselDir = QDir::homePath() + "/.quassel/";
140 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
141 if (!info.exists()) {
142 // move database, if we found it
143 QFile oldDb(quasselDir + "quassel-storage.sqlite");
144 if (oldDb.exists()) {
145 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
147 quWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
149 quWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
153 QFileInfo certInfo(quasselDir + "quasselCert.pem");
154 if (certInfo.exists()) {
155 QFile cert(quasselDir + "quasselCert.pem");
156 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
158 quWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
160 quWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
162 #endif /* !Q_OS_MAC */
163 quWarning() << "*** Migration completed.\n\n";
168 // check settings version
169 // so far, we only have 1
171 if (s.version() != 1) {
172 qCritical() << "Invalid core settings version, terminating!";
176 // Set up storage and authentication backends
177 registerStorageBackends();
178 registerAuthenticators();
180 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
181 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
187 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
188 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
191 QVariantMap db_connectionProperties;
193 QString auth_authenticator;
194 QVariantMap auth_properties;
196 bool writeError = false;
198 if (config_from_environment) {
199 db_backend = environment.value("DB_BACKEND");
200 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
204 QVariantMap dbsettings = cs.storageSettings().toMap();
205 db_backend = dbsettings.value("Backend").toString();
206 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
208 QVariantMap authSettings = cs.authSettings().toMap();
209 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
210 auth_properties = authSettings.value("AuthProperties").toMap();
212 writeError = !cs.isWritable();
216 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
218 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
220 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
223 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
224 if (Quassel::isOptionSet("select-backend")) {
225 selectBackend(Quassel::optionValue("select-backend"));
227 if (Quassel::isOptionSet("select-authenticator")) {
228 selectAuthenticator(Quassel::optionValue("select-authenticator"));
234 if (config_from_environment) {
235 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
236 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
239 qWarning() << "Cannot configure from environment";
243 if (_registeredStorageBackends.empty()) {
244 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
246 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
247 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
249 exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
251 quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
254 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
260 if (Quassel::isOptionSet("add-user")) {
261 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
265 if (Quassel::isOptionSet("change-userpass")) {
266 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
267 EXIT_SUCCESS : EXIT_FAILURE);
270 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
271 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
272 if (!startListening()) exit(1); // TODO make this less brutal
274 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
275 if (_strictIdentEnabled) {
279 if (Quassel::isOptionSet("oidentd")) {
280 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
287 // FIXME do we need more cleanup for handlers?
288 foreach(CoreAuthHandler *handler, _connectingClients) {
289 handler->deleteLater(); // disconnect non authed clients
291 qDeleteAll(_sessions);
295 /*** Session Restore ***/
297 void Core::saveState()
299 QVariantList activeSessions;
300 foreach(UserId user, instance()->_sessions.keys())
301 activeSessions << QVariant::fromValue<UserId>(user);
302 instance()->_storage->setCoreState(activeSessions);
306 void Core::restoreState()
308 if (!instance()->_configured) {
309 // quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
312 if (instance()->_sessions.count()) {
313 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
317 /* We don't check, since we are at the first version since switching to Git
318 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
320 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
325 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
326 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
328 if (activeSessions.count() > 0) {
329 quInfo() << "Restoring previous core state...";
330 foreach(QVariant v, activeSessions) {
331 UserId user = v.value<UserId>();
332 instance()->sessionForUser(user, true);
340 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
342 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
346 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
349 return tr("Core is already configured! Not configuring again...");
351 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
352 return tr("Admin user or password not set.");
354 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
355 return tr("Could not setup storage!");
358 quInfo() << "Selected authenticator:" << authenticator;
359 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
361 return tr("Could not setup authenticator!");
364 if (!saveBackendSettings(backend, setupData)) {
365 return tr("Could not save backend settings, probably a permission problem.");
367 saveAuthenticatorSettings(authenticator, authSetupData);
369 quInfo() << qPrintable(tr("Creating admin user..."));
370 _storage->addUser(adminUser, adminPassword);
372 startListening(); // TODO check when we need this
377 QString Core::setupCoreForInternalUsage()
379 Q_ASSERT(!_registeredStorageBackends.empty());
381 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
383 for (int i = 0; i < 10; i++) {
385 pass += qrand() % 10;
388 // mono client currently needs sqlite
389 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
393 /*** Storage Handling ***/
395 template<typename Storage>
396 void Core::registerStorageBackend()
398 auto backend = makeDeferredShared<Storage>(this);
399 if (backend->isAvailable())
400 _registeredStorageBackends.emplace_back(std::move(backend));
402 backend->deleteLater();
406 void Core::registerStorageBackends()
408 if (_registeredStorageBackends.empty()) {
409 registerStorageBackend<SqliteStorage>();
410 registerStorageBackend<PostgreSqlStorage>();
415 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
417 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
418 [backendId](const DeferredSharedPtr<Storage> &backend) {
419 return backend->displayName() == backendId;
421 return it != _registeredStorageBackends.end() ? *it : nullptr;
425 // "Type" => "sqlite"
426 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
427 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
429 if (backend.isEmpty()) {
430 quWarning() << "No storage backend selected!";
434 auto storage = storageBackend(backend);
436 qCritical() << "Selected storage backend is not available:" << backend;
440 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
441 switch (storageState) {
442 case Storage::NeedsSetup:
444 return false; // trigger setup process
445 if (storage->setup(settings, environment, loadFromEnvironment))
446 return initStorage(backend, settings, environment, loadFromEnvironment, false);
449 // if initialization wasn't successful, we quit to keep from coming up unconfigured
450 case Storage::NotAvailable:
451 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
456 case Storage::IsReady:
457 // delete all other backends
458 _registeredStorageBackends.clear();
459 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
460 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
463 _storage = std::move(storage);
468 void Core::syncStorage()
475 /*** Storage Access ***/
476 bool Core::createNetwork(UserId user, NetworkInfo &info)
478 NetworkId networkId = instance()->_storage->createNetwork(user, info);
479 if (!networkId.isValid())
482 info.networkId = networkId;
487 /*** Authenticators ***/
489 // Authentication handling, now independent from storage.
490 template<typename Authenticator>
491 void Core::registerAuthenticator()
493 auto authenticator = makeDeferredShared<Authenticator>(this);
494 if (authenticator->isAvailable())
495 _registeredAuthenticators.emplace_back(std::move(authenticator));
497 authenticator->deleteLater();
501 void Core::registerAuthenticators()
503 if (_registeredAuthenticators.empty()) {
504 registerAuthenticator<SqlAuthenticator>();
506 registerAuthenticator<LdapAuthenticator>();
512 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
514 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
515 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
516 return authenticator->backendId() == backendId;
518 return it != _registeredAuthenticators.end() ? *it : nullptr;
522 // FIXME: Apparently, this is the legacy way of initting storage backends?
523 // If there's a not-legacy way, it should be used here
524 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
525 const QProcessEnvironment &environment, bool loadFromEnvironment,
528 if (backend.isEmpty()) {
529 quWarning() << "No authenticator selected!";
533 auto auth = authenticator(backend);
535 qCritical() << "Selected auth backend is not available:" << backend;
539 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
541 case Authenticator::NeedsSetup:
543 return false; // trigger setup process
544 if (auth->setup(settings, environment, loadFromEnvironment))
545 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
548 // if initialization wasn't successful, we quit to keep from coming up unconfigured
549 case Authenticator::NotAvailable:
550 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
555 case Authenticator::IsReady:
556 // delete all other backends
557 _registeredAuthenticators.clear();
560 _authenticator = std::move(auth);
565 /*** Network Management ***/
567 bool Core::sslSupported()
570 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
571 return sslServer && sslServer->isCertValid();
578 bool Core::reloadCerts()
581 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
582 bool retv4 = sslServerv4->reloadCerts();
584 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
585 bool retv6 = sslServerv6->reloadCerts();
587 return retv4 && retv6;
589 // SSL not supported, don't mark configuration reload as failed
595 void Core::cacheSysIdent()
597 if (isConfigured()) {
598 instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
603 QString Core::strictSysIdent(UserId user) const
605 if (_authUserNames.contains(user)) {
606 return _authUserNames[user];
609 // A new user got added since we last pulled our cache from the database.
610 // There's no way to avoid a database hit - we don't even know the authname!
613 if (_authUserNames.contains(user)) {
614 return _authUserNames[user];
617 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
618 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
619 return "unknown"; // Should we just terminate the program instead?
623 bool Core::startListening()
625 // in mono mode we only start a local port if a port is specified in the cli call
626 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
629 bool success = false;
630 uint port = Quassel::optionValue("port").toUInt();
632 const QString listen = Quassel::optionValue("listen");
633 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
634 if (listen_list.size() > 0) {
635 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
637 if (!addr.setAddress(listen_term)) {
638 qCritical() << qPrintable(
639 tr("Invalid listen address %1")
644 switch (addr.protocol()) {
645 case QAbstractSocket::IPv6Protocol:
646 if (_v6server.listen(addr, port)) {
647 quInfo() << qPrintable(
648 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
649 .arg(addr.toString())
650 .arg(_v6server.serverPort())
651 .arg(Quassel::buildInfo().protocolVersion)
656 quWarning() << qPrintable(
657 tr("Could not open IPv6 interface %1:%2: %3")
658 .arg(addr.toString())
660 .arg(_v6server.errorString()));
662 case QAbstractSocket::IPv4Protocol:
663 if (_server.listen(addr, port)) {
664 quInfo() << qPrintable(
665 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
666 .arg(addr.toString())
667 .arg(_server.serverPort())
668 .arg(Quassel::buildInfo().protocolVersion)
673 // if v6 succeeded on Any, the port will be already in use - don't display the error then
674 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
675 quWarning() << qPrintable(
676 tr("Could not open IPv4 interface %1:%2: %3")
677 .arg(addr.toString())
679 .arg(_server.errorString()));
683 qCritical() << qPrintable(
684 tr("Invalid listen address %1, unknown network protocol")
693 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
699 void Core::stopListening(const QString &reason)
701 bool wasListening = false;
702 if (_server.isListening()) {
706 if (_v6server.isListening()) {
711 if (reason.isEmpty())
712 quInfo() << "No longer listening for GUI clients.";
714 quInfo() << qPrintable(reason);
719 void Core::incomingConnection()
721 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
723 while (server->hasPendingConnections()) {
724 QTcpSocket *socket = server->nextPendingConnection();
726 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
727 _connectingClients.insert(handler);
729 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
730 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
731 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
733 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
736 stopListening(tr("Closing server for basic setup."));
742 // Potentially called during the initialization phase (before handing the connection off to the session)
743 void Core::clientDisconnected()
745 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
748 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
749 _connectingClients.remove(handler);
750 handler->deleteLater();
752 // make server listen again if still not configured
757 // TODO remove unneeded sessions - if necessary/possible...
758 // Suggestion: kill sessions if they are not connected to any network and client.
762 void Core::setupClientSession(RemotePeer *peer, UserId uid)
764 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
767 // From now on everything is handled by the client session
768 disconnect(handler, 0, this, 0);
769 _connectingClients.remove(handler);
770 handler->deleteLater();
772 // Find or create session for validated user
775 // as we are currently handling an event triggered by incoming data on this socket
776 // it is unsafe to directly move the socket to the client thread.
777 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
781 void Core::customEvent(QEvent *event)
783 if (event->type() == AddClientEventId) {
784 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
785 addClientHelper(addClientEvent->peer, addClientEvent->userId);
791 void Core::addClientHelper(RemotePeer *peer, UserId uid)
793 // Find or create session for validated user
794 SessionThread *session = sessionForUser(uid);
795 session->addClient(peer);
799 void Core::setupInternalClientSession(InternalPeer *clientPeer)
803 setupCoreForInternalUsage();
808 uid = _storage->internalUser();
811 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
815 InternalPeer *corePeer = new InternalPeer(this);
816 corePeer->setPeer(clientPeer);
817 clientPeer->setPeer(corePeer);
819 // Find or create session for validated user
820 SessionThread *sessionThread = sessionForUser(uid);
821 sessionThread->addClient(corePeer);
825 SessionThread *Core::sessionForUser(UserId uid, bool restore)
827 if (_sessions.contains(uid))
828 return _sessions[uid];
830 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
831 _sessions[uid] = session;
837 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
839 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
843 QVariantList Core::backendInfo()
845 instance()->registerStorageBackends();
847 QVariantList backendInfos;
848 for (auto &&backend : instance()->_registeredStorageBackends) {
850 v["BackendId"] = backend->backendId();
851 v["DisplayName"] = backend->displayName();
852 v["Description"] = backend->description();
853 v["SetupData"] = backend->setupData(); // ignored by legacy clients
855 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
856 const auto &setupData = backend->setupData();
857 QStringList setupKeys;
858 QVariantMap setupDefaults;
859 for (int i = 0; i + 2 < setupData.size(); i += 3) {
860 setupKeys << setupData[i].toString();
861 setupDefaults[setupData[i].toString()] = setupData[i + 2];
863 v["SetupKeys"] = setupKeys;
864 v["SetupDefaults"] = setupDefaults;
865 // TODO Protocol Break: Remove
866 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
874 QVariantList Core::authenticatorInfo()
876 instance()->registerAuthenticators();
878 QVariantList authInfos;
879 for(auto &&backend : instance()->_registeredAuthenticators) {
881 v["BackendId"] = backend->backendId();
882 v["DisplayName"] = backend->displayName();
883 v["Description"] = backend->description();
884 v["SetupData"] = backend->setupData();
890 // migration / backend selection
891 bool Core::selectBackend(const QString &backend)
893 // reregister all storage backends
894 registerStorageBackends();
895 auto storage = storageBackend(backend);
897 QStringList backends;
898 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
899 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
900 return backend->displayName();
902 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
903 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
907 QVariantMap settings = promptForSettings(storage.get());
909 Storage::State storageState = storage->init(settings);
910 switch (storageState) {
911 case Storage::IsReady:
912 if (!saveBackendSettings(backend, settings)) {
913 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
915 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
916 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
918 case Storage::NotAvailable:
919 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
921 case Storage::NeedsSetup:
922 if (!storage->setup(settings)) {
923 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
927 if (storage->init(settings) != Storage::IsReady) {
928 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
932 if (!saveBackendSettings(backend, settings)) {
933 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
935 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
939 // let's see if we have a current storage object we can migrate from
940 auto reader = getMigrationReader(_storage.get());
941 auto writer = getMigrationWriter(storage.get());
942 if (reader && writer) {
943 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
946 if (reader->migrateTo(writer.get())) {
947 qDebug() << "Migration finished!";
948 qDebug() << qPrintable(tr("Migration finished!"));
949 if (!saveBackendSettings(backend, settings)) {
950 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
955 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
959 // inform the user why we cannot merge
961 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
964 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
967 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
970 // so we were unable to merge, but let's create a user \o/
971 _storage = std::move(storage);
976 // TODO: I am not sure if this function is implemented correctly.
977 // There is currently no concept of migraiton between auth backends.
978 bool Core::selectAuthenticator(const QString &backend)
980 // Register all authentication backends.
981 registerAuthenticators();
982 auto auther = authenticator(backend);
984 QStringList authenticators;
985 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
986 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
987 return authenticator->displayName();
989 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
990 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
994 QVariantMap settings = promptForSettings(auther.get());
996 Authenticator::State state = auther->init(settings);
998 case Authenticator::IsReady:
999 saveAuthenticatorSettings(backend, settings);
1000 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1002 case Authenticator::NotAvailable:
1003 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
1005 case Authenticator::NeedsSetup:
1006 if (!auther->setup(settings)) {
1007 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
1011 if (auther->init(settings) != Authenticator::IsReady) {
1012 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
1016 saveAuthenticatorSettings(backend, settings);
1017 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1020 _authenticator = std::move(auther);
1025 bool Core::createUser()
1027 QTextStream out(stdout);
1028 QTextStream in(stdin);
1029 out << "Add a new user:" << endl;
1030 out << "Username: ";
1032 QString username = in.readLine().trimmed();
1035 out << "Password: ";
1037 QString password = in.readLine().trimmed();
1039 out << "Repeat Password: ";
1041 QString password2 = in.readLine().trimmed();
1045 if (password != password2) {
1046 quWarning() << "Passwords don't match!";
1049 if (password.isEmpty()) {
1050 quWarning() << "Password is empty!";
1054 if (_configured && _storage->addUser(username, password).isValid()) {
1055 out << "Added user " << username << " successfully!" << endl;
1059 quWarning() << "Unable to add user:" << qPrintable(username);
1065 bool Core::changeUserPass(const QString &username)
1067 QTextStream out(stdout);
1068 QTextStream in(stdin);
1069 UserId userId = _storage->getUserId(username);
1070 if (!userId.isValid()) {
1071 out << "User " << username << " does not exist." << endl;
1075 if (!canChangeUserPassword(userId)) {
1076 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1080 out << "Change password for user: " << username << endl;
1083 out << "New Password: ";
1085 QString password = in.readLine().trimmed();
1087 out << "Repeat Password: ";
1089 QString password2 = in.readLine().trimmed();
1093 if (password != password2) {
1094 quWarning() << "Passwords don't match!";
1097 if (password.isEmpty()) {
1098 quWarning() << "Password is empty!";
1102 if (_configured && _storage->updateUser(userId, password)) {
1103 out << "Password changed successfully!" << endl;
1107 quWarning() << "Failed to change password!";
1113 bool Core::changeUserPassword(UserId userId, const QString &password)
1115 if (!isConfigured() || !userId.isValid())
1118 if (!canChangeUserPassword(userId))
1121 return instance()->_storage->updateUser(userId, password);
1124 // TODO: this code isn't currently 100% optimal because the core
1125 // doesn't know it can have multiple auth providers configured (there aren't
1126 // multiple auth providers at the moment anyway) and we have hardcoded the
1127 // Database provider to be always allowed.
1128 bool Core::canChangeUserPassword(UserId userId)
1130 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1131 if (authProvider != "Database") {
1132 if (authProvider != instance()->_authenticator->backendId()) {
1135 else if (instance()->_authenticator->canChangePassword()) {
1143 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1148 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1150 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1154 return sqlStorage->createMigrationReader();
1158 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1163 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1165 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1169 return sqlStorage->createMigrationWriter();
1173 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1175 QVariantMap dbsettings;
1176 dbsettings["Backend"] = backend;
1177 dbsettings["ConnectionProperties"] = settings;
1178 CoreSettings s = CoreSettings();
1179 s.setStorageSettings(dbsettings);
1184 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1186 QVariantMap dbsettings;
1187 dbsettings["Authenticator"] = backend;
1188 dbsettings["AuthProperties"] = settings;
1189 CoreSettings().setAuthSettings(dbsettings);
1192 // Generic version of promptForSettings that doesn't care what *type* of
1193 // backend it runs over.
1194 template<typename Backend>
1195 QVariantMap Core::promptForSettings(const Backend *backend)
1197 QVariantMap settings;
1198 const QVariantList& setupData = backend->setupData();
1200 if (setupData.isEmpty())
1203 QTextStream out(stdout);
1204 QTextStream in(stdin);
1205 out << "Default values are in brackets" << endl;
1207 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1208 QString key = setupData[i].toString();
1209 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1211 bool noEcho = key.toLower().contains("password");
1215 QString input = in.readLine().trimmed();
1221 QVariant value{setupData[i+2]};
1222 if (!input.isEmpty()) {
1223 switch (value.type()) {
1225 value = input.toInt();
1231 settings[key] = value;
1238 void Core::stdInEcho(bool on)
1240 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1242 GetConsoleMode(hStdin, &mode);
1244 mode |= ENABLE_ECHO_INPUT;
1246 mode &= ~ENABLE_ECHO_INPUT;
1247 SetConsoleMode(hStdin, mode);
1251 void Core::stdInEcho(bool on)
1254 tcgetattr(STDIN_FILENO, &t);
1259 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1262 #endif /* Q_OS_WIN */