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 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!
193 QVariantMap authSettings = cs.authSettings().toMap();
194 initAuthenticator(authSettings.value("Authenticator").toString(), authSettings.value("AuthProperties").toMap());
196 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
197 if (Quassel::isOptionSet("select-backend")) {
198 selectBackend(Quassel::optionValue("select-backend"));
200 if (Quassel::isOptionSet("select-authenticator")) {
201 selectAuthenticator(Quassel::optionValue("select-authenticator"));
207 if (!_storageBackends.count()) {
208 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
209 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
210 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
212 exit(1); // TODO make this less brutal (especially for mono client -> popup)
215 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
217 if (!cs.isWritable()) {
218 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
224 if (Quassel::isOptionSet("add-user")) {
225 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
229 if (Quassel::isOptionSet("change-userpass")) {
230 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
231 EXIT_SUCCESS : EXIT_FAILURE);
234 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
235 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
236 if (!startListening()) exit(1); // TODO make this less brutal
238 if (Quassel::isOptionSet("oidentd"))
239 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
245 // FIXME do we need more cleanup for handlers?
246 foreach(CoreAuthHandler *handler, _connectingClients) {
247 handler->deleteLater(); // disconnect non authed clients
249 qDeleteAll(_sessions);
250 qDeleteAll(_storageBackends);
251 qDeleteAll(_authenticators);
255 /*** Session Restore ***/
257 void Core::saveState()
261 QVariantList activeSessions;
262 foreach(UserId user, instance()->_sessions.keys())
263 activeSessions << QVariant::fromValue<UserId>(user);
264 state["CoreStateVersion"] = 1;
265 state["ActiveSessions"] = activeSessions;
266 s.setCoreState(state);
270 void Core::restoreState()
272 if (!instance()->_configured) {
273 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
276 if (instance()->_sessions.count()) {
277 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
281 /* We don't check, since we are at the first version since switching to Git
282 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
284 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
289 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
290 if (activeSessions.count() > 0) {
291 quInfo() << "Restoring previous core state...";
292 foreach(QVariant v, activeSessions) {
293 UserId user = v.value<UserId>();
294 instance()->sessionForUser(user, true);
302 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
304 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
308 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
311 return tr("Core is already configured! Not configuring again...");
313 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
314 return tr("Admin user or password not set.");
316 if (!(_configured = initStorage(backend, setupData, true))) {
317 return tr("Could not setup storage!");
320 quInfo() << "Selected authenticator:" << authenticator;
321 if (!(_configured = initAuthenticator(authenticator, authSetupData, true)))
323 return tr("Could not setup authenticator!");
326 if (!saveBackendSettings(backend, setupData)) {
327 return tr("Could not save backend settings, probably a permission problem.");
329 saveAuthenticatorSettings(authenticator, authSetupData);
331 quInfo() << qPrintable(tr("Creating admin user..."));
332 _storage->addUser(adminUser, adminPassword);
333 startListening(); // TODO check when we need this
338 QString Core::setupCoreForInternalUsage()
340 Q_ASSERT(!_storageBackends.isEmpty());
342 qsrand(QDateTime::currentDateTime().toTime_t());
344 for (int i = 0; i < 10; i++) {
346 pass += qrand() % 10;
349 // mono client currently needs sqlite
350 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
354 /*** Storage Handling ***/
355 void Core::registerStorageBackends()
357 // Register storage backends here!
358 registerStorageBackend(new SqliteStorage(this));
359 registerStorageBackend(new PostgreSqlStorage(this));
363 bool Core::registerStorageBackend(Storage *backend)
365 if (backend->isAvailable()) {
366 _storageBackends[backend->displayName()] = backend;
370 backend->deleteLater();
376 void Core::unregisterStorageBackends()
378 foreach(Storage *s, _storageBackends.values()) {
381 _storageBackends.clear();
385 void Core::unregisterStorageBackend(Storage *backend)
387 _storageBackends.remove(backend->displayName());
388 backend->deleteLater();
391 // Authentication handling, now independent from storage.
392 // Register and unregister authenticators.
394 void Core::registerAuthenticators()
396 // Register new authentication backends here!
397 registerAuthenticator(new SqlAuthenticator(this));
399 registerAuthenticator(new LdapAuthenticator(this));
404 bool Core::registerAuthenticator(Authenticator *authenticator)
406 if (authenticator->isAvailable()) {
407 _authenticators[authenticator->backendId()] = authenticator;
411 authenticator->deleteLater();
417 void Core::unregisterAuthenticators()
419 foreach(Authenticator* a, _authenticators.values()) {
422 _authenticators.clear();
426 void Core::unregisterAuthenticator(Authenticator *backend)
428 _authenticators.remove(backend->backendId());
429 backend->deleteLater();
433 // "Type" => "sqlite"
434 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
438 if (backend.isEmpty()) {
442 Storage *storage = 0;
443 if (_storageBackends.contains(backend)) {
444 storage = _storageBackends[backend];
447 qCritical() << "Selected storage backend is not available:" << backend;
451 Storage::State storageState = storage->init(settings);
452 switch (storageState) {
453 case Storage::NeedsSetup:
455 return false; // trigger setup process
456 if (storage->setup(settings))
457 return initStorage(backend, settings, false);
458 // if initialization wasn't successful, we quit to keep from coming up unconfigured
459 case Storage::NotAvailable:
460 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
462 case Storage::IsReady:
463 // delete all other backends
464 _storageBackends.remove(backend);
465 unregisterStorageBackends();
466 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
472 // FIXME: Apparently, this is the legacy way of initting storage backends?
473 // If there's a not-legacy way, it should be used here
474 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
478 if (backend.isEmpty()) {
482 Authenticator *authenticator = 0;
483 if (_authenticators.contains(backend)) {
484 authenticator = _authenticators[backend];
487 qCritical() << "Selected auth backend is not available:" << backend;
491 Authenticator::State authState = authenticator->init(settings);
493 case Authenticator::NeedsSetup:
495 return false; // trigger setup process
496 if (authenticator->setup(settings))
497 return initAuthenticator(backend, settings, false);
498 // if initialization wasn't successful, we quit to keep from coming up unconfigured
499 case Authenticator::NotAvailable:
500 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
502 case Authenticator::IsReady:
503 // delete all other backends
504 _authenticators.remove(backend);
505 unregisterAuthenticators();
507 _authenticator = authenticator;
512 void Core::syncStorage()
519 /*** Storage Access ***/
520 bool Core::createNetwork(UserId user, NetworkInfo &info)
522 NetworkId networkId = instance()->_storage->createNetwork(user, info);
523 if (!networkId.isValid())
526 info.networkId = networkId;
531 /*** Network Management ***/
533 bool Core::sslSupported()
536 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
537 return sslServer && sslServer->isCertValid();
544 bool Core::reloadCerts()
547 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
548 bool retv4 = sslServerv4->reloadCerts();
550 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
551 bool retv6 = sslServerv6->reloadCerts();
553 return retv4 && retv6;
555 // SSL not supported, don't mark configuration reload as failed
561 bool Core::startListening()
563 // in mono mode we only start a local port if a port is specified in the cli call
564 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
567 bool success = false;
568 uint port = Quassel::optionValue("port").toUInt();
570 const QString listen = Quassel::optionValue("listen");
571 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
572 if (listen_list.size() > 0) {
573 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
575 if (!addr.setAddress(listen_term)) {
576 qCritical() << qPrintable(
577 tr("Invalid listen address %1")
582 switch (addr.protocol()) {
583 case QAbstractSocket::IPv6Protocol:
584 if (_v6server.listen(addr, port)) {
585 quInfo() << qPrintable(
586 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
587 .arg(addr.toString())
588 .arg(_v6server.serverPort())
589 .arg(Quassel::buildInfo().protocolVersion)
594 quWarning() << qPrintable(
595 tr("Could not open IPv6 interface %1:%2: %3")
596 .arg(addr.toString())
598 .arg(_v6server.errorString()));
600 case QAbstractSocket::IPv4Protocol:
601 if (_server.listen(addr, port)) {
602 quInfo() << qPrintable(
603 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
604 .arg(addr.toString())
605 .arg(_server.serverPort())
606 .arg(Quassel::buildInfo().protocolVersion)
611 // if v6 succeeded on Any, the port will be already in use - don't display the error then
612 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
613 quWarning() << qPrintable(
614 tr("Could not open IPv4 interface %1:%2: %3")
615 .arg(addr.toString())
617 .arg(_server.errorString()));
621 qCritical() << qPrintable(
622 tr("Invalid listen address %1, unknown network protocol")
631 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
637 void Core::stopListening(const QString &reason)
639 bool wasListening = false;
640 if (_server.isListening()) {
644 if (_v6server.isListening()) {
649 if (reason.isEmpty())
650 quInfo() << "No longer listening for GUI clients.";
652 quInfo() << qPrintable(reason);
657 void Core::incomingConnection()
659 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
661 while (server->hasPendingConnections()) {
662 QTcpSocket *socket = server->nextPendingConnection();
664 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
665 _connectingClients.insert(handler);
667 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
668 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
669 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
671 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
674 stopListening(tr("Closing server for basic setup."));
680 // Potentially called during the initialization phase (before handing the connection off to the session)
681 void Core::clientDisconnected()
683 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
686 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
687 _connectingClients.remove(handler);
688 handler->deleteLater();
690 // make server listen again if still not configured
695 // TODO remove unneeded sessions - if necessary/possible...
696 // Suggestion: kill sessions if they are not connected to any network and client.
700 void Core::setupClientSession(RemotePeer *peer, UserId uid)
702 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
705 // From now on everything is handled by the client session
706 disconnect(handler, 0, this, 0);
707 _connectingClients.remove(handler);
708 handler->deleteLater();
710 // Find or create session for validated user
713 // as we are currently handling an event triggered by incoming data on this socket
714 // it is unsafe to directly move the socket to the client thread.
715 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
719 void Core::customEvent(QEvent *event)
721 if (event->type() == AddClientEventId) {
722 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
723 addClientHelper(addClientEvent->peer, addClientEvent->userId);
729 void Core::addClientHelper(RemotePeer *peer, UserId uid)
731 // Find or create session for validated user
732 SessionThread *session = sessionForUser(uid);
733 session->addClient(peer);
737 void Core::setupInternalClientSession(InternalPeer *clientPeer)
741 setupCoreForInternalUsage();
746 uid = _storage->internalUser();
749 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
753 InternalPeer *corePeer = new InternalPeer(this);
754 corePeer->setPeer(clientPeer);
755 clientPeer->setPeer(corePeer);
757 // Find or create session for validated user
758 SessionThread *sessionThread = sessionForUser(uid);
759 sessionThread->addClient(corePeer);
763 SessionThread *Core::sessionForUser(UserId uid, bool restore)
765 if (_sessions.contains(uid))
766 return _sessions[uid];
768 SessionThread *session = new SessionThread(uid, restore, this);
769 _sessions[uid] = session;
775 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
777 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
781 QVariantList Core::backendInfo()
783 QVariantList backends;
784 foreach(const Storage *backend, instance()->_storageBackends.values()) {
786 v["DisplayName"] = backend->displayName();
787 v["Description"] = backend->description();
788 v["SetupKeys"] = backend->setupKeys();
789 v["SetupDefaults"] = backend->setupDefaults();
790 v["IsDefault"] = isStorageBackendDefault(backend);
797 QVariantList Core::authenticatorInfo()
799 QVariantList backends;
800 foreach(const Authenticator *backend, instance()->_authenticators.values()) {
802 v["DisplayName"] = backend->backendId();
803 v["Description"] = backend->description();
804 v["SetupKeys"] = backend->setupKeys();
805 v["SetupDefaults"] = backend->setupDefaults();
811 // migration / backend selection
812 bool Core::selectBackend(const QString &backend)
814 // reregister all storage backends
815 registerStorageBackends();
816 if (!_storageBackends.contains(backend)) {
817 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
818 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
822 Storage *storage = _storageBackends[backend];
823 QVariantMap settings = promptForSettings(storage);
825 Storage::State storageState = storage->init(settings);
826 switch (storageState) {
827 case Storage::IsReady:
828 if (!saveBackendSettings(backend, settings)) {
829 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
831 qWarning() << "Switched backend to:" << qPrintable(backend);
832 qWarning() << "Backend already initialized. Skipping Migration";
834 case Storage::NotAvailable:
835 qCritical() << "Backend is not available:" << qPrintable(backend);
837 case Storage::NeedsSetup:
838 if (!storage->setup(settings)) {
839 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
843 if (storage->init(settings) != Storage::IsReady) {
844 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
848 if (!saveBackendSettings(backend, settings)) {
849 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
851 qWarning() << "Switched backend to:" << qPrintable(backend);
855 // let's see if we have a current storage object we can migrate from
856 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
857 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
858 if (reader && writer) {
859 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
864 if (reader->migrateTo(writer)) {
865 qDebug() << "Migration finished!";
866 if (!saveBackendSettings(backend, settings)) {
867 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
873 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
876 // inform the user why we cannot merge
878 qWarning() << "No currently active backend. Skipping migration.";
881 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
884 qWarning() << "New backend does not support migration:" << qPrintable(backend);
887 // so we were unable to merge, but let's create a user \o/
893 // TODO: I am not sure if this function is implemented correctly.
894 // There is currently no concept of migraiton between auth backends.
895 bool Core::selectAuthenticator(const QString &backend)
897 // Register all authentication backends.
898 registerAuthenticators();
899 if (!_authenticators.contains(backend)) {
900 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unsupported backend: %1").arg(backend));
901 qWarning() << " supported backends are:" << qPrintable(QStringList(_authenticators.keys()).join(", "));
905 Authenticator *authenticator = _authenticators[backend];
906 QVariantMap settings = promptForSettings(authenticator);
908 Authenticator::State state = authenticator->init(settings);
910 case Authenticator::IsReady:
911 saveAuthenticatorSettings(backend, settings);
912 qWarning() << "Switched auth backend to:" << qPrintable(backend);
913 // qWarning() << "Auth backend already initialized. Skipping Migration";
915 case Authenticator::NotAvailable:
916 qCritical() << "Auth backend is not available:" << qPrintable(backend);
918 case Authenticator::NeedsSetup:
919 if (!authenticator->setup(settings)) {
920 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unable to setup authenticator: %1").arg(backend));
924 if (authenticator->init(settings) != Authenticator::IsReady) {
925 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize authenticator: %1").arg(backend));
929 saveAuthenticatorSettings(backend, settings);
930 qWarning() << "Switched auth backend to:" << qPrintable(backend);
933 _authenticator = authenticator;
938 bool Core::createUser()
940 QTextStream out(stdout);
941 QTextStream in(stdin);
942 out << "Add a new user:" << endl;
945 QString username = in.readLine().trimmed();
950 QString password = in.readLine().trimmed();
952 out << "Repeat Password: ";
954 QString password2 = in.readLine().trimmed();
958 if (password != password2) {
959 qWarning() << "Passwords don't match!";
962 if (password.isEmpty()) {
963 qWarning() << "Password is empty!";
967 if (_configured && _storage->addUser(username, password).isValid()) {
968 out << "Added user " << username << " successfully!" << endl;
972 qWarning() << "Unable to add user:" << qPrintable(username);
978 bool Core::changeUserPass(const QString &username)
980 QTextStream out(stdout);
981 QTextStream in(stdin);
982 UserId userId = _storage->getUserId(username);
983 if (!userId.isValid()) {
984 out << "User " << username << " does not exist." << endl;
988 if (!canChangeUserPassword(userId)) {
989 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
993 out << "Change password for user: " << username << endl;
996 out << "New Password: ";
998 QString password = in.readLine().trimmed();
1000 out << "Repeat Password: ";
1002 QString password2 = in.readLine().trimmed();
1006 if (password != password2) {
1007 qWarning() << "Passwords don't match!";
1010 if (password.isEmpty()) {
1011 qWarning() << "Password is empty!";
1015 if (_configured && _storage->updateUser(userId, password)) {
1016 out << "Password changed successfully!" << endl;
1020 qWarning() << "Failed to change password!";
1026 bool Core::changeUserPassword(UserId userId, const QString &password)
1028 if (!isConfigured() || !userId.isValid())
1031 if (!canChangeUserPassword(userId))
1034 return instance()->_storage->updateUser(userId, password);
1037 // TODO: this code isn't currently 100% optimal because the core
1038 // doesn't know it can have multiple auth providers configured (there aren't
1039 // multiple auth providers at the moment anyway) and we have hardcoded the
1040 // Database provider to be always allowed.
1041 bool Core::canChangeUserPassword(UserId userId)
1043 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1044 if (authProvider != "Database") {
1045 if (authProvider != instance()->_authenticator->backendId()) {
1048 else if (instance()->_authenticator->canChangePassword()) {
1056 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
1061 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1063 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1067 return sqlStorage->createMigrationReader();
1071 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
1076 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1078 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1082 return sqlStorage->createMigrationWriter();
1086 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1088 QVariantMap dbsettings;
1089 dbsettings["Backend"] = backend;
1090 dbsettings["ConnectionProperties"] = settings;
1091 CoreSettings s = CoreSettings();
1092 s.setStorageSettings(dbsettings);
1097 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1099 QVariantMap dbsettings;
1100 dbsettings["Authenticator"] = backend;
1101 dbsettings["AuthProperties"] = settings;
1102 CoreSettings().setAuthSettings(dbsettings);
1105 // Generic version of promptForSettings that doesn't care what *type* of
1106 // backend it runs over.
1107 QVariantMap Core::promptForSettings(QStringList keys, QVariantMap defaults)
1109 QVariantMap settings;
1114 QTextStream out(stdout);
1115 QTextStream in(stdin);
1116 out << "Default values are in brackets" << endl;
1119 foreach(QString key, keys) {
1121 if (defaults.contains(key)) {
1122 val = defaults[key];
1125 if (!val.toString().isEmpty()) {
1126 out << " (" << val.toString() << ")";
1131 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1135 value = in.readLine().trimmed();
1141 if (!value.isEmpty()) {
1142 switch (defaults[key].type()) {
1144 val = QVariant(value.toInt());
1147 val = QVariant(value);
1150 settings[key] = val;
1155 // Since an auth and storage backend work basically the same way,
1156 // use polymorphism here on this routine.
1157 QVariantMap Core::promptForSettings(const Storage *storage)
1159 QStringList keys = storage->setupKeys();
1160 QVariantMap defaults = storage->setupDefaults();
1161 return Core::promptForSettings(keys, defaults);
1165 QVariantMap Core::promptForSettings(const Authenticator *authenticator)
1167 QStringList keys = authenticator->setupKeys();
1168 QVariantMap defaults = authenticator->setupDefaults();
1169 return Core::promptForSettings(keys, defaults);
1174 void Core::stdInEcho(bool on)
1176 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1178 GetConsoleMode(hStdin, &mode);
1180 mode |= ENABLE_ECHO_INPUT;
1182 mode &= ~ENABLE_ECHO_INPUT;
1183 SetConsoleMode(hStdin, mode);
1188 void Core::stdInEcho(bool on)
1191 tcgetattr(STDIN_FILENO, &t);
1196 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1200 #endif /* Q_OS_WIN */