1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 ***************************************************************************/
21 #include <QCoreApplication>
24 #include "coreauthhandler.h"
25 #include "coresession.h"
26 #include "coresettings.h"
28 #include "internalpeer.h"
30 #include "postgresqlstorage.h"
32 #include "sqlauthenticator.h"
33 #include "sqlitestorage.h"
36 // Currently building with LDAP bindings is optional.
38 #include "ldapauthenticator.h"
51 # include <sys/types.h>
52 # include <sys/stat.h>
53 #endif /* HAVE_UMASK */
55 // ==============================
57 // ==============================
58 const int Core::AddClientEventId = QEvent::registerEventType();
60 class AddClientEvent : public QEvent
63 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
69 // ==============================
71 // ==============================
72 Core *Core::instanceptr = 0;
74 Core *Core::instance()
76 if (instanceptr) return instanceptr;
77 instanceptr = new Core();
96 umask(S_IRWXG | S_IRWXO);
98 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
100 Quassel::loadTranslation(QLocale::system());
102 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
103 // Move settings, note this does not delete the old files
105 QSettings newSettings("quassel-irc.org", "quasselcore");
109 QSettings::Format format = QSettings::IniFormat;
111 QSettings::Format format = QSettings::NativeFormat;
113 QString newFilePath = Quassel::configDirPath() + "quasselcore"
114 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
115 QSettings newSettings(newFilePath, format);
116 #endif /* Q_OS_MAC */
118 if (newSettings.value("Config/Version").toUInt() == 0) {
120 QString org = "quassel-irc.org";
122 QString org = "Quassel Project";
124 QSettings oldSettings(org, "Quassel Core");
125 if (oldSettings.allKeys().count()) {
126 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
127 foreach(QString key, oldSettings.allKeys())
128 newSettings.setValue(key, oldSettings.value(key));
129 newSettings.setValue("Config/Version", 1);
130 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
132 #ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
134 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
135 #elif defined Q_OS_MAC
136 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
138 QString quasselDir = QDir::homePath() + "/.quassel/";
141 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
142 if (!info.exists()) {
143 // move database, if we found it
144 QFile oldDb(quasselDir + "quassel-storage.sqlite");
145 if (oldDb.exists()) {
146 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
148 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
150 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
154 QFileInfo certInfo(quasselDir + "quasselCert.pem");
155 if (certInfo.exists()) {
156 QFile cert(quasselDir + "quasselCert.pem");
157 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
159 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
161 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
163 #endif /* !Q_OS_MAC */
164 qWarning() << "*** Migration completed.\n\n";
169 // check settings version
170 // so far, we only have 1
172 if (s.version() != 1) {
173 qCritical() << "Invalid core settings version, terminating!";
177 registerStorageBackends();
178 registerAuthenticatorBackends();
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!
193 QVariantMap authSettings = cs.authSettings().toMap();
194 initAuthenticator(authSettings.value("AuthBackend").toString(), authSettings.value("ConnectionProperties").toMap());
196 if (Quassel::isOptionSet("select-backend")) {
197 selectBackend(Quassel::optionValue("select-backend"));
201 // TODO: add --select-authenticator command line option and code.
204 if (!_storageBackends.count()) {
205 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
206 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
207 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
209 exit(1); // TODO make this less brutal (especially for mono client -> popup)
212 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
214 if (!cs.isWritable()) {
215 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
221 if (Quassel::isOptionSet("add-user")) {
222 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
226 if (Quassel::isOptionSet("change-userpass")) {
227 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
228 EXIT_SUCCESS : EXIT_FAILURE);
231 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
232 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
233 if (!startListening()) exit(1); // TODO make this less brutal
235 if (Quassel::isOptionSet("oidentd"))
236 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
242 // FIXME do we need more cleanup for handlers?
243 foreach(CoreAuthHandler *handler, _connectingClients) {
244 handler->deleteLater(); // disconnect non authed clients
246 qDeleteAll(_sessions);
247 qDeleteAll(_storageBackends);
251 /*** Session Restore ***/
253 void Core::saveState()
257 QVariantList activeSessions;
258 foreach(UserId user, instance()->_sessions.keys())
259 activeSessions << QVariant::fromValue<UserId>(user);
260 state["CoreStateVersion"] = 1;
261 state["ActiveSessions"] = activeSessions;
262 s.setCoreState(state);
266 void Core::restoreState()
268 if (!instance()->_configured) {
269 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
272 if (instance()->_sessions.count()) {
273 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
277 /* We don't check, since we are at the first version since switching to Git
278 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
280 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
285 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
286 if (activeSessions.count() > 0) {
287 quInfo() << "Restoring previous core state...";
288 foreach(QVariant v, activeSessions) {
289 UserId user = v.value<UserId>();
290 instance()->sessionForUser(user, true);
298 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData)
300 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authBackend, authSetupData);
304 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData)
307 return tr("Core is already configured! Not configuring again...");
309 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
310 return tr("Admin user or password not set.");
312 if (!(_configured = initStorage(backend, setupData, true))) {
313 return tr("Could not setup storage!");
316 quInfo() << "Selected authenticator: " << authBackend;
317 if (!(_configured = initAuthenticator(authBackend, authSetupData, true)))
319 return tr("Could not setup authenticator!");
322 if (!saveBackendSettings(backend, setupData)) {
323 return tr("Could not save backend settings, probably a permission problem.");
325 saveAuthBackendSettings(authBackend, authSetupData);
327 quInfo() << qPrintable(tr("Creating admin user..."));
328 _storage->addUser(adminUser, adminPassword);
329 startListening(); // TODO check when we need this
334 QString Core::setupCoreForInternalUsage()
336 Q_ASSERT(!_storageBackends.isEmpty());
338 qsrand(QDateTime::currentDateTime().toTime_t());
340 for (int i = 0; i < 10; i++) {
342 pass += qrand() % 10;
345 // mono client currently needs sqlite
346 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "StorageAuth", QVariantMap());
350 /*** Storage Handling ***/
351 void Core::registerStorageBackends()
353 // Register storage backends here!
354 registerStorageBackend(new SqliteStorage(this));
355 registerStorageBackend(new PostgreSqlStorage(this));
359 bool Core::registerStorageBackend(Storage *backend)
361 if (backend->isAvailable()) {
362 _storageBackends[backend->displayName()] = backend;
366 backend->deleteLater();
371 void Core::unregisterStorageBackends()
373 foreach(Storage *s, _storageBackends.values()) {
376 _storageBackends.clear();
380 void Core::unregisterStorageBackend(Storage *backend)
382 _storageBackends.remove(backend->displayName());
383 backend->deleteLater();
386 // Authentication handling, now independent from storage.
387 // Register and unregister authenticators.
389 void Core::registerAuthenticatorBackends()
391 // Register new authentication backends here!
392 registerAuthenticatorBackend(new SqlAuthenticator(this));
394 registerAuthenticatorBackend(new LdapAuthenticator(this));
399 bool Core::registerAuthenticatorBackend(Authenticator *authenticator)
401 if (authenticator->isAvailable())
403 _authenticatorBackends[authenticator->displayName()] = authenticator;
406 authenticator->deleteLater();
411 void Core::unregisterAuthenticatorBackends()
413 foreach(Authenticator* a, _authenticatorBackends.values())
417 _authenticatorBackends.clear();
420 void Core::unregisterAuthenticatorBackend(Authenticator *backend)
422 _authenticatorBackends.remove(backend->displayName());
423 backend->deleteLater();
427 // "Type" => "sqlite"
428 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
432 if (backend.isEmpty()) {
436 Storage *storage = 0;
437 if (_storageBackends.contains(backend)) {
438 storage = _storageBackends[backend];
441 qCritical() << "Selected storage backend is not available:" << backend;
445 Storage::State storageState = storage->init(settings);
446 switch (storageState) {
447 case Storage::NeedsSetup:
449 return false; // trigger setup process
450 if (storage->setup(settings))
451 return initStorage(backend, settings, false);
452 // if initialization wasn't successful, we quit to keep from coming up unconfigured
453 case Storage::NotAvailable:
454 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
456 case Storage::IsReady:
457 // delete all other backends
458 _storageBackends.remove(backend);
459 unregisterStorageBackends();
460 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
466 // XXX: TODO: Apparently, this is legacy?
467 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
471 if (backend.isEmpty()) {
475 Authenticator *authenticator = 0;
476 if (_authenticatorBackends.contains(backend)) {
477 authenticator = _authenticatorBackends[backend];
480 qCritical() << "Selected auth backend is not available:" << backend;
484 Authenticator::State authState = authenticator->init(settings);
486 case Authenticator::NeedsSetup:
488 return false; // trigger setup process
489 if (authenticator->setup(settings))
490 return initAuthenticator(backend, settings, false);
491 // if initialization wasn't successful, we quit to keep from coming up unconfigured
492 case Authenticator::NotAvailable:
493 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
495 case Authenticator::IsReady:
496 // delete all other backends
497 _authenticatorBackends.remove(backend);
498 unregisterAuthenticatorBackends();
500 _authenticator = authenticator;
504 void Core::syncStorage()
511 /*** Storage Access ***/
512 bool Core::createNetwork(UserId user, NetworkInfo &info)
514 NetworkId networkId = instance()->_storage->createNetwork(user, info);
515 if (!networkId.isValid())
518 info.networkId = networkId;
523 /*** Network Management ***/
525 bool Core::sslSupported()
528 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
529 return sslServer && sslServer->isCertValid();
536 bool Core::reloadCerts()
539 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
540 bool retv4 = sslServerv4->reloadCerts();
542 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
543 bool retv6 = sslServerv6->reloadCerts();
545 return retv4 && retv6;
547 // SSL not supported, don't mark configuration reload as failed
553 bool Core::startListening()
555 // in mono mode we only start a local port if a port is specified in the cli call
556 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
559 bool success = false;
560 uint port = Quassel::optionValue("port").toUInt();
562 const QString listen = Quassel::optionValue("listen");
563 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
564 if (listen_list.size() > 0) {
565 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
567 if (!addr.setAddress(listen_term)) {
568 qCritical() << qPrintable(
569 tr("Invalid listen address %1")
574 switch (addr.protocol()) {
575 case QAbstractSocket::IPv6Protocol:
576 if (_v6server.listen(addr, port)) {
577 quInfo() << qPrintable(
578 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
579 .arg(addr.toString())
580 .arg(_v6server.serverPort())
581 .arg(Quassel::buildInfo().protocolVersion)
586 quWarning() << qPrintable(
587 tr("Could not open IPv6 interface %1:%2: %3")
588 .arg(addr.toString())
590 .arg(_v6server.errorString()));
592 case QAbstractSocket::IPv4Protocol:
593 if (_server.listen(addr, port)) {
594 quInfo() << qPrintable(
595 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
596 .arg(addr.toString())
597 .arg(_server.serverPort())
598 .arg(Quassel::buildInfo().protocolVersion)
603 // if v6 succeeded on Any, the port will be already in use - don't display the error then
604 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
605 quWarning() << qPrintable(
606 tr("Could not open IPv4 interface %1:%2: %3")
607 .arg(addr.toString())
609 .arg(_server.errorString()));
613 qCritical() << qPrintable(
614 tr("Invalid listen address %1, unknown network protocol")
623 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
629 void Core::stopListening(const QString &reason)
631 bool wasListening = false;
632 if (_server.isListening()) {
636 if (_v6server.isListening()) {
641 if (reason.isEmpty())
642 quInfo() << "No longer listening for GUI clients.";
644 quInfo() << qPrintable(reason);
649 void Core::incomingConnection()
651 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
653 while (server->hasPendingConnections()) {
654 QTcpSocket *socket = server->nextPendingConnection();
656 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
657 _connectingClients.insert(handler);
659 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
660 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
661 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
663 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
666 stopListening(tr("Closing server for basic setup."));
672 // Potentially called during the initialization phase (before handing the connection off to the session)
673 void Core::clientDisconnected()
675 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
678 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
679 _connectingClients.remove(handler);
680 handler->deleteLater();
682 // make server listen again if still not configured
687 // TODO remove unneeded sessions - if necessary/possible...
688 // Suggestion: kill sessions if they are not connected to any network and client.
692 void Core::setupClientSession(RemotePeer *peer, UserId uid)
694 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
697 // From now on everything is handled by the client session
698 disconnect(handler, 0, this, 0);
699 _connectingClients.remove(handler);
700 handler->deleteLater();
702 // Find or create session for validated user
705 // as we are currently handling an event triggered by incoming data on this socket
706 // it is unsafe to directly move the socket to the client thread.
707 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
711 void Core::customEvent(QEvent *event)
713 if (event->type() == AddClientEventId) {
714 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
715 addClientHelper(addClientEvent->peer, addClientEvent->userId);
721 void Core::addClientHelper(RemotePeer *peer, UserId uid)
723 // Find or create session for validated user
724 SessionThread *session = sessionForUser(uid);
725 session->addClient(peer);
729 void Core::setupInternalClientSession(InternalPeer *clientPeer)
733 setupCoreForInternalUsage();
738 uid = _storage->internalUser();
741 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
745 InternalPeer *corePeer = new InternalPeer(this);
746 corePeer->setPeer(clientPeer);
747 clientPeer->setPeer(corePeer);
749 // Find or create session for validated user
750 SessionThread *sessionThread = sessionForUser(uid);
751 sessionThread->addClient(corePeer);
755 SessionThread *Core::sessionForUser(UserId uid, bool restore)
757 if (_sessions.contains(uid))
758 return _sessions[uid];
760 SessionThread *session = new SessionThread(uid, restore, this);
761 _sessions[uid] = session;
767 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
769 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
773 QVariantList Core::backendInfo()
775 QVariantList backends;
776 foreach(const Storage *backend, instance()->_storageBackends.values()) {
778 v["DisplayName"] = backend->displayName();
779 v["Description"] = backend->description();
780 v["SetupKeys"] = backend->setupKeys();
781 v["SetupDefaults"] = backend->setupDefaults();
782 v["IsDefault"] = isStorageBackendDefault(backend);
788 QVariantList Core::authenticatorInfo()
790 QVariantList backends;
791 foreach(const Authenticator *backend, instance()->_authenticatorBackends.values()) {
793 v["DisplayName"] = backend->displayName();
794 v["Description"] = backend->description();
795 v["SetupKeys"] = backend->setupKeys();
796 v["SetupDefaults"] = backend->setupDefaults();
802 // migration / backend selection
803 bool Core::selectBackend(const QString &backend)
805 // reregister all storage backends
806 registerStorageBackends();
807 if (!_storageBackends.contains(backend)) {
808 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
809 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
813 Storage *storage = _storageBackends[backend];
814 QVariantMap settings = promptForSettings(storage);
816 Storage::State storageState = storage->init(settings);
817 switch (storageState) {
818 case Storage::IsReady:
819 if (!saveBackendSettings(backend, settings)) {
820 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
822 qWarning() << "Switched backend to:" << qPrintable(backend);
823 qWarning() << "Backend already initialized. Skipping Migration";
825 case Storage::NotAvailable:
826 qCritical() << "Backend is not available:" << qPrintable(backend);
828 case Storage::NeedsSetup:
829 if (!storage->setup(settings)) {
830 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
834 if (storage->init(settings) != Storage::IsReady) {
835 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
839 if (!saveBackendSettings(backend, settings)) {
840 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
842 qWarning() << "Switched backend to:" << qPrintable(backend);
846 // let's see if we have a current storage object we can migrate from
847 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
848 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
849 if (reader && writer) {
850 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
855 if (reader->migrateTo(writer)) {
856 qDebug() << "Migration finished!";
857 if (!saveBackendSettings(backend, settings)) {
858 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
864 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
867 // inform the user why we cannot merge
869 qWarning() << "No currently active backend. Skipping migration.";
872 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
875 qWarning() << "New backend does not support migration:" << qPrintable(backend);
878 // so we were unable to merge, but let's create a user \o/
885 bool Core::createUser()
887 QTextStream out(stdout);
888 QTextStream in(stdin);
889 out << "Add a new user:" << endl;
892 QString username = in.readLine().trimmed();
897 QString password = in.readLine().trimmed();
899 out << "Repeat Password: ";
901 QString password2 = in.readLine().trimmed();
905 if (password != password2) {
906 qWarning() << "Passwords don't match!";
909 if (password.isEmpty()) {
910 qWarning() << "Password is empty!";
914 if (_configured && _storage->addUser(username, password).isValid()) {
915 out << "Added user " << username << " successfully!" << endl;
919 qWarning() << "Unable to add user:" << qPrintable(username);
925 bool Core::changeUserPass(const QString &username)
927 QTextStream out(stdout);
928 QTextStream in(stdin);
929 UserId userId = _storage->getUserId(username);
930 if (!userId.isValid()) {
931 out << "User " << username << " does not exist." << endl;
935 out << "Change password for user: " << username << endl;
938 out << "New Password: ";
940 QString password = in.readLine().trimmed();
942 out << "Repeat Password: ";
944 QString password2 = in.readLine().trimmed();
948 if (password != password2) {
949 qWarning() << "Passwords don't match!";
952 if (password.isEmpty()) {
953 qWarning() << "Password is empty!";
957 if (_configured && _storage->updateUser(userId, password)) {
958 out << "Password changed successfully!" << endl;
962 qWarning() << "Failed to change password!";
968 bool Core::changeUserPassword(UserId userId, const QString &password)
970 if (!isConfigured() || !userId.isValid())
973 return instance()->_storage->updateUser(userId, password);
977 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
982 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
984 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
988 return sqlStorage->createMigrationReader();
992 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
997 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
999 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1003 return sqlStorage->createMigrationWriter();
1007 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1009 QVariantMap dbsettings;
1010 dbsettings["Backend"] = backend;
1011 dbsettings["ConnectionProperties"] = settings;
1012 CoreSettings s = CoreSettings();
1013 s.setStorageSettings(dbsettings);
1017 void Core::saveAuthBackendSettings(const QString &backend, const QVariantMap &settings)
1019 QVariantMap dbsettings;
1020 dbsettings["AuthBackend"] = backend;
1021 dbsettings["ConnectionProperties"] = settings;
1022 CoreSettings().setAuthSettings(dbsettings);
1026 QVariantMap Core::promptForSettings(const Storage *storage)
1028 QVariantMap settings;
1030 QStringList keys = storage->setupKeys();
1034 QTextStream out(stdout);
1035 QTextStream in(stdin);
1036 out << "Default values are in brackets" << endl;
1038 QVariantMap defaults = storage->setupDefaults();
1040 foreach(QString key, keys) {
1042 if (defaults.contains(key)) {
1043 val = defaults[key];
1046 if (!val.toString().isEmpty()) {
1047 out << " (" << val.toString() << ")";
1052 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1056 value = in.readLine().trimmed();
1062 if (!value.isEmpty()) {
1063 switch (defaults[key].type()) {
1065 val = QVariant(value.toInt());
1068 val = QVariant(value);
1071 settings[key] = val;
1078 void Core::stdInEcho(bool on)
1080 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1082 GetConsoleMode(hStdin, &mode);
1084 mode |= ENABLE_ECHO_INPUT;
1086 mode &= ~ENABLE_ECHO_INPUT;
1087 SetConsoleMode(hStdin, mode);
1092 void Core::stdInEcho(bool on)
1095 tcgetattr(STDIN_FILENO, &t);
1100 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1104 #endif /* Q_OS_WIN */