1 /***************************************************************************
2 * Copyright (C) 2005-09 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include <QCoreApplication>
24 #include "coresession.h"
25 #include "coresettings.h"
26 #include "postgresqlstorage.h"
28 #include "signalproxy.h"
29 #include "sqlitestorage.h"
38 Core *Core::instanceptr = 0;
40 Core *Core::instance() {
41 if(instanceptr) return instanceptr;
42 instanceptr = new Core();
47 void Core::destroy() {
55 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
57 Quassel::loadTranslation(QLocale::system());
59 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
60 // Move settings, note this does not delete the old files
62 QSettings newSettings("quassel-irc.org", "quasselcore");
66 QSettings::Format format = QSettings::IniFormat;
68 QSettings::Format format = QSettings::NativeFormat;
70 QString newFilePath = Quassel::configDirPath() + "quasselcore"
71 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
72 QSettings newSettings(newFilePath, format);
75 if(newSettings.value("Config/Version").toUInt() == 0) {
77 QString org = "quassel-irc.org";
79 QString org = "Quassel Project";
81 QSettings oldSettings(org, "Quassel Core");
82 if(oldSettings.allKeys().count()) {
83 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
84 foreach(QString key, oldSettings.allKeys())
85 newSettings.setValue(key, oldSettings.value(key));
86 newSettings.setValue("Config/Version", 1);
87 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
89 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
91 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
92 #elif defined Q_WS_MAC
93 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
95 QString quasselDir = QDir::homePath() + "/.quassel/";
98 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
100 // move database, if we found it
101 QFile oldDb(quasselDir + "quassel-storage.sqlite");
103 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
105 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
107 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
111 QFileInfo certInfo(quasselDir + "quasselCert.pem");
112 if(certInfo.exists()) {
113 QFile cert(quasselDir + "quasselCert.pem");
114 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
116 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
118 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
120 #endif /* !Q_WS_MAC */
121 qWarning() << "*** Migration completed.\n\n";
126 // check settings version
127 // so far, we only have 1
129 if(s.version() != 1) {
130 qCritical() << "Invalid core settings version, terminating!";
134 registerStorageBackends();
136 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
137 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
141 if(Quassel::isOptionSet("select-backend")) {
142 switchBackend(Quassel::optionValue("select-backend"));
147 _configured = initStorage(cs.storageSettings().toMap());
150 if(!_storageBackends.count()) {
151 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
152 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
153 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
155 exit(1); // TODO make this less brutal (especially for mono client -> popup)
157 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
160 if(Quassel::isOptionSet("migrate-backend")) {
161 migrateBackend(Quassel::optionValue("migrate-backend"));
165 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
166 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
167 if(!startListening()) exit(1); // TODO make this less brutal
171 foreach(QTcpSocket *socket, blocksizes.keys()) {
172 socket->disconnectFromHost(); // disconnect non authed clients
174 qDeleteAll(sessions);
175 qDeleteAll(_storageBackends);
178 /*** Session Restore ***/
180 void Core::saveState() {
183 QVariantList activeSessions;
184 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
185 state["CoreStateVersion"] = 1;
186 state["ActiveSessions"] = activeSessions;
187 s.setCoreState(state);
190 void Core::restoreState() {
191 if(!instance()->_configured) {
192 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
195 if(instance()->sessions.count()) {
196 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
200 /* We don't check, since we are at the first version since switching to Git
201 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
203 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
207 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
208 if(activeSessions.count() > 0) {
209 quInfo() << "Restoring previous core state...";
210 foreach(QVariant v, activeSessions) {
211 UserId user = v.value<UserId>();
212 instance()->createSession(user, true);
218 QString Core::setupCoreForInternalUsage() {
219 Q_ASSERT(!_storageBackends.isEmpty());
220 QVariantMap setupData;
221 qsrand(QDateTime::currentDateTime().toTime_t());
223 for(int i = 0; i < 10; i++) {
225 pass += qrand() % 10;
227 setupData["AdminUser"] = "AdminUser";
228 setupData["AdminPasswd"] = QString::number(pass);
229 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
230 return setupCore(setupData);
233 QString Core::setupCore(QVariantMap setupData) {
234 QString user = setupData.take("AdminUser").toString();
235 QString password = setupData.take("AdminPasswd").toString();
236 if(user.isEmpty() || password.isEmpty()) {
237 return tr("Admin user or password not set.");
239 _configured = initStorage(setupData, true);
241 return tr("Could not setup storage!");
244 s.setStorageSettings(setupData);
245 quInfo() << qPrintable(tr("Creating admin user..."));
246 _storage->addUser(user, password);
247 startListening(); // TODO check when we need this
251 /*** Storage Handling ***/
252 void Core::registerStorageBackends() {
253 // Register storage backends here!
254 registerStorageBackend(new SqliteStorage(this));
255 registerStorageBackend(new PostgreSqlStorage(this));
258 bool Core::registerStorageBackend(Storage *backend) {
259 if(backend->isAvailable()) {
260 _storageBackends[backend->displayName()] = backend;
263 backend->deleteLater();
268 void Core::unregisterStorageBackends() {
269 foreach(Storage *s, _storageBackends.values()) {
272 _storageBackends.clear();
275 void Core::unregisterStorageBackend(Storage *backend) {
276 _storageBackends.remove(backend->displayName());
277 backend->deleteLater();
281 // "Type" => "sqlite"
282 bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup) {
285 if(backend.isEmpty()) {
289 Storage *storage = 0;
290 if(_storageBackends.contains(backend)) {
291 storage = _storageBackends[backend];
293 qCritical() << "Selected storage backend is not available:" << backend;
297 Storage::State storageState = storage->init(settings);
298 switch(storageState) {
299 case Storage::NeedsSetup:
301 return false; // trigger setup process
302 if(storage->setup(settings))
303 return initStorage(backend, settings, false);
304 // if setup wasn't successfull we mark the backend as unavailable
305 case Storage::NotAvailable:
306 qCritical() << "Selected storage backend is not available:" << backend;
307 storage->deleteLater();
308 _storageBackends.remove(backend);
311 case Storage::IsReady:
312 // delete all other backends
313 _storageBackends.remove(backend);
314 unregisterStorageBackends();
315 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
321 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
322 return initStorage(dbSettings["Backend"].toString(), dbSettings["ConnectionProperties"].toMap(), setup);
326 void Core::syncStorage() {
331 /*** Storage Access ***/
332 bool Core::createNetwork(UserId user, NetworkInfo &info) {
333 NetworkId networkId = instance()->_storage->createNetwork(user, info);
334 if(!networkId.isValid())
337 info.networkId = networkId;
341 /*** Network Management ***/
343 bool Core::startListening() {
344 // in mono mode we only start a local port if a port is specified in the cli call
345 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
348 bool success = false;
349 uint port = Quassel::optionValue("port").toUInt();
351 const QString listen = Quassel::optionValue("listen");
352 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
353 if(listen_list.size() > 0) {
354 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
356 if(!addr.setAddress(listen_term)) {
357 qCritical() << qPrintable(
358 tr("Invalid listen address %1")
362 switch(addr.protocol()) {
363 case QAbstractSocket::IPv4Protocol:
364 if(_server.listen(addr, port)) {
365 quInfo() << qPrintable(
366 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
367 .arg(addr.toString())
368 .arg(_server.serverPort())
369 .arg(Quassel::buildInfo().protocolVersion)
373 quWarning() << qPrintable(
374 tr("Could not open IPv4 interface %1:%2: %3")
375 .arg(addr.toString())
377 .arg(_server.errorString()));
379 case QAbstractSocket::IPv6Protocol:
380 if(_v6server.listen(addr, port)) {
381 quInfo() << qPrintable(
382 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
383 .arg(addr.toString())
384 .arg(_v6server.serverPort())
385 .arg(Quassel::buildInfo().protocolVersion)
389 // if v4 succeeded on Any, the port will be already in use - don't display the error then
390 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
391 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
392 quWarning() << qPrintable(
393 tr("Could not open IPv6 interface %1:%2: %3")
394 .arg(addr.toString())
396 .arg(_v6server.errorString()));
400 qCritical() << qPrintable(
401 tr("Invalid listen address %1, unknown network protocol")
410 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
415 void Core::stopListening(const QString &reason) {
416 bool wasListening = false;
417 if(_server.isListening()) {
421 if(_v6server.isListening()) {
427 quInfo() << "No longer listening for GUI clients.";
429 quInfo() << qPrintable(reason);
433 void Core::incomingConnection() {
434 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
436 while(server->hasPendingConnections()) {
437 QTcpSocket *socket = server->nextPendingConnection();
438 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
439 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
440 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
442 QVariantMap clientInfo;
443 blocksizes.insert(socket, (quint32)0);
444 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
447 stopListening(tr("Closing server for basic setup."));
452 void Core::clientHasData() {
453 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
454 Q_ASSERT(socket && blocksizes.contains(socket));
456 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
457 QVariantMap msg = item.toMap();
458 processClientMessage(socket, msg);
459 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
463 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
464 if(!msg.contains("MsgType")) {
465 // Client is way too old, does not even use the current init format
466 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
470 // OK, so we have at least an init message format we can understand
471 if(msg["MsgType"] == "ClientInit") {
474 // Just version information -- check it!
475 uint ver = msg["ProtocolVersion"].toUInt();
476 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
477 reply["MsgType"] = "ClientInitReject";
478 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
479 "This core needs at least client/core protocol version %1.<br>"
480 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
481 SignalProxy::writeDataToDevice(socket, reply);
482 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
483 socket->close(); return;
486 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
487 reply["CoreDate"] = Quassel::buildInfo().buildDate;
488 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
489 // TODO: Make the core info configurable
490 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
491 int updays = uptime / 86400; uptime %= 86400;
492 int uphours = uptime / 3600; uptime %= 3600;
493 int upmins = uptime / 60;
494 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
496 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
497 .arg(Quassel::buildInfo().buildDate)
498 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
501 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
502 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
503 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
505 bool supportSsl = false;
508 #ifndef QT_NO_COMPRESS
509 bool supportsCompression = true;
511 bool supportsCompression = false;
514 reply["SupportSsl"] = supportSsl;
515 reply["SupportsCompression"] = supportsCompression;
516 // switch to ssl/compression after client has been informed about our capabilities (see below)
518 reply["LoginEnabled"] = true;
520 // check if we are configured, start wizard otherwise
522 reply["Configured"] = false;
523 QList<QVariant> backends;
524 foreach(Storage *backend, _storageBackends.values()) {
526 v["DisplayName"] = backend->displayName();
527 v["Description"] = backend->description();
528 v["SetupKeys"] = backend->setupKeys();
529 v["SetupDefaults"] = backend->setupDefaults();
532 reply["StorageBackends"] = backends;
533 reply["LoginEnabled"] = false;
535 reply["Configured"] = true;
537 clientInfo[socket] = msg; // store for future reference
538 reply["MsgType"] = "ClientInitAck";
539 SignalProxy::writeDataToDevice(socket, reply);
542 // after we told the client that we are ssl capable we switch to ssl mode
543 if(supportSsl && msg["UseSsl"].toBool()) {
544 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
545 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
546 sslSocket->startServerEncryption();
550 #ifndef QT_NO_COMPRESS
551 if(supportsCompression && msg["UseCompression"].toBool()) {
552 socket->setProperty("UseCompression", true);
553 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
558 // for the rest, we need an initialized connection
559 if(!clientInfo.contains(socket)) {
561 reply["MsgType"] = "ClientLoginReject";
562 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
563 SignalProxy::writeDataToDevice(socket, reply);
564 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
565 socket->close(); return;
567 if(msg["MsgType"] == "CoreSetupData") {
569 QString result = setupCore(msg["SetupData"].toMap());
570 if(!result.isEmpty()) {
571 reply["MsgType"] = "CoreSetupReject";
572 reply["Error"] = result;
574 reply["MsgType"] = "CoreSetupAck";
576 SignalProxy::writeDataToDevice(socket, reply);
577 } else if(msg["MsgType"] == "ClientLogin") {
579 UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
581 reply["MsgType"] = "ClientLoginReject";
582 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
583 SignalProxy::writeDataToDevice(socket, reply);
586 reply["MsgType"] = "ClientLoginAck";
587 SignalProxy::writeDataToDevice(socket, reply);
588 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt()));
589 setupClientSession(socket, uid);
594 // Potentially called during the initialization phase (before handing the connection off to the session)
595 void Core::clientDisconnected() {
596 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
598 // here it's safe to call methods on socket!
599 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
600 blocksizes.remove(socket);
601 clientInfo.remove(socket);
602 socket->deleteLater();
604 // we have to crawl through the hashes and see if we find a victim to remove
605 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
607 // DO NOT CALL ANY METHODS ON socket!!
608 socket = static_cast<QTcpSocket *>(sender());
610 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
611 while(blockSizeIter != blocksizes.end()) {
612 if(blockSizeIter.key() == socket) {
613 blockSizeIter = blocksizes.erase(blockSizeIter);
619 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
620 while(clientInfoIter != clientInfo.end()) {
621 if(clientInfoIter.key() == socket) {
622 clientInfoIter = clientInfo.erase(clientInfoIter);
630 // make server listen again if still not configured
635 // TODO remove unneeded sessions - if necessary/possible...
636 // Suggestion: kill sessions if they are not connected to any network and client.
639 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
640 // Find or create session for validated user
642 if(sessions.contains(uid)) sess = sessions[uid];
643 else sess = createSession(uid);
644 // Hand over socket, session then sends state itself
645 disconnect(socket, 0, this, 0);
646 blocksizes.remove(socket);
647 clientInfo.remove(socket);
649 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
652 sess->addClient(socket);
655 void Core::setupInternalClientSession(SignalProxy *proxy) {
658 setupCoreForInternalUsage();
661 UserId uid = _storage->internalUser();
663 // Find or create session for validated user
665 if(sessions.contains(uid))
666 sess = sessions[uid];
668 sess = createSession(uid);
669 sess->addClient(proxy);
672 SessionThread *Core::createSession(UserId uid, bool restore) {
673 if(sessions.contains(uid)) {
674 qWarning() << "Calling createSession() when a session for the user already exists!";
677 SessionThread *sess = new SessionThread(uid, restore, this);
678 sessions[uid] = sess;
684 void Core::sslErrors(const QList<QSslError> &errors) {
686 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
688 socket->ignoreSslErrors();
692 void Core::socketError(QAbstractSocket::SocketError err) {
693 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
694 if(socket && err != QAbstractSocket::RemoteHostClosedError)
695 qWarning() << "Core::socketError()" << socket << err << socket->errorString();
698 bool Core::migrateBackend(const QString &backend) {
699 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(_storage);
701 qWarning() << "Core::migrateDb(): only SQL based backends can be migrated!";
705 AbstractSqlMigrationReader *reader = sqlStorage->createMigrationReader();
707 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration reader for %1)").arg(sqlStorage->displayName()));
712 // reregister all storage backends
713 registerStorageBackends();
714 if(_storageBackends.contains(sqlStorage->displayName())) {
715 unregisterStorageBackend(_storageBackends[sqlStorage->displayName()]);
717 if(!_storageBackends.contains(backend)) {
718 qWarning() << qPrintable(QString("Core::migrateBackend(): unsupported migration target: %1").arg(backend));
719 qWarning() << " supported Targets:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
723 Storage *storage = _storageBackends[backend];
724 QVariantMap settings = promptForSettings(storage);
726 Storage::State storageState = storage->init(settings);
727 switch(storageState) {
728 case Storage::NotAvailable:
729 qCritical() << "Core::migrateBackend(): selected storage backend is not available:" << backend;
731 case Storage::NeedsSetup:
732 if(!storage->setup(settings)) {
733 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to setup target: %1").arg(backend));
737 if(storage->init(settings) != Storage::IsReady) {
738 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize target: %1").arg(backend));
741 case Storage::IsReady:
745 sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
747 qWarning() << "Core::migrateDb(): only SQL based backends can be migrated!";
750 AbstractSqlMigrationWriter *writer = sqlStorage->createMigrationWriter();
752 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
756 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
761 if(reader->migrateTo(writer)) {
762 qDebug() << "Migration finished!";
763 saveBackendSettings(backend, settings);
769 bool Core::switchBackend(const QString &backend) {
770 if(!_storageBackends.contains(backend)) {
771 qWarning() << qPrintable(QString("Core::switchBackend(): unsupported backend: %1").arg(backend));
772 qWarning() << " supported backends:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
776 Storage *storage = _storageBackends[backend];
777 QVariantMap settings = promptForSettings(storage);
779 bool ok = initStorage(backend, settings, true /* initial setup is allowed */);
781 saveBackendSettings(backend, settings);
782 qWarning() << "Switched backend to:" << qPrintable(backend);
784 qWarning() << "Failed to switch backend to:" << qPrintable(backend);
789 void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings) {
790 QVariantMap dbsettings;
791 dbsettings["Backend"] = backend;
792 dbsettings["ConnectionProperties"] = settings;
793 CoreSettings().setStorageSettings(dbsettings);
796 QVariantMap Core::promptForSettings(const Storage *storage) {
797 QVariantMap settings;
799 QStringList keys = storage->setupKeys();
803 QTextStream out(stdout);
804 QTextStream in(stdin);
805 out << "!!!Warning: echo mode is always on even if asked for a password!!!" << endl;
806 out << "Default values are in brackets" << endl;
808 QVariantMap defaults = storage->setupDefaults();
810 foreach(QString key, keys) {
812 if(defaults.contains(key)) {
816 if(!val.toString().isEmpty()) {
817 out << " (" << val.toString() << ")";
821 value = in.readLine().trimmed();
823 if(!value.isEmpty()) {
824 switch(defaults[key].type()) {
826 val = QVariant(value.toInt());
829 val = QVariant(value);