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("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(_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(), "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::registerAuthenticators()
395 // Register new authentication backends here!
396 registerAuthenticator(new SqlAuthenticator(this));
398 registerAuthenticator(new LdapAuthenticator(this));
403 bool Core::registerAuthenticator(Authenticator *authenticator)
405 if (authenticator->isAvailable())
407 _authenticators[authenticator->backendId()] = authenticator;
410 authenticator->deleteLater();
415 void Core::unregisterAuthenticators()
417 foreach(Authenticator* a, _authenticators.values())
421 _authenticators.clear();
424 void Core::unregisterAuthenticator(Authenticator *backend)
426 _authenticators.remove(backend->backendId());
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 // FIXME: Apparently, this is the legacy way of initting storage backends?
471 // If there's a not-legacy way, it should be used here
472 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
476 if (backend.isEmpty()) {
480 Authenticator *authenticator = 0;
481 if (_authenticators.contains(backend)) {
482 authenticator = _authenticators[backend];
485 qCritical() << "Selected auth backend is not available:" << backend;
489 Authenticator::State authState = authenticator->init(settings);
491 case Authenticator::NeedsSetup:
493 return false; // trigger setup process
494 if (authenticator->setup(settings))
495 return initAuthenticator(backend, settings, false);
496 // if initialization wasn't successful, we quit to keep from coming up unconfigured
497 case Authenticator::NotAvailable:
498 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
500 case Authenticator::IsReady:
501 // delete all other backends
502 _authenticators.remove(backend);
503 unregisterAuthenticators();
505 _authenticator = authenticator;
509 void Core::syncStorage()
516 /*** Storage Access ***/
517 bool Core::createNetwork(UserId user, NetworkInfo &info)
519 NetworkId networkId = instance()->_storage->createNetwork(user, info);
520 if (!networkId.isValid())
523 info.networkId = networkId;
528 /*** Network Management ***/
530 bool Core::sslSupported()
533 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
534 return sslServer && sslServer->isCertValid();
541 bool Core::reloadCerts()
544 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
545 bool retv4 = sslServerv4->reloadCerts();
547 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
548 bool retv6 = sslServerv6->reloadCerts();
550 return retv4 && retv6;
552 // SSL not supported, don't mark configuration reload as failed
558 bool Core::startListening()
560 // in mono mode we only start a local port if a port is specified in the cli call
561 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
564 bool success = false;
565 uint port = Quassel::optionValue("port").toUInt();
567 const QString listen = Quassel::optionValue("listen");
568 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
569 if (listen_list.size() > 0) {
570 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
572 if (!addr.setAddress(listen_term)) {
573 qCritical() << qPrintable(
574 tr("Invalid listen address %1")
579 switch (addr.protocol()) {
580 case QAbstractSocket::IPv6Protocol:
581 if (_v6server.listen(addr, port)) {
582 quInfo() << qPrintable(
583 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
584 .arg(addr.toString())
585 .arg(_v6server.serverPort())
586 .arg(Quassel::buildInfo().protocolVersion)
591 quWarning() << qPrintable(
592 tr("Could not open IPv6 interface %1:%2: %3")
593 .arg(addr.toString())
595 .arg(_v6server.errorString()));
597 case QAbstractSocket::IPv4Protocol:
598 if (_server.listen(addr, port)) {
599 quInfo() << qPrintable(
600 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
601 .arg(addr.toString())
602 .arg(_server.serverPort())
603 .arg(Quassel::buildInfo().protocolVersion)
608 // if v6 succeeded on Any, the port will be already in use - don't display the error then
609 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
610 quWarning() << qPrintable(
611 tr("Could not open IPv4 interface %1:%2: %3")
612 .arg(addr.toString())
614 .arg(_server.errorString()));
618 qCritical() << qPrintable(
619 tr("Invalid listen address %1, unknown network protocol")
628 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
634 void Core::stopListening(const QString &reason)
636 bool wasListening = false;
637 if (_server.isListening()) {
641 if (_v6server.isListening()) {
646 if (reason.isEmpty())
647 quInfo() << "No longer listening for GUI clients.";
649 quInfo() << qPrintable(reason);
654 void Core::incomingConnection()
656 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
658 while (server->hasPendingConnections()) {
659 QTcpSocket *socket = server->nextPendingConnection();
661 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
662 _connectingClients.insert(handler);
664 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
665 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
666 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
668 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
671 stopListening(tr("Closing server for basic setup."));
677 // Potentially called during the initialization phase (before handing the connection off to the session)
678 void Core::clientDisconnected()
680 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
683 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
684 _connectingClients.remove(handler);
685 handler->deleteLater();
687 // make server listen again if still not configured
692 // TODO remove unneeded sessions - if necessary/possible...
693 // Suggestion: kill sessions if they are not connected to any network and client.
697 void Core::setupClientSession(RemotePeer *peer, UserId uid)
699 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
702 // From now on everything is handled by the client session
703 disconnect(handler, 0, this, 0);
704 _connectingClients.remove(handler);
705 handler->deleteLater();
707 // Find or create session for validated user
710 // as we are currently handling an event triggered by incoming data on this socket
711 // it is unsafe to directly move the socket to the client thread.
712 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
716 void Core::customEvent(QEvent *event)
718 if (event->type() == AddClientEventId) {
719 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
720 addClientHelper(addClientEvent->peer, addClientEvent->userId);
726 void Core::addClientHelper(RemotePeer *peer, UserId uid)
728 // Find or create session for validated user
729 SessionThread *session = sessionForUser(uid);
730 session->addClient(peer);
734 void Core::setupInternalClientSession(InternalPeer *clientPeer)
738 setupCoreForInternalUsage();
743 uid = _storage->internalUser();
746 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
750 InternalPeer *corePeer = new InternalPeer(this);
751 corePeer->setPeer(clientPeer);
752 clientPeer->setPeer(corePeer);
754 // Find or create session for validated user
755 SessionThread *sessionThread = sessionForUser(uid);
756 sessionThread->addClient(corePeer);
760 SessionThread *Core::sessionForUser(UserId uid, bool restore)
762 if (_sessions.contains(uid))
763 return _sessions[uid];
765 SessionThread *session = new SessionThread(uid, restore, this);
766 _sessions[uid] = session;
772 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
774 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
778 QVariantList Core::backendInfo()
780 QVariantList backends;
781 foreach(const Storage *backend, instance()->_storageBackends.values()) {
783 v["DisplayName"] = backend->displayName();
784 v["Description"] = backend->description();
785 v["SetupKeys"] = backend->setupKeys();
786 v["SetupDefaults"] = backend->setupDefaults();
787 v["IsDefault"] = isStorageBackendDefault(backend);
793 QVariantList Core::authenticatorInfo()
795 QVariantList backends;
796 foreach(const Authenticator *backend, instance()->_authenticators.values()) {
798 v["DisplayName"] = backend->backendId();
799 v["Description"] = backend->description();
800 v["SetupKeys"] = backend->setupKeys();
801 v["SetupDefaults"] = backend->setupDefaults();
807 // migration / backend selection
808 bool Core::selectBackend(const QString &backend)
810 // reregister all storage backends
811 registerStorageBackends();
812 if (!_storageBackends.contains(backend)) {
813 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
814 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
818 Storage *storage = _storageBackends[backend];
819 QVariantMap settings = promptForSettings(storage);
821 Storage::State storageState = storage->init(settings);
822 switch (storageState) {
823 case Storage::IsReady:
824 if (!saveBackendSettings(backend, settings)) {
825 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
827 qWarning() << "Switched backend to:" << qPrintable(backend);
828 qWarning() << "Backend already initialized. Skipping Migration";
830 case Storage::NotAvailable:
831 qCritical() << "Backend is not available:" << qPrintable(backend);
833 case Storage::NeedsSetup:
834 if (!storage->setup(settings)) {
835 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
839 if (storage->init(settings) != Storage::IsReady) {
840 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
844 if (!saveBackendSettings(backend, settings)) {
845 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
847 qWarning() << "Switched backend to:" << qPrintable(backend);
851 // let's see if we have a current storage object we can migrate from
852 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
853 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
854 if (reader && writer) {
855 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
860 if (reader->migrateTo(writer)) {
861 qDebug() << "Migration finished!";
862 if (!saveBackendSettings(backend, settings)) {
863 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
869 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
872 // inform the user why we cannot merge
874 qWarning() << "No currently active backend. Skipping migration.";
877 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
880 qWarning() << "New backend does not support migration:" << qPrintable(backend);
883 // so we were unable to merge, but let's create a user \o/
889 // TODO: I am not sure if this function is implemented correctly.
890 // There is currently no concept of migraiton between auth backends.
891 bool Core::selectAuthenticator(const QString &backend)
893 // Register all authentication backends.
894 registerAuthenticators();
895 if (!_authenticators.contains(backend)) {
896 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unsupported backend: %1").arg(backend));
897 qWarning() << " supported backends are:" << qPrintable(QStringList(_authenticators.keys()).join(", "));
901 Authenticator *authenticator = _authenticators[backend];
902 QVariantMap settings = promptForSettings(authenticator);
904 Authenticator::State state = authenticator->init(settings);
906 case Authenticator::IsReady:
907 saveAuthenticatorSettings(backend, settings);
908 qWarning() << "Switched auth backend to:" << qPrintable(backend);
909 // qWarning() << "Auth backend already initialized. Skipping Migration";
911 case Authenticator::NotAvailable:
912 qCritical() << "Auth backend is not available:" << qPrintable(backend);
914 case Authenticator::NeedsSetup:
915 if (!authenticator->setup(settings)) {
916 qWarning() << qPrintable(QString("Core::selectAuthenticator(): unable to setup authenticator: %1").arg(backend));
920 if (authenticator->init(settings) != Authenticator::IsReady) {
921 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize authenticator: %1").arg(backend));
925 saveAuthenticatorSettings(backend, settings);
926 qWarning() << "Switched auth backend to:" << qPrintable(backend);
929 _authenticator = authenticator;
934 bool Core::createUser()
936 QTextStream out(stdout);
937 QTextStream in(stdin);
938 out << "Add a new user:" << endl;
941 QString username = in.readLine().trimmed();
946 QString password = in.readLine().trimmed();
948 out << "Repeat Password: ";
950 QString password2 = in.readLine().trimmed();
954 if (password != password2) {
955 qWarning() << "Passwords don't match!";
958 if (password.isEmpty()) {
959 qWarning() << "Password is empty!";
963 if (_configured && _storage->addUser(username, password).isValid()) {
964 out << "Added user " << username << " successfully!" << endl;
968 qWarning() << "Unable to add user:" << qPrintable(username);
974 bool Core::changeUserPass(const QString &username)
976 QTextStream out(stdout);
977 QTextStream in(stdin);
978 UserId userId = _storage->getUserId(username);
979 if (!userId.isValid()) {
980 out << "User " << username << " does not exist." << endl;
984 if (!canChangeUserPassword(userId))
986 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
990 out << "Change password for user: " << username << endl;
993 out << "New Password: ";
995 QString password = in.readLine().trimmed();
997 out << "Repeat Password: ";
999 QString password2 = in.readLine().trimmed();
1003 if (password != password2) {
1004 qWarning() << "Passwords don't match!";
1007 if (password.isEmpty()) {
1008 qWarning() << "Password is empty!";
1012 if (_configured && _storage->updateUser(userId, password)) {
1013 out << "Password changed successfully!" << endl;
1017 qWarning() << "Failed to change password!";
1023 bool Core::changeUserPassword(UserId userId, const QString &password)
1025 if (!isConfigured() || !userId.isValid())
1028 if (!canChangeUserPassword(userId))
1031 return instance()->_storage->updateUser(userId, password);
1034 // TODO: this code isn't currently 100% optimal because the core
1035 // doesn't know it can have multiple auth providers configured (there aren't
1036 // multiple auth providers at the moment anyway) and we have hardcoded the
1037 // Database provider to be always allowed.
1038 bool Core::canChangeUserPassword(UserId userId)
1040 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1041 if (authProvider != "Database")
1043 if (authProvider != instance()->_authenticator->backendId()) {
1045 } else if (instance()->_authenticator->canChangePassword()) {
1052 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
1057 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1059 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1063 return sqlStorage->createMigrationReader();
1067 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
1072 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1074 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1078 return sqlStorage->createMigrationWriter();
1082 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1084 QVariantMap dbsettings;
1085 dbsettings["Backend"] = backend;
1086 dbsettings["ConnectionProperties"] = settings;
1087 CoreSettings s = CoreSettings();
1088 s.setStorageSettings(dbsettings);
1092 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1094 QVariantMap dbsettings;
1095 dbsettings["Authenticator"] = backend;
1096 dbsettings["ConnectionProperties"] = settings;
1097 CoreSettings().setAuthSettings(dbsettings);
1100 // Generic version of promptForSettings that doesn't care what *type* of
1101 // backend it runs over.
1102 QVariantMap Core::promptForSettings(QStringList keys, QVariantMap defaults)
1104 QVariantMap settings;
1109 QTextStream out(stdout);
1110 QTextStream in(stdin);
1111 out << "Default values are in brackets" << endl;
1114 foreach(QString key, keys) {
1116 if (defaults.contains(key)) {
1117 val = defaults[key];
1120 if (!val.toString().isEmpty()) {
1121 out << " (" << val.toString() << ")";
1126 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1130 value = in.readLine().trimmed();
1136 if (!value.isEmpty()) {
1137 switch (defaults[key].type()) {
1139 val = QVariant(value.toInt());
1142 val = QVariant(value);
1145 settings[key] = val;
1150 // Since an auth and storage backend work basically the same way,
1151 // use polymorphism here on this routine.
1152 QVariantMap Core::promptForSettings(const Storage *storage)
1154 QStringList keys = storage->setupKeys();
1155 QVariantMap defaults = storage->setupDefaults();
1156 return Core::promptForSettings(keys, defaults);
1160 QVariantMap Core::promptForSettings(const Authenticator *authenticator)
1162 QStringList keys = authenticator->setupKeys();
1163 QVariantMap defaults = authenticator->setupDefaults();
1164 return Core::promptForSettings(keys, defaults);
1169 void Core::stdInEcho(bool on)
1171 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1173 GetConsoleMode(hStdin, &mode);
1175 mode |= ENABLE_ECHO_INPUT;
1177 mode &= ~ENABLE_ECHO_INPUT;
1178 SetConsoleMode(hStdin, mode);
1183 void Core::stdInEcho(bool on)
1186 tcgetattr(STDIN_FILENO, &t);
1191 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1195 #endif /* Q_OS_WIN */