+
+void Core::unregisterStorageBackend(Storage *backend)
+{
+ _storageBackends.remove(backend->displayName());
+ backend->deleteLater();
+}
+
+
+// old db settings:
+// "Type" => "sqlite"
+bool Core::initStorage(const QString &backend, QVariantMap settings, bool setup)
+{
+ _storage = 0;
+
+ if (backend.isEmpty()) {
+ return false;
+ }
+
+ Storage *storage = 0;
+ if (_storageBackends.contains(backend)) {
+ storage = _storageBackends[backend];
+ }
+ else {
+ qCritical() << "Selected storage backend is not available:" << backend;
+ return false;
+ }
+
+ Storage::State storageState = storage->init(settings);
+ switch (storageState) {
+ case Storage::NeedsSetup:
+ if (!setup)
+ return false; // trigger setup process
+ if (storage->setup(settings))
+ return initStorage(backend, settings, false);
+ // if setup wasn't successfull we mark the backend as unavailable
+ case Storage::NotAvailable:
+ qCritical() << "Selected storage backend is not available:" << backend;
+ storage->deleteLater();
+ _storageBackends.remove(backend);
+ storage = 0;
+ return false;
+ case Storage::IsReady:
+ // delete all other backends
+ _storageBackends.remove(backend);
+ unregisterStorageBackends();
+ connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
+ }
+ _storage = storage;
+ return true;
+}
+
+
+bool Core::initStorage(QVariantMap dbSettings, bool setup)
+{
+ return initStorage(dbSettings["Backend"].toString(), dbSettings["ConnectionProperties"].toMap(), setup);
+}
+
+
+void Core::syncStorage()
+{
+ if (_storage)
+ _storage->sync();
+}
+
+
+/*** Storage Access ***/
+bool Core::createNetwork(UserId user, NetworkInfo &info)
+{
+ NetworkId networkId = instance()->_storage->createNetwork(user, info);
+ if (!networkId.isValid())
+ return false;
+
+ info.networkId = networkId;
+ return true;
+}
+
+
+/*** Network Management ***/
+
+bool Core::startListening()
+{
+ // in mono mode we only start a local port if a port is specified in the cli call
+ if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
+ return true;
+
+ bool success = false;
+ uint port = Quassel::optionValue("port").toUInt();
+
+ const QString listen = Quassel::optionValue("listen");
+ const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
+ if (listen_list.size() > 0) {
+ foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
+ QHostAddress addr;
+ if (!addr.setAddress(listen_term)) {
+ qCritical() << qPrintable(
+ tr("Invalid listen address %1")
+ .arg(listen_term)
+ );
+ }
+ else {
+ switch (addr.protocol()) {
+ case QAbstractSocket::IPv6Protocol:
+ if (_v6server.listen(addr, port)) {
+ quInfo() << qPrintable(
+ tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
+ .arg(addr.toString())
+ .arg(_v6server.serverPort())
+ .arg(Quassel::buildInfo().protocolVersion)
+ );
+ success = true;
+ }
+ else
+ quWarning() << qPrintable(
+ tr("Could not open IPv6 interface %1:%2: %3")
+ .arg(addr.toString())
+ .arg(port)
+ .arg(_v6server.errorString()));
+ break;
+ case QAbstractSocket::IPv4Protocol:
+ if (_server.listen(addr, port)) {
+ quInfo() << qPrintable(
+ tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
+ .arg(addr.toString())
+ .arg(_server.serverPort())
+ .arg(Quassel::buildInfo().protocolVersion)
+ );
+ success = true;
+ }
+ else {
+ // if v6 succeeded on Any, the port will be already in use - don't display the error then
+ if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
+ quWarning() << qPrintable(
+ tr("Could not open IPv4 interface %1:%2: %3")
+ .arg(addr.toString())
+ .arg(port)
+ .arg(_server.errorString()));
+ }
+ break;
+ default:
+ qCritical() << qPrintable(
+ tr("Invalid listen address %1, unknown network protocol")
+ .arg(listen_term)
+ );
+ break;
+ }
+ }
+ }
+ }
+ if (!success)
+ quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
+
+ return success;
+}
+
+
+void Core::stopListening(const QString &reason)
+{
+ bool wasListening = false;
+ if (_server.isListening()) {
+ wasListening = true;
+ _server.close();
+ }
+ if (_v6server.isListening()) {
+ wasListening = true;
+ _v6server.close();
+ }
+ if (wasListening) {
+ if (reason.isEmpty())
+ quInfo() << "No longer listening for GUI clients.";
+ else
+ quInfo() << qPrintable(reason);
+ }
+}
+
+
+void Core::incomingConnection()
+{
+ QTcpServer *server = qobject_cast<QTcpServer *>(sender());
+ Q_ASSERT(server);
+ while (server->hasPendingConnections()) {
+ QTcpSocket *socket = server->nextPendingConnection();
+ RemoteConnection *connection = new LegacyConnection(socket, this);
+
+ connect(connection, SIGNAL(disconnected()), SLOT(clientDisconnected()));
+ connect(connection, SIGNAL(dataReceived(QVariant)), SLOT(processClientMessage(QVariant)));
+ connect(connection, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)));
+
+ clientInfo.insert(connection, QVariantMap());
+ quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
+
+ if (!_configured) {
+ stopListening(tr("Closing server for basic setup."));
+ }
+ }
+}
+
+
+void Core::processClientMessage(const QVariant &data)
+{
+ RemoteConnection *connection = qobject_cast<RemoteConnection *>(sender());
+ if (!connection) {
+ qWarning() << Q_FUNC_INFO << "Message not sent by RemoteConnection!";
+ return;
+ }
+
+ QVariantMap msg = data.toMap();
+ if (!msg.contains("MsgType")) {
+ // Client is way too old, does not even use the current init format
+ qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
+ connection->close();
+ return;
+ }
+
+ // OK, so we have at least an init message format we can understand
+ if (msg["MsgType"] == "ClientInit") {
+ QVariantMap reply;
+
+ // Just version information -- check it!
+ uint ver = msg["ProtocolVersion"].toUInt();
+ if (ver < Quassel::buildInfo().coreNeedsProtocol) {
+ reply["MsgType"] = "ClientInitReject";
+ reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
+ "This core needs at least client/core protocol version %1.<br>"
+ "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
+ connection->writeSocketData(reply);
+ qWarning() << qPrintable(tr("Client")) << connection->description() << qPrintable(tr("too old, rejecting."));
+ connection->close();
+ return;
+ }
+
+ reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
+ reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
+ reply["CoreDate"] = Quassel::buildInfo().buildDate;
+ reply["CoreStartTime"] = startTime(); // v10 clients don't necessarily parse this, see below
+
+ // FIXME: newer clients no longer use the hardcoded CoreInfo (for now), since it gets the
+ // time zone wrong. With the next protocol bump (10 -> 11), we should remove this
+ // or make it properly configurable.
+
+ int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
+ int updays = uptime / 86400; uptime %= 86400;
+ int uphours = uptime / 3600; uptime %= 3600;
+ int upmins = uptime / 60;
+ reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
+ "Built: %2<br>"
+ "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
+ .arg(Quassel::buildInfo().buildDate)
+ .arg(updays).arg(uphours, 2, 10, QChar('0')).arg(upmins, 2, 10, QChar('0')).arg(startTime().toString(Qt::TextDate));
+
+ reply["CoreFeatures"] = (int)Quassel::features();
+
+#ifdef HAVE_SSL
+ SslServer *sslServer = qobject_cast<SslServer *>(&_server);
+ QSslSocket *sslSocket = qobject_cast<QSslSocket *>(connection->socket());
+ bool supportSsl = sslServer && sslSocket && sslServer->isCertValid();
+#else
+ bool supportSsl = false;
+#endif
+
+#ifndef QT_NO_COMPRESS
+ bool supportsCompression = true;
+#else
+ bool supportsCompression = false;
+#endif
+
+ reply["SupportSsl"] = supportSsl;
+ reply["SupportsCompression"] = supportsCompression;
+ // switch to ssl/compression after client has been informed about our capabilities (see below)
+
+ reply["LoginEnabled"] = true;
+
+ // check if we are configured, start wizard otherwise
+ if (!_configured) {
+ reply["Configured"] = false;
+ QList<QVariant> backends;
+ foreach(Storage *backend, _storageBackends.values()) {
+ QVariantMap v;
+ v["DisplayName"] = backend->displayName();
+ v["Description"] = backend->description();
+ v["SetupKeys"] = backend->setupKeys();
+ v["SetupDefaults"] = backend->setupDefaults();
+ backends.append(v);
+ }
+ reply["StorageBackends"] = backends;
+ reply["LoginEnabled"] = false;
+ }
+ else {
+ reply["Configured"] = true;
+ }
+ clientInfo[connection] = msg; // store for future reference
+ reply["MsgType"] = "ClientInitAck";
+ connection->writeSocketData(reply);
+ connection->socket()->flush(); // ensure that the write cache is flushed before we switch to ssl
+
+#ifdef HAVE_SSL
+ // after we told the client that we are ssl capable we switch to ssl mode
+ if (supportSsl && msg["UseSsl"].toBool()) {
+ qDebug() << qPrintable(tr("Starting TLS for Client:")) << connection->description();
+ connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors(const QList<QSslError> &)));
+ sslSocket->startServerEncryption();
+ }
+#endif
+
+#ifndef QT_NO_COMPRESS
+ if (supportsCompression && msg["UseCompression"].toBool()) {
+ connection->socket()->setProperty("UseCompression", true);
+ qDebug() << "Using compression for Client:" << qPrintable(connection->socket()->peerAddress().toString());
+ }
+#endif
+ }
+ else {
+ // for the rest, we need an initialized connection
+ if (!clientInfo.contains(connection)) {
+ QVariantMap reply;
+ reply["MsgType"] = "ClientLoginReject";
+ reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
+ connection->writeSocketData(reply);
+ qWarning() << qPrintable(tr("Client")) << qPrintable(connection->socket()->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
+ connection->close(); return;
+ }
+ if (msg["MsgType"] == "CoreSetupData") {
+ QVariantMap reply;
+ QString result = setupCore(msg["SetupData"].toMap());
+ if (!result.isEmpty()) {
+ reply["MsgType"] = "CoreSetupReject";
+ reply["Error"] = result;
+ }
+ else {
+ reply["MsgType"] = "CoreSetupAck";
+ }
+ connection->writeSocketData(reply);
+ }
+ else if (msg["MsgType"] == "ClientLogin") {
+ QVariantMap reply;
+ UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
+ if (uid == 0) {
+ reply["MsgType"] = "ClientLoginReject";
+ reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
+ connection->writeSocketData(reply);
+ return;
+ }
+ reply["MsgType"] = "ClientLoginAck";
+ connection->writeSocketData(reply);
+ quInfo() << qPrintable(tr("Client")) << qPrintable(connection->socket()->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt()));
+ setupClientSession(connection, uid);
+ }
+ }
+}
+
+
+// Potentially called during the initialization phase (before handing the connection off to the session)
+void Core::clientDisconnected()
+{
+ RemoteConnection *connection = qobject_cast<RemoteConnection *>(sender());
+ Q_ASSERT(connection);
+
+ quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(connection->socket()->peerAddress().toString());
+ clientInfo.remove(connection);
+ connection->deleteLater();
+
+ // make server listen again if still not configured
+ if (!_configured) {
+ startListening();
+ }
+
+ // TODO remove unneeded sessions - if necessary/possible...
+ // Suggestion: kill sessions if they are not connected to any network and client.
+}
+
+
+void Core::setupClientSession(RemoteConnection *connection, UserId uid)
+{
+ // From now on everything is handled by the client session
+ disconnect(connection, 0, this, 0);
+ connection->socket()->flush();
+ clientInfo.remove(connection);
+
+ // Find or create session for validated user
+ SessionThread *session;
+ if (sessions.contains(uid)) {
+ session = sessions[uid];
+ }
+ else {
+ session = createSession(uid);
+ if (!session) {
+ qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(connection->socket()->peerAddress().toString());
+ connection->close();
+ return;
+ }
+ }
+
+ // as we are currently handling an event triggered by incoming data on this socket
+ // it is unsafe to directly move the socket to the client thread.
+ QCoreApplication::postEvent(this, new AddClientEvent(connection, uid));
+}
+
+
+void Core::customEvent(QEvent *event)
+{
+ if (event->type() == AddClientEventId) {
+ AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
+ addClientHelper(addClientEvent->connection, addClientEvent->userId);
+ return;