core: Fix SQLite realname/avatarurl handling
[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
557 void Core::cacheSysIdent()
558 {
559     if (isConfigured()) {
560         instance()->_authUserNames = instance()->_storage->getAllAuthUserNames();
561     }
562 }
563
564
565 QString Core::strictSysIdent(UserId user) const
566 {
567     if (_authUserNames.contains(user)) {
568         return _authUserNames[user];
569     }
570
571     // A new user got added since we last pulled our cache from the database.
572     // There's no way to avoid a database hit - we don't even know the authname!
573     cacheSysIdent();
574
575     if (_authUserNames.contains(user)) {
576         return _authUserNames[user];
577     }
578
579     // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
580     qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
581     return "unknown"; // Should we just terminate the program instead?
582 }
583
584
585 bool Core::startListening()
586 {
587     // in mono mode we only start a local port if a port is specified in the cli call
588     if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
589         return true;
590
591     bool success = false;
592     uint port = Quassel::optionValue("port").toUInt();
593
594     const QString listen = Quassel::optionValue("listen");
595     const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
596     if (listen_list.size() > 0) {
597         foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
598             QHostAddress addr;
599             if (!addr.setAddress(listen_term)) {
600                 qCritical() << qPrintable(
601                     tr("Invalid listen address %1")
602                     .arg(listen_term)
603                     );
604             }
605             else {
606                 switch (addr.protocol()) {
607                 case QAbstractSocket::IPv6Protocol:
608                     if (_v6server.listen(addr, port)) {
609                         quInfo() << qPrintable(
610                             tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
611                             .arg(addr.toString())
612                             .arg(_v6server.serverPort())
613                             .arg(Quassel::buildInfo().protocolVersion)
614                             );
615                         success = true;
616                     }
617                     else
618                         quWarning() << qPrintable(
619                             tr("Could not open IPv6 interface %1:%2: %3")
620                             .arg(addr.toString())
621                             .arg(port)
622                             .arg(_v6server.errorString()));
623                     break;
624                 case QAbstractSocket::IPv4Protocol:
625                     if (_server.listen(addr, port)) {
626                         quInfo() << qPrintable(
627                             tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
628                             .arg(addr.toString())
629                             .arg(_server.serverPort())
630                             .arg(Quassel::buildInfo().protocolVersion)
631                             );
632                         success = true;
633                     }
634                     else {
635                         // if v6 succeeded on Any, the port will be already in use - don't display the error then
636                         if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
637                             quWarning() << qPrintable(
638                                 tr("Could not open IPv4 interface %1:%2: %3")
639                                 .arg(addr.toString())
640                                 .arg(port)
641                                 .arg(_server.errorString()));
642                     }
643                     break;
644                 default:
645                     qCritical() << qPrintable(
646                         tr("Invalid listen address %1, unknown network protocol")
647                         .arg(listen_term)
648                         );
649                     break;
650                 }
651             }
652         }
653     }
654     if (!success)
655         quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
656
657     return success;
658 }
659
660
661 void Core::stopListening(const QString &reason)
662 {
663     bool wasListening = false;
664     if (_server.isListening()) {
665         wasListening = true;
666         _server.close();
667     }
668     if (_v6server.isListening()) {
669         wasListening = true;
670         _v6server.close();
671     }
672     if (wasListening) {
673         if (reason.isEmpty())
674             quInfo() << "No longer listening for GUI clients.";
675         else
676             quInfo() << qPrintable(reason);
677     }
678 }
679
680
681 void Core::incomingConnection()
682 {
683     QTcpServer *server = qobject_cast<QTcpServer *>(sender());
684     Q_ASSERT(server);
685     while (server->hasPendingConnections()) {
686         QTcpSocket *socket = server->nextPendingConnection();
687
688         CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
689         _connectingClients.insert(handler);
690
691         connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
692         connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
693         connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
694
695         quInfo() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
696
697         if (!_configured) {
698             stopListening(tr("Closing server for basic setup."));
699         }
700     }
701 }
702
703
704 // Potentially called during the initialization phase (before handing the connection off to the session)
705 void Core::clientDisconnected()
706 {
707     CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
708     Q_ASSERT(handler);
709
710     quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
711     _connectingClients.remove(handler);
712     handler->deleteLater();
713
714     // make server listen again if still not configured
715     if (!_configured) {
716         startListening();
717     }
718
719     // TODO remove unneeded sessions - if necessary/possible...
720     // Suggestion: kill sessions if they are not connected to any network and client.
721 }
722
723
724 void Core::setupClientSession(RemotePeer *peer, UserId uid)
725 {
726     CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
727     Q_ASSERT(handler);
728
729     // From now on everything is handled by the client session
730     disconnect(handler, 0, this, 0);
731     _connectingClients.remove(handler);
732     handler->deleteLater();
733
734     // Find or create session for validated user
735     sessionForUser(uid);
736
737     // as we are currently handling an event triggered by incoming data on this socket
738     // it is unsafe to directly move the socket to the client thread.
739     QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
740 }
741
742
743 void Core::customEvent(QEvent *event)
744 {
745     if (event->type() == AddClientEventId) {
746         AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
747         addClientHelper(addClientEvent->peer, addClientEvent->userId);
748         return;
749     }
750 }
751
752
753 void Core::addClientHelper(RemotePeer *peer, UserId uid)
754 {
755     // Find or create session for validated user
756     SessionThread *session = sessionForUser(uid);
757     session->addClient(peer);
758 }
759
760
761 void Core::setupInternalClientSession(InternalPeer *clientPeer)
762 {
763     if (!_configured) {
764         stopListening();
765         setupCoreForInternalUsage();
766     }
767
768     UserId uid;
769     if (_storage) {
770         uid = _storage->internalUser();
771     }
772     else {
773         quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
774         return;
775     }
776
777     InternalPeer *corePeer = new InternalPeer(this);
778     corePeer->setPeer(clientPeer);
779     clientPeer->setPeer(corePeer);
780
781     // Find or create session for validated user
782     SessionThread *sessionThread = sessionForUser(uid);
783     sessionThread->addClient(corePeer);
784 }
785
786
787 SessionThread *Core::sessionForUser(UserId uid, bool restore)
788 {
789     if (_sessions.contains(uid))
790         return _sessions[uid];
791
792     SessionThread *session = new SessionThread(uid, restore, this);
793     _sessions[uid] = session;
794     session->start();
795     return session;
796 }
797
798
799 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
800 {
801     quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
802 }
803
804
805 QVariantList Core::backendInfo()
806 {
807     instance()->registerStorageBackends();
808
809     QVariantList backendInfos;
810     for (auto &&backend : instance()->_registeredStorageBackends) {
811         QVariantMap v;
812         v["BackendId"]   = backend->backendId();
813         v["DisplayName"] = backend->displayName();
814         v["Description"] = backend->description();
815         v["SetupData"]   = backend->setupData(); // ignored by legacy clients
816
817         // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
818         const auto &setupData = backend->setupData();
819         QStringList setupKeys;
820         QVariantMap setupDefaults;
821         for (int i = 0; i + 2 < setupData.size(); i += 3) {
822             setupKeys << setupData[i].toString();
823             setupDefaults[setupData[i].toString()] = setupData[i + 2];
824         }
825         v["SetupKeys"]     = setupKeys;
826         v["SetupDefaults"] = setupDefaults;
827         // TODO Protocol Break: Remove
828         v["IsDefault"]     = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
829
830         backendInfos << v;
831     }
832     return backendInfos;
833 }
834
835
836 QVariantList Core::authenticatorInfo()
837 {
838     instance()->registerAuthenticators();
839
840     QVariantList authInfos;
841     for(auto &&backend : instance()->_registeredAuthenticators) {
842         QVariantMap v;
843         v["BackendId"]   = backend->backendId();
844         v["DisplayName"] = backend->displayName();
845         v["Description"] = backend->description();
846         v["SetupData"]   = backend->setupData();
847         authInfos << v;
848     }
849     return authInfos;
850 }
851
852 // migration / backend selection
853 bool Core::selectBackend(const QString &backend)
854 {
855     // reregister all storage backends
856     registerStorageBackends();
857     auto storage = storageBackend(backend);
858     if (!storage) {
859         QStringList backends;
860         std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
861                        std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
862                            return backend->displayName();
863                        });
864         quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
865         quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
866         return false;
867     }
868
869     QVariantMap settings = promptForSettings(storage.get());
870
871     Storage::State storageState = storage->init(settings);
872     switch (storageState) {
873     case Storage::IsReady:
874         if (!saveBackendSettings(backend, settings)) {
875             qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
876         }
877         quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
878         quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
879         return true;
880     case Storage::NotAvailable:
881         qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
882         return false;
883     case Storage::NeedsSetup:
884         if (!storage->setup(settings)) {
885             quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
886             return false;
887         }
888
889         if (storage->init(settings) != Storage::IsReady) {
890             quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
891             return false;
892         }
893
894         if (!saveBackendSettings(backend, settings)) {
895             qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
896         }
897         quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
898         break;
899     }
900
901     // let's see if we have a current storage object we can migrate from
902     auto reader = getMigrationReader(_storage.get());
903     auto writer = getMigrationWriter(storage.get());
904     if (reader && writer) {
905         qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
906         _storage.reset();
907         storage.reset();
908         if (reader->migrateTo(writer.get())) {
909             qDebug() << "Migration finished!";
910             qDebug() << qPrintable(tr("Migration finished!"));
911             if (!saveBackendSettings(backend, settings)) {
912                 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
913                 return false;
914             }
915             return true;
916         }
917         quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
918         return false;
919     }
920
921     // inform the user why we cannot merge
922     if (!_storage) {
923         quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
924     }
925     else if (!reader) {
926         quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
927     }
928     if (writer) {
929         quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
930     }
931
932     // so we were unable to merge, but let's create a user \o/
933     _storage = std::move(storage);
934     createUser();
935     return true;
936 }
937
938 // TODO: I am not sure if this function is implemented correctly.
939 // There is currently no concept of migraiton between auth backends.
940 bool Core::selectAuthenticator(const QString &backend)
941 {
942     // Register all authentication backends.
943     registerAuthenticators();
944     auto auther = authenticator(backend);
945     if (!auther) {
946         QStringList authenticators;
947         std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
948                        std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
949                            return authenticator->displayName();
950                        });
951         quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
952         quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
953         return false;
954     }
955
956     QVariantMap settings = promptForSettings(auther.get());
957
958     Authenticator::State state = auther->init(settings);
959     switch (state) {
960     case Authenticator::IsReady:
961         saveAuthenticatorSettings(backend, settings);
962         quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
963         return true;
964     case Authenticator::NotAvailable:
965         qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
966         return false;
967     case Authenticator::NeedsSetup:
968         if (!auther->setup(settings)) {
969             quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
970             return false;
971         }
972
973         if (auther->init(settings) != Authenticator::IsReady) {
974             quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
975             return false;
976         }
977
978         saveAuthenticatorSettings(backend, settings);
979         quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
980     }
981
982     _authenticator = std::move(auther);
983     return true;
984 }
985
986
987 bool Core::createUser()
988 {
989     QTextStream out(stdout);
990     QTextStream in(stdin);
991     out << "Add a new user:" << endl;
992     out << "Username: ";
993     out.flush();
994     QString username = in.readLine().trimmed();
995
996     disableStdInEcho();
997     out << "Password: ";
998     out.flush();
999     QString password = in.readLine().trimmed();
1000     out << endl;
1001     out << "Repeat Password: ";
1002     out.flush();
1003     QString password2 = in.readLine().trimmed();
1004     out << endl;
1005     enableStdInEcho();
1006
1007     if (password != password2) {
1008         quWarning() << "Passwords don't match!";
1009         return false;
1010     }
1011     if (password.isEmpty()) {
1012         quWarning() << "Password is empty!";
1013         return false;
1014     }
1015
1016     if (_configured && _storage->addUser(username, password).isValid()) {
1017         out << "Added user " << username << " successfully!" << endl;
1018         return true;
1019     }
1020     else {
1021         quWarning() << "Unable to add user:" << qPrintable(username);
1022         return false;
1023     }
1024 }
1025
1026
1027 bool Core::changeUserPass(const QString &username)
1028 {
1029     QTextStream out(stdout);
1030     QTextStream in(stdin);
1031     UserId userId = _storage->getUserId(username);
1032     if (!userId.isValid()) {
1033         out << "User " << username << " does not exist." << endl;
1034         return false;
1035     }
1036
1037     if (!canChangeUserPassword(userId)) {
1038         out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1039         return false;
1040     }
1041
1042     out << "Change password for user: " << username << endl;
1043
1044     disableStdInEcho();
1045     out << "New Password: ";
1046     out.flush();
1047     QString password = in.readLine().trimmed();
1048     out << endl;
1049     out << "Repeat Password: ";
1050     out.flush();
1051     QString password2 = in.readLine().trimmed();
1052     out << endl;
1053     enableStdInEcho();
1054
1055     if (password != password2) {
1056         quWarning() << "Passwords don't match!";
1057         return false;
1058     }
1059     if (password.isEmpty()) {
1060         quWarning() << "Password is empty!";
1061         return false;
1062     }
1063
1064     if (_configured && _storage->updateUser(userId, password)) {
1065         out << "Password changed successfully!" << endl;
1066         return true;
1067     }
1068     else {
1069         quWarning() << "Failed to change password!";
1070         return false;
1071     }
1072 }
1073
1074
1075 bool Core::changeUserPassword(UserId userId, const QString &password)
1076 {
1077     if (!isConfigured() || !userId.isValid())
1078         return false;
1079
1080     if (!canChangeUserPassword(userId))
1081         return false;
1082
1083     return instance()->_storage->updateUser(userId, password);
1084 }
1085
1086 // TODO: this code isn't currently 100% optimal because the core
1087 // doesn't know it can have multiple auth providers configured (there aren't
1088 // multiple auth providers at the moment anyway) and we have hardcoded the
1089 // Database provider to be always allowed.
1090 bool Core::canChangeUserPassword(UserId userId)
1091 {
1092     QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1093     if (authProvider != "Database") {
1094         if (authProvider != instance()->_authenticator->backendId()) {
1095             return false;
1096         }
1097         else if (instance()->_authenticator->canChangePassword()) {
1098             return false;
1099         }
1100     }
1101     return true;
1102 }
1103
1104
1105 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1106 {
1107     if (!storage)
1108         return nullptr;
1109
1110     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1111     if (!sqlStorage) {
1112         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1113         return nullptr;
1114     }
1115
1116     return sqlStorage->createMigrationReader();
1117 }
1118
1119
1120 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1121 {
1122     if (!storage)
1123         return nullptr;
1124
1125     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1126     if (!sqlStorage) {
1127         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1128         return nullptr;
1129     }
1130
1131     return sqlStorage->createMigrationWriter();
1132 }
1133
1134
1135 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1136 {
1137     QVariantMap dbsettings;
1138     dbsettings["Backend"] = backend;
1139     dbsettings["ConnectionProperties"] = settings;
1140     CoreSettings s = CoreSettings();
1141     s.setStorageSettings(dbsettings);
1142     return s.sync();
1143 }
1144
1145
1146 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1147 {
1148     QVariantMap dbsettings;
1149     dbsettings["Authenticator"] = backend;
1150     dbsettings["AuthProperties"] = settings;
1151     CoreSettings().setAuthSettings(dbsettings);
1152 }
1153
1154 // Generic version of promptForSettings that doesn't care what *type* of
1155 // backend it runs over.
1156 template<typename Backend>
1157 QVariantMap Core::promptForSettings(const Backend *backend)
1158 {
1159     QVariantMap settings;
1160     const QVariantList& setupData = backend->setupData();
1161
1162     if (setupData.isEmpty())
1163         return settings;
1164
1165     QTextStream out(stdout);
1166     QTextStream in(stdin);
1167     out << "Default values are in brackets" << endl;
1168
1169     for (int i = 0; i + 2 < setupData.size(); i += 3) {
1170         QString key = setupData[i].toString();
1171         out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1172
1173         bool noEcho = key.toLower().contains("password");
1174         if (noEcho) {
1175             disableStdInEcho();
1176         }
1177         QString input = in.readLine().trimmed();
1178         if (noEcho) {
1179             out << endl;
1180             enableStdInEcho();
1181         }
1182
1183         QVariant value{setupData[i+2]};
1184         if (!input.isEmpty()) {
1185             switch (value.type()) {
1186             case QVariant::Int:
1187                 value = input.toInt();
1188                 break;
1189             default:
1190                 value = input;
1191             }
1192         }
1193         settings[key] = value;
1194     }
1195     return settings;
1196 }
1197
1198
1199 #ifdef Q_OS_WIN
1200 void Core::stdInEcho(bool on)
1201 {
1202     HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1203     DWORD mode = 0;
1204     GetConsoleMode(hStdin, &mode);
1205     if (on)
1206         mode |= ENABLE_ECHO_INPUT;
1207     else
1208         mode &= ~ENABLE_ECHO_INPUT;
1209     SetConsoleMode(hStdin, mode);
1210 }
1211
1212 #else
1213 void Core::stdInEcho(bool on)
1214 {
1215     termios t;
1216     tcgetattr(STDIN_FILENO, &t);
1217     if (on)
1218         t.c_lflag |= ECHO;
1219     else
1220         t.c_lflag &= ~ECHO;
1221     tcsetattr(STDIN_FILENO, TCSANOW, &t);
1222 }
1223
1224 #endif /* Q_OS_WIN */