1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
27 #include "serializers/serializers.h"
29 /* version.inc is no longer used for this */
30 const uint protocolVersion = 10;
31 const uint coreNeedsProtocol = protocolVersion;
32 const uint clientNeedsProtocol = protocolVersion;
34 using namespace Protocol;
36 LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
37 : RemotePeer(authHandler, socket, level, parent),
38 _useCompression(false)
44 void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
46 RemotePeer::setSignalProxy(proxy);
48 // FIXME only in compat mode
50 // enable compression now if requested - the initial handshake is uncompressed in the legacy protocol!
51 _useCompression = socket()->property("UseCompression").toBool();
53 qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
59 void LegacyPeer::processMessage(const QByteArray &msg)
61 QDataStream stream(msg);
62 stream.setVersion(QDataStream::Qt_4_2);
65 if (_useCompression) {
67 if (!Serializers::deserialize(stream, features(), rawItem)) {
68 close("Peer sent corrupt data: unable to load QVariant!");
72 int nbytes = rawItem.size();
74 const char *data = rawItem.constData();
75 if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) {
76 close("Peer sent corrupted compressed data!");
81 rawItem = qUncompress(rawItem);
83 QDataStream itemStream(&rawItem, QIODevice::ReadOnly);
84 itemStream.setVersion(QDataStream::Qt_4_2);
85 if (!Serializers::deserialize(itemStream, features(), item)) {
86 close("Peer sent corrupt data: unable to load QVariant!");
90 if (!Serializers::deserialize(stream, features(), item)) {
91 close("Peer sent corrupt data: unable to load QVariant!");
96 if (stream.status() != QDataStream::Ok || !item.isValid()) {
97 close("Peer sent corrupt data: unable to load QVariant!");
101 // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
103 handleHandshakeMessage(item);
105 handlePackedFunc(item);
109 void LegacyPeer::writeMessage(const QVariant &item)
112 QDataStream out(&block, QIODevice::WriteOnly);
113 out.setVersion(QDataStream::Qt_4_2);
115 if (_useCompression) {
117 QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
118 itemStream.setVersion(QDataStream::Qt_4_2);
121 rawItem = qCompress(rawItem);
133 /*** Handshake messages ***/
135 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
136 * a structure different from those being used after the handshake.
137 * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
140 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
142 QVariantMap m = msg.toMap();
144 QString msgType = m["MsgType"].toString();
145 if (msgType.isEmpty()) {
146 emit protocolError(tr("Invalid handshake message!"));
150 if (msgType == "ClientInit") {
151 // FIXME only in compat mode
152 uint ver = m["ProtocolVersion"].toUInt();
153 if (ver < coreNeedsProtocol) {
154 emit protocolVersionMismatch((int)ver, (int)coreNeedsProtocol);
158 #ifndef QT_NO_COMPRESS
159 // FIXME only in compat mode
160 if (m["UseCompression"].toBool()) {
161 socket()->setProperty("UseCompression", true);
164 handle(RegisterClient{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())},
165 m["ClientVersion"].toString(),
166 m["ClientDate"].toString(),
167 m["UseSsl"].toBool()});
170 else if (msgType == "ClientInitReject") {
171 handle(ClientDenied(m["Error"].toString()));
174 else if (msgType == "ClientInitAck") {
175 // FIXME only in compat mode
176 uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
177 if (ver < clientNeedsProtocol) {
178 emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol);
181 #ifndef QT_NO_COMPRESS
182 if (m["SupportsCompression"].toBool())
183 socket()->setProperty("UseCompression", true);
186 handle(ClientRegistered{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())},
187 m["Configured"].toBool(),
188 m["StorageBackends"].toList(),
189 m["Authenticators"].toList(),
190 m["SupportSsl"].toBool()});
193 else if (msgType == "CoreSetupData") {
194 QVariantMap map = m["SetupData"].toMap();
195 handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
198 else if (msgType == "CoreSetupReject") {
199 handle(SetupFailed(m["Error"].toString()));
202 else if (msgType == "CoreSetupAck") {
206 else if (msgType == "ClientLogin") {
207 handle(Login(m["User"].toString(), m["Password"].toString()));
210 else if (msgType == "ClientLoginReject") {
211 handle(LoginFailed(m["Error"].toString()));
214 else if (msgType == "ClientLoginAck") {
215 handle(LoginSuccess());
218 else if (msgType == "SessionInit") {
219 QVariantMap map = m["SessionState"].toMap();
220 handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
224 emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
229 void LegacyPeer::dispatch(const RegisterClient &msg) {
231 m["MsgType"] = "ClientInit";
232 m["Features"] = static_cast<quint32>(msg.features.toLegacyFeatures());
233 m["FeatureList"] = msg.features.toStringList();
234 m["ClientVersion"] = msg.clientVersion;
235 m["ClientDate"] = msg.buildDate;
237 // FIXME only in compat mode
238 m["ProtocolVersion"] = protocolVersion;
239 m["UseSsl"] = msg.sslSupported;
240 #ifndef QT_NO_COMPRESS
241 m["UseCompression"] = true;
243 m["UseCompression"] = false;
250 void LegacyPeer::dispatch(const ClientDenied &msg) {
252 m["MsgType"] = "ClientInitReject";
253 m["Error"] = msg.errorString;
259 void LegacyPeer::dispatch(const ClientRegistered &msg) {
261 m["MsgType"] = "ClientInitAck";
262 if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
263 m["FeatureList"] = msg.features.toStringList();
266 m["CoreFeatures"] = static_cast<quint32>(msg.features.toLegacyFeatures());
268 m["StorageBackends"] = msg.backendInfo;
269 if (hasFeature(Quassel::Feature::Authenticators)) {
270 m["Authenticators"] = msg.authenticatorInfo;
273 // FIXME only in compat mode
274 m["ProtocolVersion"] = protocolVersion;
275 m["SupportSsl"] = msg.sslSupported;
276 m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
278 // This is only used for display by really old v10 clients (pre-0.5), and we no longer set this
279 m["CoreInfo"] = QString();
281 m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
287 void LegacyPeer::dispatch(const SetupData &msg)
290 map["AdminUser"] = msg.adminUser;
291 map["AdminPasswd"] = msg.adminPassword;
292 map["Backend"] = msg.backend;
293 map["ConnectionProperties"] = msg.setupData;
295 // Auth backend properties.
296 map["Authenticator"] = msg.authenticator;
297 map["AuthProperties"] = msg.authSetupData;
300 m["MsgType"] = "CoreSetupData";
301 m["SetupData"] = map;
306 void LegacyPeer::dispatch(const SetupFailed &msg)
309 m["MsgType"] = "CoreSetupReject";
310 m["Error"] = msg.errorString;
316 void LegacyPeer::dispatch(const SetupDone &msg)
321 m["MsgType"] = "CoreSetupAck";
327 void LegacyPeer::dispatch(const Login &msg)
330 m["MsgType"] = "ClientLogin";
331 m["User"] = msg.user;
332 m["Password"] = msg.password;
338 void LegacyPeer::dispatch(const LoginFailed &msg)
341 m["MsgType"] = "ClientLoginReject";
342 m["Error"] = msg.errorString;
348 void LegacyPeer::dispatch(const LoginSuccess &msg)
353 m["MsgType"] = "ClientLoginAck";
359 void LegacyPeer::dispatch(const SessionState &msg)
362 m["MsgType"] = "SessionInit";
365 map["BufferInfos"] = msg.bufferInfos;
366 map["NetworkIds"] = msg.networkIds;
367 map["Identities"] = msg.identities;
368 m["SessionState"] = map;
374 /*** Standard messages ***/
376 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
378 QVariantList params(packedFunc.toList());
380 if (params.isEmpty()) {
381 qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
385 // TODO: make sure that this is a valid request type
386 RequestType requestType = (RequestType)params.takeFirst().value<int>();
387 switch (requestType) {
389 if (params.count() < 3) {
390 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
393 QByteArray className = params.takeFirst().toByteArray();
394 QString objectName = params.takeFirst().toString();
395 QByteArray slotName = params.takeFirst().toByteArray();
396 handle(Protocol::SyncMessage(className, objectName, slotName, params));
400 if (params.empty()) {
401 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
404 QByteArray slotName = params.takeFirst().toByteArray();
405 handle(Protocol::RpcCall(slotName, params));
409 if (params.count() != 2) {
410 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
413 QByteArray className = params[0].toByteArray();
414 QString objectName = params[1].toString();
415 handle(Protocol::InitRequest(className, objectName));
419 if (params.count() != 3) {
420 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
423 QByteArray className = params[0].toByteArray();
424 QString objectName = params[1].toString();
425 QVariantMap initData = params[2].toMap();
427 // we need to special-case IrcUsersAndChannels here, since the format changed
428 if (className == "Network")
429 fromLegacyIrcUsersAndChannels(initData);
430 handle(Protocol::InitData(className, objectName, initData));
434 if (params.count() != 1) {
435 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
438 // The legacy protocol would only send a QTime, no QDateTime
439 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
440 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
441 dateTime.setTime(params[0].toTime());
442 handle(Protocol::HeartBeat(dateTime));
445 case HeartBeatReply: {
446 if (params.count() != 1) {
447 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
450 // The legacy protocol would only send a QTime, no QDateTime
451 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
452 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
453 dateTime.setTime(params[0].toTime());
454 handle(Protocol::HeartBeatReply(dateTime));
462 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
464 dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
468 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
470 dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
474 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
476 dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
480 void LegacyPeer::dispatch(const Protocol::InitData &msg)
482 // We need to special-case IrcUsersAndChannels, as the format changed
483 if (msg.className == "Network") {
484 QVariantMap initData = msg.initData;
485 toLegacyIrcUsersAndChannels(initData);
486 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << initData);
489 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
493 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
495 dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
499 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
501 dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
505 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
507 writeMessage(QVariant(packedFunc));
511 // Handle the changed format for Network's initData
512 // cf. Network::initIrcUsersAndChannels()
513 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
515 const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
518 QHash<QString, QVariantList> users;
519 foreach(const QVariant &v, legacyMap["users"].toMap().values()) {
520 const QVariantMap &map = v.toMap();
521 foreach(const QString &key, map.keys())
522 users[key] << map[key];
525 foreach(const QString &key, users.keys())
526 userMap[key] = users[key];
527 newMap["Users"] = userMap;
529 QHash<QString, QVariantList> channels;
530 foreach(const QVariant &v, legacyMap["channels"].toMap().values()) {
531 const QVariantMap &map = v.toMap();
532 foreach(const QString &key, map.keys())
533 channels[key] << map[key];
535 QVariantMap channelMap;
536 foreach(const QString &key, channels.keys())
537 channelMap[key] = channels[key];
538 newMap["Channels"] = channelMap;
540 initData["IrcUsersAndChannels"] = newMap;
544 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
546 const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
547 QVariantMap legacyMap;
549 // toMap() and toList() are cheap, so no need to copy to a hash
552 const QVariantMap &users = usersAndChannels["Users"].toMap();
554 int size = users["nick"].toList().size(); // we know this key exists
555 for(int i = 0; i < size; i++) {
557 foreach(const QString &key, users.keys())
558 map[key] = users[key].toList().at(i);
559 QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString());
560 userMap[hostmask.toLower()] = map;
562 legacyMap["users"] = userMap;
564 QVariantMap channelMap;
565 const QVariantMap &channels = usersAndChannels["Channels"].toMap();
567 size = channels["name"].toList().size();
568 for(int i = 0; i < size; i++) {
570 foreach(const QString &key, channels.keys())
571 map[key] = channels[key].toList().at(i);
572 channelMap[map["name"].toString().toLower()] = map;
574 legacyMap["channels"] = channelMap;
576 initData["IrcUsersAndChannels"] = legacyMap;