1 /***************************************************************************
2 * Copyright (C) 2005-2013 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"
35 #include "protocols/legacy/legacypeer.h"
44 #endif /* Q_OS_WIN32 */
47 # include <sys/types.h>
48 # include <sys/stat.h>
49 #endif /* HAVE_UMASK */
51 // ==============================
53 // ==============================
54 const int Core::AddClientEventId = QEvent::registerEventType();
56 class AddClientEvent : public QEvent
59 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
65 // ==============================
67 // ==============================
68 Core *Core::instanceptr = 0;
70 Core *Core::instance()
72 if (instanceptr) return instanceptr;
73 instanceptr = new Core();
91 umask(S_IRWXG | S_IRWXO);
93 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
95 Quassel::loadTranslation(QLocale::system());
97 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
98 // Move settings, note this does not delete the old files
100 QSettings newSettings("quassel-irc.org", "quasselcore");
104 QSettings::Format format = QSettings::IniFormat;
106 QSettings::Format format = QSettings::NativeFormat;
108 QString newFilePath = Quassel::configDirPath() + "quasselcore"
109 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
110 QSettings newSettings(newFilePath, format);
111 #endif /* Q_WS_MAC */
113 if (newSettings.value("Config/Version").toUInt() == 0) {
115 QString org = "quassel-irc.org";
117 QString org = "Quassel Project";
119 QSettings oldSettings(org, "Quassel Core");
120 if (oldSettings.allKeys().count()) {
121 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
122 foreach(QString key, oldSettings.allKeys())
123 newSettings.setValue(key, oldSettings.value(key));
124 newSettings.setValue("Config/Version", 1);
125 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
127 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
129 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
130 #elif defined Q_WS_MAC
131 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
133 QString quasselDir = QDir::homePath() + "/.quassel/";
136 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
137 if (!info.exists()) {
138 // move database, if we found it
139 QFile oldDb(quasselDir + "quassel-storage.sqlite");
140 if (oldDb.exists()) {
141 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
143 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
145 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
149 QFileInfo certInfo(quasselDir + "quasselCert.pem");
150 if (certInfo.exists()) {
151 QFile cert(quasselDir + "quasselCert.pem");
152 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
154 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
156 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
158 #endif /* !Q_WS_MAC */
159 qWarning() << "*** Migration completed.\n\n";
164 // check settings version
165 // so far, we only have 1
167 if (s.version() != 1) {
168 qCritical() << "Invalid core settings version, terminating!";
172 registerStorageBackends();
174 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
175 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
183 QVariantMap dbsettings = cs.storageSettings().toMap();
184 _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());
186 if (Quassel::isOptionSet("select-backend")) {
187 selectBackend(Quassel::optionValue("select-backend"));
192 if (!_storageBackends.count()) {
193 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
194 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
195 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
197 exit(1); // TODO make this less brutal (especially for mono client -> popup)
199 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
202 if (Quassel::isOptionSet("add-user")) {
207 if (Quassel::isOptionSet("change-userpass")) {
208 changeUserPass(Quassel::optionValue("change-userpass"));
212 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
213 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
214 if (!startListening()) exit(1); // TODO make this less brutal
216 if (Quassel::isOptionSet("oidentd"))
217 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
223 // FIXME do we need more cleanup for handlers?
224 foreach(CoreAuthHandler *handler, _connectingClients) {
225 handler->deleteLater(); // disconnect non authed clients
227 qDeleteAll(sessions);
228 qDeleteAll(_storageBackends);
232 /*** Session Restore ***/
234 void Core::saveState()
238 QVariantList activeSessions;
239 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
240 state["CoreStateVersion"] = 1;
241 state["ActiveSessions"] = activeSessions;
242 s.setCoreState(state);
246 void Core::restoreState()
248 if (!instance()->_configured) {
249 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
252 if (instance()->sessions.count()) {
253 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
257 /* We don't check, since we are at the first version since switching to Git
258 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
260 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
265 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
266 if (activeSessions.count() > 0) {
267 quInfo() << "Restoring previous core state...";
268 foreach(QVariant v, activeSessions) {
269 UserId user = v.value<UserId>();
270 instance()->createSession(user, true);
278 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
280 return instance()->setupCore(adminUser, adminPassword, backend, setupData);
284 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData)
287 return tr("Core is already configured! Not configuring again...");
289 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
290 return tr("Admin user or password not set.");
292 if (!(_configured = initStorage(backend, setupData, true))) {
293 return tr("Could not setup storage!");
296 saveBackendSettings(backend, setupData);
298 quInfo() << qPrintable(tr("Creating admin user..."));
299 _storage->addUser(adminUser, adminPassword);
300 startListening(); // TODO check when we need this
305 QString Core::setupCoreForInternalUsage()
307 Q_ASSERT(!_storageBackends.isEmpty());
309 qsrand(QDateTime::currentDateTime().toTime_t());
311 for (int i = 0; i < 10; i++) {
313 pass += qrand() % 10;
316 // mono client currently needs sqlite
317 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap());
321 /*** Storage Handling ***/
322 void Core::registerStorageBackends()
324 // Register storage backends here!
325 registerStorageBackend(new SqliteStorage(this));
326 registerStorageBackend(new PostgreSqlStorage(this));
330 bool Core::registerStorageBackend(Storage *backend)
332 if (backend->isAvailable()) {
333 _storageBackends[backend->displayName()] = backend;
337 backend->deleteLater();
343 void Core::unregisterStorageBackends()
345 foreach(Storage *s, _storageBackends.values()) {
348 _storageBackends.clear();
352 void Core::unregisterStorageBackend(Storage *backend)
354 _storageBackends.remove(backend->displayName());
355 backend->deleteLater();
360 // "Type" => "sqlite"
361 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
365 if (backend.isEmpty()) {
369 Storage *storage = 0;
370 if (_storageBackends.contains(backend)) {
371 storage = _storageBackends[backend];
374 qCritical() << "Selected storage backend is not available:" << backend;
378 Storage::State storageState = storage->init(settings);
379 switch (storageState) {
380 case Storage::NeedsSetup:
382 return false; // trigger setup process
383 if (storage->setup(settings))
384 return initStorage(backend, settings, false);
385 // if setup wasn't successfull we mark the backend as unavailable
386 case Storage::NotAvailable:
387 qCritical() << "Selected storage backend is not available:" << backend;
388 storage->deleteLater();
389 _storageBackends.remove(backend);
392 case Storage::IsReady:
393 // delete all other backends
394 _storageBackends.remove(backend);
395 unregisterStorageBackends();
396 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
403 void Core::syncStorage()
410 /*** Storage Access ***/
411 bool Core::createNetwork(UserId user, NetworkInfo &info)
413 NetworkId networkId = instance()->_storage->createNetwork(user, info);
414 if (!networkId.isValid())
417 info.networkId = networkId;
422 /*** Network Management ***/
424 bool Core::sslSupported()
427 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
428 return sslServer && sslServer->isCertValid();
435 bool Core::startListening()
437 // in mono mode we only start a local port if a port is specified in the cli call
438 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
441 bool success = false;
442 uint port = Quassel::optionValue("port").toUInt();
444 const QString listen = Quassel::optionValue("listen");
445 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
446 if (listen_list.size() > 0) {
447 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
449 if (!addr.setAddress(listen_term)) {
450 qCritical() << qPrintable(
451 tr("Invalid listen address %1")
456 switch (addr.protocol()) {
457 case QAbstractSocket::IPv6Protocol:
458 if (_v6server.listen(addr, port)) {
459 quInfo() << qPrintable(
460 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
461 .arg(addr.toString())
462 .arg(_v6server.serverPort())
463 .arg(Quassel::buildInfo().protocolVersion)
468 quWarning() << qPrintable(
469 tr("Could not open IPv6 interface %1:%2: %3")
470 .arg(addr.toString())
472 .arg(_v6server.errorString()));
474 case QAbstractSocket::IPv4Protocol:
475 if (_server.listen(addr, port)) {
476 quInfo() << qPrintable(
477 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
478 .arg(addr.toString())
479 .arg(_server.serverPort())
480 .arg(Quassel::buildInfo().protocolVersion)
485 // if v6 succeeded on Any, the port will be already in use - don't display the error then
486 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
487 quWarning() << qPrintable(
488 tr("Could not open IPv4 interface %1:%2: %3")
489 .arg(addr.toString())
491 .arg(_server.errorString()));
495 qCritical() << qPrintable(
496 tr("Invalid listen address %1, unknown network protocol")
505 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
511 void Core::stopListening(const QString &reason)
513 bool wasListening = false;
514 if (_server.isListening()) {
518 if (_v6server.isListening()) {
523 if (reason.isEmpty())
524 quInfo() << "No longer listening for GUI clients.";
526 quInfo() << qPrintable(reason);
531 void Core::incomingConnection()
533 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
535 while (server->hasPendingConnections()) {
536 QTcpSocket *socket = server->nextPendingConnection();
538 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
539 _connectingClients.insert(handler);
541 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
542 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
543 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
545 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
548 stopListening(tr("Closing server for basic setup."));
554 // Potentially called during the initialization phase (before handing the connection off to the session)
555 void Core::clientDisconnected()
557 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
560 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
561 _connectingClients.remove(handler);
562 handler->deleteLater();
564 // make server listen again if still not configured
569 // TODO remove unneeded sessions - if necessary/possible...
570 // Suggestion: kill sessions if they are not connected to any network and client.
574 void Core::setupClientSession(RemotePeer *peer, UserId uid)
576 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
579 // From now on everything is handled by the client session
580 disconnect(handler, 0, this, 0);
581 _connectingClients.remove(handler);
582 handler->deleteLater();
584 // Find or create session for validated user
585 SessionThread *session;
586 if (sessions.contains(uid)) {
587 session = sessions[uid];
590 session = createSession(uid);
592 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(peer->description());
599 // as we are currently handling an event triggered by incoming data on this socket
600 // it is unsafe to directly move the socket to the client thread.
601 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
605 void Core::customEvent(QEvent *event)
607 if (event->type() == AddClientEventId) {
608 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
609 addClientHelper(addClientEvent->peer, addClientEvent->userId);
615 void Core::addClientHelper(RemotePeer *peer, UserId uid)
617 // Find or create session for validated user
618 if (!sessions.contains(uid)) {
619 qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(peer->description());
625 SessionThread *session = sessions[uid];
626 session->addClient(peer);
630 void Core::setupInternalClientSession(InternalPeer *clientPeer)
634 setupCoreForInternalUsage();
639 uid = _storage->internalUser();
642 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
646 InternalPeer *corePeer = new InternalPeer(this);
647 corePeer->setPeer(clientPeer);
648 clientPeer->setPeer(corePeer);
650 // Find or create session for validated user
651 SessionThread *sessionThread;
652 if (sessions.contains(uid))
653 sessionThread = sessions[uid];
655 sessionThread = createSession(uid);
657 sessionThread->addClient(corePeer);
661 SessionThread *Core::createSession(UserId uid, bool restore)
663 if (sessions.contains(uid)) {
664 qWarning() << "Calling createSession() when a session for the user already exists!";
667 SessionThread *sess = new SessionThread(uid, restore, this);
668 sessions[uid] = sess;
674 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
676 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
680 QVariantList Core::backendInfo()
682 QVariantList backends;
683 foreach(const Storage *backend, instance()->_storageBackends.values()) {
685 v["DisplayName"] = backend->displayName();
686 v["Description"] = backend->description();
687 v["SetupKeys"] = backend->setupKeys();
688 v["SetupDefaults"] = backend->setupDefaults();
695 // migration / backend selection
696 bool Core::selectBackend(const QString &backend)
698 // reregister all storage backends
699 registerStorageBackends();
700 if (!_storageBackends.contains(backend)) {
701 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
702 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
706 Storage *storage = _storageBackends[backend];
707 QVariantMap settings = promptForSettings(storage);
709 Storage::State storageState = storage->init(settings);
710 switch (storageState) {
711 case Storage::IsReady:
712 saveBackendSettings(backend, settings);
713 qWarning() << "Switched backend to:" << qPrintable(backend);
714 qWarning() << "Backend already initialized. Skipping Migration";
716 case Storage::NotAvailable:
717 qCritical() << "Backend is not available:" << qPrintable(backend);
719 case Storage::NeedsSetup:
720 if (!storage->setup(settings)) {
721 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
725 if (storage->init(settings) != Storage::IsReady) {
726 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
730 saveBackendSettings(backend, settings);
731 qWarning() << "Switched backend to:" << qPrintable(backend);
735 // let's see if we have a current storage object we can migrate from
736 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
737 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
738 if (reader && writer) {
739 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
744 if (reader->migrateTo(writer)) {
745 qDebug() << "Migration finished!";
746 saveBackendSettings(backend, settings);
750 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
753 // inform the user why we cannot merge
755 qWarning() << "No currently active backend. Skipping migration.";
758 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
761 qWarning() << "New backend does not support migration:" << qPrintable(backend);
764 // so we were unable to merge, but let's create a user \o/
771 void Core::createUser()
773 QTextStream out(stdout);
774 QTextStream in(stdin);
775 out << "Add a new user:" << endl;
778 QString username = in.readLine().trimmed();
783 QString password = in.readLine().trimmed();
785 out << "Repeat Password: ";
787 QString password2 = in.readLine().trimmed();
791 if (password != password2) {
792 qWarning() << "Passwords don't match!";
795 if (password.isEmpty()) {
796 qWarning() << "Password is empty!";
800 if (_configured && _storage->addUser(username, password).isValid()) {
801 out << "Added user " << username << " successfully!" << endl;
804 qWarning() << "Unable to add user:" << qPrintable(username);
809 void Core::changeUserPass(const QString &username)
811 QTextStream out(stdout);
812 QTextStream in(stdin);
813 UserId userId = _storage->getUserId(username);
814 if (!userId.isValid()) {
815 out << "User " << username << " does not exist." << endl;
819 out << "Change password for user: " << username << endl;
822 out << "New Password: ";
824 QString password = in.readLine().trimmed();
826 out << "Repeat Password: ";
828 QString password2 = in.readLine().trimmed();
832 if (password != password2) {
833 qWarning() << "Passwords don't match!";
836 if (password.isEmpty()) {
837 qWarning() << "Password is empty!";
841 if (_configured && _storage->updateUser(userId, password)) {
842 out << "Password changed successfully!" << endl;
845 qWarning() << "Failed to change password!";
850 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
855 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
857 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
861 return sqlStorage->createMigrationReader();
865 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
870 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
872 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
876 return sqlStorage->createMigrationWriter();
880 void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
882 QVariantMap dbsettings;
883 dbsettings["Backend"] = backend;
884 dbsettings["ConnectionProperties"] = settings;
885 CoreSettings().setStorageSettings(dbsettings);
889 QVariantMap Core::promptForSettings(const Storage *storage)
891 QVariantMap settings;
893 QStringList keys = storage->setupKeys();
897 QTextStream out(stdout);
898 QTextStream in(stdin);
899 out << "Default values are in brackets" << endl;
901 QVariantMap defaults = storage->setupDefaults();
903 foreach(QString key, keys) {
905 if (defaults.contains(key)) {
909 if (!val.toString().isEmpty()) {
910 out << " (" << val.toString() << ")";
915 bool noEcho = QString("password").toLower().startsWith(key.toLower());
919 value = in.readLine().trimmed();
925 if (!value.isEmpty()) {
926 switch (defaults[key].type()) {
928 val = QVariant(value.toInt());
931 val = QVariant(value);
941 void Core::stdInEcho(bool on)
943 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
945 GetConsoleMode(hStdin, &mode);
947 mode |= ENABLE_ECHO_INPUT;
949 mode &= ~ENABLE_ECHO_INPUT;
950 SetConsoleMode(hStdin, mode);
955 void Core::stdInEcho(bool on)
958 tcgetattr(STDIN_FILENO, &t);
963 tcsetattr(STDIN_FILENO, TCSANOW, &t);
967 #endif /* Q_OS_WIN32 */