1 /***************************************************************************
2 * Copyright (C) 2005-2015 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QCoreApplication>
24 #include "coreauthhandler.h"
25 #include "coresession.h"
26 #include "coresettings.h"
28 #include "internalpeer.h"
30 #include "postgresqlstorage.h"
32 #include "sqlitestorage.h"
45 # include <sys/types.h>
46 # include <sys/stat.h>
47 #endif /* HAVE_UMASK */
49 // ==============================
51 // ==============================
52 const int Core::AddClientEventId = QEvent::registerEventType();
54 class AddClientEvent : public QEvent
57 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
63 // ==============================
65 // ==============================
66 Core *Core::instanceptr = 0;
68 Core *Core::instance()
70 if (instanceptr) return instanceptr;
71 instanceptr = new Core();
89 umask(S_IRWXG | S_IRWXO);
91 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
93 Quassel::loadTranslation(QLocale::system());
95 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
96 // Move settings, note this does not delete the old files
98 QSettings newSettings("quassel-irc.org", "quasselcore");
102 QSettings::Format format = QSettings::IniFormat;
104 QSettings::Format format = QSettings::NativeFormat;
106 QString newFilePath = Quassel::configDirPath() + "quasselcore"
107 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
108 QSettings newSettings(newFilePath, format);
109 #endif /* Q_OS_MAC */
111 if (newSettings.value("Config/Version").toUInt() == 0) {
113 QString org = "quassel-irc.org";
115 QString org = "Quassel Project";
117 QSettings oldSettings(org, "Quassel Core");
118 if (oldSettings.allKeys().count()) {
119 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
120 foreach(QString key, oldSettings.allKeys())
121 newSettings.setValue(key, oldSettings.value(key));
122 newSettings.setValue("Config/Version", 1);
123 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
125 #ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
127 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
128 #elif defined Q_OS_MAC
129 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
131 QString quasselDir = QDir::homePath() + "/.quassel/";
134 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
135 if (!info.exists()) {
136 // move database, if we found it
137 QFile oldDb(quasselDir + "quassel-storage.sqlite");
138 if (oldDb.exists()) {
139 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
141 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
143 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
147 QFileInfo certInfo(quasselDir + "quasselCert.pem");
148 if (certInfo.exists()) {
149 QFile cert(quasselDir + "quasselCert.pem");
150 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
152 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
154 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
156 #endif /* !Q_OS_MAC */
157 qWarning() << "*** Migration completed.\n\n";
162 // check settings version
163 // so far, we only have 1
165 if (s.version() != 1) {
166 qCritical() << "Invalid core settings version, terminating!";
170 registerStorageBackends();
172 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
173 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
181 QVariantMap dbsettings = cs.storageSettings().toMap();
182 _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());
184 if (Quassel::isOptionSet("select-backend")) {
185 selectBackend(Quassel::optionValue("select-backend"));
190 if (!_storageBackends.count()) {
191 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
192 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
193 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
195 exit(1); // TODO make this less brutal (especially for mono client -> popup)
197 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
200 if (Quassel::isOptionSet("add-user")) {
201 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
205 if (Quassel::isOptionSet("change-userpass")) {
206 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
207 EXIT_SUCCESS : EXIT_FAILURE);
210 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
211 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
212 if (!startListening()) exit(1); // TODO make this less brutal
214 if (Quassel::isOptionSet("oidentd"))
215 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
221 // FIXME do we need more cleanup for handlers?
222 foreach(CoreAuthHandler *handler, _connectingClients) {
223 handler->deleteLater(); // disconnect non authed clients
225 qDeleteAll(_sessions);
226 qDeleteAll(_storageBackends);
230 /*** Session Restore ***/
232 void Core::saveState()
236 QVariantList activeSessions;
237 foreach(UserId user, instance()->_sessions.keys())
238 activeSessions << QVariant::fromValue<UserId>(user);
239 state["CoreStateVersion"] = 1;
240 state["ActiveSessions"] = activeSessions;
241 s.setCoreState(state);
245 void Core::restoreState()
247 if (!instance()->_configured) {
248 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
251 if (instance()->_sessions.count()) {
252 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
256 /* We don't check, since we are at the first version since switching to Git
257 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
259 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
264 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
265 if (activeSessions.count() > 0) {
266 quInfo() << "Restoring previous core state...";
267 foreach(QVariant v, activeSessions) {
268 UserId user = v.value<UserId>();
269 instance()->sessionForUser(user, true);
277 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
279 return instance()->setupCore(adminUser, adminPassword, backend, setupData);
283 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
286 return tr("Core is already configured! Not configuring again...");
288 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
289 return tr("Admin user or password not set.");
291 if (!(_configured = initStorage(backend, setupData, true))) {
292 return tr("Could not setup storage!");
295 saveBackendSettings(backend, setupData);
297 quInfo() << qPrintable(tr("Creating admin user..."));
298 _storage->addUser(adminUser, adminPassword);
299 startListening(); // TODO check when we need this
304 QString Core::setupCoreForInternalUsage()
306 Q_ASSERT(!_storageBackends.isEmpty());
308 qsrand(QDateTime::currentDateTime().toTime_t());
310 for (int i = 0; i < 10; i++) {
312 pass += qrand() % 10;
315 // mono client currently needs sqlite
316 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap());
320 /*** Storage Handling ***/
321 void Core::registerStorageBackends()
323 // Register storage backends here!
324 registerStorageBackend(new SqliteStorage(this));
325 registerStorageBackend(new PostgreSqlStorage(this));
329 bool Core::registerStorageBackend(Storage *backend)
331 if (backend->isAvailable()) {
332 _storageBackends[backend->displayName()] = backend;
336 backend->deleteLater();
342 void Core::unregisterStorageBackends()
344 foreach(Storage *s, _storageBackends.values()) {
347 _storageBackends.clear();
351 void Core::unregisterStorageBackend(Storage *backend)
353 _storageBackends.remove(backend->displayName());
354 backend->deleteLater();
359 // "Type" => "sqlite"
360 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
364 if (backend.isEmpty()) {
368 Storage *storage = 0;
369 if (_storageBackends.contains(backend)) {
370 storage = _storageBackends[backend];
373 qCritical() << "Selected storage backend is not available:" << backend;
377 Storage::State storageState = storage->init(settings);
378 switch (storageState) {
379 case Storage::NeedsSetup:
381 return false; // trigger setup process
382 if (storage->setup(settings))
383 return initStorage(backend, settings, false);
386 // if initialization wasn't successful, we quit to keep from coming up unconfigured
387 case Storage::NotAvailable:
388 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
393 case Storage::IsReady:
394 // delete all other backends
395 _storageBackends.remove(backend);
396 unregisterStorageBackends();
397 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
404 void Core::syncStorage()
411 /*** Storage Access ***/
412 bool Core::createNetwork(UserId user, NetworkInfo &info)
414 NetworkId networkId = instance()->_storage->createNetwork(user, info);
415 if (!networkId.isValid())
418 info.networkId = networkId;
423 /*** Network Management ***/
425 bool Core::sslSupported()
428 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
429 return sslServer && sslServer->isCertValid();
436 bool Core::reloadCerts()
439 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
440 bool retv4 = sslServerv4->reloadCerts();
442 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
443 bool retv6 = sslServerv6->reloadCerts();
445 return retv4 && retv6;
447 // SSL not supported, don't mark configuration reload as failed
453 bool Core::startListening()
455 // in mono mode we only start a local port if a port is specified in the cli call
456 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
459 bool success = false;
460 uint port = Quassel::optionValue("port").toUInt();
462 const QString listen = Quassel::optionValue("listen");
463 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
464 if (listen_list.size() > 0) {
465 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
467 if (!addr.setAddress(listen_term)) {
468 qCritical() << qPrintable(
469 tr("Invalid listen address %1")
474 switch (addr.protocol()) {
475 case QAbstractSocket::IPv6Protocol:
476 if (_v6server.listen(addr, port)) {
477 quInfo() << qPrintable(
478 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
479 .arg(addr.toString())
480 .arg(_v6server.serverPort())
481 .arg(Quassel::buildInfo().protocolVersion)
486 quWarning() << qPrintable(
487 tr("Could not open IPv6 interface %1:%2: %3")
488 .arg(addr.toString())
490 .arg(_v6server.errorString()));
492 case QAbstractSocket::IPv4Protocol:
493 if (_server.listen(addr, port)) {
494 quInfo() << qPrintable(
495 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
496 .arg(addr.toString())
497 .arg(_server.serverPort())
498 .arg(Quassel::buildInfo().protocolVersion)
503 // if v6 succeeded on Any, the port will be already in use - don't display the error then
504 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
505 quWarning() << qPrintable(
506 tr("Could not open IPv4 interface %1:%2: %3")
507 .arg(addr.toString())
509 .arg(_server.errorString()));
513 qCritical() << qPrintable(
514 tr("Invalid listen address %1, unknown network protocol")
523 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
529 void Core::stopListening(const QString &reason)
531 bool wasListening = false;
532 if (_server.isListening()) {
536 if (_v6server.isListening()) {
541 if (reason.isEmpty())
542 quInfo() << "No longer listening for GUI clients.";
544 quInfo() << qPrintable(reason);
549 void Core::incomingConnection()
551 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
553 while (server->hasPendingConnections()) {
554 QTcpSocket *socket = server->nextPendingConnection();
556 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
557 _connectingClients.insert(handler);
559 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
560 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
561 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
563 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
566 stopListening(tr("Closing server for basic setup."));
572 // Potentially called during the initialization phase (before handing the connection off to the session)
573 void Core::clientDisconnected()
575 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
578 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
579 _connectingClients.remove(handler);
580 handler->deleteLater();
582 // make server listen again if still not configured
587 // TODO remove unneeded sessions - if necessary/possible...
588 // Suggestion: kill sessions if they are not connected to any network and client.
592 void Core::setupClientSession(RemotePeer *peer, UserId uid)
594 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
597 // From now on everything is handled by the client session
598 disconnect(handler, 0, this, 0);
599 _connectingClients.remove(handler);
600 handler->deleteLater();
602 // Find or create session for validated user
605 // as we are currently handling an event triggered by incoming data on this socket
606 // it is unsafe to directly move the socket to the client thread.
607 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
611 void Core::customEvent(QEvent *event)
613 if (event->type() == AddClientEventId) {
614 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
615 addClientHelper(addClientEvent->peer, addClientEvent->userId);
621 void Core::addClientHelper(RemotePeer *peer, UserId uid)
623 // Find or create session for validated user
624 SessionThread *session = sessionForUser(uid);
625 session->addClient(peer);
629 void Core::setupInternalClientSession(InternalPeer *clientPeer)
633 setupCoreForInternalUsage();
638 uid = _storage->internalUser();
641 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
645 InternalPeer *corePeer = new InternalPeer(this);
646 corePeer->setPeer(clientPeer);
647 clientPeer->setPeer(corePeer);
649 // Find or create session for validated user
650 SessionThread *sessionThread = sessionForUser(uid);
651 sessionThread->addClient(corePeer);
655 SessionThread *Core::sessionForUser(UserId uid, bool restore)
657 if (_sessions.contains(uid))
658 return _sessions[uid];
660 SessionThread *session = new SessionThread(uid, restore, this);
661 _sessions[uid] = session;
667 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
669 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
673 QVariantList Core::backendInfo()
675 QVariantList backends;
676 foreach(const Storage *backend, instance()->_storageBackends.values()) {
678 v["DisplayName"] = backend->displayName();
679 v["Description"] = backend->description();
680 v["SetupKeys"] = backend->setupKeys();
681 v["SetupDefaults"] = backend->setupDefaults();
688 // migration / backend selection
689 bool Core::selectBackend(const QString &backend)
691 // reregister all storage backends
692 registerStorageBackends();
693 if (!_storageBackends.contains(backend)) {
694 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
695 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
699 Storage *storage = _storageBackends[backend];
700 QVariantMap settings = promptForSettings(storage);
702 Storage::State storageState = storage->init(settings);
703 switch (storageState) {
704 case Storage::IsReady:
705 saveBackendSettings(backend, settings);
706 qWarning() << "Switched backend to:" << qPrintable(backend);
707 qWarning() << "Backend already initialized. Skipping Migration";
709 case Storage::NotAvailable:
710 qCritical() << "Backend is not available:" << qPrintable(backend);
712 case Storage::NeedsSetup:
713 if (!storage->setup(settings)) {
714 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
718 if (storage->init(settings) != Storage::IsReady) {
719 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
723 saveBackendSettings(backend, settings);
724 qWarning() << "Switched backend to:" << qPrintable(backend);
728 // let's see if we have a current storage object we can migrate from
729 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
730 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
731 if (reader && writer) {
732 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
737 if (reader->migrateTo(writer)) {
738 qDebug() << "Migration finished!";
739 saveBackendSettings(backend, settings);
743 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
746 // inform the user why we cannot merge
748 qWarning() << "No currently active backend. Skipping migration.";
751 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
754 qWarning() << "New backend does not support migration:" << qPrintable(backend);
757 // so we were unable to merge, but let's create a user \o/
764 bool Core::createUser()
766 QTextStream out(stdout);
767 QTextStream in(stdin);
768 out << "Add a new user:" << endl;
771 QString username = in.readLine().trimmed();
776 QString password = in.readLine().trimmed();
778 out << "Repeat Password: ";
780 QString password2 = in.readLine().trimmed();
784 if (password != password2) {
785 qWarning() << "Passwords don't match!";
788 if (password.isEmpty()) {
789 qWarning() << "Password is empty!";
793 if (_configured && _storage->addUser(username, password).isValid()) {
794 out << "Added user " << username << " successfully!" << endl;
798 qWarning() << "Unable to add user:" << qPrintable(username);
804 bool Core::changeUserPass(const QString &username)
806 QTextStream out(stdout);
807 QTextStream in(stdin);
808 UserId userId = _storage->getUserId(username);
809 if (!userId.isValid()) {
810 out << "User " << username << " does not exist." << endl;
814 out << "Change password for user: " << username << endl;
817 out << "New Password: ";
819 QString password = in.readLine().trimmed();
821 out << "Repeat Password: ";
823 QString password2 = in.readLine().trimmed();
827 if (password != password2) {
828 qWarning() << "Passwords don't match!";
831 if (password.isEmpty()) {
832 qWarning() << "Password is empty!";
836 if (_configured && _storage->updateUser(userId, password)) {
837 out << "Password changed successfully!" << endl;
841 qWarning() << "Failed to change password!";
847 bool Core::changeUserPassword(UserId userId, const QString &password)
849 if (!isConfigured() || !userId.isValid())
852 return instance()->_storage->updateUser(userId, password);
856 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
861 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
863 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
867 return sqlStorage->createMigrationReader();
871 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
876 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
878 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
882 return sqlStorage->createMigrationWriter();
886 void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
888 QVariantMap dbsettings;
889 dbsettings["Backend"] = backend;
890 dbsettings["ConnectionProperties"] = settings;
891 CoreSettings().setStorageSettings(dbsettings);
895 QVariantMap Core::promptForSettings(const Storage *storage)
897 QVariantMap settings;
899 QStringList keys = storage->setupKeys();
903 QTextStream out(stdout);
904 QTextStream in(stdin);
905 out << "Default values are in brackets" << endl;
907 QVariantMap defaults = storage->setupDefaults();
909 foreach(QString key, keys) {
911 if (defaults.contains(key)) {
915 if (!val.toString().isEmpty()) {
916 out << " (" << val.toString() << ")";
921 bool noEcho = QString("password").toLower().startsWith(key.toLower());
925 value = in.readLine().trimmed();
931 if (!value.isEmpty()) {
932 switch (defaults[key].type()) {
934 val = QVariant(value.toInt());
937 val = QVariant(value);
947 void Core::stdInEcho(bool on)
949 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
951 GetConsoleMode(hStdin, &mode);
953 mode |= ENABLE_ECHO_INPUT;
955 mode &= ~ENABLE_ECHO_INPUT;
956 SetConsoleMode(hStdin, mode);
961 void Core::stdInEcho(bool on)
964 tcgetattr(STDIN_FILENO, &t);
969 tcsetattr(STDIN_FILENO, TCSANOW, &t);
973 #endif /* Q_OS_WIN */