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