1 /***************************************************************************
2 * Copyright (C) 2005-08 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 <QMetaObject>
22 #include <QMetaMethod>
23 #include <QMutexLocker>
24 #include <QCoreApplication>
27 #include "coresession.h"
28 #include "coresettings.h"
29 #include "signalproxy.h"
30 #include "sqlitestorage.h"
35 Core *Core::instanceptr = 0;
38 Core *Core::instance() {
39 if(instanceptr) return instanceptr;
40 instanceptr = new Core();
45 void Core::destroy() {
50 Core::Core() : storage(0) {
51 startTime = QDateTime::currentDateTime(); // for uptime :)
53 // Register storage backends here!
54 registerStorageBackend(new SqliteStorage(this));
56 if(!_storageBackends.count()) {
57 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
58 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
59 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
61 exit(1); // TODO make this less brutal (especially for mono client -> popup)
63 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
64 _storageSyncTimer.start(10 * 60 * 1000); // in msecs
72 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
73 qWarning("Core is currently not configured! Please connect with a Quassel Client for basic setup.");
75 // try to migrate old settings
76 QVariantMap old = cs.oldDbSettings().toMap();
77 if(old.count() && old["Type"].toString().toUpper() == "SQLITE") {
78 QVariantMap newSettings;
79 newSettings["Backend"] = "SQLite";
80 if((configured = initStorage(newSettings))) {
81 qWarning("...but thankfully I found some old settings to migrate!");
82 cs.setStorageSettings(newSettings);
87 connect(&server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
88 if(!startListening(cs.port())) exit(1); // TODO make this less brutal
92 foreach(QTcpSocket *socket, blocksizes.keys()) {
93 socket->disconnectFromHost(); // disconnect non authed clients
96 qDeleteAll(_storageBackends);
99 /*** Session Restore ***/
101 void Core::saveState() {
104 QVariantList activeSessions;
105 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
106 state["CoreStateVersion"] = 1;
107 state["ActiveSessions"] = activeSessions;
108 s.setCoreState(state);
111 void Core::restoreState() {
112 if(!instance()->configured) {
113 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
116 if(instance()->sessions.count()) {
117 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
121 /* We don't check, since we are at the first version since switching to Git
122 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
124 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
128 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
129 if(activeSessions.count() > 0) {
130 qDebug() << "Restoring previous core state...";
131 foreach(QVariant v, activeSessions) {
132 UserId user = v.value<UserId>();
133 instance()->createSession(user, true);
140 QString Core::setupCore(const QVariant &setupData_) {
141 QVariantMap setupData = setupData_.toMap();
142 QString user = setupData.take("AdminUser").toString();
143 QString password = setupData.take("AdminPasswd").toString();
144 if(user.isEmpty() || password.isEmpty()) {
145 return tr("Admin user or password not set.");
147 if(!initStorage(setupData, true)) {
148 return tr("Could not setup storage!");
151 s.setStorageSettings(setupData);
152 qDebug() << qPrintable(tr("Creating admin user..."));
154 storage->addUser(user, password);
156 startListening(); // TODO check when we need this
160 /*** Storage Handling ***/
162 bool Core::registerStorageBackend(Storage *backend) {
163 if(backend->isAvailable()) {
164 _storageBackends[backend->displayName()] = backend;
167 backend->deleteLater();
172 void Core::unregisterStorageBackend(Storage *backend) {
173 _storageBackends.remove(backend->displayName());
174 backend->deleteLater();
178 // "Type" => "sqlite"
179 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
180 QString backend = dbSettings["Backend"].toString();
181 if(backend.isEmpty()) {
182 //qWarning() << "No storage backend selected!";
183 return configured = false;
186 if(_storageBackends.contains(backend)) {
187 storage = _storageBackends[backend];
189 qWarning() << "Selected storage backend is not available:" << backend;
190 return configured = false;
192 if(!storage->init(dbSettings)) {
193 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
194 qWarning() << "Could not init storage!";
196 return configured = false;
199 // delete all other backends
200 foreach(Storage *s, _storageBackends.values()) {
201 if(s != storage) s->deleteLater();
203 _storageBackends.clear();
205 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
206 return configured = true;
209 void Core::syncStorage() {
210 QMutexLocker locker(&mutex);
211 if(storage) storage->sync();
214 /*** Storage Access ***/
215 void Core::setUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
216 QMutexLocker locker(&mutex);
217 instance()->storage->setUserSetting(userId, settingName, data);
220 QVariant Core::getUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
221 QMutexLocker locker(&mutex);
222 return instance()->storage->getUserSetting(userId, settingName, data);
225 bool Core::createNetwork(UserId user, NetworkInfo &info) {
226 QMutexLocker locker(&mutex);
227 NetworkId networkId = instance()->storage->createNetwork(user, info);
228 if(!networkId.isValid())
231 info.networkId = networkId;
235 bool Core::updateNetwork(UserId user, const NetworkInfo &info) {
236 QMutexLocker locker(&mutex);
237 return instance()->storage->updateNetwork(user, info);
240 bool Core::removeNetwork(UserId user, const NetworkId &networkId) {
241 QMutexLocker locker(&mutex);
242 return instance()->storage->removeNetwork(user, networkId);
245 QList<NetworkInfo> Core::networks(UserId user) {
246 QMutexLocker locker(&mutex);
247 return instance()->storage->networks(user);
250 NetworkId Core::networkId(UserId user, const QString &network) {
251 QMutexLocker locker(&mutex);
252 return instance()->storage->getNetworkId(user, network);
255 QList<NetworkId> Core::connectedNetworks(UserId user) {
256 QMutexLocker locker(&mutex);
257 return instance()->storage->connectedNetworks(user);
260 void Core::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) {
261 QMutexLocker locker(&mutex);
262 return instance()->storage->setNetworkConnected(user, networkId, isConnected);
265 QHash<QString, QString> Core::persistentChannels(UserId user, const NetworkId &networkId) {
266 QMutexLocker locker(&mutex);
267 return instance()->storage->persistentChannels(user, networkId);
270 void Core::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) {
271 QMutexLocker locker(&mutex);
272 return instance()->storage->setChannelPersistent(user, networkId, channel, isJoined);
275 void Core::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) {
276 QMutexLocker locker(&mutex);
277 return instance()->storage->setPersistentChannelKey(user, networkId, channel, key);
280 BufferInfo Core::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer) {
281 QMutexLocker locker(&mutex);
282 return instance()->storage->getBufferInfo(user, networkId, type, buffer);
285 BufferInfo Core::getBufferInfo(UserId user, const BufferId &bufferId) {
286 QMutexLocker locker(&mutex);
287 return instance()->storage->getBufferInfo(user, bufferId);
290 MsgId Core::storeMessage(const Message &message) {
291 QMutexLocker locker(&mutex);
292 return instance()->storage->logMessage(message);
295 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, int lastmsgs, int offset) {
296 QMutexLocker locker(&mutex);
297 return instance()->storage->requestMsgs(user, buffer, lastmsgs, offset);
300 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, QDateTime since, int offset) {
301 QMutexLocker locker(&mutex);
302 return instance()->storage->requestMsgs(user, buffer, since, offset);
305 QList<Message> Core::requestMsgRange(UserId user, BufferId buffer, int first, int last) {
306 QMutexLocker locker(&mutex);
307 return instance()->storage->requestMsgRange(user, buffer, first, last);
310 QList<BufferInfo> Core::requestBuffers(UserId user) {
311 QMutexLocker locker(&mutex);
312 return instance()->storage->requestBuffers(user);
315 QList<BufferId> Core::requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
316 QMutexLocker locker(&mutex);
317 return instance()->storage->requestBufferIdsForNetwork(user, networkId);
320 bool Core::removeBuffer(const UserId &user, const BufferId &bufferId) {
321 QMutexLocker locker(&mutex);
322 return instance()->storage->removeBuffer(user, bufferId);
325 BufferId Core::renameBuffer(const UserId &user, const NetworkId &networkId, const QString &newName, const QString &oldName) {
326 QMutexLocker locker(&mutex);
327 return instance()->storage->renameBuffer(user, networkId, newName, oldName);
330 void Core::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) {
331 QMutexLocker locker(&mutex);
332 return instance()->storage->setBufferLastSeenMsg(user, bufferId, msgId);
335 QHash<BufferId, MsgId> Core::bufferLastSeenMsgIds(UserId user) {
336 QMutexLocker locker(&mutex);
337 return instance()->storage->bufferLastSeenMsgIds(user);
340 /*** Network Management ***/
342 bool Core::startListening(uint port) {
343 bool success = false;
345 // let's see if ipv6 is available
346 success = server.listen(QHostAddress::AnyIPv6, port);
348 if(!success && server.serverError() == QAbstractSocket::UnsupportedSocketOperationError) {
350 success = server.listen(QHostAddress::Any, port);
354 qWarning("%s", qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())));
356 qDebug() << "Listening for GUI clients on port" << server.serverPort();
362 void Core::stopListening() {
364 qDebug() << "No longer listening for GUI clients.";
367 void Core::incomingConnection() {
368 while(server.hasPendingConnections()) {
369 QTcpSocket *socket = server.nextPendingConnection();
370 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
371 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
372 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
374 QVariantMap clientInfo;
375 blocksizes.insert(socket, (quint32)0);
376 qDebug() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
380 qDebug() << "Closing server for basic setup.";
385 void Core::clientHasData() {
386 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
387 Q_ASSERT(socket && blocksizes.contains(socket));
389 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
390 QVariantMap msg = item.toMap();
391 processClientMessage(socket, msg);
392 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
396 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
397 if(!msg.contains("MsgType")) {
398 // Client is way too old, does not even use the current init format
399 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
403 // OK, so we have at least an init message format we can understand
404 if(msg["MsgType"] == "ClientInit") {
407 // Just version information -- check it!
409 if(!msg.contains("ProtocolVersion") && msg["ClientBuild"].toUInt() >= 732) ver = 1; // FIXME legacy
410 if(msg.contains("ProtocolVersion")) ver = msg["ProtocolVersion"].toUInt();
411 if(ver < Global::coreNeedsProtocol) {
412 reply["MsgType"] = "ClientInitReject";
413 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
414 "This core needs at least client/core protocol version %1.<br>"
415 "Please consider upgrading your client.").arg(Global::coreNeedsProtocol);
416 SignalProxy::writeDataToDevice(socket, reply);
417 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
418 socket->close(); return;
421 reply["CoreVersion"] = Global::quasselVersion;
422 reply["CoreDate"] = Global::quasselBuildDate;
423 reply["CoreBuild"] = 860; // FIXME legacy
424 reply["ProtocolVersion"] = Global::protocolVersion;
425 // TODO: Make the core info configurable
426 int uptime = startTime.secsTo(QDateTime::currentDateTime());
427 int updays = uptime / 86400; uptime %= 86400;
428 int uphours = uptime / 3600; uptime %= 3600;
429 int upmins = uptime / 60;
430 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
432 "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuildDate)
433 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime.toString(Qt::TextDate));
435 #ifndef QT_NO_OPENSSL
436 SslServer *sslServer = qobject_cast<SslServer *>(&server);
437 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
438 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
440 bool supportSsl = false;
443 #ifndef QT_NO_COMPRESS
444 bool supportsCompression = true;
446 bool supportsCompression = false;
449 reply["SupportSsl"] = supportSsl;
450 reply["SupportsCompression"] = supportsCompression;
451 // switch to ssl/compression after client has been informed about our capabilities (see below)
453 reply["LoginEnabled"] = true;
455 // check if we are configured, start wizard otherwise
457 reply["Configured"] = false;
458 QList<QVariant> backends;
459 foreach(Storage *backend, _storageBackends.values()) {
461 v["DisplayName"] = backend->displayName();
462 v["Description"] = backend->description();
465 reply["StorageBackends"] = backends;
466 reply["LoginEnabled"] = false;
468 reply["Configured"] = true;
470 clientInfo[socket] = msg; // store for future reference
471 reply["MsgType"] = "ClientInitAck";
472 SignalProxy::writeDataToDevice(socket, reply);
474 #ifndef QT_NO_OPENSSL
475 // after we told the client that we are ssl capable we switch to ssl mode
476 if(supportSsl && msg["UseSsl"].toBool()) {
477 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
478 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
479 sslSocket->startServerEncryption();
483 #ifndef QT_NO_COMPRESS
484 if(supportsCompression && msg["UseCompression"].toBool()) {
485 socket->setProperty("UseCompression", true);
486 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
491 // for the rest, we need an initialized connection
492 if(!clientInfo.contains(socket)) {
494 reply["MsgType"] = "ClientLoginReject";
495 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
496 SignalProxy::writeDataToDevice(socket, reply);
497 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
498 socket->close(); return;
500 if(msg["MsgType"] == "CoreSetupData") {
502 QString result = setupCore(msg["SetupData"]);
503 if(!result.isEmpty()) {
504 reply["MsgType"] = "CoreSetupReject";
505 reply["Error"] = result;
507 reply["MsgType"] = "CoreSetupAck";
509 SignalProxy::writeDataToDevice(socket, reply);
510 } else if(msg["MsgType"] == "ClientLogin") {
513 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
516 reply["MsgType"] = "ClientLoginReject";
517 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
518 SignalProxy::writeDataToDevice(socket, reply);
521 reply["MsgType"] = "ClientLoginAck";
522 SignalProxy::writeDataToDevice(socket, reply);
523 qDebug() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt()));
524 setupClientSession(socket, uid);
529 // Potentially called during the initialization phase (before handing the connection off to the session)
530 void Core::clientDisconnected() {
531 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
533 // here it's safe to call methods on socket!
534 qDebug() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
535 socket->deleteLater();
537 // we have to crawl through the hashes and see if we find a victim to remove
539 // DO NOT CALL ANY METHODS ON socket!!
540 socket = static_cast<QTcpSocket *>(sender());
542 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
543 while(blockSizeIter != blocksizes.end()) {
544 if(blockSizeIter.key() == socket) {
545 blocksizes.erase(blockSizeIter);
550 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
551 while(clientInfoIter != clientInfo.end()) {
552 if(clientInfoIter.key() == socket) {
553 clientInfo.erase(clientInfoIter);
560 // make server listen again if still not configured
565 // TODO remove unneeded sessions - if necessary/possible...
566 // Suggestion: kill sessions if they are not connected to any network and client.
569 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
570 // Find or create session for validated user
572 if(sessions.contains(uid)) sess = sessions[uid];
573 else sess = createSession(uid);
574 // Hand over socket, session then sends state itself
575 disconnect(socket, 0, this, 0);
576 blocksizes.remove(socket);
577 clientInfo.remove(socket);
579 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
582 sess->addClient(socket);
585 SessionThread *Core::createSession(UserId uid, bool restore) {
586 if(sessions.contains(uid)) {
587 qWarning() << "Calling createSession() when a session for the user already exists!";
590 SessionThread *sess = new SessionThread(uid, restore, this);
591 sessions[uid] = sess;
596 #ifndef QT_NO_OPENSSL
597 void Core::sslErrors(const QList<QSslError> &errors) {
599 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
601 socket->ignoreSslErrors();
605 void Core::socketError(QAbstractSocket::SocketError err) {
606 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
607 if(socket && err != QAbstractSocket::RemoteHostClosedError)
608 qDebug() << "Core::socketError()" << socket << err << socket->errorString();