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