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