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