DataStreamPeer: Use UTF-8 QByteArrays instead of QString for message headers
[quassel.git] / src / common / protocols / datastream / datastreampeer.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 "datastreampeer.h"
25 #include "quassel.h"
26
27 using namespace Protocol;
28
29 DataStreamPeer::DataStreamPeer(::AuthHandler *authHandler, QTcpSocket *socket, quint16 features, QObject *parent)
30     : RemotePeer(authHandler, socket, parent),
31     _blockSize(0)
32 {
33     Q_UNUSED(features);
34
35     _stream.setDevice(socket);
36     _stream.setVersion(QDataStream::Qt_4_2);
37 }
38
39
40 quint16 DataStreamPeer::supportedFeatures()
41 {
42     return 0;
43 }
44
45
46 bool DataStreamPeer::acceptsFeatures(quint16 peerFeatures)
47 {
48     Q_UNUSED(peerFeatures);
49     return true;
50 }
51
52
53 quint16 DataStreamPeer::enabledFeatures() const
54 {
55     return 0;
56 }
57
58
59 void DataStreamPeer::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 DataStreamPeer::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     _stream >> item;
98     _blockSize = 0;
99
100     if (!item.isValid()) {
101         close("Peer sent corrupt data: unable to load QVariant!");
102         return false;
103     }
104
105     return true;
106 }
107
108
109 void DataStreamPeer::writeSocketData(const QVariant &item)
110 {
111     if (!socket()->isOpen()) {
112         qWarning() << Q_FUNC_INFO << "Can't write to a closed socket!";
113         return;
114     }
115
116     QByteArray block;
117     QDataStream out(&block, QIODevice::WriteOnly);
118     out.setVersion(QDataStream::Qt_4_2);
119
120     out << item;
121
122     _stream << block;  // also writes the length as part of the serialization format
123 }
124
125
126 /*** Handshake messages ***/
127
128 /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
129  * a structure different from those being used after the handshake.
130  * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
131  */
132
133 void DataStreamPeer::handleHandshakeMessage(const QVariant &msg)
134 {
135     QVariantMap m = msg.toMap();
136
137     QString msgType = m["MsgType"].toString();
138     if (msgType.isEmpty()) {
139         emit protocolError(tr("Invalid handshake message!"));
140         return;
141     }
142
143     if (msgType == "ClientInit") {
144         handle(RegisterClient(m["ClientVersion"].toString(), false)); // UseSsl obsolete
145     }
146
147     else if (msgType == "ClientInitReject") {
148         handle(ClientDenied(m["Error"].toString()));
149     }
150
151     else if (msgType == "ClientInitAck") {
152         handle(ClientRegistered(m["CoreFeatures"].toUInt(), m["Configured"].toBool(), m["StorageBackends"].toList(), false, QDateTime())); // SupportsSsl and coreStartTime obsolete
153     }
154
155     else if (msgType == "CoreSetupData") {
156         QVariantMap map = m["SetupData"].toMap();
157         handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap()));
158     }
159
160     else if (msgType == "CoreSetupReject") {
161         handle(SetupFailed(m["Error"].toString()));
162     }
163
164     else if (msgType == "CoreSetupAck") {
165         handle(SetupDone());
166     }
167
168     else if (msgType == "ClientLogin") {
169         handle(Login(m["User"].toString(), m["Password"].toString()));
170     }
171
172     else if (msgType == "ClientLoginReject") {
173         handle(LoginFailed(m["Error"].toString()));
174     }
175
176     else if (msgType == "ClientLoginAck") {
177         handle(LoginSuccess());
178     }
179
180     else if (msgType == "SessionInit") {
181         QVariantMap map = m["SessionState"].toMap();
182         handle(SessionState(map["Identities"].toList(), map["BufferInfos"].toList(), map["NetworkIds"].toList()));
183     }
184
185     else {
186         emit protocolError(tr("Unknown protocol message of type %1").arg(msgType));
187     }
188 }
189
190
191 void DataStreamPeer::dispatch(const RegisterClient &msg) {
192     QVariantMap m;
193     m["MsgType"] = "ClientInit";
194     m["ClientVersion"] = msg.clientVersion;
195     m["ClientDate"] = Quassel::buildInfo().buildDate;
196
197     writeSocketData(m);
198 }
199
200
201 void DataStreamPeer::dispatch(const ClientDenied &msg) {
202     QVariantMap m;
203     m["MsgType"] = "ClientInitReject";
204     m["Error"] = msg.errorString;
205
206     writeSocketData(m);
207 }
208
209
210 void DataStreamPeer::dispatch(const ClientRegistered &msg) {
211     QVariantMap m;
212     m["MsgType"] = "ClientInitAck";
213     m["CoreFeatures"] = msg.coreFeatures;
214     m["StorageBackends"] = msg.backendInfo;
215     m["LoginEnabled"] = m["Configured"] = msg.coreConfigured;
216
217     writeSocketData(m);
218 }
219
220
221 void DataStreamPeer::dispatch(const SetupData &msg)
222 {
223     QVariantMap map;
224     map["AdminUser"] = msg.adminUser;
225     map["AdminPasswd"] = msg.adminPassword;
226     map["Backend"] = msg.backend;
227     map["ConnectionProperties"] = msg.setupData;
228
229     QVariantMap m;
230     m["MsgType"] = "CoreSetupData";
231     m["SetupData"] = map;
232     writeSocketData(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     writeSocketData(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     writeSocketData(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     writeSocketData(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     writeSocketData(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     writeSocketData(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     writeSocketData(m);
301 }
302
303
304 /*** Standard messages ***/
305
306 void DataStreamPeer::handlePackedFunc(const QVariant &packedFunc)
307 {
308     QVariantList params(packedFunc.toList());
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<int>();
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() != 3) {
350                 qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
351                 return;
352             }
353             QByteArray className = params[0].toByteArray();
354             QString objectName = QString::fromUtf8(params[1].toByteArray());
355             QVariantMap initData = params[2].toMap();
356             handle(Protocol::InitData(className, objectName, initData));
357             break;
358         }
359         case HeartBeat: {
360             if (params.count() != 1) {
361                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
362                 return;
363             }
364             // The legacy protocol would only send a QTime, no QDateTime
365             // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
366             QDateTime dateTime = QDateTime::currentDateTime().toUTC();
367             dateTime.setTime(params[0].toTime());
368             handle(Protocol::HeartBeat(dateTime));
369             break;
370         }
371         case HeartBeatReply: {
372             if (params.count() != 1) {
373                 qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
374                 return;
375             }
376             // The legacy protocol would only send a QTime, no QDateTime
377             // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
378             QDateTime dateTime = QDateTime::currentDateTime().toUTC();
379             dateTime.setTime(params[0].toTime());
380             handle(Protocol::HeartBeatReply(dateTime));
381             break;
382         }
383
384     }
385 }
386
387
388 void DataStreamPeer::dispatch(const Protocol::SyncMessage &msg)
389 {
390     dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName.toUtf8() << msg.slotName << msg.params);
391 }
392
393
394 void DataStreamPeer::dispatch(const Protocol::RpcCall &msg)
395 {
396     dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
397 }
398
399
400 void DataStreamPeer::dispatch(const Protocol::InitRequest &msg)
401 {
402     dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName.toUtf8());
403 }
404
405
406 void DataStreamPeer::dispatch(const Protocol::InitData &msg)
407 {
408     dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName.toUtf8() << msg.initData);
409 }
410
411
412 void DataStreamPeer::dispatch(const Protocol::HeartBeat &msg)
413 {
414     dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
415 }
416
417
418 void DataStreamPeer::dispatch(const Protocol::HeartBeatReply &msg)
419 {
420     dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
421 }
422
423
424 void DataStreamPeer::dispatchPackedFunc(const QVariantList &packedFunc)
425 {
426     writeSocketData(QVariant(packedFunc));
427 }