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