common: Represent core/client features as string list in the protocol
[quassel.git] / src / common / protocols / datastream / datastreampeer.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 <QtEndian>
22 #include <QDataStream>
23 #include <QHostAddress>
24 #include <QTcpSocket>
25
26 #include "datastreampeer.h"
27 #include "quassel.h"
28
29 using namespace Protocol;
30
31 DataStreamPeer::DataStreamPeer(::AuthHandler *authHandler, QTcpSocket *socket, quint16 features, Compressor::CompressionLevel level, QObject *parent)
32     : RemotePeer(authHandler, socket, level, parent)
33 {
34     Q_UNUSED(features);
35 }
36
37
38 quint16 DataStreamPeer::supportedFeatures()
39 {
40     return 0;
41 }
42
43
44 bool DataStreamPeer::acceptsFeatures(quint16 peerFeatures)
45 {
46     Q_UNUSED(peerFeatures);
47     return true;
48 }
49
50
51 quint16 DataStreamPeer::enabledFeatures() const
52 {
53     return 0;
54 }
55
56
57 void DataStreamPeer::processMessage(const QByteArray &msg)
58 {
59     QDataStream stream(msg);
60     stream.setVersion(QDataStream::Qt_4_2);
61     QVariantList list;
62     stream >> list;
63     if (stream.status() != QDataStream::Ok) {
64         close("Peer sent corrupt data, closing down!");
65         return;
66     }
67
68     // if no sigproxy is set, we're in handshake mode
69     if (!signalProxy())
70         handleHandshakeMessage(list);
71     else
72         handlePackedFunc(list);
73 }
74
75
76 void DataStreamPeer::writeMessage(const QVariantMap &handshakeMsg)
77 {
78     QVariantList list;
79     QVariantMap::const_iterator it = handshakeMsg.begin();
80     while (it != handshakeMsg.end()) {
81         list << it.key().toUtf8() << it.value();
82         ++it;
83     }
84
85     writeMessage(list);
86 }
87
88
89 void DataStreamPeer::writeMessage(const QVariantList &sigProxyMsg)
90 {
91     QByteArray data;
92     QDataStream msgStream(&data, QIODevice::WriteOnly);
93     msgStream.setVersion(QDataStream::Qt_4_2);
94     msgStream << sigProxyMsg;
95
96     writeMessage(data);
97 }
98
99
100 /*** Handshake messages ***/
101
102 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
103  * a structure different from those being used after the handshake.
104  * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
105  */
106
107 void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData)
108 {
109     QVariantMap m;
110     for (int i = 0; i < mapData.count()/2; ++i)
111         m[QString::fromUtf8(mapData[2*i].toByteArray())] = mapData[2*i+1];
112
113     QString msgType = m["MsgType"].toString();
114     if (msgType.isEmpty()) {
115         emit protocolError(tr("Invalid handshake message!"));
116         return;
117     }
118
119     if (msgType == "ClientInit") {
120         handle(RegisterClient{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())},
121                               m["ClientVersion"].toString(),
122                               m["ClientDate"].toString(),
123                               false  // UseSsl obsolete
124                });
125     }
126
127     else if (msgType == "ClientInitReject") {
128         handle(ClientDenied(m["Error"].toString()));
129     }
130
131     else if (msgType == "ClientInitAck") {
132         handle(ClientRegistered{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())},
133                                 m["Configured"].toBool(),
134                                 m["StorageBackends"].toList(),
135                                 m["Authenticators"].toList(),
136                                 false  // SupportsSsl obsolete
137                });
138     }
139
140     else if (msgType == "CoreSetupData") {
141         QVariantMap map = m["SetupData"].toMap();
142         handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
143     }
144
145     else if (msgType == "CoreSetupReject") {
146         handle(SetupFailed(m["Error"].toString()));
147     }
148
149     else if (msgType == "CoreSetupAck") {
150         handle(SetupDone());
151     }
152
153     else if (msgType == "ClientLogin") {
154         handle(Login(m["User"].toString(), m["Password"].toString()));
155     }
156
157     else if (msgType == "ClientLoginReject") {
158         handle(LoginFailed(m["Error"].toString()));
159     }
160
161     else if (msgType == "ClientLoginAck") {
162         handle(LoginSuccess());
163     }
164
165     else if (msgType == "SessionInit") {
166         QVariantMap map = m["SessionState"].toMap();
167         handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
168     }
169
170     else {
171         emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
172     }
173 }
174
175
176 void DataStreamPeer::dispatch(const RegisterClient &msg) {
177     QVariantMap m;
178     m["MsgType"] = "ClientInit";
179     m["Features"] = static_cast<quint32>(msg.features.toLegacyFeatures());
180     m["FeatureList"] = msg.features.toStringList();
181     m["ClientVersion"] = msg.clientVersion;
182     m["ClientDate"] = msg.buildDate;
183
184     writeMessage(m);
185 }
186
187
188 void DataStreamPeer::dispatch(const ClientDenied &msg) {
189     QVariantMap m;
190     m["MsgType"] = "ClientInitReject";
191     m["Error"] = msg.errorString;
192
193     writeMessage(m);
194 }
195
196
197 void DataStreamPeer::dispatch(const ClientRegistered &msg) {
198     QVariantMap m;
199     m["MsgType"] = "ClientInitAck";
200     if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
201         m["FeatureList"] = msg.features.toStringList();
202     }
203     else {
204         m["CoreFeatures"] = static_cast<quint32>(msg.features.toLegacyFeatures());
205     }
206     m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
207     m["StorageBackends"] = msg.backendInfo;
208     if (hasFeature(Quassel::Feature::Authenticators)) {
209         m["Authenticators"] = msg.authenticatorInfo;
210     }
211
212     writeMessage(m);
213 }
214
215
216 void DataStreamPeer::dispatch(const SetupData &msg)
217 {
218     QVariantMap map;
219     map["AdminUser"] = msg.adminUser;
220     map["AdminPasswd"] = msg.adminPassword;
221     map["Backend"] = msg.backend;
222     map["ConnectionProperties"] = msg.setupData;
223
224     // Auth backend properties.
225     map["Authenticator"] = msg.authenticator;
226     map["AuthProperties"] = msg.authSetupData;
227
228     QVariantMap m;
229     m["MsgType"] = "CoreSetupData";
230     m["SetupData"] = map;
231
232     writeMessage(m);
233 }
234
235
236 void DataStreamPeer::dispatch(const SetupFailed &msg)
237 {
238     QVariantMap m;
239     m["MsgType"] = "CoreSetupReject";
240     m["Error"] = msg.errorString;
241
242     writeMessage(m);
243 }
244
245
246 void DataStreamPeer::dispatch(const SetupDone &msg)
247 {
248     Q_UNUSED(msg)
249
250     QVariantMap m;
251     m["MsgType"] = "CoreSetupAck";
252
253     writeMessage(m);
254 }
255
256
257 void DataStreamPeer::dispatch(const Login &msg)
258 {
259     QVariantMap m;
260     m["MsgType"] = "ClientLogin";
261     m["User"] = msg.user;
262     m["Password"] = msg.password;
263
264     writeMessage(m);
265 }
266
267
268 void DataStreamPeer::dispatch(const LoginFailed &msg)
269 {
270     QVariantMap m;
271     m["MsgType"] = "ClientLoginReject";
272     m["Error"] = msg.errorString;
273
274     writeMessage(m);
275 }
276
277
278 void DataStreamPeer::dispatch(const LoginSuccess &msg)
279 {
280     Q_UNUSED(msg)
281
282     QVariantMap m;
283     m["MsgType"] = "ClientLoginAck";
284
285     writeMessage(m);
286 }
287
288
289 void DataStreamPeer::dispatch(const SessionState &msg)
290 {
291     QVariantMap m;
292     m["MsgType"] = "SessionInit";
293
294     QVariantMap map;
295     map["BufferInfos"] = msg.bufferInfos;
296     map["NetworkIds"] = msg.networkIds;
297     map["Identities"] = msg.identities;
298     m["SessionState"] = map;
299
300     writeMessage(m);
301 }
302
303
304 /*** Standard messages ***/
305
306 void DataStreamPeer::handlePackedFunc(const QVariantList &packedFunc)
307 {
308     QVariantList params(packedFunc);
309
310     if (params.isEmpty()) {
311         qWarning() << Q_FUNC_INFO << "Received incompatible data:" << packedFunc;
312         return;
313     }
314
315     // TODO: make sure that this is a valid request type
316     RequestType requestType = (RequestType)params.takeFirst().value<qint16>();
317     switch (requestType) {
318         case Sync: {
319             if (params.count() < 3) {
320                 qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
321                 return;
322             }
323             QByteArray className = params.takeFirst().toByteArray();
324             QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
325             QByteArray slotName = params.takeFirst().toByteArray();
326             handle(Protocol::SyncMessage(className, objectName, slotName, params));
327             break;
328         }
329         case RpcCall: {
330             if (params.empty()) {
331                 qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
332                 return;
333             }
334             QByteArray slotName = params.takeFirst().toByteArray();
335             handle(Protocol::RpcCall(slotName, params));
336             break;
337         }
338         case InitRequest: {
339             if (params.count() != 2) {
340                 qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
341                 return;
342             }
343             QByteArray className = params[0].toByteArray();
344             QString objectName = QString::fromUtf8(params[1].toByteArray());
345             handle(Protocol::InitRequest(className, objectName));
346             break;
347         }
348         case InitData: {
349             if (params.count() < 2) {
350                 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
351                 return;
352             }
353             QByteArray className = params.takeFirst().toByteArray();
354             QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
355             QVariantMap initData;
356             for (int i = 0; i < params.count()/2; ++i)
357                 initData[QString::fromUtf8(params[2*i].toByteArray())] = params[2*i+1];
358             handle(Protocol::InitData(className, objectName, initData));
359             break;
360         }
361         case HeartBeat: {
362             if (params.count() != 1) {
363                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
364                 return;
365             }
366             // Note: QDateTime instead of QTime as in the legacy protocol!
367             handle(Protocol::HeartBeat(params[0].toDateTime()));
368             break;
369         }
370         case HeartBeatReply: {
371             if (params.count() != 1) {
372                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
373                 return;
374             }
375             // Note: QDateTime instead of QTime as in the legacy protocol!
376             handle(Protocol::HeartBeatReply(params[0].toDateTime()));
377             break;
378         }
379
380     }
381 }
382
383
384 void DataStreamPeer::dispatch(const Protocol::SyncMessage &msg)
385 {
386     dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName.toUtf8() << msg.slotName << msg.params);
387 }
388
389
390 void DataStreamPeer::dispatch(const Protocol::RpcCall &msg)
391 {
392     dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
393 }
394
395
396 void DataStreamPeer::dispatch(const Protocol::InitRequest &msg)
397 {
398     dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName.toUtf8());
399 }
400
401
402 void DataStreamPeer::dispatch(const Protocol::InitData &msg)
403 {
404     QVariantList initData;
405     QVariantMap::const_iterator it = msg.initData.begin();
406     while (it != msg.initData.end()) {
407         initData << it.key().toUtf8() << it.value();
408         ++it;
409     }
410     dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName.toUtf8() << initData);
411 }
412
413
414 void DataStreamPeer::dispatch(const Protocol::HeartBeat &msg)
415 {
416     dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp);
417 }
418
419
420 void DataStreamPeer::dispatch(const Protocol::HeartBeatReply &msg)
421 {
422     dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp);
423 }
424
425
426 void DataStreamPeer::dispatchPackedFunc(const QVariantList &packedFunc)
427 {
428     writeMessage(packedFunc);
429 }