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