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