1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <QHostAddress>
22 #include <QDataStream>
25 #include "legacypeer.h"
28 /* version.inc is no longer used for this */
29 const uint protocolVersion = 10;
30 const uint coreNeedsProtocol = protocolVersion;
31 const uint clientNeedsProtocol = protocolVersion;
33 using namespace Protocol;
35 LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
36 : RemotePeer(authHandler, socket, level, parent),
37 _useCompression(false)
43 void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
45 RemotePeer::setSignalProxy(proxy);
47 // FIXME only in compat mode
49 // enable compression now if requested - the initial handshake is uncompressed in the legacy protocol!
50 _useCompression = socket()->property("UseCompression").toBool();
52 qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
58 void LegacyPeer::processMessage(const QByteArray &msg)
60 QDataStream stream(msg);
61 stream.setVersion(QDataStream::Qt_4_2);
64 if (_useCompression) {
68 int nbytes = rawItem.size();
70 const char *data = rawItem.constData();
71 if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) {
72 close("Peer sent corrupted compressed data!");
77 rawItem = qUncompress(rawItem);
79 QDataStream itemStream(&rawItem, QIODevice::ReadOnly);
80 itemStream.setVersion(QDataStream::Qt_4_2);
87 if (stream.status() != QDataStream::Ok || !item.isValid()) {
88 close("Peer sent corrupt data: unable to load QVariant!");
92 // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
94 handleHandshakeMessage(item);
96 handlePackedFunc(item);
100 void LegacyPeer::writeMessage(const QVariant &item)
103 QDataStream out(&block, QIODevice::WriteOnly);
104 out.setVersion(QDataStream::Qt_4_2);
106 if (_useCompression) {
108 QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
109 itemStream.setVersion(QDataStream::Qt_4_2);
112 rawItem = qCompress(rawItem);
124 /*** Handshake messages ***/
126 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
127 * a structure different from those being used after the handshake.
128 * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
131 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
133 QVariantMap m = msg.toMap();
135 QString msgType = m["MsgType"].toString();
136 if (msgType.isEmpty()) {
137 emit protocolError(tr("Invalid handshake message!"));
141 if (msgType == "ClientInit") {
142 // FIXME only in compat mode
143 uint ver = m["ProtocolVersion"].toUInt();
144 if (ver < coreNeedsProtocol) {
145 emit protocolVersionMismatch((int)ver, (int)coreNeedsProtocol);
149 #ifndef QT_NO_COMPRESS
150 // FIXME only in compat mode
151 if (m["UseCompression"].toBool()) {
152 socket()->setProperty("UseCompression", true);
155 handle(RegisterClient{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())},
156 m["ClientVersion"].toString(),
157 m["ClientDate"].toString(),
158 m["UseSsl"].toBool()});
161 else if (msgType == "ClientInitReject") {
162 handle(ClientDenied(m["Error"].toString()));
165 else if (msgType == "ClientInitAck") {
166 // FIXME only in compat mode
167 uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
168 if (ver < clientNeedsProtocol) {
169 emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol);
172 #ifndef QT_NO_COMPRESS
173 if (m["SupportsCompression"].toBool())
174 socket()->setProperty("UseCompression", true);
177 handle(ClientRegistered{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())},
178 m["Configured"].toBool(),
179 m["StorageBackends"].toList(),
180 m["Authenticators"].toList(),
181 m["SupportSsl"].toBool()});
184 else if (msgType == "CoreSetupData") {
185 QVariantMap map = m["SetupData"].toMap();
186 handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
189 else if (msgType == "CoreSetupReject") {
190 handle(SetupFailed(m["Error"].toString()));
193 else if (msgType == "CoreSetupAck") {
197 else if (msgType == "ClientLogin") {
198 handle(Login(m["User"].toString(), m["Password"].toString()));
201 else if (msgType == "ClientLoginReject") {
202 handle(LoginFailed(m["Error"].toString()));
205 else if (msgType == "ClientLoginAck") {
206 handle(LoginSuccess());
209 else if (msgType == "SessionInit") {
210 QVariantMap map = m["SessionState"].toMap();
211 handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
215 emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
220 void LegacyPeer::dispatch(const RegisterClient &msg) {
222 m["MsgType"] = "ClientInit";
223 m["Features"] = static_cast<quint32>(msg.features.toLegacyFeatures());
224 m["FeatureList"] = msg.features.toStringList();
225 m["ClientVersion"] = msg.clientVersion;
226 m["ClientDate"] = msg.buildDate;
228 // FIXME only in compat mode
229 m["ProtocolVersion"] = protocolVersion;
230 m["UseSsl"] = msg.sslSupported;
231 #ifndef QT_NO_COMPRESS
232 m["UseCompression"] = true;
234 m["UseCompression"] = false;
241 void LegacyPeer::dispatch(const ClientDenied &msg) {
243 m["MsgType"] = "ClientInitReject";
244 m["Error"] = msg.errorString;
250 void LegacyPeer::dispatch(const ClientRegistered &msg) {
252 m["MsgType"] = "ClientInitAck";
253 if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
254 m["FeatureList"] = msg.features.toStringList();
257 m["CoreFeatures"] = static_cast<quint32>(msg.features.toLegacyFeatures());
259 m["StorageBackends"] = msg.backendInfo;
260 if (hasFeature(Quassel::Feature::Authenticators)) {
261 m["Authenticators"] = msg.authenticatorInfo;
264 // FIXME only in compat mode
265 m["ProtocolVersion"] = protocolVersion;
266 m["SupportSsl"] = msg.sslSupported;
267 m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
269 // This is only used for display by really old v10 clients (pre-0.5), and we no longer set this
270 m["CoreInfo"] = QString();
272 m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
278 void LegacyPeer::dispatch(const SetupData &msg)
281 map["AdminUser"] = msg.adminUser;
282 map["AdminPasswd"] = msg.adminPassword;
283 map["Backend"] = msg.backend;
284 map["ConnectionProperties"] = msg.setupData;
286 // Auth backend properties.
287 map["Authenticator"] = msg.authenticator;
288 map["AuthProperties"] = msg.authSetupData;
291 m["MsgType"] = "CoreSetupData";
292 m["SetupData"] = map;
297 void LegacyPeer::dispatch(const SetupFailed &msg)
300 m["MsgType"] = "CoreSetupReject";
301 m["Error"] = msg.errorString;
307 void LegacyPeer::dispatch(const SetupDone &msg)
312 m["MsgType"] = "CoreSetupAck";
318 void LegacyPeer::dispatch(const Login &msg)
321 m["MsgType"] = "ClientLogin";
322 m["User"] = msg.user;
323 m["Password"] = msg.password;
329 void LegacyPeer::dispatch(const LoginFailed &msg)
332 m["MsgType"] = "ClientLoginReject";
333 m["Error"] = msg.errorString;
339 void LegacyPeer::dispatch(const LoginSuccess &msg)
344 m["MsgType"] = "ClientLoginAck";
350 void LegacyPeer::dispatch(const SessionState &msg)
353 m["MsgType"] = "SessionInit";
356 map["BufferInfos"] = msg.bufferInfos;
357 map["NetworkIds"] = msg.networkIds;
358 map["Identities"] = msg.identities;
359 m["SessionState"] = map;
365 /*** Standard messages ***/
367 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
369 QVariantList params(packedFunc.toList());
371 if (params.isEmpty()) {
372 qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
376 // TODO: make sure that this is a valid request type
377 RequestType requestType = (RequestType)params.takeFirst().value<int>();
378 switch (requestType) {
380 if (params.count() < 3) {
381 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
384 QByteArray className = params.takeFirst().toByteArray();
385 QString objectName = params.takeFirst().toString();
386 QByteArray slotName = params.takeFirst().toByteArray();
387 handle(Protocol::SyncMessage(className, objectName, slotName, params));
391 if (params.empty()) {
392 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
395 QByteArray slotName = params.takeFirst().toByteArray();
396 handle(Protocol::RpcCall(slotName, params));
400 if (params.count() != 2) {
401 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
404 QByteArray className = params[0].toByteArray();
405 QString objectName = params[1].toString();
406 handle(Protocol::InitRequest(className, objectName));
410 if (params.count() != 3) {
411 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
414 QByteArray className = params[0].toByteArray();
415 QString objectName = params[1].toString();
416 QVariantMap initData = params[2].toMap();
418 // we need to special-case IrcUsersAndChannels here, since the format changed
419 if (className == "Network")
420 fromLegacyIrcUsersAndChannels(initData);
421 handle(Protocol::InitData(className, objectName, initData));
425 if (params.count() != 1) {
426 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
429 // The legacy protocol would only send a QTime, no QDateTime
430 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
431 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
432 dateTime.setTime(params[0].toTime());
433 handle(Protocol::HeartBeat(dateTime));
436 case HeartBeatReply: {
437 if (params.count() != 1) {
438 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
441 // The legacy protocol would only send a QTime, no QDateTime
442 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
443 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
444 dateTime.setTime(params[0].toTime());
445 handle(Protocol::HeartBeatReply(dateTime));
453 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
455 dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
459 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
461 dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
465 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
467 dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
471 void LegacyPeer::dispatch(const Protocol::InitData &msg)
473 // We need to special-case IrcUsersAndChannels, as the format changed
474 if (msg.className == "Network") {
475 QVariantMap initData = msg.initData;
476 toLegacyIrcUsersAndChannels(initData);
477 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << initData);
480 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
484 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
486 dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
490 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
492 dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
496 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
498 writeMessage(QVariant(packedFunc));
502 // Handle the changed format for Network's initData
503 // cf. Network::initIrcUsersAndChannels()
504 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
506 const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
509 QHash<QString, QVariantList> users;
510 foreach(const QVariant &v, legacyMap["users"].toMap().values()) {
511 const QVariantMap &map = v.toMap();
512 foreach(const QString &key, map.keys())
513 users[key] << map[key];
516 foreach(const QString &key, users.keys())
517 userMap[key] = users[key];
518 newMap["Users"] = userMap;
520 QHash<QString, QVariantList> channels;
521 foreach(const QVariant &v, legacyMap["channels"].toMap().values()) {
522 const QVariantMap &map = v.toMap();
523 foreach(const QString &key, map.keys())
524 channels[key] << map[key];
526 QVariantMap channelMap;
527 foreach(const QString &key, channels.keys())
528 channelMap[key] = channels[key];
529 newMap["Channels"] = channelMap;
531 initData["IrcUsersAndChannels"] = newMap;
535 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
537 const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
538 QVariantMap legacyMap;
540 // toMap() and toList() are cheap, so no need to copy to a hash
543 const QVariantMap &users = usersAndChannels["Users"].toMap();
545 int size = users["nick"].toList().size(); // we know this key exists
546 for(int i = 0; i < size; i++) {
548 foreach(const QString &key, users.keys())
549 map[key] = users[key].toList().at(i);
550 QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString());
551 userMap[hostmask.toLower()] = map;
553 legacyMap["users"] = userMap;
555 QVariantMap channelMap;
556 const QVariantMap &channels = usersAndChannels["Channels"].toMap();
558 size = channels["name"].toList().size();
559 for(int i = 0; i < size; i++) {
561 foreach(const QString &key, channels.keys())
562 map[key] = channels[key].toList().at(i);
563 channelMap[map["name"].toString().toLower()] = map;
565 legacyMap["channels"] = channelMap;
567 initData["IrcUsersAndChannels"] = legacyMap;