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