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