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