summaryrefslogtreecommitdiffstats
path: root/tests/auto/network/access/qnetworkreply_local/minihttpserver.h
blob: eb0697a6f8432e9e8c908c60145c4de536f1182b (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
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#ifndef MINIHTTPSERVER_H
#define MINIHTTPSERVER_H

#include <QtNetwork/qtnetworkglobal.h>

#include <QtNetwork/qtcpserver.h>
#include <QtNetwork/qtcpsocket.h>
#include <QtNetwork/qlocalsocket.h>
#if QT_CONFIG(ssl)
#  include <QtNetwork/qsslsocket.h>
#endif
#if QT_CONFIG(localserver)
#  include <QtNetwork/qlocalserver.h>
#endif

#include <QtCore/qpointer.h>
#include <QtCore/qhash.h>

#include <utility>

static inline QByteArray default200Response()
{
    return QByteArrayLiteral("HTTP/1.1 200 OK\r\n"
                             "Content-Type: text/plain\r\n"
                             "Content-Length: 12\r\n"
                             "\r\n"
                             "Hello World!");
}
class MiniHttpServerV2 : public QObject
{
    Q_OBJECT

public:
    struct State;

#if QT_CONFIG(localserver)
    void bind(QLocalServer *server)
    {
        Q_ASSERT(!localServer);
        localServer = server;
        connect(server, &QLocalServer::newConnection, this,
                &MiniHttpServerV2::incomingLocalConnection);
    }
#endif

    void bind(QTcpServer *server)
    {
        Q_ASSERT(!tcpServer);
        tcpServer = server;
        connect(server, &QTcpServer::pendingConnectionAvailable, this,
                &MiniHttpServerV2::incomingConnection);
    }

    void setDataToTransmit(QByteArray data) { dataToTransmit = std::move(data); }

    void clearServerState()
    {
        auto copy = std::exchange(clientStates, {});
        for (auto [socket, _] : copy.asKeyValueRange()) {
            if (auto *tcpSocket = qobject_cast<QTcpSocket *>(socket))
                tcpSocket->disconnectFromHost();
            else if (auto *localSocket = qobject_cast<QLocalSocket *>(socket))
                localSocket->disconnectFromServer();
            else
                Q_UNREACHABLE_RETURN();
            socket->deleteLater();
        }
    }

    bool hasPendingConnections() const
    {
        return
#if QT_CONFIG(localserver)
                (localServer && localServer->hasPendingConnections()) ||
#endif
                (tcpServer && tcpServer->hasPendingConnections());
    }

    QString addressForScheme(QStringView scheme) const
    {
        using namespace Qt::StringLiterals;
        if (scheme.startsWith("unix"_L1) || scheme.startsWith("local"_L1)) {
#if QT_CONFIG(localserver)
            if (localServer)
                return localServer->serverName();
#endif
        } else if (scheme == "http"_L1) {
            if (tcpServer)
                return "%1:%2"_L1.arg(tcpServer->serverAddress().toString(),
                                      QString::number(tcpServer->serverPort()));
        }
        return {};
    }

    QList<State> peerStates() const { return clientStates.values(); }

protected:
#if QT_CONFIG(localserver)
    void incomingLocalConnection()
    {
        auto *socket = localServer->nextPendingConnection();
        connectSocketSignals(socket);
    }
#endif

    void incomingConnection()
    {
        auto *socket = tcpServer->nextPendingConnection();
        connectSocketSignals(socket);
    }

    void reply(QIODevice *socket)
    {
        Q_ASSERT(socket);
        if (dataToTransmit.isEmpty()) {
            emit socket->bytesWritten(0); // emulate having written the data
            return;
        }
        if (!stopTransfer)
            socket->write(dataToTransmit);
    }

private:
    void connectSocketSignals(QIODevice *socket)
    {
        connect(socket, &QIODevice::readyRead, this, [this, socket]() { readyReadSlot(socket); });
        connect(socket, &QIODevice::bytesWritten, this,
                [this, socket]() { bytesWrittenSlot(socket); });
#if QT_CONFIG(ssl)
        if (auto *sslSocket = qobject_cast<QSslSocket *>(socket))
            connect(sslSocket, &QSslSocket::sslErrors, this, &MiniHttpServerV2::slotSslErrors);
#endif

        if (auto *tcpSocket = qobject_cast<QTcpSocket *>(socket)) {
            connect(tcpSocket, &QAbstractSocket::errorOccurred, this, &MiniHttpServerV2::slotError);
        } else if (auto *localSocket = qobject_cast<QLocalSocket *>(socket)) {
            connect(localSocket, &QLocalSocket::errorOccurred, this,
                    [this](QLocalSocket::LocalSocketError error) {
                        slotError(QAbstractSocket::SocketError(error));
                    });
        } else {
            Q_UNREACHABLE_RETURN();
        }
    }

    void parseContentLength(State &st, QByteArrayView header)
    {
        qsizetype index = header.indexOf("\r\ncontent-length:");
        if (index == -1)
            return;
        st.foundContentLength = true;

        index += sizeof("\r\ncontent-length:") - 1;
        const auto *end = std::find(header.cbegin() + index, header.cend(), '\r');
        QByteArrayView num = header.mid(index, std::distance(header.cbegin() + index, end));
        bool ok = false;
        st.contentLength = num.toInt(&ok);
        if (!ok)
            st.contentLength = -1;
    }

private slots:
#if QT_CONFIG(ssl)
    void slotSslErrors(const QList<QSslError> &errors)
    {
        QTcpSocket *currentClient = qobject_cast<QTcpSocket *>(sender());
        Q_ASSERT(currentClient);
        qDebug() << "slotSslErrors" << currentClient->errorString() << errors;
    }
#endif
    void slotError(QAbstractSocket::SocketError err)
    {
        QTcpSocket *currentClient = qobject_cast<QTcpSocket *>(sender());
        Q_ASSERT(currentClient);
        qDebug() << "slotError" << err << currentClient->errorString();
    }

public slots:

    void readyReadSlot(QIODevice *socket)
    {
        if (stopTransfer)
            return;
        State &st = clientStates[socket];
        st.receivedData += socket->readAll();
        const qsizetype doubleEndlPos = st.receivedData.indexOf("\r\n\r\n");

        if (doubleEndlPos != -1) {
            const qsizetype endOfHeader = doubleEndlPos + 4;
            st.contentRead = st.receivedData.size() - endOfHeader;

            if (!st.checkedContentLength) {
                parseContentLength(st, QByteArrayView(st.receivedData).first(endOfHeader));
                st.checkedContentLength = true;
            }

            if (st.contentRead < st.contentLength)
                return;

            // multiple requests incoming, remove the bytes of the current one
            if (multiple)
                st.receivedData.remove(0, endOfHeader);

            reply(socket);
        }
    }

    void bytesWrittenSlot(QIODevice *socket)
    {
        // Disconnect and delete in next cycle (else Windows clients will fail with
        // RemoteHostClosedError).
        if (doClose && socket->bytesToWrite() == 0) {
            disconnect(socket, nullptr, this, nullptr);
            socket->deleteLater();
        }
    }

private:
    QByteArray dataToTransmit = default200Response();

    QTcpServer *tcpServer = nullptr;
#if QT_CONFIG(localserver)
    QLocalServer *localServer = nullptr;
#endif

    QHash<QIODevice *, State> clientStates;

public:
    struct State
    {
        QByteArray receivedData;
        qsizetype contentLength = 0;
        qsizetype contentRead = 0;
        bool checkedContentLength = false;
        bool foundContentLength = false;
    };

    bool doClose = true;
    bool multiple = false;
    bool stopTransfer = false;
};

#endif // MINIHTTPSERVER_H