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 <QMetaObject>
22 #include <QMetaMethod>
23 #include <QCoreApplication>
26 #include "coresession.h"
27 #include "coresettings.h"
29 #include "signalproxy.h"
30 #include "sqlitestorage.h"
36 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().toUTC(); // for uptime :)
53 loadTranslation(QLocale::system());
55 // Register storage backends here!
56 registerStorageBackend(new SqliteStorage(this));
58 if(!_storageBackends.count()) {
59 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
60 qWarning() << 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); // 10 minutes
74 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
75 qWarning() << "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 qWarning() << "...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 qWarning() << 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..."));
169 storage->addUser(user, password);
170 startListening(); // TODO check when we need this
174 /*** Storage Handling ***/
176 bool Core::registerStorageBackend(Storage *backend) {
177 if(backend->isAvailable()) {
178 _storageBackends[backend->displayName()] = backend;
181 backend->deleteLater();
186 void Core::unregisterStorageBackend(Storage *backend) {
187 _storageBackends.remove(backend->displayName());
188 backend->deleteLater();
192 // "Type" => "sqlite"
193 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
194 QString backend = dbSettings["Backend"].toString();
195 if(backend.isEmpty()) {
196 //qWarning() << "No storage backend selected!";
197 return configured = false;
200 if(_storageBackends.contains(backend)) {
201 storage = _storageBackends[backend];
203 qCritical() << "Selected storage backend is not available:" << backend;
204 return configured = false;
206 if(!storage->init(dbSettings)) {
207 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
208 qCritical() << "Could not init storage!";
210 return configured = false;
213 // delete all other backends
214 foreach(Storage *s, _storageBackends.values()) {
215 if(s != storage) s->deleteLater();
217 _storageBackends.clear();
219 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
220 return configured = true;
223 void Core::syncStorage() {
224 if(storage) storage->sync();
227 /*** Storage Access ***/
228 bool Core::createNetwork(UserId user, NetworkInfo &info) {
229 NetworkId networkId = instance()->storage->createNetwork(user, info);
230 if(!networkId.isValid())
233 info.networkId = networkId;
237 /*** Network Management ***/
239 bool Core::startListening() {
240 // in mono mode we only start a local port if a port is specified in the cli call
241 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
244 bool success = false;
245 uint port = Quassel::optionValue("port").toUInt();
247 if(_server.listen(QHostAddress::Any, port)) {
248 quInfo() << "Listening for GUI clients on IPv4 port" << _server.serverPort()
249 << "using protocol version" << Quassel::buildInfo().protocolVersion;
252 if(_v6server.listen(QHostAddress::AnyIPv6, port)) {
253 quInfo() << "Listening for GUI clients on IPv6 port" << _v6server.serverPort()
254 << "using protocol version" << Quassel::buildInfo().protocolVersion;
259 qCritical() << qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(_server.errorString()));
265 void Core::stopListening(const QString &reason) {
266 bool wasListening = false;
267 if(_server.isListening()) {
271 if(_v6server.isListening()) {
277 quInfo() << "No longer listening for GUI clients.";
279 quInfo() << qPrintable(reason);
283 void Core::incomingConnection() {
284 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
286 while(server->hasPendingConnections()) {
287 QTcpSocket *socket = server->nextPendingConnection();
288 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
289 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
290 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
292 QVariantMap clientInfo;
293 blocksizes.insert(socket, (quint32)0);
294 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
297 stopListening(tr("Closing server for basic setup."));
302 void Core::clientHasData() {
303 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
304 Q_ASSERT(socket && blocksizes.contains(socket));
306 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
307 QVariantMap msg = item.toMap();
308 processClientMessage(socket, msg);
309 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
313 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
314 if(!msg.contains("MsgType")) {
315 // Client is way too old, does not even use the current init format
316 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
320 // OK, so we have at least an init message format we can understand
321 if(msg["MsgType"] == "ClientInit") {
324 // Just version information -- check it!
325 uint ver = msg["ProtocolVersion"].toUInt();
326 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
327 reply["MsgType"] = "ClientInitReject";
328 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
329 "This core needs at least client/core protocol version %1.<br>"
330 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
331 SignalProxy::writeDataToDevice(socket, reply);
332 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
333 socket->close(); return;
336 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
337 reply["CoreDate"] = Quassel::buildInfo().buildDate;
338 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
339 // TODO: Make the core info configurable
340 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
341 int updays = uptime / 86400; uptime %= 86400;
342 int uphours = uptime / 3600; uptime %= 3600;
343 int upmins = uptime / 60;
344 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
346 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
347 .arg(Quassel::buildInfo().buildDate)
348 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
351 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
352 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
353 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
355 bool supportSsl = false;
358 #ifndef QT_NO_COMPRESS
359 bool supportsCompression = true;
361 bool supportsCompression = false;
364 reply["SupportSsl"] = supportSsl;
365 reply["SupportsCompression"] = supportsCompression;
366 // switch to ssl/compression after client has been informed about our capabilities (see below)
368 reply["LoginEnabled"] = true;
370 // check if we are configured, start wizard otherwise
372 reply["Configured"] = false;
373 QList<QVariant> backends;
374 foreach(Storage *backend, _storageBackends.values()) {
376 v["DisplayName"] = backend->displayName();
377 v["Description"] = backend->description();
380 reply["StorageBackends"] = backends;
381 reply["LoginEnabled"] = false;
383 reply["Configured"] = true;
385 clientInfo[socket] = msg; // store for future reference
386 reply["MsgType"] = "ClientInitAck";
387 SignalProxy::writeDataToDevice(socket, reply);
390 // after we told the client that we are ssl capable we switch to ssl mode
391 if(supportSsl && msg["UseSsl"].toBool()) {
392 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
393 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
394 sslSocket->startServerEncryption();
398 #ifndef QT_NO_COMPRESS
399 if(supportsCompression && msg["UseCompression"].toBool()) {
400 socket->setProperty("UseCompression", true);
401 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
406 // for the rest, we need an initialized connection
407 if(!clientInfo.contains(socket)) {
409 reply["MsgType"] = "ClientLoginReject";
410 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
411 SignalProxy::writeDataToDevice(socket, reply);
412 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
413 socket->close(); return;
415 if(msg["MsgType"] == "CoreSetupData") {
417 QString result = setupCore(msg["SetupData"].toMap());
418 if(!result.isEmpty()) {
419 reply["MsgType"] = "CoreSetupReject";
420 reply["Error"] = result;
422 reply["MsgType"] = "CoreSetupAck";
424 SignalProxy::writeDataToDevice(socket, reply);
425 } else if(msg["MsgType"] == "ClientLogin") {
427 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
429 reply["MsgType"] = "ClientLoginReject";
430 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
431 SignalProxy::writeDataToDevice(socket, reply);
434 reply["MsgType"] = "ClientLoginAck";
435 SignalProxy::writeDataToDevice(socket, reply);
436 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()));
437 setupClientSession(socket, uid);
442 // Potentially called during the initialization phase (before handing the connection off to the session)
443 void Core::clientDisconnected() {
444 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
446 // here it's safe to call methods on socket!
447 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
448 blocksizes.remove(socket);
449 clientInfo.remove(socket);
450 socket->deleteLater();
452 // we have to crawl through the hashes and see if we find a victim to remove
453 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
455 // DO NOT CALL ANY METHODS ON socket!!
456 socket = static_cast<QTcpSocket *>(sender());
458 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
459 while(blockSizeIter != blocksizes.end()) {
460 if(blockSizeIter.key() == socket) {
461 blockSizeIter = blocksizes.erase(blockSizeIter);
467 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
468 while(clientInfoIter != clientInfo.end()) {
469 if(clientInfoIter.key() == socket) {
470 clientInfoIter = clientInfo.erase(clientInfoIter);
478 // make server listen again if still not configured
483 // TODO remove unneeded sessions - if necessary/possible...
484 // Suggestion: kill sessions if they are not connected to any network and client.
487 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
488 // Find or create session for validated user
490 if(sessions.contains(uid)) sess = sessions[uid];
491 else sess = createSession(uid);
492 // Hand over socket, session then sends state itself
493 disconnect(socket, 0, this, 0);
494 blocksizes.remove(socket);
495 clientInfo.remove(socket);
497 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
500 sess->addClient(socket);
503 void Core::setupInternalClientSession(SignalProxy *proxy) {
506 setupCoreForInternalUsage();
509 UserId uid = storage->internalUser();
511 // Find or create session for validated user
513 if(sessions.contains(uid))
514 sess = sessions[uid];
516 sess = createSession(uid);
517 sess->addClient(proxy);
520 SessionThread *Core::createSession(UserId uid, bool restore) {
521 if(sessions.contains(uid)) {
522 qWarning() << "Calling createSession() when a session for the user already exists!";
525 SessionThread *sess = new SessionThread(uid, restore, this);
526 sessions[uid] = sess;
532 void Core::sslErrors(const QList<QSslError> &errors) {
534 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
536 socket->ignoreSslErrors();
540 void Core::socketError(QAbstractSocket::SocketError err) {
541 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
542 if(socket && err != QAbstractSocket::RemoteHostClosedError)
543 qWarning() << "Core::socketError()" << socket << err << socket->errorString();