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