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