1 /***************************************************************************
2 * Copyright (C) 2005-09 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include <QCoreApplication>
24 #include "coresession.h"
25 #include "coresettings.h"
27 #include "signalproxy.h"
28 #include "sqlitestorage.h"
37 // ==============================
39 // ==============================
40 const int Core::AddClientEventId = QEvent::registerEventType();
42 class AddClientEvent : public QEvent {
44 AddClientEvent(QTcpSocket *socket, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), socket(socket), userId(uid) {}
50 // ==============================
52 // ==============================
53 Core *Core::instanceptr = 0;
55 Core *Core::instance() {
56 if(instanceptr) return instanceptr;
57 instanceptr = new Core();
62 void Core::destroy() {
70 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
72 Quassel::loadTranslation(QLocale::system());
74 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
75 // Move settings, note this does not delete the old files
77 QSettings newSettings("quassel-irc.org", "quasselcore");
81 QSettings::Format format = QSettings::IniFormat;
83 QSettings::Format format = QSettings::NativeFormat;
85 QString newFilePath = Quassel::configDirPath() + "quasselcore"
86 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
87 QSettings newSettings(newFilePath, format);
90 if(newSettings.value("Config/Version").toUInt() == 0) {
92 QString org = "quassel-irc.org";
94 QString org = "Quassel Project";
96 QSettings oldSettings(org, "Quassel Core");
97 if(oldSettings.allKeys().count()) {
98 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
99 foreach(QString key, oldSettings.allKeys())
100 newSettings.setValue(key, oldSettings.value(key));
101 newSettings.setValue("Config/Version", 1);
102 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
104 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
106 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
107 #elif defined Q_WS_MAC
108 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
110 QString quasselDir = QDir::homePath() + "/.quassel/";
113 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
115 // move database, if we found it
116 QFile oldDb(quasselDir + "quassel-storage.sqlite");
118 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
120 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
122 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
126 QFileInfo certInfo(quasselDir + "quasselCert.pem");
127 if(certInfo.exists()) {
128 QFile cert(quasselDir + "quasselCert.pem");
129 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
131 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
133 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
135 #endif /* !Q_WS_MAC */
136 qWarning() << "*** Migration completed.\n\n";
141 // check settings version
142 // so far, we only have 1
144 if(s.version() != 1) {
145 qCritical() << "Invalid core settings version, terminating!";
149 // Register storage backends here!
150 registerStorageBackend(new SqliteStorage(this));
152 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
153 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
158 _configured = initStorage(cs.storageSettings().toMap());
161 if(!_storageBackends.count()) {
162 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
163 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
164 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
166 exit(1); // TODO make this less brutal (especially for mono client -> popup)
168 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
171 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
172 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
173 if(!startListening()) exit(1); // TODO make this less brutal
177 foreach(QTcpSocket *socket, blocksizes.keys()) {
178 socket->disconnectFromHost(); // disconnect non authed clients
180 qDeleteAll(sessions);
181 qDeleteAll(_storageBackends);
184 /*** Session Restore ***/
186 void Core::saveState() {
189 QVariantList activeSessions;
190 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
191 state["CoreStateVersion"] = 1;
192 state["ActiveSessions"] = activeSessions;
193 s.setCoreState(state);
196 void Core::restoreState() {
197 if(!instance()->_configured) {
198 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
201 if(instance()->sessions.count()) {
202 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
206 /* We don't check, since we are at the first version since switching to Git
207 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
209 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
213 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
214 if(activeSessions.count() > 0) {
215 quInfo() << "Restoring previous core state...";
216 foreach(QVariant v, activeSessions) {
217 UserId user = v.value<UserId>();
218 instance()->createSession(user, true);
224 QString Core::setupCoreForInternalUsage() {
225 Q_ASSERT(!_storageBackends.isEmpty());
226 QVariantMap setupData;
227 qsrand(QDateTime::currentDateTime().toTime_t());
229 for(int i = 0; i < 10; i++) {
231 pass += qrand() % 10;
233 setupData["AdminUser"] = "AdminUser";
234 setupData["AdminPasswd"] = QString::number(pass);
235 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
236 return setupCore(setupData);
239 QString Core::setupCore(QVariantMap setupData) {
240 QString user = setupData.take("AdminUser").toString();
241 QString password = setupData.take("AdminPasswd").toString();
242 if(user.isEmpty() || password.isEmpty()) {
243 return tr("Admin user or password not set.");
245 _configured = initStorage(setupData, true);
247 return tr("Could not setup storage!");
250 s.setStorageSettings(setupData);
251 quInfo() << qPrintable(tr("Creating admin user..."));
252 _storage->addUser(user, password);
253 startListening(); // TODO check when we need this
257 /*** Storage Handling ***/
259 bool Core::registerStorageBackend(Storage *backend) {
260 if(backend->isAvailable()) {
261 _storageBackends[backend->displayName()] = backend;
264 backend->deleteLater();
269 void Core::unregisterStorageBackend(Storage *backend) {
270 _storageBackends.remove(backend->displayName());
271 backend->deleteLater();
275 // "Type" => "sqlite"
276 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
279 QString backend = dbSettings["Backend"].toString();
280 if(backend.isEmpty()) {
284 Storage *storage = 0;
285 if(_storageBackends.contains(backend)) {
286 storage = _storageBackends[backend];
288 qCritical() << "Selected storage backend is not available:" << backend;
292 Storage::State storageState = storage->init(dbSettings);
293 switch(storageState) {
294 case Storage::NeedsSetup:
296 return false; // trigger setup process
297 if(storage->setup(dbSettings))
298 return initStorage(dbSettings, false);
299 // if setup wasn't successfull we mark the backend as unavailable
300 case Storage::NotAvailable:
301 qCritical() << "Selected storage backend is not available:" << backend;
302 storage->deleteLater();
303 _storageBackends.remove(backend);
306 case Storage::IsReady:
307 // delete all other backends
308 foreach(Storage *s, _storageBackends.values()) {
309 if(s != storage) s->deleteLater();
311 _storageBackends.clear();
312 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
318 void Core::syncStorage() {
323 /*** Storage Access ***/
324 bool Core::createNetwork(UserId user, NetworkInfo &info) {
325 NetworkId networkId = instance()->_storage->createNetwork(user, info);
326 if(!networkId.isValid())
329 info.networkId = networkId;
333 /*** Network Management ***/
335 bool Core::startListening() {
336 // in mono mode we only start a local port if a port is specified in the cli call
337 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
340 bool success = false;
341 uint port = Quassel::optionValue("port").toUInt();
343 const QString listen = Quassel::optionValue("listen");
344 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
345 if(listen_list.size() > 0) {
346 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
348 if(!addr.setAddress(listen_term)) {
349 qCritical() << qPrintable(
350 tr("Invalid listen address %1")
354 switch(addr.protocol()) {
355 case QAbstractSocket::IPv4Protocol:
356 if(_server.listen(addr, port)) {
357 quInfo() << qPrintable(
358 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
359 .arg(addr.toString())
360 .arg(_server.serverPort())
361 .arg(Quassel::buildInfo().protocolVersion)
365 quWarning() << qPrintable(
366 tr("Could not open IPv4 interface %1:%2: %3")
367 .arg(addr.toString())
369 .arg(_server.errorString()));
371 case QAbstractSocket::IPv6Protocol:
372 if(_v6server.listen(addr, port)) {
373 quInfo() << qPrintable(
374 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
375 .arg(addr.toString())
376 .arg(_v6server.serverPort())
377 .arg(Quassel::buildInfo().protocolVersion)
381 // if v4 succeeded on Any, the port will be already in use - don't display the error then
382 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
383 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
384 quWarning() << qPrintable(
385 tr("Could not open IPv6 interface %1:%2: %3")
386 .arg(addr.toString())
388 .arg(_v6server.errorString()));
392 qCritical() << qPrintable(
393 tr("Invalid listen address %1, unknown network protocol")
402 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
407 void Core::stopListening(const QString &reason) {
408 bool wasListening = false;
409 if(_server.isListening()) {
413 if(_v6server.isListening()) {
419 quInfo() << "No longer listening for GUI clients.";
421 quInfo() << qPrintable(reason);
425 void Core::incomingConnection() {
426 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
428 while(server->hasPendingConnections()) {
429 QTcpSocket *socket = server->nextPendingConnection();
430 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
431 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
432 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
434 QVariantMap clientInfo;
435 blocksizes.insert(socket, (quint32)0);
436 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
439 stopListening(tr("Closing server for basic setup."));
444 void Core::clientHasData() {
445 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
446 Q_ASSERT(socket && blocksizes.contains(socket));
448 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
449 QVariantMap msg = item.toMap();
450 processClientMessage(socket, msg);
451 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
455 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
456 if(!msg.contains("MsgType")) {
457 // Client is way too old, does not even use the current init format
458 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
462 // OK, so we have at least an init message format we can understand
463 if(msg["MsgType"] == "ClientInit") {
466 // Just version information -- check it!
467 uint ver = msg["ProtocolVersion"].toUInt();
468 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
469 reply["MsgType"] = "ClientInitReject";
470 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
471 "This core needs at least client/core protocol version %1.<br>"
472 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
473 SignalProxy::writeDataToDevice(socket, reply);
474 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
475 socket->close(); return;
478 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
479 reply["CoreDate"] = Quassel::buildInfo().buildDate;
480 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
481 // TODO: Make the core info configurable
482 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
483 int updays = uptime / 86400; uptime %= 86400;
484 int uphours = uptime / 3600; uptime %= 3600;
485 int upmins = uptime / 60;
486 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
488 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
489 .arg(Quassel::buildInfo().buildDate)
490 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
493 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
494 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
495 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
497 bool supportSsl = false;
500 #ifndef QT_NO_COMPRESS
501 bool supportsCompression = true;
503 bool supportsCompression = false;
506 reply["SupportSsl"] = supportSsl;
507 reply["SupportsCompression"] = supportsCompression;
508 // switch to ssl/compression after client has been informed about our capabilities (see below)
510 reply["LoginEnabled"] = true;
512 // check if we are configured, start wizard otherwise
514 reply["Configured"] = false;
515 QList<QVariant> backends;
516 foreach(Storage *backend, _storageBackends.values()) {
518 v["DisplayName"] = backend->displayName();
519 v["Description"] = backend->description();
522 reply["StorageBackends"] = backends;
523 reply["LoginEnabled"] = false;
525 reply["Configured"] = true;
527 clientInfo[socket] = msg; // store for future reference
528 reply["MsgType"] = "ClientInitAck";
529 SignalProxy::writeDataToDevice(socket, reply);
532 // after we told the client that we are ssl capable we switch to ssl mode
533 if(supportSsl && msg["UseSsl"].toBool()) {
534 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
535 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
536 sslSocket->startServerEncryption();
540 #ifndef QT_NO_COMPRESS
541 if(supportsCompression && msg["UseCompression"].toBool()) {
542 socket->setProperty("UseCompression", true);
543 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
548 // for the rest, we need an initialized connection
549 if(!clientInfo.contains(socket)) {
551 reply["MsgType"] = "ClientLoginReject";
552 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
553 SignalProxy::writeDataToDevice(socket, reply);
554 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
555 socket->close(); return;
557 if(msg["MsgType"] == "CoreSetupData") {
559 QString result = setupCore(msg["SetupData"].toMap());
560 if(!result.isEmpty()) {
561 reply["MsgType"] = "CoreSetupReject";
562 reply["Error"] = result;
564 reply["MsgType"] = "CoreSetupAck";
566 SignalProxy::writeDataToDevice(socket, reply);
567 } else if(msg["MsgType"] == "ClientLogin") {
569 UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
571 reply["MsgType"] = "ClientLoginReject";
572 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
573 SignalProxy::writeDataToDevice(socket, reply);
576 reply["MsgType"] = "ClientLoginAck";
577 SignalProxy::writeDataToDevice(socket, reply);
578 quInfo() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt()));
579 setupClientSession(socket, uid);
584 // Potentially called during the initialization phase (before handing the connection off to the session)
585 void Core::clientDisconnected() {
586 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
588 // here it's safe to call methods on socket!
589 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
590 blocksizes.remove(socket);
591 clientInfo.remove(socket);
592 socket->deleteLater();
594 // we have to crawl through the hashes and see if we find a victim to remove
595 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
597 // DO NOT CALL ANY METHODS ON socket!!
598 socket = static_cast<QTcpSocket *>(sender());
600 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
601 while(blockSizeIter != blocksizes.end()) {
602 if(blockSizeIter.key() == socket) {
603 blockSizeIter = blocksizes.erase(blockSizeIter);
609 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
610 while(clientInfoIter != clientInfo.end()) {
611 if(clientInfoIter.key() == socket) {
612 clientInfoIter = clientInfo.erase(clientInfoIter);
620 // make server listen again if still not configured
625 // TODO remove unneeded sessions - if necessary/possible...
626 // Suggestion: kill sessions if they are not connected to any network and client.
629 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
630 // From now on everything is handled by the client session
631 disconnect(socket, 0, this, 0);
633 blocksizes.remove(socket);
634 clientInfo.remove(socket);
636 // Find or create session for validated user
637 SessionThread *session;
638 if(sessions.contains(uid)) {
639 session = sessions[uid];
641 session = createSession(uid);
643 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
649 // as we are currently handling an event triggered by incoming data on this socket
650 // it is unsafe to directly move the socket to the client thread.
651 QCoreApplication::postEvent(this, new AddClientEvent(socket, uid));
654 void Core::customEvent(QEvent *event) {
655 if(event->type() == AddClientEventId) {
656 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
657 addClientHelper(addClientEvent->socket, addClientEvent->userId);
662 void Core::addClientHelper(QTcpSocket *socket, UserId uid) {
663 // Find or create session for validated user
664 if(!sessions.contains(uid)) {
665 qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(socket->peerAddress().toString());
670 SessionThread *session = sessions[uid];
671 session->addClient(socket);
674 void Core::setupInternalClientSession(SignalProxy *proxy) {
677 setupCoreForInternalUsage();
682 uid = _storage->internalUser();
684 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
688 // Find or create session for validated user
690 if(sessions.contains(uid))
691 sess = sessions[uid];
693 sess = createSession(uid);
694 sess->addClient(proxy);
697 SessionThread *Core::createSession(UserId uid, bool restore) {
698 if(sessions.contains(uid)) {
699 qWarning() << "Calling createSession() when a session for the user already exists!";
702 SessionThread *sess = new SessionThread(uid, restore, this);
703 sessions[uid] = sess;
709 void Core::sslErrors(const QList<QSslError> &errors) {
711 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
713 socket->ignoreSslErrors();
717 void Core::socketError(QAbstractSocket::SocketError err) {
718 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
719 if(socket && err != QAbstractSocket::RemoteHostClosedError)
720 qWarning() << "Core::socketError()" << socket << err << socket->errorString();