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") || 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(_authenticatorBackends);
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 &authBackend, const QVariantMap &authSetupData)
304 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authBackend, authSetupData);
308 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, 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: " << authBackend;
321 if (!(_configured = initAuthenticator(authBackend, 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 saveAuthBackendSettings(authBackend, 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(), "StorageAuth", 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();
375 void Core::unregisterStorageBackends()
377 foreach(Storage *s, _storageBackends.values()) {
380 _storageBackends.clear();
384 void Core::unregisterStorageBackend(Storage *backend)
386 _storageBackends.remove(backend->displayName());
387 backend->deleteLater();
390 // Authentication handling, now independent from storage.
391 // Register and unregister authenticators.
393 void Core::registerAuthenticatorBackends()
395 // Register new authentication backends here!
396 registerAuthenticatorBackend(new SqlAuthenticator(this));
398 registerAuthenticatorBackend(new LdapAuthenticator(this));
403 bool Core::registerAuthenticatorBackend(Authenticator *authenticator)
405 if (authenticator->isAvailable())
407 _authenticatorBackends[authenticator->displayName()] = authenticator;
410 authenticator->deleteLater();
415 void Core::unregisterAuthenticatorBackends()
417 foreach(Authenticator* a, _authenticatorBackends.values())
421 _authenticatorBackends.clear();
424 void Core::unregisterAuthenticatorBackend(Authenticator *backend)
426 _authenticatorBackends.remove(backend->displayName());
427 backend->deleteLater();
431 // "Type" => "sqlite"
432 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
436 if (backend.isEmpty()) {
440 Storage *storage = 0;
441 if (_storageBackends.contains(backend)) {
442 storage = _storageBackends[backend];
445 qCritical() << "Selected storage backend is not available:" << backend;
449 Storage::State storageState = storage->init(settings);
450 switch (storageState) {
451 case Storage::NeedsSetup:
453 return false; // trigger setup process
454 if (storage->setup(settings))
455 return initStorage(backend, settings, false);
456 // if initialization wasn't successful, we quit to keep from coming up unconfigured
457 case Storage::NotAvailable:
458 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
460 case Storage::IsReady:
461 // delete all other backends
462 _storageBackends.remove(backend);
463 unregisterStorageBackends();
464 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
470 // XXX: TODO: Apparently, this is legacy?
471 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
475 if (backend.isEmpty()) {
479 Authenticator *authenticator = 0;
480 if (_authenticatorBackends.contains(backend)) {
481 authenticator = _authenticatorBackends[backend];
484 qCritical() << "Selected auth backend is not available:" << backend;
488 Authenticator::State authState = authenticator->init(settings);
490 case Authenticator::NeedsSetup:
492 return false; // trigger setup process
493 if (authenticator->setup(settings))
494 return initAuthenticator(backend, settings, false);
495 // if initialization wasn't successful, we quit to keep from coming up unconfigured
496 case Authenticator::NotAvailable:
497 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
499 case Authenticator::IsReady:
500 // delete all other backends
501 _authenticatorBackends.remove(backend);
502 unregisterAuthenticatorBackends();
504 _authenticator = authenticator;
508 void Core::syncStorage()
515 /*** Storage Access ***/
516 bool Core::createNetwork(UserId user, NetworkInfo &info)
518 NetworkId networkId = instance()->_storage->createNetwork(user, info);
519 if (!networkId.isValid())
522 info.networkId = networkId;
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 bool Core::startListening()
559 // in mono mode we only start a local port if a port is specified in the cli call
560 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
563 bool success = false;
564 uint port = Quassel::optionValue("port").toUInt();
566 const QString listen = Quassel::optionValue("listen");
567 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
568 if (listen_list.size() > 0) {
569 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
571 if (!addr.setAddress(listen_term)) {
572 qCritical() << qPrintable(
573 tr("Invalid listen address %1")
578 switch (addr.protocol()) {
579 case QAbstractSocket::IPv6Protocol:
580 if (_v6server.listen(addr, port)) {
581 quInfo() << qPrintable(
582 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
583 .arg(addr.toString())
584 .arg(_v6server.serverPort())
585 .arg(Quassel::buildInfo().protocolVersion)
590 quWarning() << qPrintable(
591 tr("Could not open IPv6 interface %1:%2: %3")
592 .arg(addr.toString())
594 .arg(_v6server.errorString()));
596 case QAbstractSocket::IPv4Protocol:
597 if (_server.listen(addr, port)) {
598 quInfo() << qPrintable(
599 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
600 .arg(addr.toString())
601 .arg(_server.serverPort())
602 .arg(Quassel::buildInfo().protocolVersion)
607 // if v6 succeeded on Any, the port will be already in use - don't display the error then
608 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
609 quWarning() << qPrintable(
610 tr("Could not open IPv4 interface %1:%2: %3")
611 .arg(addr.toString())
613 .arg(_server.errorString()));
617 qCritical() << qPrintable(
618 tr("Invalid listen address %1, unknown network protocol")
627 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
633 void Core::stopListening(const QString &reason)
635 bool wasListening = false;
636 if (_server.isListening()) {
640 if (_v6server.isListening()) {
645 if (reason.isEmpty())
646 quInfo() << "No longer listening for GUI clients.";
648 quInfo() << qPrintable(reason);
653 void Core::incomingConnection()
655 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
657 while (server->hasPendingConnections()) {
658 QTcpSocket *socket = server->nextPendingConnection();
660 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
661 _connectingClients.insert(handler);
663 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
664 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
665 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
667 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
670 stopListening(tr("Closing server for basic setup."));
676 // Potentially called during the initialization phase (before handing the connection off to the session)
677 void Core::clientDisconnected()
679 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
682 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
683 _connectingClients.remove(handler);
684 handler->deleteLater();
686 // make server listen again if still not configured
691 // TODO remove unneeded sessions - if necessary/possible...
692 // Suggestion: kill sessions if they are not connected to any network and client.
696 void Core::setupClientSession(RemotePeer *peer, UserId uid)
698 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
701 // From now on everything is handled by the client session
702 disconnect(handler, 0, this, 0);
703 _connectingClients.remove(handler);
704 handler->deleteLater();
706 // Find or create session for validated user
709 // as we are currently handling an event triggered by incoming data on this socket
710 // it is unsafe to directly move the socket to the client thread.
711 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
715 void Core::customEvent(QEvent *event)
717 if (event->type() == AddClientEventId) {
718 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
719 addClientHelper(addClientEvent->peer, addClientEvent->userId);
725 void Core::addClientHelper(RemotePeer *peer, UserId uid)
727 // Find or create session for validated user
728 SessionThread *session = sessionForUser(uid);
729 session->addClient(peer);
733 void Core::setupInternalClientSession(InternalPeer *clientPeer)
737 setupCoreForInternalUsage();
742 uid = _storage->internalUser();
745 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
749 InternalPeer *corePeer = new InternalPeer(this);
750 corePeer->setPeer(clientPeer);
751 clientPeer->setPeer(corePeer);
753 // Find or create session for validated user
754 SessionThread *sessionThread = sessionForUser(uid);
755 sessionThread->addClient(corePeer);
759 SessionThread *Core::sessionForUser(UserId uid, bool restore)
761 if (_sessions.contains(uid))
762 return _sessions[uid];
764 SessionThread *session = new SessionThread(uid, restore, this);
765 _sessions[uid] = session;
771 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
773 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
777 QVariantList Core::backendInfo()
779 QVariantList backends;
780 foreach(const Storage *backend, instance()->_storageBackends.values()) {
782 v["DisplayName"] = backend->displayName();
783 v["Description"] = backend->description();
784 v["SetupKeys"] = backend->setupKeys();
785 v["SetupDefaults"] = backend->setupDefaults();
786 v["IsDefault"] = isStorageBackendDefault(backend);
792 QVariantList Core::authenticatorInfo()
794 QVariantList backends;
795 foreach(const Authenticator *backend, instance()->_authenticatorBackends.values()) {
797 v["DisplayName"] = backend->displayName();
798 v["Description"] = backend->description();
799 v["SetupKeys"] = backend->setupKeys();
800 v["SetupDefaults"] = backend->setupDefaults();
806 // migration / backend selection
807 bool Core::selectBackend(const QString &backend)
809 // reregister all storage backends
810 registerStorageBackends();
811 if (!_storageBackends.contains(backend)) {
812 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
813 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
817 Storage *storage = _storageBackends[backend];
818 QVariantMap settings = promptForSettings(storage);
820 Storage::State storageState = storage->init(settings);
821 switch (storageState) {
822 case Storage::IsReady:
823 if (!saveBackendSettings(backend, settings)) {
824 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
826 qWarning() << "Switched backend to:" << qPrintable(backend);
827 qWarning() << "Backend already initialized. Skipping Migration";
829 case Storage::NotAvailable:
830 qCritical() << "Backend is not available:" << qPrintable(backend);
832 case Storage::NeedsSetup:
833 if (!storage->setup(settings)) {
834 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
838 if (storage->init(settings) != Storage::IsReady) {
839 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
843 if (!saveBackendSettings(backend, settings)) {
844 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
846 qWarning() << "Switched backend to:" << qPrintable(backend);
850 // let's see if we have a current storage object we can migrate from
851 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
852 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
853 if (reader && writer) {
854 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
859 if (reader->migrateTo(writer)) {
860 qDebug() << "Migration finished!";
861 if (!saveBackendSettings(backend, settings)) {
862 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
868 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
871 // inform the user why we cannot merge
873 qWarning() << "No currently active backend. Skipping migration.";
876 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
879 qWarning() << "New backend does not support migration:" << qPrintable(backend);
882 // so we were unable to merge, but let's create a user \o/
888 // XXX: I am not sure if this function is implemented correctly.
889 // There is currently no concept of migraiton between auth backends.
890 bool Core::selectAuthenticator(const QString &backend)
892 // Register all authentication backends.
893 registerAuthenticatorBackends();
894 if (!_authenticatorBackends.contains(backend)) {
895 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unsupported backend: %1").arg(backend));
896 qWarning() << " supported backends are:" << qPrintable(QStringList(_authenticatorBackends.keys()).join(", "));
900 Authenticator *authenticator = _authenticatorBackends[backend];
901 QVariantMap settings = promptForSettings(authenticator);
903 Authenticator::State state = authenticator->init(settings);
905 case Authenticator::IsReady:
906 saveAuthBackendSettings(backend, settings);
907 qWarning() << "Switched auth backend to:" << qPrintable(backend);
908 // qWarning() << "Auth backend already initialized. Skipping Migration";
910 case Authenticator::NotAvailable:
911 qCritical() << "Auth backend is not available:" << qPrintable(backend);
913 case Authenticator::NeedsSetup:
914 if (!authenticator->setup(settings)) {
915 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unable to setup authenticator: %1").arg(backend));
919 if (authenticator->init(settings) != Authenticator::IsReady) {
920 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize authenticator: %1").arg(backend));
924 saveAuthBackendSettings(backend, settings);
925 qWarning() << "Switched auth backend to:" << qPrintable(backend);
928 _authenticator = authenticator;
933 bool Core::createUser()
935 QTextStream out(stdout);
936 QTextStream in(stdin);
937 out << "Add a new user:" << endl;
940 QString username = in.readLine().trimmed();
945 QString password = in.readLine().trimmed();
947 out << "Repeat Password: ";
949 QString password2 = in.readLine().trimmed();
953 if (password != password2) {
954 qWarning() << "Passwords don't match!";
957 if (password.isEmpty()) {
958 qWarning() << "Password is empty!";
962 if (_configured && _storage->addUser(username, password).isValid()) {
963 out << "Added user " << username << " successfully!" << endl;
967 qWarning() << "Unable to add user:" << qPrintable(username);
973 bool Core::changeUserPass(const QString &username)
975 QTextStream out(stdout);
976 QTextStream in(stdin);
977 UserId userId = _storage->getUserId(username);
978 if (!userId.isValid()) {
979 out << "User " << username << " does not exist." << endl;
983 if (!canChangeUserPassword(userId))
985 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
989 out << "Change password for user: " << username << endl;
992 out << "New Password: ";
994 QString password = in.readLine().trimmed();
996 out << "Repeat Password: ";
998 QString password2 = in.readLine().trimmed();
1002 if (password != password2) {
1003 qWarning() << "Passwords don't match!";
1006 if (password.isEmpty()) {
1007 qWarning() << "Password is empty!";
1011 if (_configured && _storage->updateUser(userId, password)) {
1012 out << "Password changed successfully!" << endl;
1016 qWarning() << "Failed to change password!";
1022 bool Core::changeUserPassword(UserId userId, const QString &password)
1024 if (!isConfigured() || !userId.isValid())
1027 if (!canChangeUserPassword(userId))
1030 return instance()->_storage->updateUser(userId, password);
1033 // XXX: this code isn't currently 100% optimal because the core
1034 // doesn't know it can have multiple auth providers configured (there aren't
1035 // multiple auth providers at the moment anyway) and we have hardcoded the
1036 // Database provider to be always allowed.
1037 bool Core::canChangeUserPassword(UserId userId)
1039 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1040 if (authProvider != "Database")
1042 if (authProvider != instance()->_authenticator->displayName()) {
1044 } else if (instance()->_authenticator->canChangePassword()) {
1051 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
1056 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1058 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1062 return sqlStorage->createMigrationReader();
1066 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
1071 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1073 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1077 return sqlStorage->createMigrationWriter();
1081 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1083 QVariantMap dbsettings;
1084 dbsettings["Backend"] = backend;
1085 dbsettings["ConnectionProperties"] = settings;
1086 CoreSettings s = CoreSettings();
1087 s.setStorageSettings(dbsettings);
1091 void Core::saveAuthBackendSettings(const QString &backend, const QVariantMap &settings)
1093 QVariantMap dbsettings;
1094 dbsettings["AuthBackend"] = backend;
1095 dbsettings["ConnectionProperties"] = settings;
1096 CoreSettings().setAuthSettings(dbsettings);
1099 // Generic version of promptForSettings that doesn't care what *type* of
1100 // backend it runs over.
1101 QVariantMap Core::promptForSettings(QStringList keys, QVariantMap defaults)
1103 QVariantMap settings;
1108 QTextStream out(stdout);
1109 QTextStream in(stdin);
1110 out << "Default values are in brackets" << endl;
1113 foreach(QString key, keys) {
1115 if (defaults.contains(key)) {
1116 val = defaults[key];
1119 if (!val.toString().isEmpty()) {
1120 out << " (" << val.toString() << ")";
1125 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1129 value = in.readLine().trimmed();
1135 if (!value.isEmpty()) {
1136 switch (defaults[key].type()) {
1138 val = QVariant(value.toInt());
1141 val = QVariant(value);
1144 settings[key] = val;
1149 // Since an auth and storage backend work basically the same way,
1150 // use polymorphism here on this routine.
1151 QVariantMap Core::promptForSettings(const Storage *storage)
1153 QStringList keys = storage->setupKeys();
1154 QVariantMap defaults = storage->setupDefaults();
1155 return Core::promptForSettings(keys, defaults);
1159 QVariantMap Core::promptForSettings(const Authenticator *authenticator)
1161 QStringList keys = authenticator->setupKeys();
1162 QVariantMap defaults = authenticator->setupDefaults();
1163 return Core::promptForSettings(keys, defaults);
1168 void Core::stdInEcho(bool on)
1170 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1172 GetConsoleMode(hStdin, &mode);
1174 mode |= ENABLE_ECHO_INPUT;
1176 mode &= ~ENABLE_ECHO_INPUT;
1177 SetConsoleMode(hStdin, mode);
1182 void Core::stdInEcho(bool on)
1185 tcgetattr(STDIN_FILENO, &t);
1190 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1194 #endif /* Q_OS_WIN */