Implement custom deserializer to add our own sanity checks
[quassel.git] / src / common / protocols / legacy / legacypeer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include <QHostAddress>
22 #include <QDataStream>
23 #include <QTcpSocket>
24
25 #include "legacypeer.h"
26 #include "quassel.h"
27 #include "serializers/serializers.h"
28
29 /* version.inc is no longer used for this */
30 const uint protocolVersion = 10;
31 const uint coreNeedsProtocol = protocolVersion;
32 const uint clientNeedsProtocol = protocolVersion;
33
34 using namespace Protocol;
35
36 LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
37     : RemotePeer(authHandler, socket, level, parent),
38     _useCompression(false)
39 {
40
41 }
42
43
44 void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
45 {
46     RemotePeer::setSignalProxy(proxy);
47
48     // FIXME only in compat mode
49     if (proxy) {
50         // enable compression now if requested - the initial handshake is uncompressed in the legacy protocol!
51         _useCompression = socket()->property("UseCompression").toBool();
52         if (_useCompression)
53             qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
54     }
55
56 }
57
58
59 void LegacyPeer::processMessage(const QByteArray &msg)
60 {
61     QDataStream stream(msg);
62     stream.setVersion(QDataStream::Qt_4_2);
63
64     QVariant item;
65     if (_useCompression) {
66         QByteArray rawItem;
67         if (!Serializers::deserialize(stream, features(), rawItem)) {
68             close("Peer sent corrupt data: unable to load QVariant!");
69             return;
70         }
71
72         int nbytes = rawItem.size();
73         if (nbytes <= 4) {
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!");
77                 return;
78             }
79         }
80
81         rawItem = qUncompress(rawItem);
82
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!");
87             return;
88         }
89     } else {
90         if (!Serializers::deserialize(stream, features(), item)) {
91             close("Peer sent corrupt data: unable to load QVariant!");
92             return;
93         }
94     }
95
96     if (stream.status() != QDataStream::Ok || !item.isValid()) {
97         close("Peer sent corrupt data: unable to load QVariant!");
98         return;
99     }
100
101     // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
102     if (!signalProxy())
103         handleHandshakeMessage(item);
104     else
105         handlePackedFunc(item);
106 }
107
108
109 void LegacyPeer::writeMessage(const QVariant &item)
110 {
111     QByteArray block;
112     QDataStream out(&block, QIODevice::WriteOnly);
113     out.setVersion(QDataStream::Qt_4_2);
114
115     if (_useCompression) {
116         QByteArray rawItem;
117         QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
118         itemStream.setVersion(QDataStream::Qt_4_2);
119         itemStream << item;
120
121         rawItem = qCompress(rawItem);
122
123         out << rawItem;
124     }
125     else {
126         out << item;
127     }
128
129     writeMessage(block);
130 }
131
132
133 /*** Handshake messages ***/
134
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.
138  */
139
140 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
141 {
142     QVariantMap m = msg.toMap();
143
144     QString msgType = m["MsgType"].toString();
145     if (msgType.isEmpty()) {
146         emit protocolError(tr("Invalid handshake message!"));
147         return;
148     }
149
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);
155             return;
156         }
157
158 #ifndef QT_NO_COMPRESS
159         // FIXME only in compat mode
160         if (m["UseCompression"].toBool()) {
161             socket()->setProperty("UseCompression", true);
162         }
163 #endif
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()});
168     }
169
170     else if (msgType == "ClientInitReject") {
171         handle(ClientDenied(m["Error"].toString()));
172     }
173
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);
179             return;
180         }
181 #ifndef QT_NO_COMPRESS
182         if (m["SupportsCompression"].toBool())
183             socket()->setProperty("UseCompression", true);
184 #endif
185
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()});
191     }
192
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()));
196     }
197
198     else if (msgType == "CoreSetupReject") {
199         handle(SetupFailed(m["Error"].toString()));
200     }
201
202     else if (msgType == "CoreSetupAck") {
203         handle(SetupDone());
204     }
205
206     else if (msgType == "ClientLogin") {
207         handle(Login(m["User"].toString(), m["Password"].toString()));
208     }
209
210     else if (msgType == "ClientLoginReject") {
211         handle(LoginFailed(m["Error"].toString()));
212     }
213
214     else if (msgType == "ClientLoginAck") {
215         handle(LoginSuccess());
216     }
217
218     else if (msgType == "SessionInit") {
219         QVariantMap map = m["SessionState"].toMap();
220         handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
221     }
222
223     else {
224         emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
225     }
226 }
227
228
229 void LegacyPeer::dispatch(const RegisterClient &msg) {
230     QVariantMap m;
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;
236
237     // FIXME only in compat mode
238     m["ProtocolVersion"] = protocolVersion;
239     m["UseSsl"] = msg.sslSupported;
240 #ifndef QT_NO_COMPRESS
241     m["UseCompression"] = true;
242 #else
243     m["UseCompression"] = false;
244 #endif
245
246     writeMessage(m);
247 }
248
249
250 void LegacyPeer::dispatch(const ClientDenied &msg) {
251     QVariantMap m;
252     m["MsgType"] = "ClientInitReject";
253     m["Error"] = msg.errorString;
254
255     writeMessage(m);
256 }
257
258
259 void LegacyPeer::dispatch(const ClientRegistered &msg) {
260     QVariantMap m;
261     m["MsgType"] = "ClientInitAck";
262     if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
263         m["FeatureList"] = msg.features.toStringList();
264     }
265     else {
266         m["CoreFeatures"] = static_cast<quint32>(msg.features.toLegacyFeatures());
267     }
268     m["StorageBackends"] = msg.backendInfo;
269     if (hasFeature(Quassel::Feature::Authenticators)) {
270         m["Authenticators"] = msg.authenticatorInfo;
271     }
272
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
277
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();
280
281     m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
282
283     writeMessage(m);
284 }
285
286
287 void LegacyPeer::dispatch(const SetupData &msg)
288 {
289     QVariantMap map;
290     map["AdminUser"] = msg.adminUser;
291     map["AdminPasswd"] = msg.adminPassword;
292     map["Backend"] = msg.backend;
293     map["ConnectionProperties"] = msg.setupData;
294
295     // Auth backend properties.
296     map["Authenticator"] = msg.authenticator;
297     map["AuthProperties"] = msg.authSetupData;
298
299     QVariantMap m;
300     m["MsgType"] = "CoreSetupData";
301     m["SetupData"] = map;
302     writeMessage(m);
303 }
304
305
306 void LegacyPeer::dispatch(const SetupFailed &msg)
307 {
308     QVariantMap m;
309     m["MsgType"] = "CoreSetupReject";
310     m["Error"] = msg.errorString;
311
312     writeMessage(m);
313 }
314
315
316 void LegacyPeer::dispatch(const SetupDone &msg)
317 {
318     Q_UNUSED(msg)
319
320     QVariantMap m;
321     m["MsgType"] = "CoreSetupAck";
322
323     writeMessage(m);
324 }
325
326
327 void LegacyPeer::dispatch(const Login &msg)
328 {
329     QVariantMap m;
330     m["MsgType"] = "ClientLogin";
331     m["User"] = msg.user;
332     m["Password"] = msg.password;
333
334     writeMessage(m);
335 }
336
337
338 void LegacyPeer::dispatch(const LoginFailed &msg)
339 {
340     QVariantMap m;
341     m["MsgType"] = "ClientLoginReject";
342     m["Error"] = msg.errorString;
343
344     writeMessage(m);
345 }
346
347
348 void LegacyPeer::dispatch(const LoginSuccess &msg)
349 {
350     Q_UNUSED(msg)
351
352     QVariantMap m;
353     m["MsgType"] = "ClientLoginAck";
354
355     writeMessage(m);
356 }
357
358
359 void LegacyPeer::dispatch(const SessionState &msg)
360 {
361     QVariantMap m;
362     m["MsgType"] = "SessionInit";
363
364     QVariantMap map;
365     map["BufferInfos"] = msg.bufferInfos;
366     map["NetworkIds"] = msg.networkIds;
367     map["Identities"] = msg.identities;
368     m["SessionState"] = map;
369
370     writeMessage(m);
371 }
372
373
374 /*** Standard messages ***/
375
376 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
377 {
378     QVariantList params(packedFunc.toList());
379
380     if (params.isEmpty()) {
381         qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
382         return;
383     }
384
385     // TODO: make sure that this is a valid request type
386     RequestType requestType = (RequestType)params.takeFirst().value<int>();
387     switch (requestType) {
388         case Sync: {
389             if (params.count() < 3) {
390                 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
391                 return;
392             }
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));
397             break;
398         }
399         case RpcCall: {
400             if (params.empty()) {
401                 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
402                 return;
403             }
404             QByteArray slotName = params.takeFirst().toByteArray();
405             handle(Protocol::RpcCall(slotName, params));
406             break;
407         }
408         case InitRequest: {
409             if (params.count() != 2) {
410                 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
411                 return;
412             }
413             QByteArray className = params[0].toByteArray();
414             QString objectName = params[1].toString();
415             handle(Protocol::InitRequest(className, objectName));
416             break;
417         }
418         case InitData: {
419             if (params.count() != 3) {
420                 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
421                 return;
422             }
423             QByteArray className = params[0].toByteArray();
424             QString objectName = params[1].toString();
425             QVariantMap initData = params[2].toMap();
426
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));
431             break;
432         }
433         case HeartBeat: {
434             if (params.count() != 1) {
435                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
436                 return;
437             }
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));
443             break;
444         }
445         case HeartBeatReply: {
446             if (params.count() != 1) {
447                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
448                 return;
449             }
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));
455             break;
456         }
457
458     }
459 }
460
461
462 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
463 {
464     dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
465 }
466
467
468 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
469 {
470     dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
471 }
472
473
474 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
475 {
476     dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
477 }
478
479
480 void LegacyPeer::dispatch(const Protocol::InitData &msg)
481 {
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);
487     }
488     else
489         dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
490 }
491
492
493 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
494 {
495     dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
496 }
497
498
499 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
500 {
501     dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
502 }
503
504
505 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
506 {
507     writeMessage(QVariant(packedFunc));
508 }
509
510
511 // Handle the changed format for Network's initData
512 // cf. Network::initIrcUsersAndChannels()
513 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
514 {
515     const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
516     QVariantMap newMap;
517
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];
523     }
524     QVariantMap userMap;
525     foreach(const QString &key, users.keys())
526         userMap[key] = users[key];
527     newMap["Users"] = userMap;
528
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];
534     }
535     QVariantMap channelMap;
536     foreach(const QString &key, channels.keys())
537         channelMap[key] = channels[key];
538     newMap["Channels"] = channelMap;
539
540     initData["IrcUsersAndChannels"] = newMap;
541 }
542
543
544 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
545 {
546     const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
547     QVariantMap legacyMap;
548
549     // toMap() and toList() are cheap, so no need to copy to a hash
550
551     QVariantMap userMap;
552     const QVariantMap &users = usersAndChannels["Users"].toMap();
553
554     int size = users["nick"].toList().size(); // we know this key exists
555     for(int i = 0; i < size; i++) {
556         QVariantMap map;
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;
561     }
562     legacyMap["users"] = userMap;
563
564     QVariantMap channelMap;
565     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
566
567     size = channels["name"].toList().size();
568     for(int i = 0; i < size; i++) {
569         QVariantMap map;
570         foreach(const QString &key, channels.keys())
571             map[key] = channels[key].toList().at(i);
572         channelMap[map["name"].toString().toLower()] = map;
573     }
574     legacyMap["channels"] = channelMap;
575
576     initData["IrcUsersAndChannels"] = legacyMap;
577 }