19806742e1bf1c53bd0fe1fc4ba0795c32d1ca14
[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
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         stream >> rawItem;
67
68         int nbytes = rawItem.size();
69         if (nbytes <= 4) {
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!");
73                 return;
74             }
75         }
76
77         rawItem = qUncompress(rawItem);
78
79         QDataStream itemStream(&rawItem, QIODevice::ReadOnly);
80         itemStream.setVersion(QDataStream::Qt_4_2);
81         itemStream >> item;
82     }
83     else {
84         stream >> item;
85     }
86
87     if (stream.status() != QDataStream::Ok || !item.isValid()) {
88         close("Peer sent corrupt data: unable to load QVariant!");
89         return;
90     }
91
92     // if no sigproxy is set, we're in handshake mode and let the data be handled elsewhere
93     if (!signalProxy())
94         handleHandshakeMessage(item);
95     else
96         handlePackedFunc(item);
97 }
98
99
100 void LegacyPeer::writeMessage(const QVariant &item)
101 {
102     QByteArray block;
103     QDataStream out(&block, QIODevice::WriteOnly);
104     out.setVersion(QDataStream::Qt_4_2);
105
106     if (_useCompression) {
107         QByteArray rawItem;
108         QDataStream itemStream(&rawItem, QIODevice::WriteOnly);
109         itemStream.setVersion(QDataStream::Qt_4_2);
110         itemStream << item;
111
112         rawItem = qCompress(rawItem);
113
114         out << rawItem;
115     }
116     else {
117         out << item;
118     }
119
120     writeMessage(block);
121 }
122
123
124 /*** Handshake messages ***/
125
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.
129  */
130
131 void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
132 {
133     QVariantMap m = msg.toMap();
134
135     QString msgType = m["MsgType"].toString();
136     if (msgType.isEmpty()) {
137         emit protocolError(tr("Invalid handshake message!"));
138         return;
139     }
140
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);
146             return;
147         }
148
149 #ifndef QT_NO_COMPRESS
150         // FIXME only in compat mode
151         if (m["UseCompression"].toBool()) {
152             socket()->setProperty("UseCompression", true);
153         }
154 #endif
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()});
159     }
160
161     else if (msgType == "ClientInitReject") {
162         handle(ClientDenied(m["Error"].toString()));
163     }
164
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);
170             return;
171         }
172 #ifndef QT_NO_COMPRESS
173         if (m["SupportsCompression"].toBool())
174             socket()->setProperty("UseCompression", true);
175 #endif
176
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()});
182     }
183
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()));
187     }
188
189     else if (msgType == "CoreSetupReject") {
190         handle(SetupFailed(m["Error"].toString()));
191     }
192
193     else if (msgType == "CoreSetupAck") {
194         handle(SetupDone());
195     }
196
197     else if (msgType == "ClientLogin") {
198         handle(Login(m["User"].toString(), m["Password"].toString()));
199     }
200
201     else if (msgType == "ClientLoginReject") {
202         handle(LoginFailed(m["Error"].toString()));
203     }
204
205     else if (msgType == "ClientLoginAck") {
206         handle(LoginSuccess());
207     }
208
209     else if (msgType == "SessionInit") {
210         QVariantMap map = m["SessionState"].toMap();
211         handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
212     }
213
214     else {
215         emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
216     }
217 }
218
219
220 void LegacyPeer::dispatch(const RegisterClient &msg) {
221     QVariantMap m;
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;
227
228     // FIXME only in compat mode
229     m["ProtocolVersion"] = protocolVersion;
230     m["UseSsl"] = msg.sslSupported;
231 #ifndef QT_NO_COMPRESS
232     m["UseCompression"] = true;
233 #else
234     m["UseCompression"] = false;
235 #endif
236
237     writeMessage(m);
238 }
239
240
241 void LegacyPeer::dispatch(const ClientDenied &msg) {
242     QVariantMap m;
243     m["MsgType"] = "ClientInitReject";
244     m["Error"] = msg.errorString;
245
246     writeMessage(m);
247 }
248
249
250 void LegacyPeer::dispatch(const ClientRegistered &msg) {
251     QVariantMap m;
252     m["MsgType"] = "ClientInitAck";
253     if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
254         m["FeatureList"] = msg.features.toStringList();
255     }
256     else {
257         m["CoreFeatures"] = static_cast<quint32>(msg.features.toLegacyFeatures());
258     }
259     m["StorageBackends"] = msg.backendInfo;
260     if (hasFeature(Quassel::Feature::Authenticators)) {
261         m["Authenticators"] = msg.authenticatorInfo;
262     }
263
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
268
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();
271
272     m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
273
274     writeMessage(m);
275 }
276
277
278 void LegacyPeer::dispatch(const SetupData &msg)
279 {
280     QVariantMap map;
281     map["AdminUser"] = msg.adminUser;
282     map["AdminPasswd"] = msg.adminPassword;
283     map["Backend"] = msg.backend;
284     map["ConnectionProperties"] = msg.setupData;
285
286     // Auth backend properties.
287     map["Authenticator"] = msg.authenticator;
288     map["AuthProperties"] = msg.authSetupData;
289
290     QVariantMap m;
291     m["MsgType"] = "CoreSetupData";
292     m["SetupData"] = map;
293     writeMessage(m);
294 }
295
296
297 void LegacyPeer::dispatch(const SetupFailed &msg)
298 {
299     QVariantMap m;
300     m["MsgType"] = "CoreSetupReject";
301     m["Error"] = msg.errorString;
302
303     writeMessage(m);
304 }
305
306
307 void LegacyPeer::dispatch(const SetupDone &msg)
308 {
309     Q_UNUSED(msg)
310
311     QVariantMap m;
312     m["MsgType"] = "CoreSetupAck";
313
314     writeMessage(m);
315 }
316
317
318 void LegacyPeer::dispatch(const Login &msg)
319 {
320     QVariantMap m;
321     m["MsgType"] = "ClientLogin";
322     m["User"] = msg.user;
323     m["Password"] = msg.password;
324
325     writeMessage(m);
326 }
327
328
329 void LegacyPeer::dispatch(const LoginFailed &msg)
330 {
331     QVariantMap m;
332     m["MsgType"] = "ClientLoginReject";
333     m["Error"] = msg.errorString;
334
335     writeMessage(m);
336 }
337
338
339 void LegacyPeer::dispatch(const LoginSuccess &msg)
340 {
341     Q_UNUSED(msg)
342
343     QVariantMap m;
344     m["MsgType"] = "ClientLoginAck";
345
346     writeMessage(m);
347 }
348
349
350 void LegacyPeer::dispatch(const SessionState &msg)
351 {
352     QVariantMap m;
353     m["MsgType"] = "SessionInit";
354
355     QVariantMap map;
356     map["BufferInfos"] = msg.bufferInfos;
357     map["NetworkIds"] = msg.networkIds;
358     map["Identities"] = msg.identities;
359     m["SessionState"] = map;
360
361     writeMessage(m);
362 }
363
364
365 /*** Standard messages ***/
366
367 void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
368 {
369     QVariantList params(packedFunc.toList());
370
371     if (params.isEmpty()) {
372         qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
373         return;
374     }
375
376     // TODO: make sure that this is a valid request type
377     RequestType requestType = (RequestType)params.takeFirst().value<int>();
378     switch (requestType) {
379         case Sync: {
380             if (params.count() < 3) {
381                 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
382                 return;
383             }
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));
388             break;
389         }
390         case RpcCall: {
391             if (params.empty()) {
392                 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
393                 return;
394             }
395             QByteArray slotName = params.takeFirst().toByteArray();
396             handle(Protocol::RpcCall(slotName, params));
397             break;
398         }
399         case InitRequest: {
400             if (params.count() != 2) {
401                 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
402                 return;
403             }
404             QByteArray className = params[0].toByteArray();
405             QString objectName = params[1].toString();
406             handle(Protocol::InitRequest(className, objectName));
407             break;
408         }
409         case InitData: {
410             if (params.count() != 3) {
411                 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
412                 return;
413             }
414             QByteArray className = params[0].toByteArray();
415             QString objectName = params[1].toString();
416             QVariantMap initData = params[2].toMap();
417
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));
422             break;
423         }
424         case HeartBeat: {
425             if (params.count() != 1) {
426                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
427                 return;
428             }
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));
434             break;
435         }
436         case HeartBeatReply: {
437             if (params.count() != 1) {
438                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
439                 return;
440             }
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));
446             break;
447         }
448
449     }
450 }
451
452
453 void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
454 {
455     dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
456 }
457
458
459 void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
460 {
461     dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
462 }
463
464
465 void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
466 {
467     dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
468 }
469
470
471 void LegacyPeer::dispatch(const Protocol::InitData &msg)
472 {
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);
478     }
479     else
480         dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
481 }
482
483
484 void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
485 {
486     dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
487 }
488
489
490 void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
491 {
492     dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
493 }
494
495
496 void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
497 {
498     writeMessage(QVariant(packedFunc));
499 }
500
501
502 // Handle the changed format for Network's initData
503 // cf. Network::initIrcUsersAndChannels()
504 void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
505 {
506     const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
507     QVariantMap newMap;
508
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];
514     }
515     QVariantMap userMap;
516     foreach(const QString &key, users.keys())
517         userMap[key] = users[key];
518     newMap["Users"] = userMap;
519
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];
525     }
526     QVariantMap channelMap;
527     foreach(const QString &key, channels.keys())
528         channelMap[key] = channels[key];
529     newMap["Channels"] = channelMap;
530
531     initData["IrcUsersAndChannels"] = newMap;
532 }
533
534
535 void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
536 {
537     const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
538     QVariantMap legacyMap;
539
540     // toMap() and toList() are cheap, so no need to copy to a hash
541
542     QVariantMap userMap;
543     const QVariantMap &users = usersAndChannels["Users"].toMap();
544
545     int size = users["nick"].toList().size(); // we know this key exists
546     for(int i = 0; i < size; i++) {
547         QVariantMap map;
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;
552     }
553     legacyMap["users"] = userMap;
554
555     QVariantMap channelMap;
556     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
557
558     size = channels["name"].toList().size();
559     for(int i = 0; i < size; i++) {
560         QVariantMap map;
561         foreach(const QString &key, channels.keys())
562             map[key] = channels[key].toList().at(i);
563         channelMap[map["name"].toString().toLower()] = map;
564     }
565     legacyMap["channels"] = channelMap;
566
567     initData["IrcUsersAndChannels"] = legacyMap;
568 }