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
189 QVariantMap dbsettings = cs.storageSettings().toMap();
190 _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());
192 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
194 QVariantMap authSettings = cs.authSettings().toMap();
195 initAuthenticator(authSettings.value("Authenticator", "Database").toString(), authSettings.value("AuthProperties").toMap());
198 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
199 if (Quassel::isOptionSet("select-backend")) {
200 selectBackend(Quassel::optionValue("select-backend"));
202 if (Quassel::isOptionSet("select-authenticator")) {
203 selectAuthenticator(Quassel::optionValue("select-authenticator"));
209 if (_registeredStorageBackends.size() == 0) {
210 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
211 quWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
212 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
214 exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
216 quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
218 if (!cs.isWritable()) {
219 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
225 if (Quassel::isOptionSet("add-user")) {
226 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
230 if (Quassel::isOptionSet("change-userpass")) {
231 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
232 EXIT_SUCCESS : EXIT_FAILURE);
235 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
236 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
237 if (!startListening()) exit(1); // TODO make this less brutal
239 if (Quassel::isOptionSet("oidentd")) {
240 _oidentdConfigGenerator = new OidentdConfigGenerator(Quassel::isOptionSet("oidentd-strict"), this);
241 if (Quassel::isOptionSet("oidentd-strict")) {
250 // FIXME do we need more cleanup for handlers?
251 foreach(CoreAuthHandler *handler, _connectingClients) {
252 handler->deleteLater(); // disconnect non authed clients
254 qDeleteAll(_sessions);
258 /*** Session Restore ***/
260 void Core::saveState()
264 QVariantList activeSessions;
265 foreach(UserId user, instance()->_sessions.keys())
266 activeSessions << QVariant::fromValue<UserId>(user);
267 state["CoreStateVersion"] = 1;
268 state["ActiveSessions"] = activeSessions;
269 s.setCoreState(state);
273 void Core::restoreState()
275 if (!instance()->_configured) {
276 // quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
279 if (instance()->_sessions.count()) {
280 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
284 /* We don't check, since we are at the first version since switching to Git
285 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
287 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
292 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
293 if (activeSessions.count() > 0) {
294 quInfo() << "Restoring previous core state...";
295 foreach(QVariant v, activeSessions) {
296 UserId user = v.value<UserId>();
297 instance()->sessionForUser(user, true);
305 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
307 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
311 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
314 return tr("Core is already configured! Not configuring again...");
316 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
317 return tr("Admin user or password not set.");
319 if (!(_configured = initStorage(backend, setupData, true))) {
320 return tr("Could not setup storage!");
323 quInfo() << "Selected authenticator:" << authenticator;
324 if (!(_configured = initAuthenticator(authenticator, authSetupData, true)))
326 return tr("Could not setup authenticator!");
329 if (!saveBackendSettings(backend, setupData)) {
330 return tr("Could not save backend settings, probably a permission problem.");
332 saveAuthenticatorSettings(authenticator, authSetupData);
334 quInfo() << qPrintable(tr("Creating admin user..."));
335 _storage->addUser(adminUser, adminPassword);
337 startListening(); // TODO check when we need this
342 QString Core::setupCoreForInternalUsage()
344 Q_ASSERT(!_registeredStorageBackends.empty());
346 qsrand(QDateTime::currentDateTime().toTime_t());
348 for (int i = 0; i < 10; i++) {
350 pass += qrand() % 10;
353 // mono client currently needs sqlite
354 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
358 /*** Storage Handling ***/
360 template<typename Storage>
361 void Core::registerStorageBackend()
363 auto backend = makeDeferredShared<Storage>(this);
364 if (backend->isAvailable())
365 _registeredStorageBackends.emplace_back(std::move(backend));
367 backend->deleteLater();
371 void Core::registerStorageBackends()
373 if (_registeredStorageBackends.empty()) {
374 registerStorageBackend<SqliteStorage>();
375 registerStorageBackend<PostgreSqlStorage>();
380 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
382 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
383 [backendId](const DeferredSharedPtr<Storage> &backend) {
384 return backend->displayName() == backendId;
386 return it != _registeredStorageBackends.end() ? *it : nullptr;
390 // "Type" => "sqlite"
391 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
393 if (backend.isEmpty()) {
394 quWarning() << "No storage backend selected!";
398 auto storage = storageBackend(backend);
400 qCritical() << "Selected storage backend is not available:" << backend;
404 Storage::State storageState = storage->init(settings);
405 switch (storageState) {
406 case Storage::NeedsSetup:
408 return false; // trigger setup process
409 if (storage->setup(settings))
410 return initStorage(backend, settings, false);
413 // if initialization wasn't successful, we quit to keep from coming up unconfigured
414 case Storage::NotAvailable:
415 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
420 case Storage::IsReady:
421 // delete all other backends
422 _registeredStorageBackends.clear();
423 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
424 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
427 _storage = std::move(storage);
432 void Core::syncStorage()
439 /*** Storage Access ***/
440 bool Core::createNetwork(UserId user, NetworkInfo &info)
442 NetworkId networkId = instance()->_storage->createNetwork(user, info);
443 if (!networkId.isValid())
446 info.networkId = networkId;
451 /*** Authenticators ***/
453 // Authentication handling, now independent from storage.
454 template<typename Authenticator>
455 void Core::registerAuthenticator()
457 auto authenticator = makeDeferredShared<Authenticator>(this);
458 if (authenticator->isAvailable())
459 _registeredAuthenticators.emplace_back(std::move(authenticator));
461 authenticator->deleteLater();
465 void Core::registerAuthenticators()
467 if (_registeredAuthenticators.empty()) {
468 registerAuthenticator<SqlAuthenticator>();
470 registerAuthenticator<LdapAuthenticator>();
476 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
478 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
479 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
480 return authenticator->backendId() == backendId;
482 return it != _registeredAuthenticators.end() ? *it : nullptr;
486 // FIXME: Apparently, this is the legacy way of initting storage backends?
487 // If there's a not-legacy way, it should be used here
488 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
490 if (backend.isEmpty()) {
491 quWarning() << "No authenticator selected!";
495 auto auth = authenticator(backend);
497 qCritical() << "Selected auth backend is not available:" << backend;
501 Authenticator::State authState = auth->init(settings);
503 case Authenticator::NeedsSetup:
505 return false; // trigger setup process
506 if (auth->setup(settings))
507 return initAuthenticator(backend, settings, false);
510 // if initialization wasn't successful, we quit to keep from coming up unconfigured
511 case Authenticator::NotAvailable:
512 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
517 case Authenticator::IsReady:
518 // delete all other backends
519 _registeredAuthenticators.clear();
522 _authenticator = std::move(auth);
527 /*** Network Management ***/
529 bool Core::sslSupported()
532 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
533 return sslServer && sslServer->isCertValid();
540 bool Core::reloadCerts()
543 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
544 bool retv4 = sslServerv4->reloadCerts();
546 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
547 bool retv6 = sslServerv6->reloadCerts();
549 return retv4 && retv6;
551 // SSL not supported, don't mark configuration reload as failed
557 void Core::cacheSysIdent()
559 if (isConfigured()) {
560 instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
565 QString Core::strictSysIdent(UserId user) const
567 if (_authUserNames.contains(user)) {
568 return _authUserNames[user];
571 // A new user got added since we last pulled our cache from the database.
572 // There's no way to avoid a database hit - we don't even know the authname!
575 if (_authUserNames.contains(user)) {
576 return _authUserNames[user];
579 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
580 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
581 return "unknown"; // Should we just terminate the program instead?
585 bool Core::startListening()
587 // in mono mode we only start a local port if a port is specified in the cli call
588 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
591 bool success = false;
592 uint port = Quassel::optionValue("port").toUInt();
594 const QString listen = Quassel::optionValue("listen");
595 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
596 if (listen_list.size() > 0) {
597 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
599 if (!addr.setAddress(listen_term)) {
600 qCritical() << qPrintable(
601 tr("Invalid listen address %1")
606 switch (addr.protocol()) {
607 case QAbstractSocket::IPv6Protocol:
608 if (_v6server.listen(addr, port)) {
609 quInfo() << qPrintable(
610 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
611 .arg(addr.toString())
612 .arg(_v6server.serverPort())
613 .arg(Quassel::buildInfo().protocolVersion)
618 quWarning() << qPrintable(
619 tr("Could not open IPv6 interface %1:%2: %3")
620 .arg(addr.toString())
622 .arg(_v6server.errorString()));
624 case QAbstractSocket::IPv4Protocol:
625 if (_server.listen(addr, port)) {
626 quInfo() << qPrintable(
627 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
628 .arg(addr.toString())
629 .arg(_server.serverPort())
630 .arg(Quassel::buildInfo().protocolVersion)
635 // if v6 succeeded on Any, the port will be already in use - don't display the error then
636 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
637 quWarning() << qPrintable(
638 tr("Could not open IPv4 interface %1:%2: %3")
639 .arg(addr.toString())
641 .arg(_server.errorString()));
645 qCritical() << qPrintable(
646 tr("Invalid listen address %1, unknown network protocol")
655 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
661 void Core::stopListening(const QString &reason)
663 bool wasListening = false;
664 if (_server.isListening()) {
668 if (_v6server.isListening()) {
673 if (reason.isEmpty())
674 quInfo() << "No longer listening for GUI clients.";
676 quInfo() << qPrintable(reason);
681 void Core::incomingConnection()
683 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
685 while (server->hasPendingConnections()) {
686 QTcpSocket *socket = server->nextPendingConnection();
688 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
689 _connectingClients.insert(handler);
691 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
692 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
693 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
695 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
698 stopListening(tr("Closing server for basic setup."));
704 // Potentially called during the initialization phase (before handing the connection off to the session)
705 void Core::clientDisconnected()
707 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
710 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
711 _connectingClients.remove(handler);
712 handler->deleteLater();
714 // make server listen again if still not configured
719 // TODO remove unneeded sessions - if necessary/possible...
720 // Suggestion: kill sessions if they are not connected to any network and client.
724 void Core::setupClientSession(RemotePeer *peer, UserId uid)
726 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
729 // From now on everything is handled by the client session
730 disconnect(handler, 0, this, 0);
731 _connectingClients.remove(handler);
732 handler->deleteLater();
734 // Find or create session for validated user
737 // as we are currently handling an event triggered by incoming data on this socket
738 // it is unsafe to directly move the socket to the client thread.
739 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
743 void Core::customEvent(QEvent *event)
745 if (event->type() == AddClientEventId) {
746 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
747 addClientHelper(addClientEvent->peer, addClientEvent->userId);
753 void Core::addClientHelper(RemotePeer *peer, UserId uid)
755 // Find or create session for validated user
756 SessionThread *session = sessionForUser(uid);
757 session->addClient(peer);
761 void Core::setupInternalClientSession(InternalPeer *clientPeer)
765 setupCoreForInternalUsage();
770 uid = _storage->internalUser();
773 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
777 InternalPeer *corePeer = new InternalPeer(this);
778 corePeer->setPeer(clientPeer);
779 clientPeer->setPeer(corePeer);
781 // Find or create session for validated user
782 SessionThread *sessionThread = sessionForUser(uid);
783 sessionThread->addClient(corePeer);
787 SessionThread *Core::sessionForUser(UserId uid, bool restore)
789 if (_sessions.contains(uid))
790 return _sessions[uid];
792 SessionThread *session = new SessionThread(uid, restore, this);
793 _sessions[uid] = session;
799 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
801 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
805 QVariantList Core::backendInfo()
807 instance()->registerStorageBackends();
809 QVariantList backendInfos;
810 for (auto &&backend : instance()->_registeredStorageBackends) {
812 v["BackendId"] = backend->backendId();
813 v["DisplayName"] = backend->displayName();
814 v["Description"] = backend->description();
815 v["SetupData"] = backend->setupData(); // ignored by legacy clients
817 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
818 const auto &setupData = backend->setupData();
819 QStringList setupKeys;
820 QVariantMap setupDefaults;
821 for (int i = 0; i + 2 < setupData.size(); i += 3) {
822 setupKeys << setupData[i].toString();
823 setupDefaults[setupData[i].toString()] = setupData[i + 2];
825 v["SetupKeys"] = setupKeys;
826 v["SetupDefaults"] = setupDefaults;
827 // TODO Protocol Break: Remove
828 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
836 QVariantList Core::authenticatorInfo()
838 instance()->registerAuthenticators();
840 QVariantList authInfos;
841 for(auto &&backend : instance()->_registeredAuthenticators) {
843 v["BackendId"] = backend->backendId();
844 v["DisplayName"] = backend->displayName();
845 v["Description"] = backend->description();
846 v["SetupData"] = backend->setupData();
852 // migration / backend selection
853 bool Core::selectBackend(const QString &backend)
855 // reregister all storage backends
856 registerStorageBackends();
857 auto storage = storageBackend(backend);
859 QStringList backends;
860 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
861 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
862 return backend->displayName();
864 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
865 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
869 QVariantMap settings = promptForSettings(storage.get());
871 Storage::State storageState = storage->init(settings);
872 switch (storageState) {
873 case Storage::IsReady:
874 if (!saveBackendSettings(backend, settings)) {
875 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
877 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
878 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
880 case Storage::NotAvailable:
881 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
883 case Storage::NeedsSetup:
884 if (!storage->setup(settings)) {
885 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
889 if (storage->init(settings) != Storage::IsReady) {
890 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
894 if (!saveBackendSettings(backend, settings)) {
895 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
897 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
901 // let's see if we have a current storage object we can migrate from
902 auto reader = getMigrationReader(_storage.get());
903 auto writer = getMigrationWriter(storage.get());
904 if (reader && writer) {
905 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
908 if (reader->migrateTo(writer.get())) {
909 qDebug() << "Migration finished!";
910 qDebug() << qPrintable(tr("Migration finished!"));
911 if (!saveBackendSettings(backend, settings)) {
912 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
917 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
921 // inform the user why we cannot merge
923 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
926 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
929 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
932 // so we were unable to merge, but let's create a user \o/
933 _storage = std::move(storage);
938 // TODO: I am not sure if this function is implemented correctly.
939 // There is currently no concept of migraiton between auth backends.
940 bool Core::selectAuthenticator(const QString &backend)
942 // Register all authentication backends.
943 registerAuthenticators();
944 auto auther = authenticator(backend);
946 QStringList authenticators;
947 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
948 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
949 return authenticator->displayName();
951 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
952 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
956 QVariantMap settings = promptForSettings(auther.get());
958 Authenticator::State state = auther->init(settings);
960 case Authenticator::IsReady:
961 saveAuthenticatorSettings(backend, settings);
962 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
964 case Authenticator::NotAvailable:
965 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
967 case Authenticator::NeedsSetup:
968 if (!auther->setup(settings)) {
969 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
973 if (auther->init(settings) != Authenticator::IsReady) {
974 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
978 saveAuthenticatorSettings(backend, settings);
979 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
982 _authenticator = std::move(auther);
987 bool Core::createUser()
989 QTextStream out(stdout);
990 QTextStream in(stdin);
991 out << "Add a new user:" << endl;
994 QString username = in.readLine().trimmed();
999 QString password = in.readLine().trimmed();
1001 out << "Repeat Password: ";
1003 QString password2 = in.readLine().trimmed();
1007 if (password != password2) {
1008 quWarning() << "Passwords don't match!";
1011 if (password.isEmpty()) {
1012 quWarning() << "Password is empty!";
1016 if (_configured && _storage->addUser(username, password).isValid()) {
1017 out << "Added user " << username << " successfully!" << endl;
1021 quWarning() << "Unable to add user:" << qPrintable(username);
1027 bool Core::changeUserPass(const QString &username)
1029 QTextStream out(stdout);
1030 QTextStream in(stdin);
1031 UserId userId = _storage->getUserId(username);
1032 if (!userId.isValid()) {
1033 out << "User " << username << " does not exist." << endl;
1037 if (!canChangeUserPassword(userId)) {
1038 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1042 out << "Change password for user: " << username << endl;
1045 out << "New Password: ";
1047 QString password = in.readLine().trimmed();
1049 out << "Repeat Password: ";
1051 QString password2 = in.readLine().trimmed();
1055 if (password != password2) {
1056 quWarning() << "Passwords don't match!";
1059 if (password.isEmpty()) {
1060 quWarning() << "Password is empty!";
1064 if (_configured && _storage->updateUser(userId, password)) {
1065 out << "Password changed successfully!" << endl;
1069 quWarning() << "Failed to change password!";
1075 bool Core::changeUserPassword(UserId userId, const QString &password)
1077 if (!isConfigured() || !userId.isValid())
1080 if (!canChangeUserPassword(userId))
1083 return instance()->_storage->updateUser(userId, password);
1086 // TODO: this code isn't currently 100% optimal because the core
1087 // doesn't know it can have multiple auth providers configured (there aren't
1088 // multiple auth providers at the moment anyway) and we have hardcoded the
1089 // Database provider to be always allowed.
1090 bool Core::canChangeUserPassword(UserId userId)
1092 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1093 if (authProvider != "Database") {
1094 if (authProvider != instance()->_authenticator->backendId()) {
1097 else if (instance()->_authenticator->canChangePassword()) {
1105 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1110 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1112 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1116 return sqlStorage->createMigrationReader();
1120 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1125 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1127 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1131 return sqlStorage->createMigrationWriter();
1135 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1137 QVariantMap dbsettings;
1138 dbsettings["Backend"] = backend;
1139 dbsettings["ConnectionProperties"] = settings;
1140 CoreSettings s = CoreSettings();
1141 s.setStorageSettings(dbsettings);
1146 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1148 QVariantMap dbsettings;
1149 dbsettings["Authenticator"] = backend;
1150 dbsettings["AuthProperties"] = settings;
1151 CoreSettings().setAuthSettings(dbsettings);
1154 // Generic version of promptForSettings that doesn't care what *type* of
1155 // backend it runs over.
1156 template<typename Backend>
1157 QVariantMap Core::promptForSettings(const Backend *backend)
1159 QVariantMap settings;
1160 const QVariantList& setupData = backend->setupData();
1162 if (setupData.isEmpty())
1165 QTextStream out(stdout);
1166 QTextStream in(stdin);
1167 out << "Default values are in brackets" << endl;
1169 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1170 QString key = setupData[i].toString();
1171 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1173 bool noEcho = key.toLower().contains("password");
1177 QString input = in.readLine().trimmed();
1183 QVariant value{setupData[i+2]};
1184 if (!input.isEmpty()) {
1185 switch (value.type()) {
1187 value = input.toInt();
1193 settings[key] = value;
1200 void Core::stdInEcho(bool on)
1202 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1204 GetConsoleMode(hStdin, &mode);
1206 mode |= ENABLE_ECHO_INPUT;
1208 mode &= ~ENABLE_ECHO_INPUT;
1209 SetConsoleMode(hStdin, mode);
1213 void Core::stdInEcho(bool on)
1216 tcgetattr(STDIN_FILENO, &t);
1221 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1224 #endif /* Q_OS_WIN */