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"
39 Core *Core::instanceptr = 0;
41 Core *Core::instance() {
42 if(instanceptr) return instanceptr;
43 instanceptr = new Core();
48 void Core::destroy() {
53 Core::Core() : storage(0) {
54 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
56 loadTranslation(QLocale::system());
58 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
59 // Move settings, note this does not delete the old files
61 QSettings::Format format = QSettings::IniFormat;
63 QSettings::Format format = QSettings::NativeFormat;
65 QString newFilePath = Quassel::configDirPath() + "quasselcore"
66 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
67 QSettings newSettings(newFilePath, format);
69 if(newSettings.value("Config/Version").toUInt() != 1) {
70 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
72 QString org = "quassel-irc.org";
74 QString org = "Quassel Project";
76 QSettings oldSettings(org, "Quassel Core");
77 if(oldSettings.allKeys().count()) {
78 foreach(QString key, oldSettings.allKeys())
79 newSettings.setValue(key, oldSettings.value(key));
80 newSettings.setValue("Config/Version", 1);
81 qWarning() << "* Your core settings have been migrated to" << newFilePath;
84 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
85 #elif defined Q_WS_MAC
86 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
88 QString quasselDir = QDir::homePath() + "/.quassel/";
91 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
93 // move database, if we found it
94 QFile oldDb(quasselDir + "quassel-storage.sqlite");
96 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
98 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
100 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
104 QFileInfo certInfo(quasselDir + "quasselCert.pem");
105 if(certInfo.exists()) {
106 QFile cert(quasselDir + "quasselCert.pem");
107 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
109 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
111 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
113 qWarning() << "*** Migration completed.\n\n";
119 // Register storage backends here!
120 registerStorageBackend(new SqliteStorage(this));
122 if(!_storageBackends.count()) {
123 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
124 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
125 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
127 exit(1); // TODO make this less brutal (especially for mono client -> popup)
129 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
130 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
138 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
139 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
143 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
144 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
145 if(!startListening()) exit(1); // TODO make this less brutal
149 foreach(QTcpSocket *socket, blocksizes.keys()) {
150 socket->disconnectFromHost(); // disconnect non authed clients
152 qDeleteAll(sessions);
153 qDeleteAll(_storageBackends);
156 /*** Session Restore ***/
158 void Core::saveState() {
161 QVariantList activeSessions;
162 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
163 state["CoreStateVersion"] = 1;
164 state["ActiveSessions"] = activeSessions;
165 s.setCoreState(state);
168 void Core::restoreState() {
169 if(!instance()->configured) {
170 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
173 if(instance()->sessions.count()) {
174 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
178 /* We don't check, since we are at the first version since switching to Git
179 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
181 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
185 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
186 if(activeSessions.count() > 0) {
187 quInfo() << "Restoring previous core state...";
188 foreach(QVariant v, activeSessions) {
189 UserId user = v.value<UserId>();
190 instance()->createSession(user, true);
196 QString Core::setupCoreForInternalUsage() {
197 Q_ASSERT(!_storageBackends.isEmpty());
198 QVariantMap setupData;
199 qsrand(QDateTime::currentDateTime().toTime_t());
201 for(int i = 0; i < 10; i++) {
203 pass += qrand() % 10;
205 setupData["AdminUser"] = "AdminUser";
206 setupData["AdminPasswd"] = QString::number(pass);
207 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
208 return setupCore(setupData);
211 QString Core::setupCore(QVariantMap setupData) {
212 QString user = setupData.take("AdminUser").toString();
213 QString password = setupData.take("AdminPasswd").toString();
214 if(user.isEmpty() || password.isEmpty()) {
215 return tr("Admin user or password not set.");
217 if(!initStorage(setupData, true)) {
218 return tr("Could not setup storage!");
221 s.setStorageSettings(setupData);
222 quInfo() << qPrintable(tr("Creating admin user..."));
223 storage->addUser(user, password);
224 startListening(); // TODO check when we need this
228 /*** Storage Handling ***/
230 bool Core::registerStorageBackend(Storage *backend) {
231 if(backend->isAvailable()) {
232 _storageBackends[backend->displayName()] = backend;
235 backend->deleteLater();
240 void Core::unregisterStorageBackend(Storage *backend) {
241 _storageBackends.remove(backend->displayName());
242 backend->deleteLater();
246 // "Type" => "sqlite"
247 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
248 QString backend = dbSettings["Backend"].toString();
249 if(backend.isEmpty()) {
250 //qWarning() << "No storage backend selected!";
251 return configured = false;
254 if(_storageBackends.contains(backend)) {
255 storage = _storageBackends[backend];
257 qCritical() << "Selected storage backend is not available:" << backend;
258 return configured = false;
260 if(!storage->init(dbSettings)) {
261 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
262 qCritical() << "Could not init storage!";
264 return configured = false;
267 // delete all other backends
268 foreach(Storage *s, _storageBackends.values()) {
269 if(s != storage) s->deleteLater();
271 _storageBackends.clear();
273 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
274 return configured = true;
277 void Core::syncStorage() {
278 if(storage) storage->sync();
281 /*** Storage Access ***/
282 bool Core::createNetwork(UserId user, NetworkInfo &info) {
283 NetworkId networkId = instance()->storage->createNetwork(user, info);
284 if(!networkId.isValid())
287 info.networkId = networkId;
291 /*** Network Management ***/
293 bool Core::startListening() {
294 // in mono mode we only start a local port if a port is specified in the cli call
295 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
298 bool success = false;
299 uint port = Quassel::optionValue("port").toUInt();
301 const QString listen = Quassel::optionValue("listen");
302 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
303 if(listen_list.size() > 0) {
304 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
306 if(!addr.setAddress(listen_term)) {
307 qCritical() << qPrintable(
308 tr("Invalid listen address %1")
312 switch(addr.protocol()) {
313 case QAbstractSocket::IPv4Protocol:
314 if(_server.listen(addr, port)) {
315 quInfo() << qPrintable(
316 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
317 .arg(addr.toString())
318 .arg(_server.serverPort())
319 .arg(Quassel::buildInfo().protocolVersion)
323 quWarning() << qPrintable(
324 tr("Could not open IPv4 interface %1:%2: %3")
325 .arg(addr.toString())
327 .arg(_server.errorString()));
329 case QAbstractSocket::IPv6Protocol:
330 if(_v6server.listen(addr, port)) {
331 quInfo() << qPrintable(
332 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
333 .arg(addr.toString())
334 .arg(_v6server.serverPort())
335 .arg(Quassel::buildInfo().protocolVersion)
339 // if v4 succeeded on Any, the port will be already in use - don't display the error then
340 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
341 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
342 quWarning() << qPrintable(
343 tr("Could not open IPv6 interface %1:%2: %3")
344 .arg(addr.toString())
346 .arg(_v6server.errorString()));
350 qCritical() << qPrintable(
351 tr("Invalid listen address %1, unknown network protocol")
360 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
365 void Core::stopListening(const QString &reason) {
366 bool wasListening = false;
367 if(_server.isListening()) {
371 if(_v6server.isListening()) {
377 quInfo() << "No longer listening for GUI clients.";
379 quInfo() << qPrintable(reason);
383 void Core::incomingConnection() {
384 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
386 while(server->hasPendingConnections()) {
387 QTcpSocket *socket = server->nextPendingConnection();
388 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
389 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
390 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
392 QVariantMap clientInfo;
393 blocksizes.insert(socket, (quint32)0);
394 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
397 stopListening(tr("Closing server for basic setup."));
402 void Core::clientHasData() {
403 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
404 Q_ASSERT(socket && blocksizes.contains(socket));
406 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
407 QVariantMap msg = item.toMap();
408 processClientMessage(socket, msg);
409 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
413 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
414 if(!msg.contains("MsgType")) {
415 // Client is way too old, does not even use the current init format
416 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
420 // OK, so we have at least an init message format we can understand
421 if(msg["MsgType"] == "ClientInit") {
424 // Just version information -- check it!
425 uint ver = msg["ProtocolVersion"].toUInt();
426 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
427 reply["MsgType"] = "ClientInitReject";
428 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
429 "This core needs at least client/core protocol version %1.<br>"
430 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
431 SignalProxy::writeDataToDevice(socket, reply);
432 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
433 socket->close(); return;
436 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
437 reply["CoreDate"] = Quassel::buildInfo().buildDate;
438 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
439 // TODO: Make the core info configurable
440 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
441 int updays = uptime / 86400; uptime %= 86400;
442 int uphours = uptime / 3600; uptime %= 3600;
443 int upmins = uptime / 60;
444 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
446 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
447 .arg(Quassel::buildInfo().buildDate)
448 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
451 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
452 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
453 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
455 bool supportSsl = false;
458 #ifndef QT_NO_COMPRESS
459 bool supportsCompression = true;
461 bool supportsCompression = false;
464 reply["SupportSsl"] = supportSsl;
465 reply["SupportsCompression"] = supportsCompression;
466 // switch to ssl/compression after client has been informed about our capabilities (see below)
468 reply["LoginEnabled"] = true;
470 // check if we are configured, start wizard otherwise
472 reply["Configured"] = false;
473 QList<QVariant> backends;
474 foreach(Storage *backend, _storageBackends.values()) {
476 v["DisplayName"] = backend->displayName();
477 v["Description"] = backend->description();
480 reply["StorageBackends"] = backends;
481 reply["LoginEnabled"] = false;
483 reply["Configured"] = true;
485 clientInfo[socket] = msg; // store for future reference
486 reply["MsgType"] = "ClientInitAck";
487 SignalProxy::writeDataToDevice(socket, reply);
490 // after we told the client that we are ssl capable we switch to ssl mode
491 if(supportSsl && msg["UseSsl"].toBool()) {
492 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
493 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
494 sslSocket->startServerEncryption();
498 #ifndef QT_NO_COMPRESS
499 if(supportsCompression && msg["UseCompression"].toBool()) {
500 socket->setProperty("UseCompression", true);
501 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
506 // for the rest, we need an initialized connection
507 if(!clientInfo.contains(socket)) {
509 reply["MsgType"] = "ClientLoginReject";
510 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
511 SignalProxy::writeDataToDevice(socket, reply);
512 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
513 socket->close(); return;
515 if(msg["MsgType"] == "CoreSetupData") {
517 QString result = setupCore(msg["SetupData"].toMap());
518 if(!result.isEmpty()) {
519 reply["MsgType"] = "CoreSetupReject";
520 reply["Error"] = result;
522 reply["MsgType"] = "CoreSetupAck";
524 SignalProxy::writeDataToDevice(socket, reply);
525 } else if(msg["MsgType"] == "ClientLogin") {
527 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
529 reply["MsgType"] = "ClientLoginReject";
530 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
531 SignalProxy::writeDataToDevice(socket, reply);
534 reply["MsgType"] = "ClientLoginAck";
535 SignalProxy::writeDataToDevice(socket, reply);
536 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()));
537 setupClientSession(socket, uid);
542 // Potentially called during the initialization phase (before handing the connection off to the session)
543 void Core::clientDisconnected() {
544 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
546 // here it's safe to call methods on socket!
547 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
548 blocksizes.remove(socket);
549 clientInfo.remove(socket);
550 socket->deleteLater();
552 // we have to crawl through the hashes and see if we find a victim to remove
553 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
555 // DO NOT CALL ANY METHODS ON socket!!
556 socket = static_cast<QTcpSocket *>(sender());
558 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
559 while(blockSizeIter != blocksizes.end()) {
560 if(blockSizeIter.key() == socket) {
561 blockSizeIter = blocksizes.erase(blockSizeIter);
567 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
568 while(clientInfoIter != clientInfo.end()) {
569 if(clientInfoIter.key() == socket) {
570 clientInfoIter = clientInfo.erase(clientInfoIter);
578 // make server listen again if still not configured
583 // TODO remove unneeded sessions - if necessary/possible...
584 // Suggestion: kill sessions if they are not connected to any network and client.
587 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
588 // Find or create session for validated user
590 if(sessions.contains(uid)) sess = sessions[uid];
591 else sess = createSession(uid);
592 // Hand over socket, session then sends state itself
593 disconnect(socket, 0, this, 0);
594 blocksizes.remove(socket);
595 clientInfo.remove(socket);
597 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
600 sess->addClient(socket);
603 void Core::setupInternalClientSession(SignalProxy *proxy) {
606 setupCoreForInternalUsage();
609 UserId uid = storage->internalUser();
611 // Find or create session for validated user
613 if(sessions.contains(uid))
614 sess = sessions[uid];
616 sess = createSession(uid);
617 sess->addClient(proxy);
620 SessionThread *Core::createSession(UserId uid, bool restore) {
621 if(sessions.contains(uid)) {
622 qWarning() << "Calling createSession() when a session for the user already exists!";
625 SessionThread *sess = new SessionThread(uid, restore, this);
626 sessions[uid] = sess;
632 void Core::sslErrors(const QList<QSslError> &errors) {
634 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
636 socket->ignoreSslErrors();
640 void Core::socketError(QAbstractSocket::SocketError err) {
641 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
642 if(socket && err != QAbstractSocket::RemoteHostClosedError)
643 qWarning() << "Core::socketError()" << socket << err << socket->errorString();