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