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"
30 #include "signalproxy.h"
31 #include "sqlitestorage.h"
37 Core *Core::instanceptr = 0;
40 Core *Core::instance() {
41 if(instanceptr) return instanceptr;
42 instanceptr = new Core();
47 void Core::destroy() {
52 Core::Core() : storage(0) {
53 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
55 // Register storage backends here!
56 registerStorageBackend(new SqliteStorage(this));
58 if(!_storageBackends.count()) {
59 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
60 quWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
61 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
63 exit(1); // TODO make this less brutal (especially for mono client -> popup)
65 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
66 _storageSyncTimer.start(10 * 60 * 1000); // in msecs
74 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
75 quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
77 // try to migrate old settings
78 QVariantMap old = cs.oldDbSettings().toMap();
79 if(old.count() && old["Type"].toString().toUpper() == "SQLITE") {
80 QVariantMap newSettings;
81 newSettings["Backend"] = "SQLite";
82 if((configured = initStorage(newSettings))) {
83 quWarning() << "...but thankfully I found some old settings to migrate!";
84 cs.setStorageSettings(newSettings);
89 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
90 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
91 if(!startListening()) exit(1); // TODO make this less brutal
95 foreach(QTcpSocket *socket, blocksizes.keys()) {
96 socket->disconnectFromHost(); // disconnect non authed clients
99 qDeleteAll(_storageBackends);
102 /*** Session Restore ***/
104 void Core::saveState() {
107 QVariantList activeSessions;
108 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
109 state["CoreStateVersion"] = 1;
110 state["ActiveSessions"] = activeSessions;
111 s.setCoreState(state);
114 void Core::restoreState() {
115 if(!instance()->configured) {
116 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
119 if(instance()->sessions.count()) {
120 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
124 /* We don't check, since we are at the first version since switching to Git
125 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
127 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
131 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
132 if(activeSessions.count() > 0) {
133 quInfo() << "Restoring previous core state...";
134 foreach(QVariant v, activeSessions) {
135 UserId user = v.value<UserId>();
136 instance()->createSession(user, true);
142 QString Core::setupCoreForInternalUsage() {
143 Q_ASSERT(!_storageBackends.isEmpty());
144 QVariantMap setupData;
145 qsrand(QDateTime::currentDateTime().toTime_t());
147 for(int i = 0; i < 10; i++) {
149 pass += qrand() % 10;
151 setupData["AdminUser"] = "AdminUser";
152 setupData["AdminPasswd"] = QString::number(pass);
153 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
154 return setupCore(setupData);
157 QString Core::setupCore(QVariantMap setupData) {
158 QString user = setupData.take("AdminUser").toString();
159 QString password = setupData.take("AdminPasswd").toString();
160 if(user.isEmpty() || password.isEmpty()) {
161 return tr("Admin user or password not set.");
163 if(!initStorage(setupData, true)) {
164 return tr("Could not setup storage!");
167 s.setStorageSettings(setupData);
168 quInfo() << qPrintable(tr("Creating admin user..."));
170 storage->addUser(user, password);
172 startListening(); // TODO check when we need this
176 /*** Storage Handling ***/
178 bool Core::registerStorageBackend(Storage *backend) {
179 if(backend->isAvailable()) {
180 _storageBackends[backend->displayName()] = backend;
183 backend->deleteLater();
188 void Core::unregisterStorageBackend(Storage *backend) {
189 _storageBackends.remove(backend->displayName());
190 backend->deleteLater();
194 // "Type" => "sqlite"
195 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
196 QString backend = dbSettings["Backend"].toString();
197 if(backend.isEmpty()) {
198 //qWarning() << "No storage backend selected!";
199 return configured = false;
202 if(_storageBackends.contains(backend)) {
203 storage = _storageBackends[backend];
205 quError() << "Selected storage backend is not available:" << backend;
206 return configured = false;
208 if(!storage->init(dbSettings)) {
209 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
210 quError() << "Could not init storage!";
212 return configured = false;
215 // delete all other backends
216 foreach(Storage *s, _storageBackends.values()) {
217 if(s != storage) s->deleteLater();
219 _storageBackends.clear();
221 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
222 return configured = true;
225 void Core::syncStorage() {
226 QMutexLocker locker(&mutex);
227 if(storage) storage->sync();
230 /*** Storage Access ***/
231 void Core::setUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
232 QMutexLocker locker(&mutex);
233 instance()->storage->setUserSetting(userId, settingName, data);
236 QVariant Core::getUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
237 QMutexLocker locker(&mutex);
238 return instance()->storage->getUserSetting(userId, settingName, data);
241 bool Core::createNetwork(UserId user, NetworkInfo &info) {
242 QMutexLocker locker(&mutex);
243 NetworkId networkId = instance()->storage->createNetwork(user, info);
244 if(!networkId.isValid())
247 info.networkId = networkId;
251 bool Core::updateNetwork(UserId user, const NetworkInfo &info) {
252 QMutexLocker locker(&mutex);
253 return instance()->storage->updateNetwork(user, info);
256 bool Core::removeNetwork(UserId user, const NetworkId &networkId) {
257 QMutexLocker locker(&mutex);
258 return instance()->storage->removeNetwork(user, networkId);
261 QList<NetworkInfo> Core::networks(UserId user) {
262 QMutexLocker locker(&mutex);
263 return instance()->storage->networks(user);
266 NetworkId Core::networkId(UserId user, const QString &network) {
267 QMutexLocker locker(&mutex);
268 return instance()->storage->getNetworkId(user, network);
271 QList<NetworkId> Core::connectedNetworks(UserId user) {
272 QMutexLocker locker(&mutex);
273 return instance()->storage->connectedNetworks(user);
276 void Core::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) {
277 QMutexLocker locker(&mutex);
278 return instance()->storage->setNetworkConnected(user, networkId, isConnected);
281 QHash<QString, QString> Core::persistentChannels(UserId user, const NetworkId &networkId) {
282 QMutexLocker locker(&mutex);
283 return instance()->storage->persistentChannels(user, networkId);
286 void Core::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) {
287 QMutexLocker locker(&mutex);
288 return instance()->storage->setChannelPersistent(user, networkId, channel, isJoined);
291 void Core::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) {
292 QMutexLocker locker(&mutex);
293 return instance()->storage->setPersistentChannelKey(user, networkId, channel, key);
296 BufferInfo Core::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer) {
297 QMutexLocker locker(&mutex);
298 return instance()->storage->getBufferInfo(user, networkId, type, buffer);
301 BufferInfo Core::getBufferInfo(UserId user, const BufferId &bufferId) {
302 QMutexLocker locker(&mutex);
303 return instance()->storage->getBufferInfo(user, bufferId);
306 MsgId Core::storeMessage(const Message &message) {
307 QMutexLocker locker(&mutex);
308 return instance()->storage->logMessage(message);
311 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, int lastmsgs, int offset) {
312 QMutexLocker locker(&mutex);
313 return instance()->storage->requestMsgs(user, buffer, lastmsgs, offset);
316 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, QDateTime since, int offset) {
317 QMutexLocker locker(&mutex);
318 return instance()->storage->requestMsgs(user, buffer, since, offset);
321 QList<Message> Core::requestMsgRange(UserId user, BufferId buffer, int first, int last) {
322 QMutexLocker locker(&mutex);
323 return instance()->storage->requestMsgRange(user, buffer, first, last);
326 QList<BufferInfo> Core::requestBuffers(UserId user) {
327 QMutexLocker locker(&mutex);
328 return instance()->storage->requestBuffers(user);
331 QList<BufferId> Core::requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
332 QMutexLocker locker(&mutex);
333 return instance()->storage->requestBufferIdsForNetwork(user, networkId);
336 bool Core::removeBuffer(const UserId &user, const BufferId &bufferId) {
337 QMutexLocker locker(&mutex);
338 return instance()->storage->removeBuffer(user, bufferId);
341 BufferId Core::renameBuffer(const UserId &user, const NetworkId &networkId, const QString &newName, const QString &oldName) {
342 QMutexLocker locker(&mutex);
343 return instance()->storage->renameBuffer(user, networkId, newName, oldName);
346 void Core::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) {
347 QMutexLocker locker(&mutex);
348 return instance()->storage->setBufferLastSeenMsg(user, bufferId, msgId);
351 QHash<BufferId, MsgId> Core::bufferLastSeenMsgIds(UserId user) {
352 QMutexLocker locker(&mutex);
353 return instance()->storage->bufferLastSeenMsgIds(user);
356 /*** Network Management ***/
358 bool Core::startListening() {
359 // in mono mode we only start a local port if a port is specified in the cli call
360 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
363 bool success = false;
364 uint port = Quassel::optionValue("port").toUInt();
366 if(_server.listen(QHostAddress::Any, port)) {
367 quInfo() << "Listening for GUI clients on IPv6 port" << _server.serverPort()
368 << "using protocol version" << Quassel::buildInfo().protocolVersion;
371 if(_v6server.listen(QHostAddress::AnyIPv6, port)) {
372 quInfo() << "Listening for GUI clients on IPv4 port" << _v6server.serverPort()
373 << "using protocol version" << Quassel::buildInfo().protocolVersion;
378 quError() << qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(_server.errorString()));
384 void Core::stopListening(const QString &reason) {
385 bool wasListening = false;
386 if(_server.isListening()) {
390 if(_v6server.isListening()) {
396 quInfo() << "No longer listening for GUI clients.";
398 quInfo() << qPrintable(reason);
402 void Core::incomingConnection() {
403 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
405 while(server->hasPendingConnections()) {
406 QTcpSocket *socket = server->nextPendingConnection();
407 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
408 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
409 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
411 QVariantMap clientInfo;
412 blocksizes.insert(socket, (quint32)0);
413 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
416 stopListening(tr("Closing server for basic setup."));
421 void Core::clientHasData() {
422 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
423 Q_ASSERT(socket && blocksizes.contains(socket));
425 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
426 QVariantMap msg = item.toMap();
427 processClientMessage(socket, msg);
428 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
432 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
433 if(!msg.contains("MsgType")) {
434 // Client is way too old, does not even use the current init format
435 quWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
439 // OK, so we have at least an init message format we can understand
440 if(msg["MsgType"] == "ClientInit") {
443 // Just version information -- check it!
444 uint ver = msg["ProtocolVersion"].toUInt();
445 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
446 reply["MsgType"] = "ClientInitReject";
447 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
448 "This core needs at least client/core protocol version %1.<br>"
449 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
450 SignalProxy::writeDataToDevice(socket, reply);
451 quWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
452 socket->close(); return;
455 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
456 reply["CoreDate"] = Quassel::buildInfo().buildDate;
457 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
458 // TODO: Make the core info configurable
459 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
460 int updays = uptime / 86400; uptime %= 86400;
461 int uphours = uptime / 3600; uptime %= 3600;
462 int upmins = uptime / 60;
463 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
465 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
466 .arg(Quassel::buildInfo().buildDate)
467 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
470 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
471 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
472 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
474 bool supportSsl = false;
477 #ifndef QT_NO_COMPRESS
478 bool supportsCompression = true;
480 bool supportsCompression = false;
483 reply["SupportSsl"] = supportSsl;
484 reply["SupportsCompression"] = supportsCompression;
485 // switch to ssl/compression after client has been informed about our capabilities (see below)
487 reply["LoginEnabled"] = true;
489 // check if we are configured, start wizard otherwise
491 reply["Configured"] = false;
492 QList<QVariant> backends;
493 foreach(Storage *backend, _storageBackends.values()) {
495 v["DisplayName"] = backend->displayName();
496 v["Description"] = backend->description();
499 reply["StorageBackends"] = backends;
500 reply["LoginEnabled"] = false;
502 reply["Configured"] = true;
504 clientInfo[socket] = msg; // store for future reference
505 reply["MsgType"] = "ClientInitAck";
506 SignalProxy::writeDataToDevice(socket, reply);
509 // after we told the client that we are ssl capable we switch to ssl mode
510 if(supportSsl && msg["UseSsl"].toBool()) {
511 quDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
512 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
513 sslSocket->startServerEncryption();
517 #ifndef QT_NO_COMPRESS
518 if(supportsCompression && msg["UseCompression"].toBool()) {
519 socket->setProperty("UseCompression", true);
520 quDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
525 // for the rest, we need an initialized connection
526 if(!clientInfo.contains(socket)) {
528 reply["MsgType"] = "ClientLoginReject";
529 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
530 SignalProxy::writeDataToDevice(socket, reply);
531 quWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
532 socket->close(); return;
534 if(msg["MsgType"] == "CoreSetupData") {
536 QString result = setupCore(msg["SetupData"].toMap());
537 if(!result.isEmpty()) {
538 reply["MsgType"] = "CoreSetupReject";
539 reply["Error"] = result;
541 reply["MsgType"] = "CoreSetupAck";
543 SignalProxy::writeDataToDevice(socket, reply);
544 } else if(msg["MsgType"] == "ClientLogin") {
547 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
550 reply["MsgType"] = "ClientLoginReject";
551 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
552 SignalProxy::writeDataToDevice(socket, reply);
555 reply["MsgType"] = "ClientLoginAck";
556 SignalProxy::writeDataToDevice(socket, reply);
557 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()));
558 setupClientSession(socket, uid);
563 // Potentially called during the initialization phase (before handing the connection off to the session)
564 void Core::clientDisconnected() {
565 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
567 // here it's safe to call methods on socket!
568 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
569 blocksizes.remove(socket);
570 clientInfo.remove(socket);
571 socket->deleteLater();
573 // we have to crawl through the hashes and see if we find a victim to remove
574 quDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
576 // DO NOT CALL ANY METHODS ON socket!!
577 socket = static_cast<QTcpSocket *>(sender());
579 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
580 while(blockSizeIter != blocksizes.end()) {
581 if(blockSizeIter.key() == socket) {
582 blocksizes.erase(blockSizeIter);
587 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
588 while(clientInfoIter != clientInfo.end()) {
589 if(clientInfoIter.key() == socket) {
590 clientInfo.erase(clientInfoIter);
597 // make server listen again if still not configured
602 // TODO remove unneeded sessions - if necessary/possible...
603 // Suggestion: kill sessions if they are not connected to any network and client.
606 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
607 // Find or create session for validated user
609 if(sessions.contains(uid)) sess = sessions[uid];
610 else sess = createSession(uid);
611 // Hand over socket, session then sends state itself
612 disconnect(socket, 0, this, 0);
613 blocksizes.remove(socket);
614 clientInfo.remove(socket);
616 quWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
619 sess->addClient(socket);
622 void Core::setupInternalClientSession(SignalProxy *proxy) {
625 setupCoreForInternalUsage();
629 UserId uid = storage->internalUser();
632 // Find or create session for validated user
634 if(sessions.contains(uid))
635 sess = sessions[uid];
637 sess = createSession(uid);
638 sess->addClient(proxy);
641 SessionThread *Core::createSession(UserId uid, bool restore) {
642 if(sessions.contains(uid)) {
643 quWarning() << "Calling createSession() when a session for the user already exists!";
646 SessionThread *sess = new SessionThread(uid, restore, this);
647 sessions[uid] = sess;
653 void Core::sslErrors(const QList<QSslError> &errors) {
655 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
657 socket->ignoreSslErrors();
661 void Core::socketError(QAbstractSocket::SocketError err) {
662 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
663 if(socket && err != QAbstractSocket::RemoteHostClosedError)
664 quWarning() << "Core::socketError()" << socket << err << socket->errorString();