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() == 0) {
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 // check settings version
126 // so far, we only have 1
128 if(s.version() != 1) {
129 qCritical() << "Invalid core settings version, terminating!";
133 // Register storage backends here!
134 registerStorageBackend(new SqliteStorage(this));
136 if(!_storageBackends.count()) {
137 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
138 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
139 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
141 exit(1); // TODO make this less brutal (especially for mono client -> popup)
143 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
144 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
152 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
153 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 if(!initStorage(setupData, true)) {
232 return tr("Could not setup storage!");
235 s.setStorageSettings(setupData);
236 quInfo() << qPrintable(tr("Creating admin user..."));
237 storage->addUser(user, password);
238 startListening(); // TODO check when we need this
242 /*** Storage Handling ***/
244 bool Core::registerStorageBackend(Storage *backend) {
245 if(backend->isAvailable()) {
246 _storageBackends[backend->displayName()] = backend;
249 backend->deleteLater();
254 void Core::unregisterStorageBackend(Storage *backend) {
255 _storageBackends.remove(backend->displayName());
256 backend->deleteLater();
260 // "Type" => "sqlite"
261 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
262 QString backend = dbSettings["Backend"].toString();
263 if(backend.isEmpty()) {
264 //qWarning() << "No storage backend selected!";
265 return configured = false;
268 if(_storageBackends.contains(backend)) {
269 storage = _storageBackends[backend];
271 qCritical() << "Selected storage backend is not available:" << backend;
272 return configured = false;
274 if(!storage->init(dbSettings)) {
275 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
276 qCritical() << "Could not init storage!";
278 return configured = false;
281 // delete all other backends
282 foreach(Storage *s, _storageBackends.values()) {
283 if(s != storage) s->deleteLater();
285 _storageBackends.clear();
287 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
288 return configured = true;
291 void Core::syncStorage() {
292 if(storage) storage->sync();
295 /*** Storage Access ***/
296 bool Core::createNetwork(UserId user, NetworkInfo &info) {
297 NetworkId networkId = instance()->storage->createNetwork(user, info);
298 if(!networkId.isValid())
301 info.networkId = networkId;
305 /*** Network Management ***/
307 bool Core::startListening() {
308 // in mono mode we only start a local port if a port is specified in the cli call
309 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
312 bool success = false;
313 uint port = Quassel::optionValue("port").toUInt();
315 const QString listen = Quassel::optionValue("listen");
316 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
317 if(listen_list.size() > 0) {
318 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
320 if(!addr.setAddress(listen_term)) {
321 qCritical() << qPrintable(
322 tr("Invalid listen address %1")
326 switch(addr.protocol()) {
327 case QAbstractSocket::IPv4Protocol:
328 if(_server.listen(addr, port)) {
329 quInfo() << qPrintable(
330 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
331 .arg(addr.toString())
332 .arg(_server.serverPort())
333 .arg(Quassel::buildInfo().protocolVersion)
337 quWarning() << qPrintable(
338 tr("Could not open IPv4 interface %1:%2: %3")
339 .arg(addr.toString())
341 .arg(_server.errorString()));
343 case QAbstractSocket::IPv6Protocol:
344 if(_v6server.listen(addr, port)) {
345 quInfo() << qPrintable(
346 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
347 .arg(addr.toString())
348 .arg(_v6server.serverPort())
349 .arg(Quassel::buildInfo().protocolVersion)
353 // if v4 succeeded on Any, the port will be already in use - don't display the error then
354 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
355 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
356 quWarning() << qPrintable(
357 tr("Could not open IPv6 interface %1:%2: %3")
358 .arg(addr.toString())
360 .arg(_v6server.errorString()));
364 qCritical() << qPrintable(
365 tr("Invalid listen address %1, unknown network protocol")
374 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
379 void Core::stopListening(const QString &reason) {
380 bool wasListening = false;
381 if(_server.isListening()) {
385 if(_v6server.isListening()) {
391 quInfo() << "No longer listening for GUI clients.";
393 quInfo() << qPrintable(reason);
397 void Core::incomingConnection() {
398 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
400 while(server->hasPendingConnections()) {
401 QTcpSocket *socket = server->nextPendingConnection();
402 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
403 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
404 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
406 QVariantMap clientInfo;
407 blocksizes.insert(socket, (quint32)0);
408 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
411 stopListening(tr("Closing server for basic setup."));
416 void Core::clientHasData() {
417 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
418 Q_ASSERT(socket && blocksizes.contains(socket));
420 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
421 QVariantMap msg = item.toMap();
422 processClientMessage(socket, msg);
423 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
427 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
428 if(!msg.contains("MsgType")) {
429 // Client is way too old, does not even use the current init format
430 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
434 // OK, so we have at least an init message format we can understand
435 if(msg["MsgType"] == "ClientInit") {
438 // Just version information -- check it!
439 uint ver = msg["ProtocolVersion"].toUInt();
440 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
441 reply["MsgType"] = "ClientInitReject";
442 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
443 "This core needs at least client/core protocol version %1.<br>"
444 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
445 SignalProxy::writeDataToDevice(socket, reply);
446 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
447 socket->close(); return;
450 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
451 reply["CoreDate"] = Quassel::buildInfo().buildDate;
452 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
453 // TODO: Make the core info configurable
454 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
455 int updays = uptime / 86400; uptime %= 86400;
456 int uphours = uptime / 3600; uptime %= 3600;
457 int upmins = uptime / 60;
458 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
460 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
461 .arg(Quassel::buildInfo().buildDate)
462 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
465 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
466 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
467 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
469 bool supportSsl = false;
472 #ifndef QT_NO_COMPRESS
473 bool supportsCompression = true;
475 bool supportsCompression = false;
478 reply["SupportSsl"] = supportSsl;
479 reply["SupportsCompression"] = supportsCompression;
480 // switch to ssl/compression after client has been informed about our capabilities (see below)
482 reply["LoginEnabled"] = true;
484 // check if we are configured, start wizard otherwise
486 reply["Configured"] = false;
487 QList<QVariant> backends;
488 foreach(Storage *backend, _storageBackends.values()) {
490 v["DisplayName"] = backend->displayName();
491 v["Description"] = backend->description();
494 reply["StorageBackends"] = backends;
495 reply["LoginEnabled"] = false;
497 reply["Configured"] = true;
499 clientInfo[socket] = msg; // store for future reference
500 reply["MsgType"] = "ClientInitAck";
501 SignalProxy::writeDataToDevice(socket, reply);
504 // after we told the client that we are ssl capable we switch to ssl mode
505 if(supportSsl && msg["UseSsl"].toBool()) {
506 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
507 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
508 sslSocket->startServerEncryption();
512 #ifndef QT_NO_COMPRESS
513 if(supportsCompression && msg["UseCompression"].toBool()) {
514 socket->setProperty("UseCompression", true);
515 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
520 // for the rest, we need an initialized connection
521 if(!clientInfo.contains(socket)) {
523 reply["MsgType"] = "ClientLoginReject";
524 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
525 SignalProxy::writeDataToDevice(socket, reply);
526 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
527 socket->close(); return;
529 if(msg["MsgType"] == "CoreSetupData") {
531 QString result = setupCore(msg["SetupData"].toMap());
532 if(!result.isEmpty()) {
533 reply["MsgType"] = "CoreSetupReject";
534 reply["Error"] = result;
536 reply["MsgType"] = "CoreSetupAck";
538 SignalProxy::writeDataToDevice(socket, reply);
539 } else if(msg["MsgType"] == "ClientLogin") {
541 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
543 reply["MsgType"] = "ClientLoginReject";
544 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
545 SignalProxy::writeDataToDevice(socket, reply);
548 reply["MsgType"] = "ClientLoginAck";
549 SignalProxy::writeDataToDevice(socket, reply);
550 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()));
551 setupClientSession(socket, uid);
556 // Potentially called during the initialization phase (before handing the connection off to the session)
557 void Core::clientDisconnected() {
558 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
560 // here it's safe to call methods on socket!
561 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
562 blocksizes.remove(socket);
563 clientInfo.remove(socket);
564 socket->deleteLater();
566 // we have to crawl through the hashes and see if we find a victim to remove
567 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
569 // DO NOT CALL ANY METHODS ON socket!!
570 socket = static_cast<QTcpSocket *>(sender());
572 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
573 while(blockSizeIter != blocksizes.end()) {
574 if(blockSizeIter.key() == socket) {
575 blockSizeIter = blocksizes.erase(blockSizeIter);
581 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
582 while(clientInfoIter != clientInfo.end()) {
583 if(clientInfoIter.key() == socket) {
584 clientInfoIter = clientInfo.erase(clientInfoIter);
592 // make server listen again if still not configured
597 // TODO remove unneeded sessions - if necessary/possible...
598 // Suggestion: kill sessions if they are not connected to any network and client.
601 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
602 // Find or create session for validated user
604 if(sessions.contains(uid)) sess = sessions[uid];
605 else sess = createSession(uid);
606 // Hand over socket, session then sends state itself
607 disconnect(socket, 0, this, 0);
608 blocksizes.remove(socket);
609 clientInfo.remove(socket);
611 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
614 sess->addClient(socket);
617 void Core::setupInternalClientSession(SignalProxy *proxy) {
620 setupCoreForInternalUsage();
623 UserId uid = storage->internalUser();
625 // Find or create session for validated user
627 if(sessions.contains(uid))
628 sess = sessions[uid];
630 sess = createSession(uid);
631 sess->addClient(proxy);
634 SessionThread *Core::createSession(UserId uid, bool restore) {
635 if(sessions.contains(uid)) {
636 qWarning() << "Calling createSession() when a session for the user already exists!";
639 SessionThread *sess = new SessionThread(uid, restore, this);
640 sessions[uid] = sess;
646 void Core::sslErrors(const QList<QSslError> &errors) {
648 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
650 socket->ignoreSslErrors();
654 void Core::socketError(QAbstractSocket::SocketError err) {
655 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
656 if(socket && err != QAbstractSocket::RemoteHostClosedError)
657 qWarning() << "Core::socketError()" << socket << err << socket->errorString();