summaryrefslogtreecommitdiff
path: root/src/webchannel/qwebsocketserver.cpp
blob: 5a5b5a7445f49d207e2a38ea96d5902f36652a49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/****************************************************************************
**
** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebChannel module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwebsocketserver_p.h"

#include <QTcpServer>
#include <QTcpSocket>
#include <QCryptographicHash>
#include <QtEndian>

#include <limits>

QT_BEGIN_NAMESPACE

namespace {
template<typename T>
inline static void appendBytes(QByteArray& data, T value)
{
    data.append(reinterpret_cast<const char*>(&value), sizeof(value));
}

inline static void unmask(QByteArray& data, char mask[4])
{
    for (int i = 0; i < data.size(); ++i) {
        int j = i % 4;
        data[i] = data[i] ^ mask[j];
    }
}

inline static char bitMask(int bit)
{
    return 1 << bit;
}

// see: http://tools.ietf.org/html/rfc6455#page-28
static const char FIN_BIT = bitMask(7);
static const char MASKED_BIT = bitMask(7);
static const char OPCODE_RANGE = bitMask(4) - 1;
static const char PAYLOAD_RANGE = bitMask(7) - 1;
static const char EXTENDED_PAYLOAD = 126;
static const char EXTENDED_LONG_PAYLOAD = 127;
}

QWebSocketServer::QWebSocketServer(QObject* parent)
: QObject(parent)
, m_server(new QTcpServer(this))
{
    connect(m_server, SIGNAL(newConnection()),
            SLOT(newConnection()));
    connect(m_server, SIGNAL(acceptError(QAbstractSocket::SocketError)),
            SIGNAL(error(QAbstractSocket::SocketError)));
}

QWebSocketServer::~QWebSocketServer()
{
    close();
}

bool QWebSocketServer::listen(const QHostAddress& address, quint16 port)
{
    return m_server->listen(address, port);
}

void QWebSocketServer::close()
{
    sendFrame(Frame::ConnectionClose, QByteArray());
    m_server->close();
}

quint16 QWebSocketServer::port() const
{
    return m_server->serverPort();
}

QHostAddress QWebSocketServer::address() const
{
    return m_server->serverAddress();
}

QString QWebSocketServer::errorString() const
{
    return m_server->errorString();
}

void QWebSocketServer::newConnection()
{
    if (!m_server->hasPendingConnections())
        return;

    QTcpSocket* connection = m_server->nextPendingConnection();
    m_connections.insert(connection, Connection());
    connect(connection, SIGNAL(readyRead()),
            SLOT(readSocketData()));
    connect(connection, SIGNAL(error(QAbstractSocket::SocketError)),
            SIGNAL(error(QAbstractSocket::SocketError)));
    connect(connection, SIGNAL(disconnected()),
            SLOT(disconnected()));
}

void QWebSocketServer::disconnected()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);

    m_connections.remove(socket);
}

static const QByteArray headerSwitchProtocols = QByteArrayLiteral("HTTP/1.1 101 Switching Protocols");
static const QByteArray headerGet = QByteArrayLiteral("GET ");
static const QByteArray headerHTTP = QByteArrayLiteral("HTTP/1.1");
static const QByteArray headerHost = QByteArrayLiteral("Host: ");
static const QByteArray headerUpgrade = QByteArrayLiteral("Upgrade: websocket");
static const QByteArray headerConnection = QByteArrayLiteral("Connection: Upgrade");
static const QByteArray headerSecKey = QByteArrayLiteral("Sec-WebSocket-Key: ");
static const QByteArray headerSecProtocol = QByteArrayLiteral("Sec-WebSocket-Protocol: ");
static const QByteArray headerSecVersion = QByteArrayLiteral("Sec-WebSocket-Version: 13");
static const QByteArray headerSecAccept = QByteArrayLiteral("Sec-WebSocket-Accept: ");
static const QByteArray headerOrigin = QByteArrayLiteral("Origin: ");
static const QByteArray headerMagicKey = QByteArrayLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
static const QByteArray headerEOL = QByteArrayLiteral("\r\n");
static const QByteArray httpBadRequest = QByteArrayLiteral("HTTP/1.1 400 Bad Request\r\n");

void QWebSocketServer::readSocketData()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);

    Connection& connection = m_connections[socket];

    if (!connection.header.wasUpgraded) {
        readHeaderData(socket, connection.header);
    }

    if (connection.header.wasUpgraded) {
        while (socket->bytesAvailable()) {
            if (!readFrameData(socket, connection.currentFrame)) {
                close(socket, connection.header);
            }
        }
    }
}

void QWebSocketServer::readHeaderData(QTcpSocket* socket, HeaderData& header)
{
    while (socket->canReadLine()) {
        QByteArray line = socket->readLine().trimmed();
        if (line.isEmpty()) {
            // finalize
            if (isValid(header)) {
                upgrade(socket, header);
            } else {
                close(socket, header);
            }
            break;
        } else if (line.startsWith(headerGet) && line.endsWith(headerHTTP)) {
            header.path = line.mid(headerGet.size(), line.size() - headerGet.size() - headerHTTP.size()).trimmed();
        } else if (line.startsWith(headerHost)) {
            header.host = line.mid(headerHost.size()).trimmed();
        } else if (line.startsWith(headerSecKey)) {
            header.key = line.mid(headerSecKey.size()).trimmed();
        } else if (line.startsWith(headerOrigin)) {
            header.origin = line.mid(headerOrigin.size()).trimmed();
        } else if (line.startsWith(headerSecProtocol)) {
            header.protocol = line.mid(headerSecProtocol.size()).trimmed();
        } else if (line == headerUpgrade) {
            header.hasUpgrade = true;
        } else if (line == headerConnection) {
            header.hasConnection = true;
        } else if (line == headerSecVersion) {
            header.hasVersion = true;
        } else {
            header.otherHeaders << line;
        }
    }
}

// see: http://tools.ietf.org/html/rfc6455#page-28
bool QWebSocketServer::readFrameData(QTcpSocket* socket, Frame& frame)
{
    int bytesAvailable = socket->bytesAvailable();
    if (frame.state == Frame::ReadStart) {
        if (bytesAvailable < 2) {
            return true;
        }
        uchar buffer[2];
        socket->read(reinterpret_cast<char*>(buffer), 2);
        bytesAvailable -= 2;
        frame.fin = buffer[0] & FIN_BIT;
        // skip rsv1, rsv2, rsv3
        // last four bits are the opcode
        quint8 opcode = buffer[0] & OPCODE_RANGE;
        if (opcode != Frame::ContinuationFrame && opcode != Frame::BinaryFrame &&
            opcode != Frame::ConnectionClose && opcode != Frame::TextFrame &&
            opcode != Frame::Ping && opcode != Frame::Pong)
        {
            qWarning() << "invalid opcode: " << opcode;
            return false;
        }
        frame.opcode = static_cast<Frame::Opcode>(opcode);
        // test first, i.e. highest bit for mask
        frame.masked = buffer[1] & MASKED_BIT;
        if (!frame.masked) {
            qWarning() << "unmasked frame received";
            return false;
        }
        // final seven bits are the payload length
        frame.length = static_cast<quint8>(buffer[1] & PAYLOAD_RANGE);
        if (frame.length == EXTENDED_PAYLOAD) {
            frame.state = Frame::ReadExtendedPayload;
        } else if (frame.length == EXTENDED_LONG_PAYLOAD) {
            frame.state = Frame::ReadExtendedLongPayload;
        } else {
            frame.state = Frame::ReadMask;
        }
    }
    if (frame.state == Frame::ReadExtendedPayload) {
        if (bytesAvailable < 2) {
            return true;
        }
        uchar buffer[2];
        socket->read(reinterpret_cast<char*>(buffer), 2);
        bytesAvailable -= 2;
        frame.length = qFromBigEndian<quint16>(buffer);
        frame.state = Frame::ReadMask;
    }
    if (frame.state == Frame::ReadExtendedLongPayload) {
        if (bytesAvailable < 8) {
            return true;
        }
        uchar buffer[8];
        socket->read(reinterpret_cast<char*>(buffer), 8);
        bytesAvailable -= 8;
        quint64 longSize = qFromBigEndian<quint64>(buffer);
        // QByteArray uses int for size type so limit ourselves to that size as well
        if (longSize > static_cast<quint64>(std::numeric_limits<int>::max())) {
            return false;
        }
        frame.length = static_cast<int>(longSize);
        frame.state = Frame::ReadMask;
    }
    if (frame.state == Frame::ReadMask) {
        if (bytesAvailable < 4) {
            return true;
        }
        socket->read(frame.mask, 4);
        bytesAvailable -= 4;
        frame.state = Frame::ReadData;
        frame.data.reserve(frame.length);
    }
    if (frame.state == Frame::ReadData && (bytesAvailable || !frame.length)) {
        frame.data.append(socket->read(qMin(frame.length - frame.data.size(), bytesAvailable)));
        if (frame.data.size() == frame.length) {
            frame.state = Frame::ReadStart;
            handleFrame(socket, frame);
        }
    }
    return true;
}

void QWebSocketServer::handleFrame(QTcpSocket* socket, Frame& frame)
{
    unmask(frame.data, frame.mask);

    // fragmentation support -  see http://tools.ietf.org/html/rfc6455#page-33
    if (!frame.fin) {
        if (frame.opcode != Frame::ContinuationFrame) {
            frame.initialOpcode = frame.opcode;
        }
        frame.fragments += frame.data;
    } else if (frame.fin && frame.opcode == Frame::ContinuationFrame) {
        frame.opcode = frame.initialOpcode;
        frame.data = frame.fragments + frame.data;
    } // otherwise if it's fin and a non-continuation frame its a single-frame message

    switch (frame.opcode) {
    case Frame::ContinuationFrame:
        // do nothing
        break;
    case Frame::Ping:
        socket->write(frameHeader(Frame::Pong, 0));
        break;
    case Frame::Pong:
        emit pongReceived();
        break;
    case Frame::ConnectionClose:
        ///TODO: handle?
        qWarning("Unhandled connection close frame");
        break;
    case Frame::BinaryFrame:
        emit binaryDataReceived(frame.data);
        break;
    case Frame::TextFrame:
        emit textDataReceived(QString::fromUtf8(frame.data));
        break;
    }

    if (frame.fin) {
        frame = Frame();
    }
}

bool QWebSocketServer::isValid(const HeaderData& header)
{
    return !header.path.isEmpty() && !header.host.isEmpty() && !header.key.isEmpty()
        && header.hasUpgrade && header.hasConnection && header.hasVersion;
}

void QWebSocketServer::close(QTcpSocket* socket, const HeaderData& header)
{
    if (header.wasUpgraded) {
        //TODO: implement this properly - see http://tools.ietf.org/html/rfc6455#page-36
        socket->write(frameHeader(Frame::Frame::ConnectionClose, 0));
    } else {
        socket->write(httpBadRequest);
    }
    socket->close();
}

void QWebSocketServer::upgrade(QTcpSocket* socket, HeaderData& header)
{
    socket->write(headerSwitchProtocols);
    socket->write(headerEOL);

    socket->write(headerUpgrade);
    socket->write(headerEOL);

    socket->write(headerConnection);
    socket->write(headerEOL);

    socket->write(headerSecAccept);
    socket->write(QCryptographicHash::hash( header.key + headerMagicKey, QCryptographicHash::Sha1 ).toBase64());
    socket->write(headerEOL);

    if (!header.protocol.isEmpty()) {
        socket->write(headerSecProtocol);
        socket->write(header.protocol);
        socket->write(headerEOL);
    }

    socket->write(headerEOL);

    header.wasUpgraded = true;
}

void QWebSocketServer::sendMessage(const QByteArray& message) const
{
    sendFrame(Frame::TextFrame, message);
}

void QWebSocketServer::sendFrame(Frame::Opcode opcode, const QByteArray& data) const
{
    if (m_connections.isEmpty()) {
        return;
    }
    const QByteArray& header = frameHeader(opcode, data.size());
    QHash< QTcpSocket*, Connection >::const_iterator it = m_connections.constBegin();
    while (it != m_connections.constEnd()) {
        if (it.value().header.wasUpgraded) {
            it.key()->write(header);
            it.key()->write(data);
        }
        ++it;
    }
}

// see: http://tools.ietf.org/html/rfc6455#page-28
QByteArray QWebSocketServer::frameHeader(QWebSocketServer::Frame::Opcode opcode, const int dataSize) const
{
    // we only support single frames for now
    Q_ASSERT(opcode != Frame::ContinuationFrame);

    QByteArray header;
    header.reserve(4);
    header.append(FIN_BIT | opcode);
    if (dataSize < EXTENDED_PAYLOAD) {
        header.append(static_cast<char>(dataSize));
    } else if (dataSize < std::numeric_limits<quint16>::max()) {
        header.append(EXTENDED_PAYLOAD);
        appendBytes(header, qToBigEndian<quint16>(dataSize));
    } else {
        header.append(EXTENDED_LONG_PAYLOAD);
        appendBytes(header, qToBigEndian<quint64>(dataSize));
    }
    return header;
}

void QWebSocketServer::ping() const
{
    sendFrame(Frame::Ping, QByteArray());
}

QT_END_NAMESPACE