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