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"
27 #include "signalproxy.h"
28 #include "sqlitestorage.h"
37 Core *Core::instanceptr = 0;
39 Core *Core::instance() {
40 if(instanceptr) return instanceptr;
41 instanceptr = new Core();
46 void Core::destroy() {
51 Core::Core() : storage(0) {
52 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
54 Quassel::loadTranslation(QLocale::system());
56 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
57 // Move settings, note this does not delete the old files
59 QSettings newSettings("quassel-irc.org", "quasselcore");
63 QSettings::Format format = QSettings::IniFormat;
65 QSettings::Format format = QSettings::NativeFormat;
67 QString newFilePath = Quassel::configDirPath() + "quasselcore"
68 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
69 QSettings newSettings(newFilePath, format);
72 if(newSettings.value("Config/Version").toUInt() == 0) {
74 QString org = "quassel-irc.org";
76 QString org = "Quassel Project";
78 QSettings oldSettings(org, "Quassel Core");
79 if(oldSettings.allKeys().count()) {
80 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
81 foreach(QString key, oldSettings.allKeys())
82 newSettings.setValue(key, oldSettings.value(key));
83 newSettings.setValue("Config/Version", 1);
84 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
86 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
88 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
89 #elif defined Q_WS_MAC
90 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
92 QString quasselDir = QDir::homePath() + "/.quassel/";
95 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
97 // move database, if we found it
98 QFile oldDb(quasselDir + "quassel-storage.sqlite");
100 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
102 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
104 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
108 QFileInfo certInfo(quasselDir + "quasselCert.pem");
109 if(certInfo.exists()) {
110 QFile cert(quasselDir + "quasselCert.pem");
111 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
113 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
115 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
117 #endif /* !Q_WS_MAC */
118 qWarning() << "*** Migration completed.\n\n";
123 // check settings version
124 // so far, we only have 1
126 if(s.version() != 1) {
127 qCritical() << "Invalid core settings version, terminating!";
131 // Register storage backends here!
132 registerStorageBackend(new SqliteStorage(this));
134 if(!_storageBackends.count()) {
135 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
136 qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
137 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
139 exit(1); // TODO make this less brutal (especially for mono client -> popup)
141 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
142 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
150 if(!(configured = initStorage(cs.storageSettings().toMap()))) {
151 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
155 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
156 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
157 if(!startListening()) exit(1); // TODO make this less brutal
163 foreach(QTcpSocket *socket, blocksizes.keys()) {
164 socket->disconnectFromHost(); // disconnect non authed clients
168 foreach(SessionThread *session, sessions) {
169 session->stopSession();
175 // qDeleteAll(sessions);
176 qDeleteAll(_storageBackends);
179 /*** Session Restore ***/
181 void Core::saveState() {
184 QVariantList activeSessions;
185 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
186 state["CoreStateVersion"] = 1;
187 state["ActiveSessions"] = activeSessions;
188 s.setCoreState(state);
191 void Core::restoreState() {
192 if(!instance()->configured) {
193 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
196 if(instance()->sessions.count()) {
197 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
201 /* We don't check, since we are at the first version since switching to Git
202 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
204 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
208 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
209 if(activeSessions.count() > 0) {
210 quInfo() << "Restoring previous core state...";
211 foreach(QVariant v, activeSessions) {
212 UserId user = v.value<UserId>();
213 instance()->createSession(user, true);
219 QString Core::setupCoreForInternalUsage() {
220 Q_ASSERT(!_storageBackends.isEmpty());
221 QVariantMap setupData;
222 qsrand(QDateTime::currentDateTime().toTime_t());
224 for(int i = 0; i < 10; i++) {
226 pass += qrand() % 10;
228 setupData["AdminUser"] = "AdminUser";
229 setupData["AdminPasswd"] = QString::number(pass);
230 setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
231 return setupCore(setupData);
234 QString Core::setupCore(QVariantMap setupData) {
235 QString user = setupData.take("AdminUser").toString();
236 QString password = setupData.take("AdminPasswd").toString();
237 if(user.isEmpty() || password.isEmpty()) {
238 return tr("Admin user or password not set.");
240 if(!initStorage(setupData, true)) {
241 return tr("Could not setup storage!");
244 s.setStorageSettings(setupData);
245 quInfo() << qPrintable(tr("Creating admin user..."));
246 storage->addUser(user, password);
247 startListening(); // TODO check when we need this
251 /*** Storage Handling ***/
253 bool Core::registerStorageBackend(Storage *backend) {
254 if(backend->isAvailable()) {
255 _storageBackends[backend->displayName()] = backend;
258 backend->deleteLater();
263 void Core::unregisterStorageBackend(Storage *backend) {
264 _storageBackends.remove(backend->displayName());
265 backend->deleteLater();
269 // "Type" => "sqlite"
270 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
271 QString backend = dbSettings["Backend"].toString();
272 if(backend.isEmpty()) {
273 //qWarning() << "No storage backend selected!";
274 return configured = false;
277 if(_storageBackends.contains(backend)) {
278 storage = _storageBackends[backend];
280 qCritical() << "Selected storage backend is not available:" << backend;
281 return configured = false;
283 if(!storage->init(dbSettings)) {
284 if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
285 qCritical() << "Could not init storage!";
287 return configured = false;
290 // delete all other backends
291 foreach(Storage *s, _storageBackends.values()) {
292 if(s != storage) s->deleteLater();
294 _storageBackends.clear();
296 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
297 return configured = true;
300 void Core::syncStorage() {
301 if(storage) storage->sync();
304 /*** Storage Access ***/
305 bool Core::createNetwork(UserId user, NetworkInfo &info) {
306 NetworkId networkId = instance()->storage->createNetwork(user, info);
307 if(!networkId.isValid())
310 info.networkId = networkId;
314 /*** Network Management ***/
316 bool Core::startListening() {
317 // in mono mode we only start a local port if a port is specified in the cli call
318 if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
321 bool success = false;
322 uint port = Quassel::optionValue("port").toUInt();
324 const QString listen = Quassel::optionValue("listen");
325 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
326 if(listen_list.size() > 0) {
327 foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
329 if(!addr.setAddress(listen_term)) {
330 qCritical() << qPrintable(
331 tr("Invalid listen address %1")
335 switch(addr.protocol()) {
336 case QAbstractSocket::IPv4Protocol:
337 if(_server.listen(addr, port)) {
338 quInfo() << qPrintable(
339 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
340 .arg(addr.toString())
341 .arg(_server.serverPort())
342 .arg(Quassel::buildInfo().protocolVersion)
346 quWarning() << qPrintable(
347 tr("Could not open IPv4 interface %1:%2: %3")
348 .arg(addr.toString())
350 .arg(_server.errorString()));
352 case QAbstractSocket::IPv6Protocol:
353 if(_v6server.listen(addr, port)) {
354 quInfo() << qPrintable(
355 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
356 .arg(addr.toString())
357 .arg(_v6server.serverPort())
358 .arg(Quassel::buildInfo().protocolVersion)
362 // if v4 succeeded on Any, the port will be already in use - don't display the error then
363 // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
364 if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
365 quWarning() << qPrintable(
366 tr("Could not open IPv6 interface %1:%2: %3")
367 .arg(addr.toString())
369 .arg(_v6server.errorString()));
373 qCritical() << qPrintable(
374 tr("Invalid listen address %1, unknown network protocol")
383 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
388 void Core::stopListening(const QString &reason) {
389 bool wasListening = false;
390 if(_server.isListening()) {
394 if(_v6server.isListening()) {
400 quInfo() << "No longer listening for GUI clients.";
402 quInfo() << qPrintable(reason);
406 void Core::incomingConnection() {
407 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
409 while(server->hasPendingConnections()) {
410 QTcpSocket *socket = server->nextPendingConnection();
411 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
412 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
413 connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
415 QVariantMap clientInfo;
416 blocksizes.insert(socket, (quint32)0);
417 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
420 stopListening(tr("Closing server for basic setup."));
425 void Core::clientHasData() {
426 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
427 Q_ASSERT(socket && blocksizes.contains(socket));
429 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
430 QVariantMap msg = item.toMap();
431 processClientMessage(socket, msg);
432 if(!blocksizes.contains(socket)) break; // this socket is no longer ours to handle!
436 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
437 if(!msg.contains("MsgType")) {
438 // Client is way too old, does not even use the current init format
439 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
443 // OK, so we have at least an init message format we can understand
444 if(msg["MsgType"] == "ClientInit") {
447 // Just version information -- check it!
448 uint ver = msg["ProtocolVersion"].toUInt();
449 if(ver < Quassel::buildInfo().coreNeedsProtocol) {
450 reply["MsgType"] = "ClientInitReject";
451 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
452 "This core needs at least client/core protocol version %1.<br>"
453 "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
454 SignalProxy::writeDataToDevice(socket, reply);
455 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
456 socket->close(); return;
459 reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
460 reply["CoreDate"] = Quassel::buildInfo().buildDate;
461 reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
462 // TODO: Make the core info configurable
463 int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
464 int updays = uptime / 86400; uptime %= 86400;
465 int uphours = uptime / 3600; uptime %= 3600;
466 int upmins = uptime / 60;
467 reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
469 "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
470 .arg(Quassel::buildInfo().buildDate)
471 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
474 SslServer *sslServer = qobject_cast<SslServer *>(&_server);
475 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
476 bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
478 bool supportSsl = false;
481 #ifndef QT_NO_COMPRESS
482 bool supportsCompression = true;
484 bool supportsCompression = false;
487 reply["SupportSsl"] = supportSsl;
488 reply["SupportsCompression"] = supportsCompression;
489 // switch to ssl/compression after client has been informed about our capabilities (see below)
491 reply["LoginEnabled"] = true;
493 // check if we are configured, start wizard otherwise
495 reply["Configured"] = false;
496 QList<QVariant> backends;
497 foreach(Storage *backend, _storageBackends.values()) {
499 v["DisplayName"] = backend->displayName();
500 v["Description"] = backend->description();
503 reply["StorageBackends"] = backends;
504 reply["LoginEnabled"] = false;
506 reply["Configured"] = true;
508 clientInfo[socket] = msg; // store for future reference
509 reply["MsgType"] = "ClientInitAck";
510 SignalProxy::writeDataToDevice(socket, reply);
513 // after we told the client that we are ssl capable we switch to ssl mode
514 if(supportSsl && msg["UseSsl"].toBool()) {
515 qDebug() << qPrintable(tr("Starting TLS for Client:")) << qPrintable(socket->peerAddress().toString());
516 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
517 sslSocket->startServerEncryption();
521 #ifndef QT_NO_COMPRESS
522 if(supportsCompression && msg["UseCompression"].toBool()) {
523 socket->setProperty("UseCompression", true);
524 qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
529 // for the rest, we need an initialized connection
530 if(!clientInfo.contains(socket)) {
532 reply["MsgType"] = "ClientLoginReject";
533 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
534 SignalProxy::writeDataToDevice(socket, reply);
535 qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
536 socket->close(); return;
538 if(msg["MsgType"] == "CoreSetupData") {
540 QString result = setupCore(msg["SetupData"].toMap());
541 if(!result.isEmpty()) {
542 reply["MsgType"] = "CoreSetupReject";
543 reply["Error"] = result;
545 reply["MsgType"] = "CoreSetupAck";
547 SignalProxy::writeDataToDevice(socket, reply);
548 } else if(msg["MsgType"] == "ClientLogin") {
550 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
552 reply["MsgType"] = "ClientLoginReject";
553 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
554 SignalProxy::writeDataToDevice(socket, reply);
557 reply["MsgType"] = "ClientLoginAck";
558 SignalProxy::writeDataToDevice(socket, reply);
559 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()));
560 setupClientSession(socket, uid);
565 // Potentially called during the initialization phase (before handing the connection off to the session)
566 void Core::clientDisconnected() {
567 QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
569 // here it's safe to call methods on socket!
570 quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
571 blocksizes.remove(socket);
572 clientInfo.remove(socket);
573 socket->deleteLater();
575 // we have to crawl through the hashes and see if we find a victim to remove
576 qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
578 // DO NOT CALL ANY METHODS ON socket!!
579 socket = static_cast<QTcpSocket *>(sender());
581 QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
582 while(blockSizeIter != blocksizes.end()) {
583 if(blockSizeIter.key() == socket) {
584 blockSizeIter = blocksizes.erase(blockSizeIter);
590 QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
591 while(clientInfoIter != clientInfo.end()) {
592 if(clientInfoIter.key() == socket) {
593 clientInfoIter = clientInfo.erase(clientInfoIter);
601 // make server listen again if still not configured
606 // TODO remove unneeded sessions - if necessary/possible...
607 // Suggestion: kill sessions if they are not connected to any network and client.
610 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
611 // Find or create session for validated user
613 if(sessions.contains(uid)) sess = sessions[uid];
614 else sess = createSession(uid);
615 // Hand over socket, session then sends state itself
616 disconnect(socket, 0, this, 0);
617 blocksizes.remove(socket);
618 clientInfo.remove(socket);
620 qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
623 sess->addClient(socket);
626 void Core::setupInternalClientSession(SignalProxy *proxy) {
629 setupCoreForInternalUsage();
632 UserId uid = storage->internalUser();
634 // Find or create session for validated user
636 if(sessions.contains(uid))
637 sess = sessions[uid];
639 sess = createSession(uid);
640 sess->addClient(proxy);
643 SessionThread *Core::createSession(UserId uid, bool restore) {
644 if(sessions.contains(uid)) {
645 qWarning() << "Calling createSession() when a session for the user already exists!";
648 SessionThread *sess = new SessionThread(uid, restore, this);
649 sessions[uid] = sess;
655 void Core::sslErrors(const QList<QSslError> &errors) {
657 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
659 socket->ignoreSslErrors();
663 void Core::socketError(QAbstractSocket::SocketError err) {
664 QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
665 if(socket && err != QAbstractSocket::RemoteHostClosedError)
666 qWarning() << "Core::socketError()" << socket << err << socket->errorString();