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