+ }
+ // 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);
+ SignalProxy::writeDataToDevice(socket, reply);
+ qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
+ socket->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 *>(socket);
+ bool supportSsl = (bool)sslServer && (bool)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[socket] = msg; // store for future reference
+ reply["MsgType"] = "ClientInitAck";
+ SignalProxy::writeDataToDevice(socket, reply);
+ 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:")) << qPrintable(socket->peerAddress().toString());
+ connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
+ sslSocket->startServerEncryption();
+ }
+#endif
+
+#ifndef QT_NO_COMPRESS
+ if (supportsCompression && msg["UseCompression"].toBool()) {
+ socket->setProperty("UseCompression", true);
+ qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
+ }
+#endif
+ }
+ else {
+ // for the rest, we need an initialized connection
+ if (!clientInfo.contains(socket)) {
+ 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.");
+ SignalProxy::writeDataToDevice(socket, reply);
+ qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
+ socket->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";
+ }
+ SignalProxy::writeDataToDevice(socket, 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.");
+ SignalProxy::writeDataToDevice(socket, reply);
+ return;
+ }
+ reply["MsgType"] = "ClientLoginAck";
+ SignalProxy::writeDataToDevice(socket, reply);
+ 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()));
+ setupClientSession(socket, uid);
+ }
+ }
+}
+
+
+// Potentially called during the initialization phase (before handing the connection off to the session)
+void Core::clientDisconnected()
+{
+ QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
+ if (socket) {
+ // here it's safe to call methods on socket!
+ quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
+ blocksizes.remove(socket);
+ clientInfo.remove(socket);
+ socket->deleteLater();
+ }
+ else {
+ // we have to crawl through the hashes and see if we find a victim to remove
+ qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
+
+ // DO NOT CALL ANY METHODS ON socket!!
+ socket = static_cast<QTcpSocket *>(sender());
+
+ QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
+ while (blockSizeIter != blocksizes.end()) {
+ if (blockSizeIter.key() == socket) {
+ blockSizeIter = blocksizes.erase(blockSizeIter);
+ }
+ else {
+ blockSizeIter++;
+ }
+ }
+
+ QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
+ while (clientInfoIter != clientInfo.end()) {
+ if (clientInfoIter.key() == socket) {
+ clientInfoIter = clientInfo.erase(clientInfoIter);
+ }
+ else {
+ clientInfoIter++;
+ }
+ }
+ }
+
+ // 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(QTcpSocket *socket, UserId uid)
+{
+ // From now on everything is handled by the client session
+ disconnect(socket, 0, this, 0);
+ socket->flush();
+ blocksizes.remove(socket);
+ clientInfo.remove(socket);
+
+ // 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(socket->peerAddress().toString());
+ socket->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(socket, uid));
+}
+
+
+void Core::customEvent(QEvent *event)
+{
+ if (event->type() == AddClientEventId) {
+ AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
+ addClientHelper(addClientEvent->socket, addClientEvent->userId);
+ return;
+ }
+}
+
+
+void Core::addClientHelper(QTcpSocket *socket, UserId uid)
+{
+ // Find or create session for validated user
+ if (!sessions.contains(uid)) {
+ qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(socket->peerAddress().toString());