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