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 if (Quassel::isOptionSet("oidentd")) {
275 _oidentdConfigGenerator = new OidentdConfigGenerator(Quassel::isOptionSet("oidentd-strict"), this);
276 if (Quassel::isOptionSet("oidentd-strict")) {
285 // FIXME do we need more cleanup for handlers?
286 foreach(CoreAuthHandler *handler, _connectingClients) {
287 handler->deleteLater(); // disconnect non authed clients
289 qDeleteAll(_sessions);
293 /*** Session Restore ***/
295 void Core::saveState()
297 QVariantList activeSessions;
298 foreach(UserId user, instance()->_sessions.keys())
299 activeSessions << QVariant::fromValue<UserId>(user);
300 instance()->_storage->setCoreState(activeSessions);
304 void Core::restoreState()
306 if (!instance()->_configured) {
307 // quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
310 if (instance()->_sessions.count()) {
311 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
315 /* We don't check, since we are at the first version since switching to Git
316 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
318 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
323 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
324 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
326 if (activeSessions.count() > 0) {
327 quInfo() << "Restoring previous core state...";
328 foreach(QVariant v, activeSessions) {
329 UserId user = v.value<UserId>();
330 instance()->sessionForUser(user, true);
338 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
340 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
344 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
347 return tr("Core is already configured! Not configuring again...");
349 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
350 return tr("Admin user or password not set.");
352 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
353 return tr("Could not setup storage!");
356 quInfo() << "Selected authenticator:" << authenticator;
357 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
359 return tr("Could not setup authenticator!");
362 if (!saveBackendSettings(backend, setupData)) {
363 return tr("Could not save backend settings, probably a permission problem.");
365 saveAuthenticatorSettings(authenticator, authSetupData);
367 quInfo() << qPrintable(tr("Creating admin user..."));
368 _storage->addUser(adminUser, adminPassword);
370 startListening(); // TODO check when we need this
375 QString Core::setupCoreForInternalUsage()
377 Q_ASSERT(!_registeredStorageBackends.empty());
379 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
381 for (int i = 0; i < 10; i++) {
383 pass += qrand() % 10;
386 // mono client currently needs sqlite
387 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
391 /*** Storage Handling ***/
393 template<typename Storage>
394 void Core::registerStorageBackend()
396 auto backend = makeDeferredShared<Storage>(this);
397 if (backend->isAvailable())
398 _registeredStorageBackends.emplace_back(std::move(backend));
400 backend->deleteLater();
404 void Core::registerStorageBackends()
406 if (_registeredStorageBackends.empty()) {
407 registerStorageBackend<SqliteStorage>();
408 registerStorageBackend<PostgreSqlStorage>();
413 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
415 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
416 [backendId](const DeferredSharedPtr<Storage> &backend) {
417 return backend->displayName() == backendId;
419 return it != _registeredStorageBackends.end() ? *it : nullptr;
423 // "Type" => "sqlite"
424 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
425 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
427 if (backend.isEmpty()) {
428 quWarning() << "No storage backend selected!";
432 auto storage = storageBackend(backend);
434 qCritical() << "Selected storage backend is not available:" << backend;
438 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
439 switch (storageState) {
440 case Storage::NeedsSetup:
442 return false; // trigger setup process
443 if (storage->setup(settings, environment, loadFromEnvironment))
444 return initStorage(backend, settings, environment, loadFromEnvironment, false);
447 // if initialization wasn't successful, we quit to keep from coming up unconfigured
448 case Storage::NotAvailable:
449 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
454 case Storage::IsReady:
455 // delete all other backends
456 _registeredStorageBackends.clear();
457 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
458 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
461 _storage = std::move(storage);
466 void Core::syncStorage()
473 /*** Storage Access ***/
474 bool Core::createNetwork(UserId user, NetworkInfo &info)
476 NetworkId networkId = instance()->_storage->createNetwork(user, info);
477 if (!networkId.isValid())
480 info.networkId = networkId;
485 /*** Authenticators ***/
487 // Authentication handling, now independent from storage.
488 template<typename Authenticator>
489 void Core::registerAuthenticator()
491 auto authenticator = makeDeferredShared<Authenticator>(this);
492 if (authenticator->isAvailable())
493 _registeredAuthenticators.emplace_back(std::move(authenticator));
495 authenticator->deleteLater();
499 void Core::registerAuthenticators()
501 if (_registeredAuthenticators.empty()) {
502 registerAuthenticator<SqlAuthenticator>();
504 registerAuthenticator<LdapAuthenticator>();
510 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
512 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
513 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
514 return authenticator->backendId() == backendId;
516 return it != _registeredAuthenticators.end() ? *it : nullptr;
520 // FIXME: Apparently, this is the legacy way of initting storage backends?
521 // If there's a not-legacy way, it should be used here
522 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
523 const QProcessEnvironment &environment, bool loadFromEnvironment,
526 if (backend.isEmpty()) {
527 quWarning() << "No authenticator selected!";
531 auto auth = authenticator(backend);
533 qCritical() << "Selected auth backend is not available:" << backend;
537 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
539 case Authenticator::NeedsSetup:
541 return false; // trigger setup process
542 if (auth->setup(settings, environment, loadFromEnvironment))
543 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
546 // if initialization wasn't successful, we quit to keep from coming up unconfigured
547 case Authenticator::NotAvailable:
548 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
553 case Authenticator::IsReady:
554 // delete all other backends
555 _registeredAuthenticators.clear();
558 _authenticator = std::move(auth);
563 /*** Network Management ***/
565 bool Core::sslSupported()
568 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
569 return sslServer && sslServer->isCertValid();
576 bool Core::reloadCerts()
579 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
580 bool retv4 = sslServerv4->reloadCerts();
582 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
583 bool retv6 = sslServerv6->reloadCerts();
585 return retv4 && retv6;
587 // SSL not supported, don't mark configuration reload as failed
593 void Core::cacheSysIdent()
595 if (isConfigured()) {
596 instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
601 QString Core::strictSysIdent(UserId user) const
603 if (_authUserNames.contains(user)) {
604 return _authUserNames[user];
607 // A new user got added since we last pulled our cache from the database.
608 // There's no way to avoid a database hit - we don't even know the authname!
611 if (_authUserNames.contains(user)) {
612 return _authUserNames[user];
615 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
616 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
617 return "unknown"; // Should we just terminate the program instead?
621 bool Core::startListening()
623 // in mono mode we only start a local port if a port is specified in the cli call
624 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
627 bool success = false;
628 uint port = Quassel::optionValue("port").toUInt();
630 const QString listen = Quassel::optionValue("listen");
631 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
632 if (listen_list.size() > 0) {
633 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
635 if (!addr.setAddress(listen_term)) {
636 qCritical() << qPrintable(
637 tr("Invalid listen address %1")
642 switch (addr.protocol()) {
643 case QAbstractSocket::IPv6Protocol:
644 if (_v6server.listen(addr, port)) {
645 quInfo() << qPrintable(
646 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
647 .arg(addr.toString())
648 .arg(_v6server.serverPort())
649 .arg(Quassel::buildInfo().protocolVersion)
654 quWarning() << qPrintable(
655 tr("Could not open IPv6 interface %1:%2: %3")
656 .arg(addr.toString())
658 .arg(_v6server.errorString()));
660 case QAbstractSocket::IPv4Protocol:
661 if (_server.listen(addr, port)) {
662 quInfo() << qPrintable(
663 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
664 .arg(addr.toString())
665 .arg(_server.serverPort())
666 .arg(Quassel::buildInfo().protocolVersion)
671 // if v6 succeeded on Any, the port will be already in use - don't display the error then
672 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
673 quWarning() << qPrintable(
674 tr("Could not open IPv4 interface %1:%2: %3")
675 .arg(addr.toString())
677 .arg(_server.errorString()));
681 qCritical() << qPrintable(
682 tr("Invalid listen address %1, unknown network protocol")
691 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
697 void Core::stopListening(const QString &reason)
699 bool wasListening = false;
700 if (_server.isListening()) {
704 if (_v6server.isListening()) {
709 if (reason.isEmpty())
710 quInfo() << "No longer listening for GUI clients.";
712 quInfo() << qPrintable(reason);
717 void Core::incomingConnection()
719 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
721 while (server->hasPendingConnections()) {
722 QTcpSocket *socket = server->nextPendingConnection();
724 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
725 _connectingClients.insert(handler);
727 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
728 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
729 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
731 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
734 stopListening(tr("Closing server for basic setup."));
740 // Potentially called during the initialization phase (before handing the connection off to the session)
741 void Core::clientDisconnected()
743 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
746 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
747 _connectingClients.remove(handler);
748 handler->deleteLater();
750 // make server listen again if still not configured
755 // TODO remove unneeded sessions - if necessary/possible...
756 // Suggestion: kill sessions if they are not connected to any network and client.
760 void Core::setupClientSession(RemotePeer *peer, UserId uid)
762 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
765 // From now on everything is handled by the client session
766 disconnect(handler, 0, this, 0);
767 _connectingClients.remove(handler);
768 handler->deleteLater();
770 // Find or create session for validated user
773 // as we are currently handling an event triggered by incoming data on this socket
774 // it is unsafe to directly move the socket to the client thread.
775 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
779 void Core::customEvent(QEvent *event)
781 if (event->type() == AddClientEventId) {
782 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
783 addClientHelper(addClientEvent->peer, addClientEvent->userId);
789 void Core::addClientHelper(RemotePeer *peer, UserId uid)
791 // Find or create session for validated user
792 SessionThread *session = sessionForUser(uid);
793 session->addClient(peer);
797 void Core::setupInternalClientSession(InternalPeer *clientPeer)
801 setupCoreForInternalUsage();
806 uid = _storage->internalUser();
809 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
813 InternalPeer *corePeer = new InternalPeer(this);
814 corePeer->setPeer(clientPeer);
815 clientPeer->setPeer(corePeer);
817 // Find or create session for validated user
818 SessionThread *sessionThread = sessionForUser(uid);
819 sessionThread->addClient(corePeer);
823 SessionThread *Core::sessionForUser(UserId uid, bool restore)
825 if (_sessions.contains(uid))
826 return _sessions[uid];
828 SessionThread *session = new SessionThread(uid, restore, this);
829 _sessions[uid] = session;
835 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
837 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
841 QVariantList Core::backendInfo()
843 instance()->registerStorageBackends();
845 QVariantList backendInfos;
846 for (auto &&backend : instance()->_registeredStorageBackends) {
848 v["BackendId"] = backend->backendId();
849 v["DisplayName"] = backend->displayName();
850 v["Description"] = backend->description();
851 v["SetupData"] = backend->setupData(); // ignored by legacy clients
853 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
854 const auto &setupData = backend->setupData();
855 QStringList setupKeys;
856 QVariantMap setupDefaults;
857 for (int i = 0; i + 2 < setupData.size(); i += 3) {
858 setupKeys << setupData[i].toString();
859 setupDefaults[setupData[i].toString()] = setupData[i + 2];
861 v["SetupKeys"] = setupKeys;
862 v["SetupDefaults"] = setupDefaults;
863 // TODO Protocol Break: Remove
864 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
872 QVariantList Core::authenticatorInfo()
874 instance()->registerAuthenticators();
876 QVariantList authInfos;
877 for(auto &&backend : instance()->_registeredAuthenticators) {
879 v["BackendId"] = backend->backendId();
880 v["DisplayName"] = backend->displayName();
881 v["Description"] = backend->description();
882 v["SetupData"] = backend->setupData();
888 // migration / backend selection
889 bool Core::selectBackend(const QString &backend)
891 // reregister all storage backends
892 registerStorageBackends();
893 auto storage = storageBackend(backend);
895 QStringList backends;
896 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
897 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
898 return backend->displayName();
900 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
901 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
905 QVariantMap settings = promptForSettings(storage.get());
907 Storage::State storageState = storage->init(settings);
908 switch (storageState) {
909 case Storage::IsReady:
910 if (!saveBackendSettings(backend, settings)) {
911 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
913 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
914 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
916 case Storage::NotAvailable:
917 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
919 case Storage::NeedsSetup:
920 if (!storage->setup(settings)) {
921 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
925 if (storage->init(settings) != Storage::IsReady) {
926 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
930 if (!saveBackendSettings(backend, settings)) {
931 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
933 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
937 // let's see if we have a current storage object we can migrate from
938 auto reader = getMigrationReader(_storage.get());
939 auto writer = getMigrationWriter(storage.get());
940 if (reader && writer) {
941 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
944 if (reader->migrateTo(writer.get())) {
945 qDebug() << "Migration finished!";
946 qDebug() << qPrintable(tr("Migration finished!"));
947 if (!saveBackendSettings(backend, settings)) {
948 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
953 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
957 // inform the user why we cannot merge
959 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
962 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
965 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
968 // so we were unable to merge, but let's create a user \o/
969 _storage = std::move(storage);
974 // TODO: I am not sure if this function is implemented correctly.
975 // There is currently no concept of migraiton between auth backends.
976 bool Core::selectAuthenticator(const QString &backend)
978 // Register all authentication backends.
979 registerAuthenticators();
980 auto auther = authenticator(backend);
982 QStringList authenticators;
983 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
984 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
985 return authenticator->displayName();
987 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
988 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
992 QVariantMap settings = promptForSettings(auther.get());
994 Authenticator::State state = auther->init(settings);
996 case Authenticator::IsReady:
997 saveAuthenticatorSettings(backend, settings);
998 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1000 case Authenticator::NotAvailable:
1001 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
1003 case Authenticator::NeedsSetup:
1004 if (!auther->setup(settings)) {
1005 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
1009 if (auther->init(settings) != Authenticator::IsReady) {
1010 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
1014 saveAuthenticatorSettings(backend, settings);
1015 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
1018 _authenticator = std::move(auther);
1023 bool Core::createUser()
1025 QTextStream out(stdout);
1026 QTextStream in(stdin);
1027 out << "Add a new user:" << endl;
1028 out << "Username: ";
1030 QString username = in.readLine().trimmed();
1033 out << "Password: ";
1035 QString password = in.readLine().trimmed();
1037 out << "Repeat Password: ";
1039 QString password2 = in.readLine().trimmed();
1043 if (password != password2) {
1044 quWarning() << "Passwords don't match!";
1047 if (password.isEmpty()) {
1048 quWarning() << "Password is empty!";
1052 if (_configured && _storage->addUser(username, password).isValid()) {
1053 out << "Added user " << username << " successfully!" << endl;
1057 quWarning() << "Unable to add user:" << qPrintable(username);
1063 bool Core::changeUserPass(const QString &username)
1065 QTextStream out(stdout);
1066 QTextStream in(stdin);
1067 UserId userId = _storage->getUserId(username);
1068 if (!userId.isValid()) {
1069 out << "User " << username << " does not exist." << endl;
1073 if (!canChangeUserPassword(userId)) {
1074 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1078 out << "Change password for user: " << username << endl;
1081 out << "New Password: ";
1083 QString password = in.readLine().trimmed();
1085 out << "Repeat Password: ";
1087 QString password2 = in.readLine().trimmed();
1091 if (password != password2) {
1092 quWarning() << "Passwords don't match!";
1095 if (password.isEmpty()) {
1096 quWarning() << "Password is empty!";
1100 if (_configured && _storage->updateUser(userId, password)) {
1101 out << "Password changed successfully!" << endl;
1105 quWarning() << "Failed to change password!";
1111 bool Core::changeUserPassword(UserId userId, const QString &password)
1113 if (!isConfigured() || !userId.isValid())
1116 if (!canChangeUserPassword(userId))
1119 return instance()->_storage->updateUser(userId, password);
1122 // TODO: this code isn't currently 100% optimal because the core
1123 // doesn't know it can have multiple auth providers configured (there aren't
1124 // multiple auth providers at the moment anyway) and we have hardcoded the
1125 // Database provider to be always allowed.
1126 bool Core::canChangeUserPassword(UserId userId)
1128 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1129 if (authProvider != "Database") {
1130 if (authProvider != instance()->_authenticator->backendId()) {
1133 else if (instance()->_authenticator->canChangePassword()) {
1141 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1146 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1148 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1152 return sqlStorage->createMigrationReader();
1156 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1161 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1163 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1167 return sqlStorage->createMigrationWriter();
1171 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1173 QVariantMap dbsettings;
1174 dbsettings["Backend"] = backend;
1175 dbsettings["ConnectionProperties"] = settings;
1176 CoreSettings s = CoreSettings();
1177 s.setStorageSettings(dbsettings);
1182 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1184 QVariantMap dbsettings;
1185 dbsettings["Authenticator"] = backend;
1186 dbsettings["AuthProperties"] = settings;
1187 CoreSettings().setAuthSettings(dbsettings);
1190 // Generic version of promptForSettings that doesn't care what *type* of
1191 // backend it runs over.
1192 template<typename Backend>
1193 QVariantMap Core::promptForSettings(const Backend *backend)
1195 QVariantMap settings;
1196 const QVariantList& setupData = backend->setupData();
1198 if (setupData.isEmpty())
1201 QTextStream out(stdout);
1202 QTextStream in(stdin);
1203 out << "Default values are in brackets" << endl;
1205 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1206 QString key = setupData[i].toString();
1207 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1209 bool noEcho = key.toLower().contains("password");
1213 QString input = in.readLine().trimmed();
1219 QVariant value{setupData[i+2]};
1220 if (!input.isEmpty()) {
1221 switch (value.type()) {
1223 value = input.toInt();
1229 settings[key] = value;
1236 void Core::stdInEcho(bool on)
1238 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1240 GetConsoleMode(hStdin, &mode);
1242 mode |= ENABLE_ECHO_INPUT;
1244 mode &= ~ENABLE_ECHO_INPUT;
1245 SetConsoleMode(hStdin, mode);
1249 void Core::stdInEcho(bool on)
1252 tcgetattr(STDIN_FILENO, &t);
1257 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1260 #endif /* Q_OS_WIN */