ldap: Don't use the backend's display name as identifier
[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("AuthProperties").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(), "Database", 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["BackendId"] = backend->backendId();
803         v["DisplayName"] = backend->displayName();
804         v["Description"] = backend->description();
805         v["SetupKeys"] = backend->setupKeys();
806         v["SetupDefaults"] = backend->setupDefaults();
807         backends.append(v);
808     }
809     return backends;
810 }
811
812 // migration / backend selection
813 bool Core::selectBackend(const QString &backend)
814 {
815     // reregister all storage backends
816     registerStorageBackends();
817     if (!_storageBackends.contains(backend)) {
818         qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
819         qWarning() << "    supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
820         return false;
821     }
822
823     Storage *storage = _storageBackends[backend];
824     QVariantMap settings = promptForSettings(storage);
825
826     Storage::State storageState = storage->init(settings);
827     switch (storageState) {
828     case Storage::IsReady:
829         if (!saveBackendSettings(backend, settings)) {
830             qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
831         }
832         qWarning() << "Switched backend to:" << qPrintable(backend);
833         qWarning() << "Backend already initialized. Skipping Migration";
834         return true;
835     case Storage::NotAvailable:
836         qCritical() << "Backend is not available:" << qPrintable(backend);
837         return false;
838     case Storage::NeedsSetup:
839         if (!storage->setup(settings)) {
840             qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
841             return false;
842         }
843
844         if (storage->init(settings) != Storage::IsReady) {
845             qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
846             return false;
847         }
848
849         if (!saveBackendSettings(backend, settings)) {
850             qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
851         }
852         qWarning() << "Switched backend to:" << qPrintable(backend);
853         break;
854     }
855
856     // let's see if we have a current storage object we can migrate from
857     AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
858     AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
859     if (reader && writer) {
860         qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
861         delete _storage;
862         _storage = 0;
863         delete storage;
864         storage = 0;
865         if (reader->migrateTo(writer)) {
866             qDebug() << "Migration finished!";
867             if (!saveBackendSettings(backend, settings)) {
868                 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
869                 return false;
870             }
871             return true;
872         }
873         return false;
874         qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
875     }
876
877     // inform the user why we cannot merge
878     if (!_storage) {
879         qWarning() << "No currently active backend. Skipping migration.";
880     }
881     else if (!reader) {
882         qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
883     }
884     if (writer) {
885         qWarning() << "New backend does not support migration:" << qPrintable(backend);
886     }
887
888     // so we were unable to merge, but let's create a user \o/
889     _storage = storage;
890     createUser();
891     return true;
892 }
893
894 // TODO: I am not sure if this function is implemented correctly.
895 // There is currently no concept of migraiton between auth backends.
896 bool Core::selectAuthenticator(const QString &backend)
897 {
898     // Register all authentication backends.
899     registerAuthenticators();
900     if (!_authenticators.contains(backend)) {
901         qWarning() << qPrintable(QString("Core::selectAuthenticator(): unsupported backend: %1").arg(backend));
902         qWarning() << "    supported backends are:" << qPrintable(QStringList(_authenticators.keys()).join(", "));
903         return false;
904     }
905
906     Authenticator *authenticator = _authenticators[backend];
907     QVariantMap settings = promptForSettings(authenticator);
908
909     Authenticator::State state = authenticator->init(settings);
910     switch (state) {
911     case Authenticator::IsReady:
912         saveAuthenticatorSettings(backend, settings);
913         qWarning() << "Switched auth backend to:" << qPrintable(backend);
914 //        qWarning() << "Auth backend already initialized. Skipping Migration";
915         return true;
916     case Authenticator::NotAvailable:
917         qCritical() << "Auth backend is not available:" << qPrintable(backend);
918         return false;
919     case Authenticator::NeedsSetup:
920         if (!authenticator->setup(settings)) {
921             qWarning() << qPrintable(QString("Core::selectAuthenticator(): unable to setup authenticator: %1").arg(backend));
922             return false;
923         }
924
925         if (authenticator->init(settings) != Authenticator::IsReady) {
926             qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize authenticator: %1").arg(backend));
927             return false;
928         }
929
930         saveAuthenticatorSettings(backend, settings);
931         qWarning() << "Switched auth backend to:" << qPrintable(backend);
932     }
933
934     _authenticator = authenticator;
935     return true;
936 }
937
938
939 bool Core::createUser()
940 {
941     QTextStream out(stdout);
942     QTextStream in(stdin);
943     out << "Add a new user:" << endl;
944     out << "Username: ";
945     out.flush();
946     QString username = in.readLine().trimmed();
947
948     disableStdInEcho();
949     out << "Password: ";
950     out.flush();
951     QString password = in.readLine().trimmed();
952     out << endl;
953     out << "Repeat Password: ";
954     out.flush();
955     QString password2 = in.readLine().trimmed();
956     out << endl;
957     enableStdInEcho();
958
959     if (password != password2) {
960         qWarning() << "Passwords don't match!";
961         return false;
962     }
963     if (password.isEmpty()) {
964         qWarning() << "Password is empty!";
965         return false;
966     }
967
968     if (_configured && _storage->addUser(username, password).isValid()) {
969         out << "Added user " << username << " successfully!" << endl;
970         return true;
971     }
972     else {
973         qWarning() << "Unable to add user:" << qPrintable(username);
974         return false;
975     }
976 }
977
978
979 bool Core::changeUserPass(const QString &username)
980 {
981     QTextStream out(stdout);
982     QTextStream in(stdin);
983     UserId userId = _storage->getUserId(username);
984     if (!userId.isValid()) {
985         out << "User " << username << " does not exist." << endl;
986         return false;
987     }
988
989     if (!canChangeUserPassword(userId)) {
990         out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
991         return false;
992     }
993
994     out << "Change password for user: " << username << endl;
995
996     disableStdInEcho();
997     out << "New Password: ";
998     out.flush();
999     QString password = in.readLine().trimmed();
1000     out << endl;
1001     out << "Repeat Password: ";
1002     out.flush();
1003     QString password2 = in.readLine().trimmed();
1004     out << endl;
1005     enableStdInEcho();
1006
1007     if (password != password2) {
1008         qWarning() << "Passwords don't match!";
1009         return false;
1010     }
1011     if (password.isEmpty()) {
1012         qWarning() << "Password is empty!";
1013         return false;
1014     }
1015
1016     if (_configured && _storage->updateUser(userId, password)) {
1017         out << "Password changed successfully!" << endl;
1018         return true;
1019     }
1020     else {
1021         qWarning() << "Failed to change password!";
1022         return false;
1023     }
1024 }
1025
1026
1027 bool Core::changeUserPassword(UserId userId, const QString &password)
1028 {
1029     if (!isConfigured() || !userId.isValid())
1030         return false;
1031
1032     if (!canChangeUserPassword(userId))
1033         return false;
1034
1035     return instance()->_storage->updateUser(userId, password);
1036 }
1037
1038 // TODO: this code isn't currently 100% optimal because the core
1039 // doesn't know it can have multiple auth providers configured (there aren't
1040 // multiple auth providers at the moment anyway) and we have hardcoded the
1041 // Database provider to be always allowed.
1042 bool Core::canChangeUserPassword(UserId userId)
1043 {
1044     QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1045     if (authProvider != "Database") {
1046         if (authProvider != instance()->_authenticator->backendId()) {
1047             return false;
1048         }
1049         else if (instance()->_authenticator->canChangePassword()) {
1050             return false;
1051         }
1052     }
1053     return true;
1054 }
1055
1056
1057 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
1058 {
1059     if (!storage)
1060         return 0;
1061
1062     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1063     if (!sqlStorage) {
1064         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1065         return 0;
1066     }
1067
1068     return sqlStorage->createMigrationReader();
1069 }
1070
1071
1072 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
1073 {
1074     if (!storage)
1075         return 0;
1076
1077     AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1078     if (!sqlStorage) {
1079         qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1080         return 0;
1081     }
1082
1083     return sqlStorage->createMigrationWriter();
1084 }
1085
1086
1087 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1088 {
1089     QVariantMap dbsettings;
1090     dbsettings["Backend"] = backend;
1091     dbsettings["ConnectionProperties"] = settings;
1092     CoreSettings s = CoreSettings();
1093     s.setStorageSettings(dbsettings);
1094     return s.sync();
1095 }
1096
1097
1098 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1099 {
1100     QVariantMap dbsettings;
1101     dbsettings["Authenticator"] = backend;
1102     dbsettings["AuthProperties"] = settings;
1103     CoreSettings().setAuthSettings(dbsettings);
1104 }
1105
1106 // Generic version of promptForSettings that doesn't care what *type* of
1107 // backend it runs over.
1108 QVariantMap Core::promptForSettings(QStringList keys, QVariantMap defaults)
1109 {
1110     QVariantMap settings;
1111
1112     if (keys.isEmpty())
1113         return settings;
1114
1115     QTextStream out(stdout);
1116     QTextStream in(stdin);
1117     out << "Default values are in brackets" << endl;
1118
1119     QString value;
1120     foreach(QString key, keys) {
1121         QVariant val;
1122         if (defaults.contains(key)) {
1123             val = defaults[key];
1124         }
1125         out << key;
1126         if (!val.toString().isEmpty()) {
1127             out << " (" << val.toString() << ")";
1128         }
1129         out << ": ";
1130         out.flush();
1131
1132         bool noEcho = QString("password").toLower().startsWith(key.toLower());
1133         if (noEcho) {
1134             disableStdInEcho();
1135         }
1136         value = in.readLine().trimmed();
1137         if (noEcho) {
1138             out << endl;
1139             enableStdInEcho();
1140         }
1141
1142         if (!value.isEmpty()) {
1143             switch (defaults[key].type()) {
1144             case QVariant::Int:
1145                 val = QVariant(value.toInt());
1146                 break;
1147             default:
1148                 val = QVariant(value);
1149             }
1150         }
1151         settings[key] = val;
1152     }
1153     return settings;
1154 }
1155
1156 // Since an auth and storage backend work basically the same way,
1157 // use polymorphism here on this routine.
1158 QVariantMap Core::promptForSettings(const Storage *storage)
1159 {
1160     QStringList keys = storage->setupKeys();
1161     QVariantMap defaults = storage->setupDefaults();
1162     return Core::promptForSettings(keys, defaults);
1163 }
1164
1165
1166 QVariantMap Core::promptForSettings(const Authenticator *authenticator)
1167 {
1168     QStringList keys = authenticator->setupKeys();
1169     QVariantMap defaults = authenticator->setupDefaults();
1170     return Core::promptForSettings(keys, defaults);
1171 }
1172
1173
1174 #ifdef Q_OS_WIN
1175 void Core::stdInEcho(bool on)
1176 {
1177     HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1178     DWORD mode = 0;
1179     GetConsoleMode(hStdin, &mode);
1180     if (on)
1181         mode |= ENABLE_ECHO_INPUT;
1182     else
1183         mode &= ~ENABLE_ECHO_INPUT;
1184     SetConsoleMode(hStdin, mode);
1185 }
1186
1187
1188 #else
1189 void Core::stdInEcho(bool on)
1190 {
1191     termios t;
1192     tcgetattr(STDIN_FILENO, &t);
1193     if (on)
1194         t.c_lflag |= ECHO;
1195     else
1196         t.c_lflag &= ~ECHO;
1197     tcsetattr(STDIN_FILENO, TCSANOW, &t);
1198 }
1199
1200
1201 #endif /* Q_OS_WIN */