Make reloadCerts also handle the IPv6 server
[quassel.git] / src / core / core.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include <QCoreApplication>
22
23 #include "core.h"
24 #include "coreauthhandler.h"
25 #include "coresession.h"
26 #include "coresettings.h"
27 #include "logger.h"
28 #include "internalpeer.h"
29 #include "network.h"
30 #include "postgresqlstorage.h"
31 #include "quassel.h"
32 #include "sqlitestorage.h"
33 #include "util.h"
34
35 // migration related
36 #include <QFile>
37 #ifdef Q_OS_WIN
38 #  include <windows.h>
39 #else
40 #  include <unistd.h>
41 #  include <termios.h>
42 #endif /* Q_OS_WIN */
43
44 #ifdef HAVE_UMASK
45 #  include <sys/types.h>
46 #  include <sys/stat.h>
47 #endif /* HAVE_UMASK */
48
49 // ==============================
50 //  Custom Events
51 // ==============================
52 const int Core::AddClientEventId = QEvent::registerEventType();
53
54 class AddClientEvent : public QEvent
55 {
56 public:
57     AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
58     RemotePeer *peer;
59     UserId userId;
60 };
61
62
63 // ==============================
64 //  Core
65 // ==============================
66 Core *Core::instanceptr = 0;
67
68 Core *Core::instance()
69 {
70     if (instanceptr) return instanceptr;
71     instanceptr = new Core();
72     instanceptr->init();
73     return instanceptr;
74 }
75
76
77 void Core::destroy()
78 {
79     delete instanceptr;
80     instanceptr = 0;
81 }
82
83
84 Core::Core()
85     : QObject(),
86       _storage(0)
87 {
88 #ifdef HAVE_UMASK
89     umask(S_IRWXG | S_IRWXO);
90 #endif
91     _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
92
93     Quassel::loadTranslation(QLocale::system());
94
95     // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
96     // Move settings, note this does not delete the old files
97 #ifdef Q_OS_MAC
98     QSettings newSettings("quassel-irc.org", "quasselcore");
99 #else
100
101 # ifdef Q_OS_WIN
102     QSettings::Format format = QSettings::IniFormat;
103 # else
104     QSettings::Format format = QSettings::NativeFormat;
105 # endif
106     QString newFilePath = Quassel::configDirPath() + "quasselcore"
107                           + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
108     QSettings newSettings(newFilePath, format);
109 #endif /* Q_OS_MAC */
110
111     if (newSettings.value("Config/Version").toUInt() == 0) {
112 #   ifdef Q_OS_MAC
113         QString org = "quassel-irc.org";
114 #   else
115         QString org = "Quassel Project";
116 #   endif
117         QSettings oldSettings(org, "Quassel Core");
118         if (oldSettings.allKeys().count()) {
119             qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
120             foreach(QString key, oldSettings.allKeys())
121             newSettings.setValue(key, oldSettings.value(key));
122             newSettings.setValue("Config/Version", 1);
123             qWarning() << "*   Your core settings have been migrated to" << newSettings.fileName();
124
125 #ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
126 #ifdef Q_OS_WIN
127             QString quasselDir = qgetenv("APPDATA") + "/quassel/";
128 #elif defined Q_OS_MAC
129             QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
130 #else
131             QString quasselDir = QDir::homePath() + "/.quassel/";
132 #endif
133
134             QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
135             if (!info.exists()) {
136                 // move database, if we found it
137                 QFile oldDb(quasselDir + "quassel-storage.sqlite");
138                 if (oldDb.exists()) {
139                     bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
140                     if (success)
141                         qWarning() << "*   Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
142                     else
143                         qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
144                 }
145             }
146             // move certificate
147             QFileInfo certInfo(quasselDir + "quasselCert.pem");
148             if (certInfo.exists()) {
149                 QFile cert(quasselDir + "quasselCert.pem");
150                 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
151                 if (success)
152                     qWarning() << "*   Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
153                 else
154                     qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
155             }
156 #endif /* !Q_OS_MAC */
157             qWarning() << "*** Migration completed.\n\n";
158         }
159     }
160     // MIGRATION end
161
162     // check settings version
163     // so far, we only have 1
164     CoreSettings s;
165     if (s.version() != 1) {
166         qCritical() << "Invalid core settings version, terminating!";
167         exit(EXIT_FAILURE);
168     }
169
170     registerStorageBackends();
171
172     connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
173     _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
174 }
175
176
177 void Core::init()
178 {
179     CoreSettings cs;
180     // legacy
181     QVariantMap dbsettings = cs.storageSettings().toMap();
182     _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());
183
184     if (Quassel::isOptionSet("select-backend")) {
185         selectBackend(Quassel::optionValue("select-backend"));
186         exit(0);
187     }
188
189     if (!_configured) {
190         if (!_storageBackends.count()) {
191             qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
192             qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
193                                         "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
194                                         "to work."));
195             exit(1); // TODO make this less brutal (especially for mono client -> popup)
196         }
197         qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
198     }
199
200     if (Quassel::isOptionSet("add-user")) {
201         exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
202
203     }
204
205     if (Quassel::isOptionSet("change-userpass")) {
206         exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
207                        EXIT_SUCCESS : EXIT_FAILURE);
208     }
209
210     connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
211     connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
212     if (!startListening()) exit(1);  // TODO make this less brutal
213
214     if (Quassel::isOptionSet("oidentd"))
215         _oidentdConfigGenerator = new OidentdConfigGenerator(this);
216 }
217
218
219 Core::~Core()
220 {
221     // FIXME do we need more cleanup for handlers?
222     foreach(CoreAuthHandler *handler, _connectingClients) {
223         handler->deleteLater(); // disconnect non authed clients
224     }
225     qDeleteAll(_sessions);
226     qDeleteAll(_storageBackends);
227 }
228
229
230 /*** Session Restore ***/
231
232 void Core::saveState()
233 {
234     CoreSettings s;
235     QVariantMap state;
236     QVariantList activeSessions;
237     foreach(UserId user, instance()->_sessions.keys())
238         activeSessions << QVariant::fromValue<UserId>(user);
239     state["CoreStateVersion"] = 1;
240     state["ActiveSessions"] = activeSessions;
241     s.setCoreState(state);
242 }
243
244
245 void Core::restoreState()
246 {
247     if (!instance()->_configured) {
248         // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
249         return;
250     }
251     if (instance()->_sessions.count()) {
252         qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
253         return;
254     }
255     CoreSettings s;
256     /* We don't check, since we are at the first version since switching to Git
257     uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
258     if(statever < 1) {
259       qWarning() << qPrintable(tr("Core state too old, ignoring..."));
260       return;
261     }
262     */
263
264     QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
265     if (activeSessions.count() > 0) {
266         quInfo() << "Restoring previous core state...";
267         foreach(QVariant v, activeSessions) {
268             UserId user = v.value<UserId>();
269             instance()->sessionForUser(user, true);
270         }
271     }
272 }
273
274
275 /*** Core Setup ***/
276
277 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
278 {
279     return instance()->setupCore(adminUser, adminPassword, backend, setupData);
280 }
281
282
283 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
284 {
285     if (_configured)
286         return tr("Core is already configured! Not configuring again...");
287
288     if (adminUser.isEmpty() || adminPassword.isEmpty()) {
289         return tr("Admin user or password not set.");
290     }
291     if (!(_configured = initStorage(backend, setupData, true))) {
292         return tr("Could not setup storage!");
293     }
294
295     saveBackendSettings(backend, setupData);
296
297     quInfo() << qPrintable(tr("Creating admin user..."));
298     _storage->addUser(adminUser, adminPassword);
299     startListening(); // TODO check when we need this
300     return QString();
301 }
302
303
304 QString Core::setupCoreForInternalUsage()
305 {
306     Q_ASSERT(!_storageBackends.isEmpty());
307
308     qsrand(QDateTime::currentDateTime().toTime_t());
309     int pass = 0;
310     for (int i = 0; i < 10; i++) {
311         pass *= 10;
312         pass += qrand() % 10;
313     }
314
315     // mono client currently needs sqlite
316     return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap());
317 }
318
319
320 /*** Storage Handling ***/
321 void Core::registerStorageBackends()
322 {
323     // Register storage backends here!
324     registerStorageBackend(new SqliteStorage(this));
325     registerStorageBackend(new PostgreSqlStorage(this));
326 }
327
328
329 bool Core::registerStorageBackend(Storage *backend)
330 {
331     if (backend->isAvailable()) {
332         _storageBackends[backend->displayName()] = backend;
333         return true;
334     }
335     else {
336         backend->deleteLater();
337         return false;
338     }
339 }
340
341
342 void Core::unregisterStorageBackends()
343 {
344     foreach(Storage *s, _storageBackends.values()) {
345         s->deleteLater();
346     }
347     _storageBackends.clear();
348 }
349
350
351 void Core::unregisterStorageBackend(Storage *backend)
352 {
353     _storageBackends.remove(backend->displayName());
354     backend->deleteLater();
355 }
356
357
358 // old db settings:
359 // "Type" => "sqlite"
360 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
361 {
362     _storage = 0;
363
364     if (backend.isEmpty()) {
365         return false;
366     }
367
368     Storage *storage = 0;
369     if (_storageBackends.contains(backend)) {
370         storage = _storageBackends[backend];
371     }
372     else {
373         qCritical() << "Selected storage backend is not available:" << backend;
374         return false;
375     }
376
377     Storage::State storageState = storage->init(settings);
378     switch (storageState) {
379     case Storage::NeedsSetup:
380         if (!setup)
381             return false;  // trigger setup process
382         if (storage->setup(settings))
383             return initStorage(backend, settings, false);
384     // if initialization wasn't successful, we quit to keep from coming up unconfigured
385     case Storage::NotAvailable:
386         qCritical() << "FATAL: Selected storage backend is not available:" << backend;
387         exit(EXIT_FAILURE);
388     case Storage::IsReady:
389         // delete all other backends
390         _storageBackends.remove(backend);
391         unregisterStorageBackends();
392         connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
393     }
394     _storage = storage;
395     return true;
396 }
397
398
399 void Core::syncStorage()
400 {
401     if (_storage)
402         _storage->sync();
403 }
404
405
406 /*** Storage Access ***/
407 bool Core::createNetwork(UserId user, NetworkInfo &info)
408 {
409     NetworkId networkId = instance()->_storage->createNetwork(user, info);
410     if (!networkId.isValid())
411         return false;
412
413     info.networkId = networkId;
414     return true;
415 }
416
417
418 /*** Network Management ***/
419
420 bool Core::sslSupported()
421 {
422 #ifdef HAVE_SSL
423     SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
424     return sslServer && sslServer->isCertValid();
425 #else
426     return false;
427 #endif
428 }
429
430
431 bool Core::reloadCerts()
432 {
433 #ifdef HAVE_SSL
434     SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
435     bool retv4 = sslServerv4->reloadCerts();
436
437     SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
438     bool retv6 = sslServerv6->reloadCerts();
439
440     return retv4 && retv6;
441 #else
442     // SSL not supported, don't mark configuration reload as failed
443     return true;
444 #endif
445 }
446
447
448 bool Core::startListening()
449 {
450     // in mono mode we only start a local port if a port is specified in the cli call
451     if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
452         return true;
453
454     bool success = false;
455     uint port = Quassel::optionValue("port").toUInt();
456
457     const QString listen = Quassel::optionValue("listen");
458     const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
459     if (listen_list.size() > 0) {
460         foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
461             QHostAddress addr;
462             if (!addr.setAddress(listen_term)) {
463                 qCritical() << qPrintable(
464                     tr("Invalid listen address %1")
465                     .arg(listen_term)
466                     );
467             }
468             else {
469                 switch (addr.protocol()) {
470                 case QAbstractSocket::IPv6Protocol:
471                     if (_v6server.listen(addr, port)) {
472                         quInfo() << qPrintable(
473                             tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
474                             .arg(addr.toString())
475                             .arg(_v6server.serverPort())
476                             .arg(Quassel::buildInfo().protocolVersion)
477                             );
478                         success = true;
479                     }
480                     else
481                         quWarning() << qPrintable(
482                             tr("Could not open IPv6 interface %1:%2: %3")
483                             .arg(addr.toString())
484                             .arg(port)
485                             .arg(_v6server.errorString()));
486                     break;
487                 case QAbstractSocket::IPv4Protocol:
488                     if (_server.listen(addr, port)) {
489                         quInfo() << qPrintable(
490                             tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
491                             .arg(addr.toString())
492                             .arg(_server.serverPort())
493                             .arg(Quassel::buildInfo().protocolVersion)
494                             );
495                         success = true;
496                     }
497                     else {
498                         // if v6 succeeded on Any, the port will be already in use - don't display the error then
499                         if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
500                             quWarning() << qPrintable(
501                                 tr("Could not open IPv4 interface %1:%2: %3")
502                                 .arg(addr.toString())
503                                 .arg(port)
504                                 .arg(_server.errorString()));
505                     }
506                     break;
507                 default:
508                     qCritical() << qPrintable(
509                         tr("Invalid listen address %1, unknown network protocol")
510                         .arg(listen_term)
511                         );
512                     break;
513                 }
514             }
515         }
516     }
517     if (!success)
518         quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
519
520     return success;
521 }
522
523
524 void Core::stopListening(const QString &reason)
525 {
526     bool wasListening = false;
527     if (_server.isListening()) {
528         wasListening = true;
529         _server.close();
530     }
531     if (_v6server.isListening()) {
532         wasListening = true;
533         _v6server.close();
534     }
535     if (wasListening) {
536         if (reason.isEmpty())
537             quInfo() << "No longer listening for GUI clients.";
538         else
539             quInfo() << qPrintable(reason);
540     }
541 }
542
543
544 void Core::incomingConnection()
545 {
546     QTcpServer *server = qobject_cast<QTcpServer *>(sender());
547     Q_ASSERT(server);
548     while (server->hasPendingConnections()) {
549         QTcpSocket *socket = server->nextPendingConnection();
550
551         CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
552         _connectingClients.insert(handler);
553
554         connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
555         connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
556         connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
557
558         quInfo() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
559
560         if (!_configured) {
561             stopListening(tr("Closing server for basic setup."));
562         }
563     }
564 }
565
566
567 // Potentially called during the initialization phase (before handing the connection off to the session)
568 void Core::clientDisconnected()
569 {
570     CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
571     Q_ASSERT(handler);
572
573     quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
574     _connectingClients.remove(handler);
575     handler->deleteLater();
576
577     // make server listen again if still not configured
578     if (!_configured) {
579         startListening();
580     }
581
582     // TODO remove unneeded sessions - if necessary/possible...
583     // Suggestion: kill sessions if they are not connected to any network and client.
584 }
585
586
587 void Core::setupClientSession(RemotePeer *peer, UserId uid)
588 {
589     CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
590     Q_ASSERT(handler);
591
592     // From now on everything is handled by the client session
593     disconnect(handler, 0, this, 0);
594     _connectingClients.remove(handler);
595     handler->deleteLater();
596
597     // Find or create session for validated user
598     sessionForUser(uid);
599
600     // as we are currently handling an event triggered by incoming data on this socket
601     // it is unsafe to directly move the socket to the client thread.
602     QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
603 }
604
605
606 void Core::customEvent(QEvent *event)
607 {
608     if (event->type() == AddClientEventId) {
609         AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
610         addClientHelper(addClientEvent->peer, addClientEvent->userId);
611         return;
612     }
613 }
614
615
616 void Core::addClientHelper(RemotePeer *peer, UserId uid)
617 {
618     // Find or create session for validated user
619     SessionThread *session = sessionForUser(uid);
620     session->addClient(peer);
621 }
622
623
624 void Core::setupInternalClientSession(InternalPeer *clientPeer)
625 {
626     if (!_configured) {
627         stopListening();
628         setupCoreForInternalUsage();
629     }
630
631     UserId uid;
632     if (_storage) {
633         uid = _storage->internalUser();
634     }
635     else {
636         qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
637         return;
638     }
639
640     InternalPeer *corePeer = new InternalPeer(this);
641     corePeer->setPeer(clientPeer);
642     clientPeer->setPeer(corePeer);
643
644     // Find or create session for validated user
645     SessionThread *sessionThread = sessionForUser(uid);
646     sessionThread->addClient(corePeer);
647 }
648
649
650 SessionThread *Core::sessionForUser(UserId uid, bool restore)
651 {
652     if (_sessions.contains(uid))
653         return _sessions[uid];
654
655     SessionThread *session = new SessionThread(uid, restore, this);
656     _sessions[uid] = session;
657     session->start();
658     return session;
659 }
660
661
662 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
663 {
664     qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
665 }
666
667
668 QVariantList Core::backendInfo()
669 {
670     QVariantList backends;
671     foreach(const Storage *backend, instance()->_storageBackends.values()) {
672         QVariantMap v;
673         v["DisplayName"] = backend->displayName();
674         v["Description"] = backend->description();
675         v["SetupKeys"] = backend->setupKeys();
676         v["SetupDefaults"] = backend->setupDefaults();
677         v["IsDefault"] = isStorageBackendDefault(backend);
678         backends.append(v);
679     }
680     return backends;
681 }
682
683
684 // migration / backend selection
685 bool Core::selectBackend(const QString &backend)
686 {
687     // reregister all storage backends
688     registerStorageBackends();
689     if (!_storageBackends.contains(backend)) {
690         qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
691         qWarning() << "    supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
692         return false;
693     }
694
695     Storage *storage = _storageBackends[backend];
696     QVariantMap settings = promptForSettings(storage);
697
698     Storage::State storageState = storage->init(settings);
699     switch (storageState) {
700     case Storage::IsReady:
701         saveBackendSettings(backend, settings);
702         qWarning() << "Switched backend to:" << qPrintable(backend);
703         qWarning() << "Backend already initialized. Skipping Migration";
704         return true;
705     case Storage::NotAvailable:
706         qCritical() << "Backend is not available:" << qPrintable(backend);
707         return false;
708     case Storage::NeedsSetup:
709         if (!storage->setup(settings)) {
710             qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
711             return false;
712         }
713
714         if (storage->init(settings) != Storage::IsReady) {
715             qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
716             return false;
717         }
718
719         saveBackendSettings(backend, settings);
720         qWarning() << "Switched backend to:" << qPrintable(backend);
721         break;
722     }
723
724     // let's see if we have a current storage object we can migrate from
725     AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
726     AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
727     if (reader && writer) {
728         qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
729         delete _storage;
730         _storage = 0;
731         delete storage;
732         storage = 0;
733         if (reader->migrateTo(writer)) {
734             qDebug() << "Migration finished!";
735             saveBackendSettings(backend, settings);
736             return true;
737         }
738         return false;
739         qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
740     }
741
742     // inform the user why we cannot merge
743     if (!_storage) {
744         qWarning() << "No currently active backend. Skipping migration.";
745     }
746     else if (!reader) {
747         qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
748     }
749     if (writer) {
750         qWarning() << "New backend does not support migration:" << qPrintable(backend);
751     }
752
753     // so we were unable to merge, but let's create a user \o/
754     _storage = storage;
755     createUser();
756     return true;
757 }
758
759
760 bool Core::createUser()
761 {
762     QTextStream out(stdout);
763     QTextStream in(stdin);
764     out << "Add a new user:" << endl;
765     out << "Username: ";
766     out.flush();
767     QString username = in.readLine().trimmed();
768
769     disableStdInEcho();
770     out << "Password: ";
771     out.flush();
772     QString password = in.readLine().trimmed();
773     out << endl;
774     out << "Repeat Password: ";
775     out.flush();
776     QString password2 = in.readLine().trimmed();
777     out << endl;
778     enableStdInEcho();
779
780     if (password != password2) {
781         qWarning() << "Passwords don't match!";
782         return false;
783     }
784     if (password.isEmpty()) {
785         qWarning() << "Password is empty!";
786         return false;
787     }
788
789     if (_configured && _storage->addUser(username, password).isValid()) {
790         out << "Added user " << username << " successfully!" << endl;
791         return true;
792     }
793     else {
794         qWarning() << "Unable to add user:" << qPrintable(username);
795         return false;
796     }
797 }
798
799
800 bool Core::changeUserPass(const QString &username)
801 {
802     QTextStream out(stdout);
803     QTextStream in(stdin);
804     UserId userId = _storage->getUserId(username);
805     if (!userId.isValid()) {
806         out << "User " << username << " does not exist." << endl;
807         return false;
808     }
809
810     out << "Change password for user: " << username << endl;
811
812     disableStdInEcho();
813     out << "New Password: ";
814     out.flush();
815     QString password = in.readLine().trimmed();
816     out << endl;
817     out << "Repeat Password: ";
818     out.flush();
819     QString password2 = in.readLine().trimmed();
820     out << endl;
821     enableStdInEcho();
822
823     if (password != password2) {
824         qWarning() << "Passwords don't match!";
825         return false;
826     }
827     if (password.isEmpty()) {
828         qWarning() << "Password is empty!";
829         return false;
830     }
831
832     if (_configured && _storage->updateUser(userId, password)) {
833         out << "Password changed successfully!" << endl;
834         return true;
835     }
836     else {
837         qWarning() << "Failed to change password!";
838         return false;
839     }
840 }
841
842
843 bool Core::changeUserPassword(UserId userId, const QString &password)
844 {
845     if (!isConfigured() || !userId.isValid())
846         return false;
847
848     return instance()->_storage->updateUser(userId, password);
849 }
850
851
852 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
853 {
854     if (!storage)
855         return 0;
856
857     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
858     if (!sqlStorage) {
859         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
860         return 0;
861     }
862
863     return sqlStorage->createMigrationReader();
864 }
865
866
867 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
868 {
869     if (!storage)
870         return 0;
871
872     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
873     if (!sqlStorage) {
874         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
875         return 0;
876     }
877
878     return sqlStorage->createMigrationWriter();
879 }
880
881
882 void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
883 {
884     QVariantMap dbsettings;
885     dbsettings["Backend"] = backend;
886     dbsettings["ConnectionProperties"] = settings;
887     CoreSettings().setStorageSettings(dbsettings);
888 }
889
890
891 QVariantMap Core::promptForSettings(const Storage *storage)
892 {
893     QVariantMap settings;
894
895     QStringList keys = storage->setupKeys();
896     if (keys.isEmpty())
897         return settings;
898
899     QTextStream out(stdout);
900     QTextStream in(stdin);
901     out << "Default values are in brackets" << endl;
902
903     QVariantMap defaults = storage->setupDefaults();
904     QString value;
905     foreach(QString key, keys) {
906         QVariant val;
907         if (defaults.contains(key)) {
908             val = defaults[key];
909         }
910         out << key;
911         if (!val.toString().isEmpty()) {
912             out << " (" << val.toString() << ")";
913         }
914         out << ": ";
915         out.flush();
916
917         bool noEcho = QString("password").toLower().startsWith(key.toLower());
918         if (noEcho) {
919             disableStdInEcho();
920         }
921         value = in.readLine().trimmed();
922         if (noEcho) {
923             out << endl;
924             enableStdInEcho();
925         }
926
927         if (!value.isEmpty()) {
928             switch (defaults[key].type()) {
929             case QVariant::Int:
930                 val = QVariant(value.toInt());
931                 break;
932             default:
933                 val = QVariant(value);
934             }
935         }
936         settings[key] = val;
937     }
938     return settings;
939 }
940
941
942 #ifdef Q_OS_WIN
943 void Core::stdInEcho(bool on)
944 {
945     HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
946     DWORD mode = 0;
947     GetConsoleMode(hStdin, &mode);
948     if (on)
949         mode |= ENABLE_ECHO_INPUT;
950     else
951         mode &= ~ENABLE_ECHO_INPUT;
952     SetConsoleMode(hStdin, mode);
953 }
954
955
956 #else
957 void Core::stdInEcho(bool on)
958 {
959     termios t;
960     tcgetattr(STDIN_FILENO, &t);
961     if (on)
962         t.c_lflag |= ECHO;
963     else
964         t.c_lflag &= ~ECHO;
965     tcsetattr(STDIN_FILENO, TCSANOW, &t);
966 }
967
968
969 #endif /* Q_OS_WIN */