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