summaryrefslogtreecommitdiffstats
path: root/tests/auto/network/access/http2/http2srv.cpp
blob: f919937fc3211094b4e4870dadb2609e4f0768ae (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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <QtNetwork/private/http2protocol_p.h>
#include <QtNetwork/private/bitstreams_p.h>

#include "http2srv.h"

#ifndef QT_NO_SSL
#include <QtNetwork/qsslconfiguration.h>
#include <QtNetwork/qsslsocket.h>
#include <QtNetwork/qsslkey.h>
#endif

#include <QtNetwork/qtcpsocket.h>

#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qfile.h>

#include <cstdlib>
#include <cstring>
#include <limits>

QT_BEGIN_NAMESPACE

using namespace Http2;
using namespace HPack;

namespace
{

inline bool is_valid_client_stream(quint32 streamID)
{
    // A valid client stream ID is an odd integer number in the range [1, INT_MAX].
    return (streamID & 0x1) && streamID <= std::numeric_limits<qint32>::max();
}

}

Http2Server::Http2Server(bool h2c, const Http2Settings &ss, const Http2Settings &cs)
    : serverSettings(ss),
      clearTextHTTP2(h2c)
{
    for (const auto &s : cs)
        expectedClientSettings[quint16(s.identifier)] = s.value;

    responseBody = "<html>\n"
                   "<head>\n"
                   "<title>Sample \"Hello, World\" Application</title>\n"
                   "</head>\n"
                   "<body bgcolor=white>\n"
                   "<table border=\"0\" cellpadding=\"10\">\n"
                   "<tr>\n"
                   "<td>\n"
                   "<img src=\"images/springsource.png\">\n"
                   "</td>\n"
                   "<td>\n"
                   "<h1>Sample \"Hello, World\" Application</h1>\n"
                   "</td>\n"
                   "</tr>\n"
                   "</table>\n"
                   "<p>This is the home page for the HelloWorld Web application. </p>\n"
                   "</body>\n"
                   "</html>";
}

Http2Server::~Http2Server()
{
}

void Http2Server::setResponseBody(const QByteArray &body)
{
    responseBody = body;
}

void Http2Server::startServer()
{
#ifdef QT_NO_SSL
    // Let the test fail with timeout.
    if (!clearTextHTTP2)
        return;
#endif
    if (listen())
        emit serverStarted(serverPort());
}


void Http2Server::sendServerSettings()
{
    Q_ASSERT(socket);

    if (!serverSettings.size())
        return;

    writer.start(FrameType::SETTINGS, FrameFlag::EMPTY, connectionStreamID);
    for (const auto &s : serverSettings) {
        writer.append(s.identifier);
        writer.append(s.value);
        if (s.identifier == Settings::INITIAL_WINDOW_SIZE_ID)
            streamRecvWindowSize = s.value;
    }
    writer.write(*socket);
    // Now, let's update our peer on a session recv window size:
    const quint32 updatedSize = 10 * streamRecvWindowSize;
    if (sessionRecvWindowSize < updatedSize) {
        const quint32 delta = updatedSize - sessionRecvWindowSize;
        sessionRecvWindowSize = updatedSize;
        sessionCurrRecvWindow = updatedSize;
        sendWINDOW_UPDATE(connectionStreamID, delta);
    }

    waitingClientAck = true;
    settingsSent = true;
}

void Http2Server::sendGOAWAY(quint32 streamID, quint32 error, quint32 lastStreamID)
{
    Q_ASSERT(socket);

    writer.start(FrameType::GOAWAY, FrameFlag::EMPTY, streamID);
    writer.append(lastStreamID);
    writer.append(error);
    writer.write(*socket);
}

void Http2Server::sendRST_STREAM(quint32 streamID, quint32 error)
{
    Q_ASSERT(socket);

    writer.start(FrameType::RST_STREAM, FrameFlag::EMPTY, streamID);
    writer.append(error);
    writer.write(*socket);
}

void Http2Server::sendDATA(quint32 streamID, quint32 windowSize)
{
    Q_ASSERT(socket);

    const auto it = suspendedStreams.find(streamID);
    Q_ASSERT(it != suspendedStreams.end());

    const quint32 offset = it->second;
    Q_ASSERT(offset < quint32(responseBody.size()));

    const quint32 bytes = std::min<quint32>(windowSize, responseBody.size() - offset);
    const quint32 frameSizeLimit(clientSetting(Settings::MAX_FRAME_SIZE_ID, Http2::maxFrameSize));
    const uchar *src = reinterpret_cast<const uchar *>(responseBody.constData() + offset);
    const bool last = offset + bytes == quint32(responseBody.size());

    writer.start(FrameType::DATA, FrameFlag::EMPTY, streamID);
    writer.writeDATA(*socket, frameSizeLimit, src, bytes);

    if (last) {
        writer.start(FrameType::DATA, FrameFlag::END_STREAM, streamID);
        writer.setPayloadSize(0);
        writer.write(*socket);
        suspendedStreams.erase(it);
        activeRequests.erase(streamID);

        Q_ASSERT(closedStreams.find(streamID) == closedStreams.end());
        closedStreams.insert(streamID);
    } else {
        it->second += bytes;
    }
}

void Http2Server::sendWINDOW_UPDATE(quint32 streamID, quint32 delta)
{
    Q_ASSERT(socket);

    writer.start(FrameType::WINDOW_UPDATE, FrameFlag::EMPTY, streamID);
    writer.append(delta);
    writer.write(*socket);
}

void Http2Server::incomingConnection(qintptr socketDescriptor)
{
    if (clearTextHTTP2) {
        socket.reset(new QTcpSocket);
        const bool set = socket->setSocketDescriptor(socketDescriptor);
        Q_UNUSED(set) Q_ASSERT(set);
        // Stop listening:
        close();
        QMetaObject::invokeMethod(this, "connectionEstablished",
                                  Qt::QueuedConnection);
    } else {
#ifndef QT_NO_SSL
        socket.reset(new QSslSocket);
        QSslSocket *sslSocket = static_cast<QSslSocket *>(socket.data());
        // Add HTTP2 as supported protocol:
        auto conf = QSslConfiguration::defaultConfiguration();
        auto protos = conf.allowedNextProtocols();
        protos.prepend(QSslConfiguration::ALPNProtocolHTTP2);
        conf.setAllowedNextProtocols(protos);
        sslSocket->setSslConfiguration(conf);
        // SSL-related setup ...
        sslSocket->setPeerVerifyMode(QSslSocket::VerifyNone);
        sslSocket->setProtocol(QSsl::TlsV1_2OrLater);
        connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)),
                this, SLOT(ignoreErrorSlot()));
        QFile file(SRCDIR "certs/fluke.key");
        file.open(QIODevice::ReadOnly);
        QSslKey key(file.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
        sslSocket->setPrivateKey(key);
        auto localCert = QSslCertificate::fromPath(SRCDIR "certs/fluke.cert");
        sslSocket->setLocalCertificateChain(localCert);
        sslSocket->setSocketDescriptor(socketDescriptor, QAbstractSocket::ConnectedState);
        // Stop listening.
        close();
        // Start SSL handshake and ALPN:
        connect(sslSocket, SIGNAL(encrypted()), this, SLOT(connectionEstablished()));
        sslSocket->startServerEncryption();
#else
        Q_UNREACHABLE();
#endif
    }
}

quint32 Http2Server::clientSetting(Http2::Settings identifier, quint32 defaultValue)
{
    const auto it = expectedClientSettings.find(quint16(identifier));
    if (it != expectedClientSettings.end())
        return  it->second;
    return defaultValue;
}

void Http2Server::connectionEstablished()
{
    using namespace Http2;

    connect(socket.data(), SIGNAL(readyRead()),
            this, SLOT(readReady()));

    waitingClientPreface = true;
    waitingClientAck = false;
    waitingClientSettings = false;
    settingsSent = false;
    // We immediately send our settings so that our client
    // can use flow control correctly.
    sendServerSettings();

    if (socket->bytesAvailable())
        readReady();
}

void Http2Server::ignoreErrorSlot()
{
#ifndef QT_NO_SSL
    static_cast<QSslSocket *>(socket.data())->ignoreSslErrors();
#endif
}

// Now HTTP2 "server" part:
/*
This code is overly simplified but it tests the basic HTTP2 expected behavior:
1. CONNECTION PREFACE
2. SETTINGS
3. sends our own settings (to modify the flow control)
4. collects and reports requests
5. if asked - sends responds to those requests
6. does some very basic error handling
7. tests frames validity/stream logic at the very basic level.
*/

void Http2Server::readReady()
{
    if (connectionError)
        return;

    if (waitingClientPreface) {
        handleConnectionPreface();
    } else {
        const auto status = reader.read(*socket);
        switch (status) {
        case FrameStatus::incompleteFrame:
            break;
        case FrameStatus::goodFrame:
            handleIncomingFrame();
            break;
        default:
            connectionError = true;
            sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
        }
    }

    if (socket->bytesAvailable())
        QMetaObject::invokeMethod(this, "readReady", Qt::QueuedConnection);
}

void Http2Server::handleConnectionPreface()
{
    Q_ASSERT(waitingClientPreface);

    if (socket->bytesAvailable() < clientPrefaceLength)
        return; // Wait for more data ...

    char buf[clientPrefaceLength] = {};
    socket->read(buf, clientPrefaceLength);
    if (std::memcmp(buf, Http2clientPreface, clientPrefaceLength)) {
        sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
        emit clientPrefaceError();
        connectionError = true;
        return;
    }

    waitingClientPreface = false;
    waitingClientSettings = true;
}

void Http2Server::handleIncomingFrame()
{
    // Frames that our implementation can send include:
    // 1. SETTINGS (happens only during connection preface,
    //    handled already by this point)
    // 2. SETTIGNS with ACK should be sent only as a response
    //    to a server's SETTINGS
    // 3. HEADERS
    // 4. CONTINUATION
    // 5. DATA
    // 6. PING
    // 7. RST_STREAM
    // 8. GOAWAY

    inboundFrame = std::move(reader.inboundFrame());

    if (continuedRequest.size()) {
        if (inboundFrame.type() != FrameType::CONTINUATION ||
            inboundFrame.streamID() != continuedRequest.front().streamID()) {
            sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
            emit invalidFrame();
            connectionError = true;
            return;
        }
    }

    switch (inboundFrame.type()) {
    case FrameType::SETTINGS:
        handleSETTINGS();
        break;
    case FrameType::HEADERS:
    case FrameType::CONTINUATION:
        continuedRequest.push_back(std::move(inboundFrame));
        processRequest();
        break;
    case FrameType::DATA:
        handleDATA();
        break;
    case FrameType::RST_STREAM:
        // TODO: this is not tested for now.
        break;
    case FrameType::PING:
        // TODO: this is not tested for now.
        break;
    case FrameType::GOAWAY:
        // TODO: this is not tested for now.
        break;
    case FrameType::WINDOW_UPDATE:
        handleWINDOW_UPDATE();
        break;
    default:;
    }
}

void Http2Server::handleSETTINGS()
{
    // SETTINGS is either a part of the connection preface,
    // or a SETTINGS ACK.
    Q_ASSERT(inboundFrame.type() == FrameType::SETTINGS);

    if (inboundFrame.flags().testFlag(FrameFlag::ACK)) {
        if (!waitingClientAck || inboundFrame.dataSize()) {
            emit invalidFrame();
            connectionError = true;
            waitingClientAck = false;
            return;
        }

        waitingClientAck = false;
        emit serverSettingsAcked();
        return;
    }

    // QHttp2ProtocolHandler always sends some settings,
    // and the size is a multiple of 6.
    if (!inboundFrame.dataSize() || inboundFrame.dataSize() % 6) {
        sendGOAWAY(connectionStreamID, FRAME_SIZE_ERROR, connectionStreamID);
        emit clientPrefaceError();
        connectionError = true;
        return;
    }

    const uchar *src = inboundFrame.dataBegin();
    const uchar *end = src + inboundFrame.dataSize();

    const auto notFound = expectedClientSettings.end();

    while (src != end) {
        const auto id = qFromBigEndian<quint16>(src);
        const auto value = qFromBigEndian<quint32>(src + 2);
        if (expectedClientSettings.find(id) == notFound ||
            expectedClientSettings[id] != value) {
            emit clientPrefaceError();
            connectionError = true;
            return;
        }

        src += 6;
    }

    // Send SETTINGS ACK:
    writer.start(FrameType::SETTINGS, FrameFlag::ACK, connectionStreamID);
    writer.write(*socket);
    waitingClientSettings = false;
    emit clientPrefaceOK();
}

void Http2Server::handleDATA()
{
    Q_ASSERT(inboundFrame.type() == FrameType::DATA);

    const auto streamID = inboundFrame.streamID();

    if (!is_valid_client_stream(streamID) ||
        closedStreams.find(streamID) != closedStreams.end()) {
        emit invalidFrame();
        connectionError = true;
        sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
        return;
    }

    const auto payloadSize = inboundFrame.payloadSize();
    if (sessionCurrRecvWindow < payloadSize) {
        // Client does not respect our session window size!
        emit invalidRequest(streamID);
        connectionError = true;
        sendGOAWAY(connectionStreamID, FLOW_CONTROL_ERROR, connectionStreamID);
        return;
    }

    auto it = streamWindows.find(streamID);
    if (it == streamWindows.end())
        it = streamWindows.insert(std::make_pair(streamID, streamRecvWindowSize)).first;


    if (it->second < payloadSize) {
        emit invalidRequest(streamID);
        connectionError = true;
        sendGOAWAY(connectionStreamID, FLOW_CONTROL_ERROR, connectionStreamID);
        return;
    }

    it->second -= payloadSize;
    if (it->second < streamRecvWindowSize / 2) {
        sendWINDOW_UPDATE(streamID, streamRecvWindowSize / 2);
        it->second += streamRecvWindowSize / 2;
    }

    sessionCurrRecvWindow -= payloadSize;

    if (sessionCurrRecvWindow < sessionRecvWindowSize / 2) {
        // This is some quite naive and trivial logic on when to update.

        sendWINDOW_UPDATE(connectionStreamID, sessionRecvWindowSize / 2);
        sessionCurrRecvWindow += sessionRecvWindowSize / 2;
    }

    if (inboundFrame.flags().testFlag(FrameFlag::END_STREAM)) {
        closedStreams.insert(streamID); // Enter "half-closed remote" state.
        streamWindows.erase(it);
        emit receivedData(streamID);
    }
}

void Http2Server::handleWINDOW_UPDATE()
{
    const auto streamID = inboundFrame.streamID();
    if (!streamID) // We ignore this for now to keep things simple.
        return;

    if (streamID && suspendedStreams.find(streamID) == suspendedStreams.end()) {
        if (closedStreams.find(streamID) == closedStreams.end()) {
            sendRST_STREAM(streamID, PROTOCOL_ERROR);
            emit invalidFrame();
            connectionError = true;
        }

        return;
    }

    const quint32 delta = qFromBigEndian<quint32>(inboundFrame.dataBegin());
    if (!delta || delta > quint32(std::numeric_limits<qint32>::max())) {
        sendRST_STREAM(streamID, PROTOCOL_ERROR);
        emit invalidFrame();
        connectionError = true;
        return;
    }

    emit windowUpdate(streamID);
    sendDATA(streamID, delta);
}

void Http2Server::sendResponse(quint32 streamID, bool emptyBody)
{
    Q_ASSERT(activeRequests.find(streamID) != activeRequests.end());

    writer.start(FrameType::HEADERS, FrameFlag::END_HEADERS, streamID);
    if (emptyBody)
        writer.addFlag(FrameFlag::END_STREAM);

    HttpHeader header = {{":status", "200"}};
    if (!emptyBody) {
        header.push_back(HPack::HeaderField("content-length",
                         QString("%1").arg(responseBody.size()).toLatin1()));
    }

    HPack::BitOStream ostream(writer.outboundFrame().buffer);
    const bool result = encoder.encodeResponse(ostream, header);
    Q_ASSERT(result);
    Q_UNUSED(result)

    const quint32 maxFrameSize(clientSetting(Settings::MAX_FRAME_SIZE_ID, Http2::maxFrameSize));
    writer.writeHEADERS(*socket, maxFrameSize);

    if (!emptyBody) {
        Q_ASSERT(suspendedStreams.find(streamID) == suspendedStreams.end());

        const quint32 windowSize = clientSetting(Settings::INITIAL_WINDOW_SIZE_ID,
                                                 Http2::defaultSessionWindowSize);
        // Suspend to immediately resume it.
        suspendedStreams[streamID] = 0; // start sending from offset 0
        sendDATA(streamID, windowSize);
    } else {
        activeRequests.erase(streamID);
        closedStreams.insert(streamID);
    }
}

void Http2Server::processRequest()
{
    Q_ASSERT(continuedRequest.size());

    if (!continuedRequest.back().flags().testFlag(FrameFlag::END_HEADERS))
        return;

    // We test here:
    // 1. stream is 'idle'.
    // 2. has priority set and dependency (it's 0x0 at the moment).
    // 3. header can be decompressed.
    const auto &headersFrame = continuedRequest.front();
    const auto streamID = headersFrame.streamID();
    if (!is_valid_client_stream(streamID)) {
        emit invalidRequest(streamID);
        connectionError = true;
        sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
        return;
    }

    if (closedStreams.find(streamID) != closedStreams.end()) {
        emit invalidFrame();
        connectionError = true;
        sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
        return;
    }

    quint32 dep = 0;
    uchar w = 0;
    if (!headersFrame.priority(&dep, &w)) {
        emit invalidFrame();
        sendRST_STREAM(streamID, PROTOCOL_ERROR);
        return;
    }

    // Assemble headers ...
    quint32 totalSize = 0;
    for (const auto &frame : continuedRequest) {
        if (std::numeric_limits<quint32>::max() - frame.dataSize() < totalSize) {
            // Resulted in overflow ...
            emit invalidFrame();
            connectionError = true;
            sendGOAWAY(connectionStreamID, PROTOCOL_ERROR, connectionStreamID);
            return;
        }
        totalSize += frame.dataSize();
    }

    std::vector<uchar> hpackBlock(totalSize);
    auto dst = hpackBlock.begin();
    for (const auto &frame : continuedRequest) {
        if (!frame.dataSize())
            continue;
        std::copy(frame.dataBegin(), frame.dataBegin() + frame.dataSize(), dst);
        dst += frame.dataSize();
    }

    HPack::BitIStream inputStream{&hpackBlock[0], &hpackBlock[0] + hpackBlock.size()};

    if (!decoder.decodeHeaderFields(inputStream)) {
        emit decompressionFailed(streamID);
        sendRST_STREAM(streamID, COMPRESSION_ERROR);
        closedStreams.insert(streamID);
        return;
    }

    // Actually, if needed, we can do a comparison here.
    activeRequests[streamID] = decoder.decodedHeader();
    if (headersFrame.flags().testFlag(FrameFlag::END_STREAM))
        emit receivedRequest(streamID);
    // else - we're waiting for incoming DATA frames ...
    continuedRequest.clear();
}

QT_END_NAMESPACE