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 if (!saveBackendSettings(backend, setupData)) {
317 return tr("Could not save backend settings, probably a permission problem.");
319 saveAuthBackendSettings(authBackend, authSetupData);
321 quInfo() << qPrintable(tr("Creating admin user..."));
322 _storage->addUser(adminUser, adminPassword);
323 startListening(); // TODO check when we need this
328 QString Core::setupCoreForInternalUsage()
330 Q_ASSERT(!_storageBackends.isEmpty());
332 qsrand(QDateTime::currentDateTime().toTime_t());
334 for (int i = 0; i < 10; i++) {
336 pass += qrand() % 10;
339 // mono client currently needs sqlite
340 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "StorageAuth", QVariantMap());
344 /*** Storage Handling ***/
345 void Core::registerStorageBackends()
347 // Register storage backends here!
348 registerStorageBackend(new SqliteStorage(this));
349 registerStorageBackend(new PostgreSqlStorage(this));
353 bool Core::registerStorageBackend(Storage *backend)
355 if (backend->isAvailable()) {
356 _storageBackends[backend->displayName()] = backend;
360 backend->deleteLater();
365 void Core::unregisterStorageBackends()
367 foreach(Storage *s, _storageBackends.values()) {
370 _storageBackends.clear();
374 void Core::unregisterStorageBackend(Storage *backend)
376 _storageBackends.remove(backend->displayName());
377 backend->deleteLater();
380 // Authentication handling, now independent from storage.
381 // Register and unregister authenticators.
383 void Core::registerAuthenticatorBackends()
385 // Register new authentication backends here!
386 registerAuthenticatorBackend(new SqlAuthenticator(this));
388 registerAuthenticatorBackend(new LdapAuthenticator(this));
393 bool Core::registerAuthenticatorBackend(Authenticator *authenticator)
395 if (authenticator->isAvailable())
397 _authenticatorBackends[authenticator->displayName()] = authenticator;
400 authenticator->deleteLater();
405 void Core::unregisterAuthenticatorBackends()
407 foreach(Authenticator* a, _authenticatorBackends.values())
411 _authenticatorBackends.clear();
414 void Core::unregisterAuthenticatorBackend(Authenticator *backend)
416 _authenticatorBackends.remove(backend->displayName());
417 backend->deleteLater();
421 // "Type" => "sqlite"
422 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
426 if (backend.isEmpty()) {
430 Storage *storage = 0;
431 if (_storageBackends.contains(backend)) {
432 storage = _storageBackends[backend];
435 qCritical() << "Selected storage backend is not available:" << backend;
439 Storage::State storageState = storage->init(settings);
440 switch (storageState) {
441 case Storage::NeedsSetup:
443 return false; // trigger setup process
444 if (storage->setup(settings))
445 return initStorage(backend, settings, false);
446 // if initialization wasn't successful, we quit to keep from coming up unconfigured
447 case Storage::NotAvailable:
448 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
450 case Storage::IsReady:
451 // delete all other backends
452 _storageBackends.remove(backend);
453 unregisterStorageBackends();
454 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
460 // XXX: TODO: Apparently, this is legacy?
461 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
465 if (backend.isEmpty()) {
469 Authenticator *authenticator = 0;
470 if (_authenticatorBackends.contains(backend)) {
471 authenticator = _authenticatorBackends[backend];
474 qCritical() << "Selected auth backend is not available:" << backend;
478 Authenticator::State authState = authenticator->init(settings);
480 case Authenticator::NeedsSetup:
482 return false; // trigger setup process
483 if (authenticator->setup(settings))
484 return initAuthenticator(backend, settings, false);
485 // if initialization wasn't successful, we quit to keep from coming up unconfigured
486 case Authenticator::NotAvailable:
487 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
489 case Authenticator::IsReady:
490 // delete all other backends
491 _authenticatorBackends.remove(backend);
492 unregisterAuthenticatorBackends();
494 _authenticator = authenticator;
498 void Core::syncStorage()
505 /*** Storage Access ***/
506 bool Core::createNetwork(UserId user, NetworkInfo &info)
508 NetworkId networkId = instance()->_storage->createNetwork(user, info);
509 if (!networkId.isValid())
512 info.networkId = networkId;
517 /*** Network Management ***/
519 bool Core::sslSupported()
522 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
523 return sslServer && sslServer->isCertValid();
530 bool Core::reloadCerts()
533 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
534 bool retv4 = sslServerv4->reloadCerts();
536 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
537 bool retv6 = sslServerv6->reloadCerts();
539 return retv4 && retv6;
541 // SSL not supported, don't mark configuration reload as failed
547 bool Core::startListening()
549 // in mono mode we only start a local port if a port is specified in the cli call
550 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
553 bool success = false;
554 uint port = Quassel::optionValue("port").toUInt();
556 const QString listen = Quassel::optionValue("listen");
557 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
558 if (listen_list.size() > 0) {
559 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
561 if (!addr.setAddress(listen_term)) {
562 qCritical() << qPrintable(
563 tr("Invalid listen address %1")
568 switch (addr.protocol()) {
569 case QAbstractSocket::IPv6Protocol:
570 if (_v6server.listen(addr, port)) {
571 quInfo() << qPrintable(
572 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
573 .arg(addr.toString())
574 .arg(_v6server.serverPort())
575 .arg(Quassel::buildInfo().protocolVersion)
580 quWarning() << qPrintable(
581 tr("Could not open IPv6 interface %1:%2: %3")
582 .arg(addr.toString())
584 .arg(_v6server.errorString()));
586 case QAbstractSocket::IPv4Protocol:
587 if (_server.listen(addr, port)) {
588 quInfo() << qPrintable(
589 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
590 .arg(addr.toString())
591 .arg(_server.serverPort())
592 .arg(Quassel::buildInfo().protocolVersion)
597 // if v6 succeeded on Any, the port will be already in use - don't display the error then
598 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
599 quWarning() << qPrintable(
600 tr("Could not open IPv4 interface %1:%2: %3")
601 .arg(addr.toString())
603 .arg(_server.errorString()));
607 qCritical() << qPrintable(
608 tr("Invalid listen address %1, unknown network protocol")
617 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
623 void Core::stopListening(const QString &reason)
625 bool wasListening = false;
626 if (_server.isListening()) {
630 if (_v6server.isListening()) {
635 if (reason.isEmpty())
636 quInfo() << "No longer listening for GUI clients.";
638 quInfo() << qPrintable(reason);
643 void Core::incomingConnection()
645 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
647 while (server->hasPendingConnections()) {
648 QTcpSocket *socket = server->nextPendingConnection();
650 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
651 _connectingClients.insert(handler);
653 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
654 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
655 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
657 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
660 stopListening(tr("Closing server for basic setup."));
666 // Potentially called during the initialization phase (before handing the connection off to the session)
667 void Core::clientDisconnected()
669 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
672 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
673 _connectingClients.remove(handler);
674 handler->deleteLater();
676 // make server listen again if still not configured
681 // TODO remove unneeded sessions - if necessary/possible...
682 // Suggestion: kill sessions if they are not connected to any network and client.
686 void Core::setupClientSession(RemotePeer *peer, UserId uid)
688 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
691 // From now on everything is handled by the client session
692 disconnect(handler, 0, this, 0);
693 _connectingClients.remove(handler);
694 handler->deleteLater();
696 // Find or create session for validated user
699 // as we are currently handling an event triggered by incoming data on this socket
700 // it is unsafe to directly move the socket to the client thread.
701 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
705 void Core::customEvent(QEvent *event)
707 if (event->type() == AddClientEventId) {
708 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
709 addClientHelper(addClientEvent->peer, addClientEvent->userId);
715 void Core::addClientHelper(RemotePeer *peer, UserId uid)
717 // Find or create session for validated user
718 SessionThread *session = sessionForUser(uid);
719 session->addClient(peer);
723 void Core::setupInternalClientSession(InternalPeer *clientPeer)
727 setupCoreForInternalUsage();
732 uid = _storage->internalUser();
735 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
739 InternalPeer *corePeer = new InternalPeer(this);
740 corePeer->setPeer(clientPeer);
741 clientPeer->setPeer(corePeer);
743 // Find or create session for validated user
744 SessionThread *sessionThread = sessionForUser(uid);
745 sessionThread->addClient(corePeer);
749 SessionThread *Core::sessionForUser(UserId uid, bool restore)
751 if (_sessions.contains(uid))
752 return _sessions[uid];
754 SessionThread *session = new SessionThread(uid, restore, this);
755 _sessions[uid] = session;
761 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
763 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
767 QVariantList Core::backendInfo()
769 QVariantList backends;
770 foreach(const Storage *backend, instance()->_storageBackends.values()) {
772 v["DisplayName"] = backend->displayName();
773 v["Description"] = backend->description();
774 v["SetupKeys"] = backend->setupKeys();
775 v["SetupDefaults"] = backend->setupDefaults();
776 v["IsDefault"] = isStorageBackendDefault(backend);
782 QVariantList Core::authenticatorInfo()
784 QVariantList backends;
785 foreach(const Authenticator *backend, instance()->_authenticatorBackends.values()) {
787 v["DisplayName"] = backend->displayName();
788 v["Description"] = backend->description();
789 v["SetupKeys"] = backend->setupKeys();
790 v["SetupDefaults"] = backend->setupDefaults();
796 // migration / backend selection
797 bool Core::selectBackend(const QString &backend)
799 // reregister all storage backends
800 registerStorageBackends();
801 if (!_storageBackends.contains(backend)) {
802 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
803 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
807 Storage *storage = _storageBackends[backend];
808 QVariantMap settings = promptForSettings(storage);
810 Storage::State storageState = storage->init(settings);
811 switch (storageState) {
812 case Storage::IsReady:
813 if (!saveBackendSettings(backend, settings)) {
814 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
816 qWarning() << "Switched backend to:" << qPrintable(backend);
817 qWarning() << "Backend already initialized. Skipping Migration";
819 case Storage::NotAvailable:
820 qCritical() << "Backend is not available:" << qPrintable(backend);
822 case Storage::NeedsSetup:
823 if (!storage->setup(settings)) {
824 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
828 if (storage->init(settings) != Storage::IsReady) {
829 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
833 if (!saveBackendSettings(backend, settings)) {
834 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
836 qWarning() << "Switched backend to:" << qPrintable(backend);
840 // let's see if we have a current storage object we can migrate from
841 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
842 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
843 if (reader && writer) {
844 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
849 if (reader->migrateTo(writer)) {
850 qDebug() << "Migration finished!";
851 if (!saveBackendSettings(backend, settings)) {
852 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
858 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
861 // inform the user why we cannot merge
863 qWarning() << "No currently active backend. Skipping migration.";
866 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
869 qWarning() << "New backend does not support migration:" << qPrintable(backend);
872 // so we were unable to merge, but let's create a user \o/
879 bool Core::createUser()
881 QTextStream out(stdout);
882 QTextStream in(stdin);
883 out << "Add a new user:" << endl;
886 QString username = in.readLine().trimmed();
891 QString password = in.readLine().trimmed();
893 out << "Repeat Password: ";
895 QString password2 = in.readLine().trimmed();
899 if (password != password2) {
900 qWarning() << "Passwords don't match!";
903 if (password.isEmpty()) {
904 qWarning() << "Password is empty!";
908 if (_configured && _storage->addUser(username, password).isValid()) {
909 out << "Added user " << username << " successfully!" << endl;
913 qWarning() << "Unable to add user:" << qPrintable(username);
919 bool Core::changeUserPass(const QString &username)
921 QTextStream out(stdout);
922 QTextStream in(stdin);
923 UserId userId = _storage->getUserId(username);
924 if (!userId.isValid()) {
925 out << "User " << username << " does not exist." << endl;
929 out << "Change password for user: " << username << endl;
932 out << "New Password: ";
934 QString password = in.readLine().trimmed();
936 out << "Repeat Password: ";
938 QString password2 = in.readLine().trimmed();
942 if (password != password2) {
943 qWarning() << "Passwords don't match!";
946 if (password.isEmpty()) {
947 qWarning() << "Password is empty!";
951 if (_configured && _storage->updateUser(userId, password)) {
952 out << "Password changed successfully!" << endl;
956 qWarning() << "Failed to change password!";
962 bool Core::changeUserPassword(UserId userId, const QString &password)
964 if (!isConfigured() || !userId.isValid())
967 return instance()->_storage->updateUser(userId, password);
971 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
976 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
978 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
982 return sqlStorage->createMigrationReader();
986 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
991 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
993 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
997 return sqlStorage->createMigrationWriter();
1001 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1003 QVariantMap dbsettings;
1004 dbsettings["Backend"] = backend;
1005 dbsettings["ConnectionProperties"] = settings;
1006 CoreSettings s = CoreSettings();
1007 s.setStorageSettings(dbsettings);
1011 void Core::saveAuthBackendSettings(const QString &backend, const QVariantMap &settings)
1013 QVariantMap dbsettings;
1014 dbsettings["AuthBackend"] = backend;
1015 dbsettings["ConnectionProperties"] = settings;
1016 CoreSettings().setAuthSettings(dbsettings);
1020 QVariantMap Core::promptForSettings(const Storage *storage)
1022 QVariantMap settings;
1024 QStringList keys = storage->setupKeys();
1028 QTextStream out(stdout);
1029 QTextStream in(stdin);
1030 out << "Default values are in brackets" << endl;
1032 QVariantMap defaults = storage->setupDefaults();
1034 foreach(QString key, keys) {
1036 if (defaults.contains(key)) {
1037 val = defaults[key];
1040 if (!val.toString().isEmpty()) {
1041 out << " (" << val.toString() << ")";
1046 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1050 value = in.readLine().trimmed();
1056 if (!value.isEmpty()) {
1057 switch (defaults[key].type()) {
1059 val = QVariant(value.toInt());
1062 val = QVariant(value);
1065 settings[key] = val;
1072 void Core::stdInEcho(bool on)
1074 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1076 GetConsoleMode(hStdin, &mode);
1078 mode |= ENABLE_ECHO_INPUT;
1080 mode &= ~ENABLE_ECHO_INPUT;
1081 SetConsoleMode(hStdin, mode);
1086 void Core::stdInEcho(bool on)
1089 tcgetattr(STDIN_FILENO, &t);
1094 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1098 #endif /* Q_OS_WIN */