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 "serializers/serializers.h"
27
28 /* version.inc is no longer used for this */
29 const uint protocolVersion = 10;
30 const uint coreNeedsProtocol = protocolVersion;
31 const uint clientNeedsProtocol = protocolVersion;
32
33 using namespace Protocol;
34
35 LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
36     : RemotePeer(authHandler, socket, level, parent),
37     _useCompression(false)
38 {
39
40 }
41
42
43 void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
44 {
45     RemotePeer::setSignalProxy(proxy);
46
47     // FIXME only in compat mode
48     if (proxy) {
49         // enable compression now if requested - the initial handshake is uncompressed in the legacy protocol!
50         _useCompression = socket()->property("UseCompression").toBool();
51         if (_useCompression)
52             qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
53     }
54
55 }
56
57
58 void LegacyPeer::processMessage(const QByteArray &msg)
59 {
60     QDataStream stream(msg);
61     stream.setVersion(QDataStream::Qt_4_2);
62
63     QVariant item;
64     if (_useCompression) {
65         QByteArray rawItem;
66         if (!Serializers::deserialize(stream, rawItem)) {
67             close("Peer sent corrupt data: unable to load QVariant!");
68             return;
69         }
70
71         int nbytes = rawItem.size();
72         if (nbytes <= 4) {
73             const char *data = rawItem.constData();
74             if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) {
75                 close("Peer sent corrupted compressed data!");
76                 return;
77             }
78         }
79
80         rawItem = qUncompress(rawItem);
81
82         QDataStream itemStream(&rawItem, QIODevice::ReadOnly);
83         itemStream.setVersion(QDataStream::Qt_4_2);
84         if (!Serializers::deserialize(itemStream, item)) {
85             close("Peer sent corrupt data: unable to load QVariant!");
86             return;
87         }
88     } else {
89         if (!Serializers::deserialize(stream, item)) {
90             close("Peer sent corrupt data: unable to load QVariant!");
91             return;
92         }
93     }
94
95     if (stream.status() != QDataStream::Ok || !item.isValid()) {
96         close("Peer sent corrupt data: unable to load QVariant!");
97         return;
98     }
99
100     // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
101     if (!signalProxy())
102         handleHandshakeMessage(item);
103     else
104         handlePackedFunc(item);
105 }
106
107
108 void LegacyPeer::writeMessage(const QVariant &item)
109 {
110     QByteArray block;
111     QDataStream out(&block, QIODevice::WriteOnly);
112     out.setVersion(QDataStream::Qt_4_2);
113
114     if (_useCompression) {
115         QByteArray rawItem;
116         QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
117         itemStream.setVersion(QDataStream::Qt_4_2);
118         itemStream << item;
119
120         rawItem = qCompress(rawItem);
121
122         out << rawItem;
123     }
124     else {
125         out << item;
126     }
127
128     writeMessage(block);
129 }
130
131
132 /*** Handshake messages ***/
133
134 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
135  * a structure different from those being used after the handshake.
136  * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
137  */
138
139 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
140 {
141     QVariantMap m = msg.toMap();
142
143     QString msgType = m["MsgType"].toString();
144     if (msgType.isEmpty()) {
145         emit protocolError(tr("Invalid handshake message!"));
146         return;
147     }
148
149     if (msgType == "ClientInit") {
150         // FIXME only in compat mode
151         uint ver = m["ProtocolVersion"].toUInt();
152         if (ver < coreNeedsProtocol) {
153             emit protocolVersionMismatch((int)ver, (int)coreNeedsProtocol);
154             return;
155         }
156
157 #ifndef QT_NO_COMPRESS
158         // FIXME only in compat mode
159         if (m["UseCompression"].toBool()) {
160             socket()->setProperty("UseCompression", true);
161         }
162 #endif
163         handle(RegisterClient(m["ClientVersion"].toString(), m["ClientDate"].toString(), m["UseSsl"].toBool()));
164     }
165
166     else if (msgType == "ClientInitReject") {
167         handle(ClientDenied(m["Error"].toString()));
168     }
169
170     else if (msgType == "ClientInitAck") {
171         // FIXME only in compat mode
172         uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
173         if (ver < clientNeedsProtocol) {
174             emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol);
175             return;
176         }
177 #ifndef QT_NO_COMPRESS
178         if (m["SupportsCompression"].toBool())
179             socket()->setProperty("UseCompression", true);
180 #endif
181
182         handle(ClientRegistered(m["CoreFeatures"].toUInt(), m["Configured"].toBool(), m["StorageBackends"].toList(), m["SupportSsl"].toBool()));
183     }
184
185     else if (msgType == "CoreSetupData") {
186         QVariantMap map = m["SetupData"].toMap();
187         handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap()));
188     }
189
190     else if (msgType == "CoreSetupReject") {
191         handle(SetupFailed(m["Error"].toString()));
192     }
193
194     else if (msgType == "CoreSetupAck") {
195         handle(SetupDone());
196     }
197
198     else if (msgType == "ClientLogin") {
199         handle(Login(m["User"].toString(), m["Password"].toString()));
200     }
201
202     else if (msgType == "ClientLoginReject") {
203         handle(LoginFailed(m["Error"].toString()));
204     }
205
206     else if (msgType == "ClientLoginAck") {
207         handle(LoginSuccess());
208     }
209
210     else if (msgType == "SessionInit") {
211         QVariantMap map = m["SessionState"].toMap();
212         handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
213     }
214
215     else {
216         emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
217     }
218 }
219
220
221 void LegacyPeer::dispatch(const RegisterClient &msg) {
222     QVariantMap m;
223     m["MsgType"] = "ClientInit";
224     m["ClientVersion"] = msg.clientVersion;
225     m["ClientDate"] = msg.buildDate;
226
227     // FIXME only in compat mode
228     m["ProtocolVersion"] = protocolVersion;
229     m["UseSsl"] = msg.sslSupported;
230 #ifndef QT_NO_COMPRESS
231     m["UseCompression"] = true;
232 #else
233     m["UseCompression"] = false;
234 #endif
235
236     writeMessage(m);
237 }
238
239
240 void LegacyPeer::dispatch(const ClientDenied &msg) {
241     QVariantMap m;
242     m["MsgType"] = "ClientInitReject";
243     m["Error"] = msg.errorString;
244
245     writeMessage(m);
246 }
247
248
249 void LegacyPeer::dispatch(const ClientRegistered &msg) {
250     QVariantMap m;
251     m["MsgType"] = "ClientInitAck";
252     m["CoreFeatures"] = msg.coreFeatures;
253     m["StorageBackends"] = msg.backendInfo;
254
255     // FIXME only in compat mode
256     m["ProtocolVersion"] = protocolVersion;
257     m["SupportSsl"] = msg.sslSupported;
258     m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
259
260     // This is only used for display by really old v10 clients (pre-0.5), and we no longer set this
261     m["CoreInfo"] = QString();
262
263     m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
264
265     writeMessage(m);
266 }
267
268
269 void LegacyPeer::dispatch(const SetupData &msg)
270 {
271     QVariantMap map;
272     map["AdminUser"] = msg.adminUser;
273     map["AdminPasswd"] = msg.adminPassword;
274     map["Backend"] = msg.backend;
275     map["ConnectionProperties"] = msg.setupData;
276
277     QVariantMap m;
278     m["MsgType"] = "CoreSetupData";
279     m["SetupData"] = map;
280     writeMessage(m);
281 }
282
283
284 void LegacyPeer::dispatch(const SetupFailed &msg)
285 {
286     QVariantMap m;
287     m["MsgType"] = "CoreSetupReject";
288     m["Error"] = msg.errorString;
289
290     writeMessage(m);
291 }
292
293
294 void LegacyPeer::dispatch(const SetupDone &msg)
295 {
296     Q_UNUSED(msg)
297
298     QVariantMap m;
299     m["MsgType"] = "CoreSetupAck";
300
301     writeMessage(m);
302 }
303
304
305 void LegacyPeer::dispatch(const Login &msg)
306 {
307     QVariantMap m;
308     m["MsgType"] = "ClientLogin";
309     m["User"] = msg.user;
310     m["Password"] = msg.password;
311
312     writeMessage(m);
313 }
314
315
316 void LegacyPeer::dispatch(const LoginFailed &msg)
317 {
318     QVariantMap m;
319     m["MsgType"] = "ClientLoginReject";
320     m["Error"] = msg.errorString;
321
322     writeMessage(m);
323 }
324
325
326 void LegacyPeer::dispatch(const LoginSuccess &msg)
327 {
328     Q_UNUSED(msg)
329
330     QVariantMap m;
331     m["MsgType"] = "ClientLoginAck";
332
333     writeMessage(m);
334 }
335
336
337 void LegacyPeer::dispatch(const SessionState &msg)
338 {
339     QVariantMap m;
340     m["MsgType"] = "SessionInit";
341
342     QVariantMap map;
343     map["BufferInfos"] = msg.bufferInfos;
344     map["NetworkIds"] = msg.networkIds;
345     map["Identities"] = msg.identities;
346     m["SessionState"] = map;
347
348     writeMessage(m);
349 }
350
351
352 /*** Standard messages ***/
353
354 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
355 {
356     QVariantList params(packedFunc.toList());
357
358     if (params.isEmpty()) {
359         qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
360         return;
361     }
362
363     // TODO: make sure that this is a valid request type
364     RequestType requestType = (RequestType)params.takeFirst().value<int>();
365     switch (requestType) {
366         case Sync: {
367             if (params.count() < 3) {
368                 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
369                 return;
370             }
371             QByteArray className = params.takeFirst().toByteArray();
372             QString objectName = params.takeFirst().toString();
373             QByteArray slotName = params.takeFirst().toByteArray();
374             handle(Protocol::SyncMessage(className, objectName, slotName, params));
375             break;
376         }
377         case RpcCall: {
378             if (params.empty()) {
379                 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
380                 return;
381             }
382             QByteArray slotName = params.takeFirst().toByteArray();
383             handle(Protocol::RpcCall(slotName, params));
384             break;
385         }
386         case InitRequest: {
387             if (params.count() != 2) {
388                 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
389                 return;
390             }
391             QByteArray className = params[0].toByteArray();
392             QString objectName = params[1].toString();
393             handle(Protocol::InitRequest(className, objectName));
394             break;
395         }
396         case InitData: {
397             if (params.count() != 3) {
398                 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
399                 return;
400             }
401             QByteArray className = params[0].toByteArray();
402             QString objectName = params[1].toString();
403             QVariantMap initData = params[2].toMap();
404
405             // we need to special-case IrcUsersAndChannels here, since the format changed
406             if (className == "Network")
407                 fromLegacyIrcUsersAndChannels(initData);
408             handle(Protocol::InitData(className, objectName, initData));
409             break;
410         }
411         case HeartBeat: {
412             if (params.count() != 1) {
413                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
414                 return;
415             }
416             // The legacy protocol would only send a QTime, no QDateTime
417             // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
418             QDateTime dateTime = QDateTime::currentDateTime().toUTC();
419             dateTime.setTime(params[0].toTime());
420             handle(Protocol::HeartBeat(dateTime));
421             break;
422         }
423         case HeartBeatReply: {
424             if (params.count() != 1) {
425                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
426                 return;
427             }
428             // The legacy protocol would only send a QTime, no QDateTime
429             // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
430             QDateTime dateTime = QDateTime::currentDateTime().toUTC();
431             dateTime.setTime(params[0].toTime());
432             handle(Protocol::HeartBeatReply(dateTime));
433             break;
434         }
435
436     }
437 }
438
439
440 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
441 {
442     dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
443 }
444
445
446 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
447 {
448     dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
449 }
450
451
452 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
453 {
454     dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
455 }
456
457
458 void LegacyPeer::dispatch(const Protocol::InitData &msg)
459 {
460     // We need to special-case IrcUsersAndChannels, as the format changed
461     if (msg.className == "Network") {
462         QVariantMap initData = msg.initData;
463         toLegacyIrcUsersAndChannels(initData);
464         dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << initData);
465     }
466     else
467         dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
468 }
469
470
471 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
472 {
473     dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
474 }
475
476
477 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
478 {
479     dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
480 }
481
482
483 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
484 {
485     writeMessage(QVariant(packedFunc));
486 }
487
488
489 // Handle the changed format for Network's initData
490 // cf. Network::initIrcUsersAndChannels()
491 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
492 {
493     const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
494     QVariantMap newMap;
495
496     QHash<QString, QVariantList> users;
497     foreach(const QVariant &v, legacyMap["users"].toMap().values()) {
498         const QVariantMap &map = v.toMap();
499         foreach(const QString &key, map.keys())
500             users[key] << map[key];
501     }
502     QVariantMap userMap;
503     foreach(const QString &key, users.keys())
504         userMap[key] = users[key];
505     newMap["Users"] = userMap;
506
507     QHash<QString, QVariantList> channels;
508     foreach(const QVariant &v, legacyMap["channels"].toMap().values()) {
509         const QVariantMap &map = v.toMap();
510         foreach(const QString &key, map.keys())
511             channels[key] << map[key];
512     }
513     QVariantMap channelMap;
514     foreach(const QString &key, channels.keys())
515         channelMap[key] = channels[key];
516     newMap["Channels"] = channelMap;
517
518     initData["IrcUsersAndChannels"] = newMap;
519 }
520
521
522 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
523 {
524     const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
525     QVariantMap legacyMap;
526
527     // toMap() and toList() are cheap, so no need to copy to a hash
528
529     QVariantMap userMap;
530     const QVariantMap &users = usersAndChannels["Users"].toMap();
531
532     int size = users["nick"].toList().size(); // we know this key exists
533     for(int i = 0; i < size; i++) {
534         QVariantMap map;
535         foreach(const QString &key, users.keys())
536             map[key] = users[key].toList().at(i);
537         QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString());
538         userMap[hostmask.toLower()] = map;
539     }
540     legacyMap["users"] = userMap;
541
542     QVariantMap channelMap;
543     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
544
545     size = channels["name"].toList().size();
546     for(int i = 0; i < size; i++) {
547         QVariantMap map;
548         foreach(const QString &key, channels.keys())
549             map[key] = channels[key].toList().at(i);
550         channelMap[map["name"].toString().toLower()] = map;
551     }
552     legacyMap["channels"] = channelMap;
553
554     initData["IrcUsersAndChannels"] = legacyMap;
555 }