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 newSettings("quassel-irc.org", "quasselcore");
65 QSettings::Format format = QSettings::IniFormat;
67 QSettings::Format format = QSettings::NativeFormat;
69 QString newFilePath = Quassel::configDirPath() + "quasselcore"
70 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
71 QSettings newSettings(newFilePath, format);
74 if(newSettings.value("Config/Version").toUInt() != 1) {
75 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
77 QString org = "quassel-irc.org";
79 QString org = "Quassel Project";
81 QSettings oldSettings(org, "Quassel Core");
82 if(oldSettings.allKeys().count()) {
83 foreach(QString key, oldSettings.allKeys())
84 newSettings.setValue(key, oldSettings.value(key));
85 newSettings.setValue("Config/Version", 1);
86 qWarning() << "* Your core settings have been migrated to" << newFilePath;
88 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
90 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
91 #elif defined Q_WS_MAC
92 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
94 QString quasselDir = QDir::homePath() + "/.quassel/";
97 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
99 // move database, if we found it
100 QFile oldDb(quasselDir + "quassel-storage.sqlite");
102 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
104 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
106 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
110 QFileInfo certInfo(quasselDir + "quasselCert.pem");
111 if(certInfo.exists()) {
112 QFile cert(quasselDir + "quasselCert.pem");
113 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
115 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
117 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
119 qWarning() << "*** Migration completed.\n\n";
122 #endif /* !Q_WS_MAC */
125 // Register storage backends here!
126 registerStorageBackend(new SqliteStorage(this));
128 if(!_storageBackends.count()) {
129 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
130 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
131 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
133 exit(1); // TODO make this less brutal (especially for mono client -> popup)
135 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
136 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
144 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
145 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
149 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
150 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
151 if(!startListening()) exit(1); // TODO make this less brutal
155 foreach(QTcpSocket *socket, blocksizes.keys()) {
156 socket->disconnectFromHost(); // disconnect non authed clients
158 qDeleteAll(sessions);
159 qDeleteAll(_storageBackends);
162 /*** Session Restore ***/
164 void Core::saveState() {
167 QVariantList activeSessions;
168 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
169 state["CoreStateVersion"] = 1;
170 state["ActiveSessions"] = activeSessions;
171 s.setCoreState(state);
174 void Core::restoreState() {
175 if(!instance()->configured) {
176 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
179 if(instance()->sessions.count()) {
180 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
184 /* We don't check, since we are at the first version since switching to Git
185 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
187 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
191 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
192 if(activeSessions.count() > 0) {
193 quInfo() << "Restoring previous core state...";
194 foreach(QVariant v, activeSessions) {
195 UserId user = v.value<UserId>();
196 instance()->createSession(user, true);
202 QString Core::setupCoreForInternalUsage() {
203 Q_ASSERT(!_storageBackends.isEmpty());
204 QVariantMap setupData;
205 qsrand(QDateTime::currentDateTime().toTime_t());
207 for(int i = 0; i < 10; i++) {
209 pass += qrand() % 10;
211 setupData["AdminUser"] = "AdminUser";
212 setupData["AdminPasswd"] = QString::number(pass);
213 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
214 return setupCore(setupData);
217 QString Core::setupCore(QVariantMap setupData) {
218 QString user = setupData.take("AdminUser").toString();
219 QString password = setupData.take("AdminPasswd").toString();
220 if(user.isEmpty() || password.isEmpty()) {
221 return tr("Admin user or password not set.");
223 if(!initStorage(setupData, true)) {
224 return tr("Could not setup storage!");
227 s.setStorageSettings(setupData);
228 quInfo() << qPrintable(tr("Creating admin user..."));
229 storage->addUser(user, password);
230 startListening(); // TODO check when we need this
234 /*** Storage Handling ***/
236 bool Core::registerStorageBackend(Storage *backend) {
237 if(backend->isAvailable()) {
238 _storageBackends[backend->displayName()] = backend;
241 backend->deleteLater();
246 void Core::unregisterStorageBackend(Storage *backend) {
247 _storageBackends.remove(backend->displayName());
248 backend->deleteLater();
252 // "Type" => "sqlite"
253 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
254 QString backend = dbSettings["Backend"].toString();
255 if(backend.isEmpty()) {
256 //qWarning() << "No storage backend selected!";
257 return configured = false;
260 if(_storageBackends.contains(backend)) {
261 storage = _storageBackends[backend];
263 qCritical() << "Selected storage backend is not available:" << backend;
264 return configured = false;
266 if(!storage->init(dbSettings)) {
267 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
268 qCritical() << "Could not init storage!";
270 return configured = false;
273 // delete all other backends
274 foreach(Storage *s, _storageBackends.values()) {
275 if(s != storage) s->deleteLater();
277 _storageBackends.clear();
279 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
280 return configured = true;
283 void Core::syncStorage() {
284 if(storage) storage->sync();
287 /*** Storage Access ***/
288 bool Core::createNetwork(UserId user, NetworkInfo &info) {
289 NetworkId networkId = instance()->storage->createNetwork(user, info);
290 if(!networkId.isValid())
293 info.networkId = networkId;
297 /*** Network Management ***/
299 bool Core::startListening() {
300 // in mono mode we only start a local port if a port is specified in the cli call
301 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
304 bool success = false;
305 uint port = Quassel::optionValue("port").toUInt();
307 const QString listen = Quassel::optionValue("listen");
308 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
309 if(listen_list.size() > 0) {
310 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
312 if(!addr.setAddress(listen_term)) {
313 qCritical() << qPrintable(
314 tr("Invalid listen address %1")
318 switch(addr.protocol()) {
319 case QAbstractSocket::IPv4Protocol:
320 if(_server.listen(addr, port)) {
321 quInfo() << qPrintable(
322 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
323 .arg(addr.toString())
324 .arg(_server.serverPort())
325 .arg(Quassel::buildInfo().protocolVersion)
329 quWarning() << qPrintable(
330 tr("Could not open IPv4 interface %1:%2: %3")
331 .arg(addr.toString())
333 .arg(_server.errorString()));
335 case QAbstractSocket::IPv6Protocol:
336 if(_v6server.listen(addr, port)) {
337 quInfo() << qPrintable(
338 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
339 .arg(addr.toString())
340 .arg(_v6server.serverPort())
341 .arg(Quassel::buildInfo().protocolVersion)
345 // if v4 succeeded on Any, the port will be already in use - don't display the error then
346 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
347 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
348 quWarning() << qPrintable(
349 tr("Could not open IPv6 interface %1:%2: %3")
350 .arg(addr.toString())
352 .arg(_v6server.errorString()));
356 qCritical() << qPrintable(
357 tr("Invalid listen address %1, unknown network protocol")
366 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
371 void Core::stopListening(const QString &reason) {
372 bool wasListening = false;
373 if(_server.isListening()) {
377 if(_v6server.isListening()) {
383 quInfo() << "No longer listening for GUI clients.";
385 quInfo() << qPrintable(reason);
389 void Core::incomingConnection() {
390 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
392 while(server->hasPendingConnections()) {
393 QTcpSocket *socket = server->nextPendingConnection();
394 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
395 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
396 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
398 QVariantMap clientInfo;
399 blocksizes.insert(socket, (quint32)0);
400 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
403 stopListening(tr("Closing server for basic setup."));
408 void Core::clientHasData() {
409 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
410 Q_ASSERT(socket && blocksizes.contains(socket));
412 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
413 QVariantMap msg = item.toMap();
414 processClientMessage(socket, msg);
415 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
419 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
420 if(!msg.contains("MsgType")) {
421 // Client is way too old, does not even use the current init format
422 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
426 // OK, so we have at least an init message format we can understand
427 if(msg["MsgType"] == "ClientInit") {
430 // Just version information -- check it!
431 uint ver = msg["ProtocolVersion"].toUInt();
432 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
433 reply["MsgType"] = "ClientInitReject";
434 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
435 "This core needs at least client/core protocol version %1.<br>"
436 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
437 SignalProxy::writeDataToDevice(socket, reply);
438 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
439 socket->close(); return;
442 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
443 reply["CoreDate"] = Quassel::buildInfo().buildDate;
444 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
445 // TODO: Make the core info configurable
446 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
447 int updays = uptime / 86400; uptime %= 86400;
448 int uphours = uptime / 3600; uptime %= 3600;
449 int upmins = uptime / 60;
450 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
452 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
453 .arg(Quassel::buildInfo().buildDate)
454 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
457 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
458 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
459 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
461 bool supportSsl = false;
464 #ifndef QT_NO_COMPRESS
465 bool supportsCompression = true;
467 bool supportsCompression = false;
470 reply["SupportSsl"] = supportSsl;
471 reply["SupportsCompression"] = supportsCompression;
472 // switch to ssl/compression after client has been informed about our capabilities (see below)
474 reply["LoginEnabled"] = true;
476 // check if we are configured, start wizard otherwise
478 reply["Configured"] = false;
479 QList<QVariant> backends;
480 foreach(Storage *backend, _storageBackends.values()) {
482 v["DisplayName"] = backend->displayName();
483 v["Description"] = backend->description();
486 reply["StorageBackends"] = backends;
487 reply["LoginEnabled"] = false;
489 reply["Configured"] = true;
491 clientInfo[socket] = msg; // store for future reference
492 reply["MsgType"] = "ClientInitAck";
493 SignalProxy::writeDataToDevice(socket, reply);
496 // after we told the client that we are ssl capable we switch to ssl mode
497 if(supportSsl && msg["UseSsl"].toBool()) {
498 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
499 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
500 sslSocket->startServerEncryption();
504 #ifndef QT_NO_COMPRESS
505 if(supportsCompression && msg["UseCompression"].toBool()) {
506 socket->setProperty("UseCompression", true);
507 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
512 // for the rest, we need an initialized connection
513 if(!clientInfo.contains(socket)) {
515 reply["MsgType"] = "ClientLoginReject";
516 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
517 SignalProxy::writeDataToDevice(socket, reply);
518 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
519 socket->close(); return;
521 if(msg["MsgType"] == "CoreSetupData") {
523 QString result = setupCore(msg["SetupData"].toMap());
524 if(!result.isEmpty()) {
525 reply["MsgType"] = "CoreSetupReject";
526 reply["Error"] = result;
528 reply["MsgType"] = "CoreSetupAck";
530 SignalProxy::writeDataToDevice(socket, reply);
531 } else if(msg["MsgType"] == "ClientLogin") {
533 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
535 reply["MsgType"] = "ClientLoginReject";
536 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
537 SignalProxy::writeDataToDevice(socket, reply);
540 reply["MsgType"] = "ClientLoginAck";
541 SignalProxy::writeDataToDevice(socket, reply);
542 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()));
543 setupClientSession(socket, uid);
548 // Potentially called during the initialization phase (before handing the connection off to the session)
549 void Core::clientDisconnected() {
550 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
552 // here it's safe to call methods on socket!
553 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
554 blocksizes.remove(socket);
555 clientInfo.remove(socket);
556 socket->deleteLater();
558 // we have to crawl through the hashes and see if we find a victim to remove
559 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
561 // DO NOT CALL ANY METHODS ON socket!!
562 socket = static_cast<QTcpSocket *>(sender());
564 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
565 while(blockSizeIter != blocksizes.end()) {
566 if(blockSizeIter.key() == socket) {
567 blockSizeIter = blocksizes.erase(blockSizeIter);
573 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
574 while(clientInfoIter != clientInfo.end()) {
575 if(clientInfoIter.key() == socket) {
576 clientInfoIter = clientInfo.erase(clientInfoIter);
584 // make server listen again if still not configured
589 // TODO remove unneeded sessions - if necessary/possible...
590 // Suggestion: kill sessions if they are not connected to any network and client.
593 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
594 // Find or create session for validated user
596 if(sessions.contains(uid)) sess = sessions[uid];
597 else sess = createSession(uid);
598 // Hand over socket, session then sends state itself
599 disconnect(socket, 0, this, 0);
600 blocksizes.remove(socket);
601 clientInfo.remove(socket);
603 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
606 sess->addClient(socket);
609 void Core::setupInternalClientSession(SignalProxy *proxy) {
612 setupCoreForInternalUsage();
615 UserId uid = storage->internalUser();
617 // Find or create session for validated user
619 if(sessions.contains(uid))
620 sess = sessions[uid];
622 sess = createSession(uid);
623 sess->addClient(proxy);
626 SessionThread *Core::createSession(UserId uid, bool restore) {
627 if(sessions.contains(uid)) {
628 qWarning() << "Calling createSession() when a session for the user already exists!";
631 SessionThread *sess = new SessionThread(uid, restore, this);
632 sessions[uid] = sess;
638 void Core::sslErrors(const QList<QSslError> &errors) {
640 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
642 socket->ignoreSslErrors();
646 void Core::socketError(QAbstractSocket::SocketError err) {
647 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
648 if(socket && err != QAbstractSocket::RemoteHostClosedError)
649 qWarning() << "Core::socketError()" << socket << err << socket->errorString();