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 <QCoreApplication>
24 #include "coresession.h"
25 #include "coresettings.h"
26 #include "postgresqlstorage.h"
28 #include "signalproxy.h"
29 #include "sqlitestorage.h"
38 Core *Core::instanceptr = 0;
40 Core *Core::instance() {
41 if(instanceptr) return instanceptr;
42 instanceptr = new Core();
47 void Core::destroy() {
55 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
57 Quassel::loadTranslation(QLocale::system());
59 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
60 // Move settings, note this does not delete the old files
62 QSettings newSettings("quassel-irc.org", "quasselcore");
66 QSettings::Format format = QSettings::IniFormat;
68 QSettings::Format format = QSettings::NativeFormat;
70 QString newFilePath = Quassel::configDirPath() + "quasselcore"
71 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
72 QSettings newSettings(newFilePath, format);
75 if(newSettings.value("Config/Version").toUInt() == 0) {
77 QString org = "quassel-irc.org";
79 QString org = "Quassel Project";
81 QSettings oldSettings(org, "Quassel Core");
82 if(oldSettings.allKeys().count()) {
83 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
84 foreach(QString key, oldSettings.allKeys())
85 newSettings.setValue(key, oldSettings.value(key));
86 newSettings.setValue("Config/Version", 1);
87 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
89 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
91 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
92 #elif defined Q_WS_MAC
93 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
95 QString quasselDir = QDir::homePath() + "/.quassel/";
98 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
100 // move database, if we found it
101 QFile oldDb(quasselDir + "quassel-storage.sqlite");
103 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
105 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
107 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
111 QFileInfo certInfo(quasselDir + "quasselCert.pem");
112 if(certInfo.exists()) {
113 QFile cert(quasselDir + "quasselCert.pem");
114 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
116 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
118 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
120 #endif /* !Q_WS_MAC */
121 qWarning() << "*** Migration completed.\n\n";
126 // check settings version
127 // so far, we only have 1
129 if(s.version() != 1) {
130 qCritical() << "Invalid core settings version, terminating!";
134 // Register storage backends here!
135 registerStorageBackend(new SqliteStorage(this));
136 registerStorageBackend(new PostgreSqlStorage(this));
138 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
139 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
144 _configured = initStorage(cs.storageSettings().toMap());
147 if(!_storageBackends.count()) {
148 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
149 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
150 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
152 exit(1); // TODO make this less brutal (especially for mono client -> popup)
154 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
157 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
158 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
159 if(!startListening()) exit(1); // TODO make this less brutal
163 foreach(QTcpSocket *socket, blocksizes.keys()) {
164 socket->disconnectFromHost(); // disconnect non authed clients
166 qDeleteAll(sessions);
167 qDeleteAll(_storageBackends);
170 /*** Session Restore ***/
172 void Core::saveState() {
175 QVariantList activeSessions;
176 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
177 state["CoreStateVersion"] = 1;
178 state["ActiveSessions"] = activeSessions;
179 s.setCoreState(state);
182 void Core::restoreState() {
183 if(!instance()->_configured) {
184 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
187 if(instance()->sessions.count()) {
188 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
192 /* We don't check, since we are at the first version since switching to Git
193 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
195 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
199 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
200 if(activeSessions.count() > 0) {
201 quInfo() << "Restoring previous core state...";
202 foreach(QVariant v, activeSessions) {
203 UserId user = v.value<UserId>();
204 instance()->createSession(user, true);
210 QString Core::setupCoreForInternalUsage() {
211 Q_ASSERT(!_storageBackends.isEmpty());
212 QVariantMap setupData;
213 qsrand(QDateTime::currentDateTime().toTime_t());
215 for(int i = 0; i < 10; i++) {
217 pass += qrand() % 10;
219 setupData["AdminUser"] = "AdminUser";
220 setupData["AdminPasswd"] = QString::number(pass);
221 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
222 return setupCore(setupData);
225 QString Core::setupCore(QVariantMap setupData) {
226 QString user = setupData.take("AdminUser").toString();
227 QString password = setupData.take("AdminPasswd").toString();
228 if(user.isEmpty() || password.isEmpty()) {
229 return tr("Admin user or password not set.");
231 _configured = initStorage(setupData, true);
233 return tr("Could not setup storage!");
236 s.setStorageSettings(setupData);
237 quInfo() << qPrintable(tr("Creating admin user..."));
238 _storage->addUser(user, password);
239 startListening(); // TODO check when we need this
243 /*** Storage Handling ***/
245 bool Core::registerStorageBackend(Storage *backend) {
246 if(backend->isAvailable()) {
247 _storageBackends[backend->displayName()] = backend;
250 backend->deleteLater();
255 void Core::unregisterStorageBackend(Storage *backend) {
256 _storageBackends.remove(backend->displayName());
257 backend->deleteLater();
261 // "Type" => "sqlite"
262 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
265 QString backend = dbSettings["Backend"].toString();
266 if(backend.isEmpty()) {
270 Storage *storage = 0;
271 if(_storageBackends.contains(backend)) {
272 storage = _storageBackends[backend];
274 qCritical() << "Selected storage backend is not available:" << backend;
278 QVariantMap connectionProperties = dbSettings["ConnectionProperties"].toMap();
280 Storage::State storageState = storage->init(connectionProperties);
281 switch(storageState) {
282 case Storage::NeedsSetup:
284 return false; // trigger setup process
285 if(storage->setup(connectionProperties))
286 return initStorage(dbSettings, false);
287 // if setup wasn't successfull we mark the backend as unavailable
288 case Storage::NotAvailable:
289 qCritical() << "Selected storage backend is not available:" << backend;
290 storage->deleteLater();
291 _storageBackends.remove(backend);
294 case Storage::IsReady:
295 // delete all other backends
296 foreach(Storage *s, _storageBackends.values()) {
297 if(s != storage) s->deleteLater();
299 _storageBackends.clear();
300 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
306 void Core::syncStorage() {
311 /*** Storage Access ***/
312 bool Core::createNetwork(UserId user, NetworkInfo &info) {
313 NetworkId networkId = instance()->_storage->createNetwork(user, info);
314 if(!networkId.isValid())
317 info.networkId = networkId;
321 /*** Network Management ***/
323 bool Core::startListening() {
324 // in mono mode we only start a local port if a port is specified in the cli call
325 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
328 bool success = false;
329 uint port = Quassel::optionValue("port").toUInt();
331 const QString listen = Quassel::optionValue("listen");
332 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
333 if(listen_list.size() > 0) {
334 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
336 if(!addr.setAddress(listen_term)) {
337 qCritical() << qPrintable(
338 tr("Invalid listen address %1")
342 switch(addr.protocol()) {
343 case QAbstractSocket::IPv4Protocol:
344 if(_server.listen(addr, port)) {
345 quInfo() << qPrintable(
346 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
347 .arg(addr.toString())
348 .arg(_server.serverPort())
349 .arg(Quassel::buildInfo().protocolVersion)
353 quWarning() << qPrintable(
354 tr("Could not open IPv4 interface %1:%2: %3")
355 .arg(addr.toString())
357 .arg(_server.errorString()));
359 case QAbstractSocket::IPv6Protocol:
360 if(_v6server.listen(addr, port)) {
361 quInfo() << qPrintable(
362 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
363 .arg(addr.toString())
364 .arg(_v6server.serverPort())
365 .arg(Quassel::buildInfo().protocolVersion)
369 // if v4 succeeded on Any, the port will be already in use - don't display the error then
370 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
371 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
372 quWarning() << qPrintable(
373 tr("Could not open IPv6 interface %1:%2: %3")
374 .arg(addr.toString())
376 .arg(_v6server.errorString()));
380 qCritical() << qPrintable(
381 tr("Invalid listen address %1, unknown network protocol")
390 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
395 void Core::stopListening(const QString &reason) {
396 bool wasListening = false;
397 if(_server.isListening()) {
401 if(_v6server.isListening()) {
407 quInfo() << "No longer listening for GUI clients.";
409 quInfo() << qPrintable(reason);
413 void Core::incomingConnection() {
414 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
416 while(server->hasPendingConnections()) {
417 QTcpSocket *socket = server->nextPendingConnection();
418 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
419 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
420 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
422 QVariantMap clientInfo;
423 blocksizes.insert(socket, (quint32)0);
424 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
427 stopListening(tr("Closing server for basic setup."));
432 void Core::clientHasData() {
433 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
434 Q_ASSERT(socket && blocksizes.contains(socket));
436 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
437 QVariantMap msg = item.toMap();
438 processClientMessage(socket, msg);
439 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
443 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
444 if(!msg.contains("MsgType")) {
445 // Client is way too old, does not even use the current init format
446 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
450 // OK, so we have at least an init message format we can understand
451 if(msg["MsgType"] == "ClientInit") {
454 // Just version information -- check it!
455 uint ver = msg["ProtocolVersion"].toUInt();
456 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
457 reply["MsgType"] = "ClientInitReject";
458 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
459 "This core needs at least client/core protocol version %1.<br>"
460 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
461 SignalProxy::writeDataToDevice(socket, reply);
462 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
463 socket->close(); return;
466 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
467 reply["CoreDate"] = Quassel::buildInfo().buildDate;
468 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
469 // TODO: Make the core info configurable
470 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
471 int updays = uptime / 86400; uptime %= 86400;
472 int uphours = uptime / 3600; uptime %= 3600;
473 int upmins = uptime / 60;
474 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
476 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
477 .arg(Quassel::buildInfo().buildDate)
478 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
481 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
482 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
483 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
485 bool supportSsl = false;
488 #ifndef QT_NO_COMPRESS
489 bool supportsCompression = true;
491 bool supportsCompression = false;
494 reply["SupportSsl"] = supportSsl;
495 reply["SupportsCompression"] = supportsCompression;
496 // switch to ssl/compression after client has been informed about our capabilities (see below)
498 reply["LoginEnabled"] = true;
500 // check if we are configured, start wizard otherwise
502 reply["Configured"] = false;
503 QList<QVariant> backends;
504 foreach(Storage *backend, _storageBackends.values()) {
506 v["DisplayName"] = backend->displayName();
507 v["Description"] = backend->description();
508 v["ConnectionProperties"] = backend->setupKeys();
509 qDebug() << backend->setupKeys();
512 reply["StorageBackends"] = backends;
513 reply["LoginEnabled"] = false;
515 reply["Configured"] = true;
517 clientInfo[socket] = msg; // store for future reference
518 reply["MsgType"] = "ClientInitAck";
519 SignalProxy::writeDataToDevice(socket, reply);
522 // after we told the client that we are ssl capable we switch to ssl mode
523 if(supportSsl && msg["UseSsl"].toBool()) {
524 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
525 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
526 sslSocket->startServerEncryption();
530 #ifndef QT_NO_COMPRESS
531 if(supportsCompression && msg["UseCompression"].toBool()) {
532 socket->setProperty("UseCompression", true);
533 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
538 // for the rest, we need an initialized connection
539 if(!clientInfo.contains(socket)) {
541 reply["MsgType"] = "ClientLoginReject";
542 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
543 SignalProxy::writeDataToDevice(socket, reply);
544 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
545 socket->close(); return;
547 if(msg["MsgType"] == "CoreSetupData") {
549 QString result = setupCore(msg["SetupData"].toMap());
550 if(!result.isEmpty()) {
551 reply["MsgType"] = "CoreSetupReject";
552 reply["Error"] = result;
554 reply["MsgType"] = "CoreSetupAck";
556 SignalProxy::writeDataToDevice(socket, reply);
557 } else if(msg["MsgType"] == "ClientLogin") {
559 UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
561 reply["MsgType"] = "ClientLoginReject";
562 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
563 SignalProxy::writeDataToDevice(socket, reply);
566 reply["MsgType"] = "ClientLoginAck";
567 SignalProxy::writeDataToDevice(socket, reply);
568 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()));
569 setupClientSession(socket, uid);
574 // Potentially called during the initialization phase (before handing the connection off to the session)
575 void Core::clientDisconnected() {
576 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
578 // here it's safe to call methods on socket!
579 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
580 blocksizes.remove(socket);
581 clientInfo.remove(socket);
582 socket->deleteLater();
584 // we have to crawl through the hashes and see if we find a victim to remove
585 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
587 // DO NOT CALL ANY METHODS ON socket!!
588 socket = static_cast<QTcpSocket *>(sender());
590 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
591 while(blockSizeIter != blocksizes.end()) {
592 if(blockSizeIter.key() == socket) {
593 blockSizeIter = blocksizes.erase(blockSizeIter);
599 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
600 while(clientInfoIter != clientInfo.end()) {
601 if(clientInfoIter.key() == socket) {
602 clientInfoIter = clientInfo.erase(clientInfoIter);
610 // make server listen again if still not configured
615 // TODO remove unneeded sessions - if necessary/possible...
616 // Suggestion: kill sessions if they are not connected to any network and client.
619 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
620 // Find or create session for validated user
622 if(sessions.contains(uid)) sess = sessions[uid];
623 else sess = createSession(uid);
624 // Hand over socket, session then sends state itself
625 disconnect(socket, 0, this, 0);
626 blocksizes.remove(socket);
627 clientInfo.remove(socket);
629 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
632 sess->addClient(socket);
635 void Core::setupInternalClientSession(SignalProxy *proxy) {
638 setupCoreForInternalUsage();
641 UserId uid = _storage->internalUser();
643 // Find or create session for validated user
645 if(sessions.contains(uid))
646 sess = sessions[uid];
648 sess = createSession(uid);
649 sess->addClient(proxy);
652 SessionThread *Core::createSession(UserId uid, bool restore) {
653 if(sessions.contains(uid)) {
654 qWarning() << "Calling createSession() when a session for the user already exists!";
657 SessionThread *sess = new SessionThread(uid, restore, this);
658 sessions[uid] = sess;
664 void Core::sslErrors(const QList<QSslError> &errors) {
666 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
668 socket->ignoreSslErrors();
672 void Core::socketError(QAbstractSocket::SocketError err) {
673 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
674 if(socket && err != QAbstractSocket::RemoteHostClosedError)
675 qWarning() << "Core::socketError()" << socket << err << socket->errorString();