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