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"
27 /* version.inc is no longer used for this */
28 const uint protocolVersion = 10;
29 const uint coreNeedsProtocol = protocolVersion;
30 const uint clientNeedsProtocol = protocolVersion;
32 using namespace Protocol;
34 LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
35 : RemotePeer(authHandler, socket, level, parent),
36 _useCompression(false)
42 void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
44 RemotePeer::setSignalProxy(proxy);
46 // FIXME only in compat mode
48 // enable compression now if requested - the initial handshake is uncompressed in the legacy protocol!
49 _useCompression = socket()->property("UseCompression").toBool();
51 qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
57 void LegacyPeer::processMessage(const QByteArray &msg)
59 QDataStream stream(msg);
60 stream.setVersion(QDataStream::Qt_4_2);
63 if (_useCompression) {
67 int nbytes = rawItem.size();
69 const char *data = rawItem.constData();
70 if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) {
71 close("Peer sent corrupted compressed data!");
76 rawItem = qUncompress(rawItem);
78 QDataStream itemStream(&rawItem, QIODevice::ReadOnly);
79 itemStream.setVersion(QDataStream::Qt_4_2);
86 if (stream.status() != QDataStream::Ok || !item.isValid()) {
87 close("Peer sent corrupt data: unable to load QVariant!");
91 // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
93 handleHandshakeMessage(item);
95 handlePackedFunc(item);
99 void LegacyPeer::writeMessage(const QVariant &item)
102 QDataStream out(&block, QIODevice::WriteOnly);
103 out.setVersion(QDataStream::Qt_4_2);
105 if (_useCompression) {
107 QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
108 itemStream.setVersion(QDataStream::Qt_4_2);
111 rawItem = qCompress(rawItem);
123 /*** Handshake messages ***/
125 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
126 * a structure different from those being used after the handshake.
127 * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
130 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
132 QVariantMap m = msg.toMap();
134 QString msgType = m["MsgType"].toString();
135 if (msgType.isEmpty()) {
136 emit protocolError(tr("Invalid handshake message!"));
140 if (msgType == "ClientInit") {
141 // FIXME only in compat mode
142 uint ver = m["ProtocolVersion"].toUInt();
143 if (ver < coreNeedsProtocol) {
144 emit protocolVersionMismatch((int)ver, (int)coreNeedsProtocol);
148 #ifndef QT_NO_COMPRESS
149 // FIXME only in compat mode
150 if (m["UseCompression"].toBool()) {
151 socket()->setProperty("UseCompression", true);
154 handle(RegisterClient(m["ClientVersion"].toString(), m["ClientDate"].toString(), m["UseSsl"].toBool()));
157 else if (msgType == "ClientInitReject") {
158 handle(ClientDenied(m["Error"].toString()));
161 else if (msgType == "ClientInitAck") {
162 // FIXME only in compat mode
163 uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
164 if (ver < clientNeedsProtocol) {
165 emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol);
168 #ifndef QT_NO_COMPRESS
169 if (m["SupportsCompression"].toBool())
170 socket()->setProperty("UseCompression", true);
173 handle(ClientRegistered(m["CoreFeatures"].toUInt(), m["Configured"].toBool(), m["StorageBackends"].toList(), m["SupportSsl"].toBool(), m["Authenticators"].toList()));
176 else if (msgType == "CoreSetupData") {
177 QVariantMap map = m["SetupData"].toMap();
178 handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
181 else if (msgType == "CoreSetupReject") {
182 handle(SetupFailed(m["Error"].toString()));
185 else if (msgType == "CoreSetupAck") {
189 else if (msgType == "ClientLogin") {
190 handle(Login(m["User"].toString(), m["Password"].toString()));
193 else if (msgType == "ClientLoginReject") {
194 handle(LoginFailed(m["Error"].toString()));
197 else if (msgType == "ClientLoginAck") {
198 handle(LoginSuccess());
201 else if (msgType == "SessionInit") {
202 QVariantMap map = m["SessionState"].toMap();
203 handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
207 emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
212 void LegacyPeer::dispatch(const RegisterClient &msg) {
214 m["MsgType"] = "ClientInit";
215 m["ClientVersion"] = msg.clientVersion;
216 m["ClientDate"] = msg.buildDate;
218 // FIXME only in compat mode
219 m["ProtocolVersion"] = protocolVersion;
220 m["UseSsl"] = msg.sslSupported;
221 #ifndef QT_NO_COMPRESS
222 m["UseCompression"] = true;
224 m["UseCompression"] = false;
231 void LegacyPeer::dispatch(const ClientDenied &msg) {
233 m["MsgType"] = "ClientInitReject";
234 m["Error"] = msg.errorString;
240 void LegacyPeer::dispatch(const ClientRegistered &msg) {
242 m["MsgType"] = "ClientInitAck";
243 m["CoreFeatures"] = msg.coreFeatures;
244 m["StorageBackends"] = msg.backendInfo;
245 m["Authenticators"] = msg.authenticatorInfo;
247 // FIXME only in compat mode
248 m["ProtocolVersion"] = protocolVersion;
249 m["SupportSsl"] = msg.sslSupported;
250 m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
252 // This is only used for display by really old v10 clients (pre-0.5), and we no longer set this
253 m["CoreInfo"] = QString();
255 m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
261 void LegacyPeer::dispatch(const SetupData &msg)
264 map["AdminUser"] = msg.adminUser;
265 map["AdminPasswd"] = msg.adminPassword;
266 map["Backend"] = msg.backend;
267 map["ConnectionProperties"] = msg.setupData;
269 // Auth backend properties.
270 map["Authenticator"] = msg.authenticator;
271 map["AuthProperties"] = msg.authSetupData;
274 m["MsgType"] = "CoreSetupData";
275 m["SetupData"] = map;
280 void LegacyPeer::dispatch(const SetupFailed &msg)
283 m["MsgType"] = "CoreSetupReject";
284 m["Error"] = msg.errorString;
290 void LegacyPeer::dispatch(const SetupDone &msg)
295 m["MsgType"] = "CoreSetupAck";
301 void LegacyPeer::dispatch(const Login &msg)
304 m["MsgType"] = "ClientLogin";
305 m["User"] = msg.user;
306 m["Password"] = msg.password;
312 void LegacyPeer::dispatch(const LoginFailed &msg)
315 m["MsgType"] = "ClientLoginReject";
316 m["Error"] = msg.errorString;
322 void LegacyPeer::dispatch(const LoginSuccess &msg)
327 m["MsgType"] = "ClientLoginAck";
333 void LegacyPeer::dispatch(const SessionState &msg)
336 m["MsgType"] = "SessionInit";
339 map["BufferInfos"] = msg.bufferInfos;
340 map["NetworkIds"] = msg.networkIds;
341 map["Identities"] = msg.identities;
342 m["SessionState"] = map;
348 /*** Standard messages ***/
350 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
352 QVariantList params(packedFunc.toList());
354 if (params.isEmpty()) {
355 qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
359 // TODO: make sure that this is a valid request type
360 RequestType requestType = (RequestType)params.takeFirst().value<int>();
361 switch (requestType) {
363 if (params.count() < 3) {
364 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
367 QByteArray className = params.takeFirst().toByteArray();
368 QString objectName = params.takeFirst().toString();
369 QByteArray slotName = params.takeFirst().toByteArray();
370 handle(Protocol::SyncMessage(className, objectName, slotName, params));
374 if (params.empty()) {
375 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
378 QByteArray slotName = params.takeFirst().toByteArray();
379 handle(Protocol::RpcCall(slotName, params));
383 if (params.count() != 2) {
384 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
387 QByteArray className = params[0].toByteArray();
388 QString objectName = params[1].toString();
389 handle(Protocol::InitRequest(className, objectName));
393 if (params.count() != 3) {
394 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
397 QByteArray className = params[0].toByteArray();
398 QString objectName = params[1].toString();
399 QVariantMap initData = params[2].toMap();
401 // we need to special-case IrcUsersAndChannels here, since the format changed
402 if (className == "Network")
403 fromLegacyIrcUsersAndChannels(initData);
404 handle(Protocol::InitData(className, objectName, initData));
408 if (params.count() != 1) {
409 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
412 // The legacy protocol would only send a QTime, no QDateTime
413 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
414 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
415 dateTime.setTime(params[0].toTime());
416 handle(Protocol::HeartBeat(dateTime));
419 case HeartBeatReply: {
420 if (params.count() != 1) {
421 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
424 // The legacy protocol would only send a QTime, no QDateTime
425 // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
426 QDateTime dateTime = QDateTime::currentDateTime().toUTC();
427 dateTime.setTime(params[0].toTime());
428 handle(Protocol::HeartBeatReply(dateTime));
436 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
438 dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
442 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
444 dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
448 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
450 dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
454 void LegacyPeer::dispatch(const Protocol::InitData &msg)
456 // We need to special-case IrcUsersAndChannels, as the format changed
457 if (msg.className == "Network") {
458 QVariantMap initData = msg.initData;
459 toLegacyIrcUsersAndChannels(initData);
460 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << initData);
463 dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
467 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
469 dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
473 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
475 dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
479 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
481 writeMessage(QVariant(packedFunc));
485 // Handle the changed format for Network's initData
486 // cf. Network::initIrcUsersAndChannels()
487 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
489 const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
492 QHash<QString, QVariantList> users;
493 foreach(const QVariant &v, legacyMap["users"].toMap().values()) {
494 const QVariantMap &map = v.toMap();
495 foreach(const QString &key, map.keys())
496 users[key] << map[key];
499 foreach(const QString &key, users.keys())
500 userMap[key] = users[key];
501 newMap["Users"] = userMap;
503 QHash<QString, QVariantList> channels;
504 foreach(const QVariant &v, legacyMap["channels"].toMap().values()) {
505 const QVariantMap &map = v.toMap();
506 foreach(const QString &key, map.keys())
507 channels[key] << map[key];
509 QVariantMap channelMap;
510 foreach(const QString &key, channels.keys())
511 channelMap[key] = channels[key];
512 newMap["Channels"] = channelMap;
514 initData["IrcUsersAndChannels"] = newMap;
518 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
520 const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
521 QVariantMap legacyMap;
523 // toMap() and toList() are cheap, so no need to copy to a hash
526 const QVariantMap &users = usersAndChannels["Users"].toMap();
528 int size = users["nick"].toList().size(); // we know this key exists
529 for(int i = 0; i < size; i++) {
531 foreach(const QString &key, users.keys())
532 map[key] = users[key].toList().at(i);
533 QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString());
534 userMap[hostmask.toLower()] = map;
536 legacyMap["users"] = userMap;
538 QVariantMap channelMap;
539 const QVariantMap &channels = usersAndChannels["Channels"].toMap();
541 size = channels["name"].toList().size();
542 for(int i = 0; i < size; i++) {
544 foreach(const QString &key, channels.keys())
545 map[key] = channels[key].toList().at(i);
546 channelMap[map["name"].toString().toLower()] = map;
548 legacyMap["channels"] = channelMap;
550 initData["IrcUsersAndChannels"] = legacyMap;