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