File: httpserver_p.h

package info (click to toggle)
kdsoap 2.2.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,996 kB
  • sloc: cpp: 19,877; python: 63; makefile: 16
file content (267 lines) | stat: -rw-r--r-- 8,187 bytes parent folder | download | duplicates (2)
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
/****************************************************************************
**
** This file is part of the KD Soap project.
**
** SPDX-FileCopyrightText: 2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
**
** SPDX-License-Identifier: MIT
**
****************************************************************************/

#ifndef HTTPSERVER_P_H
#define HTTPSERVER_P_H

#include "KDSoapGlobal.h"
#include <QBuffer>
#include <QMutex>
#include <QSemaphore>
#include <QTcpServer>
#include <QTcpSocket>
#include <QThread>
#ifndef QT_NO_OPENSSL
#include <QSslSocket>
#endif
#include <QSslCertificate>
#include <QSslKey>
#include <QStringList>
#include <QUrl>

class BlockingHttpServer;

namespace KDSoapUnitTestHelpers {
bool xmlBufferCompare(const QByteArray &source, const QByteArray &dest);
void httpGet(const QUrl &url);
bool setSslConfiguration();
const char *xmlEnvBegin11();
const char *xmlEnvBegin11WithWSAddressing();
const char *xmlEnvBegin12();
const char *xmlEnvBegin12WithWSAddressing();
const char *xmlEnvEnd();
}

class HttpServerThread : public QThread
{
    Q_OBJECT
public:
    enum Feature
    {
        Public = 0, // HTTP with no ssl and no authentication needed
        Ssl = 1, // HTTPS
        BasicAuth = 2, // Requires authentication
        Error404 = 4 // Return "404 not found"
                     // bitfield, next item is 8
    };
    Q_DECLARE_FLAGS(Features, Feature)

    HttpServerThread(const QByteArray &dataToSend, Features features)
        : m_dataToSend(dataToSend)
        , m_port(0)
        , m_features(features)
        , m_server(0)
    {
        start();
        m_ready.acquire();
    }
    ~HttpServerThread()
    {
        finish();
        wait();
    }

    void disableSsl();
    inline int serverPort() const
    {
        QMutexLocker lock(&m_mutex);
        return m_port;
    }
    QString endPoint() const
    {
        return QString::fromLatin1("%1://127.0.0.1:%2/path").arg(QString::fromLatin1((m_features & Ssl) ? "https" : "http")).arg(serverPort());
    }

    inline void finish()
    {
        KDSoapUnitTestHelpers::httpGet(QUrl(endPoint() + QLatin1String("/terminateThread")));
    }

    QByteArray receivedData() const
    {
        QMutexLocker lock(&m_mutex);
        return m_receivedData;
    }
    QByteArray receivedHeaders() const
    {
        QMutexLocker lock(&m_mutex);
        return m_receivedHeaders;
    }
    void resetReceivedBuffers()
    {
        QMutexLocker lock(&m_mutex);
        m_receivedData.clear();
        m_receivedHeaders.clear();
    }

    QByteArray header(const QByteArray &value) const
    {
        QMutexLocker lock(&m_mutex);
        return m_headers.value(value);
    }

    /**
     * @brief clientUseWSAddressing
     * @return
     * Returns true if the server expects clients to use WS-Addressing.
     */
    bool clientSendsActionInHttpHeader() const;

    /**
     * @brief setClientSendsActionInHttpHeader
     * @param clientSendsActionInHttpHeader
     * If this function is called with clientSendsActionInHttpHeader set to false then
     * (in the case of SOAP 1.2 requests) the Content-type HTTP header will not checked
     * for containing the proper SOAP action. In this case the client should send the SOAP action
     * embedded to the SOAP envelope's header section).
     */
    void setClientSendsActionInHttpHeader(bool clientSendsActionInHttpHeader);

    /**
     * @brief setExpectedSoapAction
     * @param expectedSoapAction
     * This function could be used to specify the expected SOAP action in the incoming request's header.
     * In the case of SOAP 1.1 requests the SOAP action should be in the SoapAction HTTP header,
     * in the case of SOAP 1.2 requests the SOAP action is sent in the Content-Type HTTP header's
     * action parameter. Please note if setClientSendsActionInHttpHeader is called with false argument
     * then this check is skipped. (In this case the SOAP action should be passed in the envelope's
     * header). To disable the SOAP action checking call this function with an empty expectedSoapAction
     * parameter. (This is the default behaviour of the HttpServerThread).
     */
    void setExpectedSoapAction(const QByteArray &expectedSoapAction);

    /**
     * @brief expectedSoapAction
     * @return the expected SOAP action against which the request's headers will be checked.
     * If the function returns an empty string then the SOAP actions of the incoming requests
     * will not be checked.
     */
    QByteArray expectedSoapAction() const;

protected:
    /* \reimp */ void run() override;

private:
    enum Method
    {
        None,
        Basic,
        Plain,
        Login,
        Ntlm,
        CramMd5,
        DigestMd5
    };
    static void parseAuthLine(const QString &str, Method *method, QString *headerVal)
    {
        *method = None;
        // The code below (from QAuthenticatorPrivate::parseHttpResponse)
        // is supposed to be run in a loop, apparently
        // (multiple WWW-Authenticate lines? multiple values in the line?)

        // qDebug() << "parseAuthLine() " << str;
        if (*method < Basic && str.startsWith(QLatin1String("Basic"), Qt::CaseInsensitive)) {
            *method = Basic;
            *headerVal = str.mid(6);
        } else if (*method < Ntlm && str.startsWith(QLatin1String("NTLM"), Qt::CaseInsensitive)) {
            *method = Ntlm;
            *headerVal = str.mid(5);
        } else if (*method < DigestMd5 && str.startsWith(QLatin1String("Digest"), Qt::CaseInsensitive)) {
            *method = DigestMd5;
            *headerVal = str.mid(7);
        }
    }

    QByteArray makeHttpResponse(const QByteArray &responseData)
    {
        QByteArray httpResponse;
        // ### missing here: error code 500 if response is a fault
        if (m_features & Error404) {
            httpResponse += "HTTP/1.1 404 Not Found\r\n";
        } else {
            httpResponse += "HTTP/1.1 200 OK\r\n";
        }
        httpResponse += "Content-Type: text/xml\r\nContent-Length: ";
        httpResponse += QByteArray::number(responseData.size());
        httpResponse += "\r\n";

        // We don't support multiple connexions so let's ask the client
        // to close the connection every time. See testCallNoReply which performs
        // multiple connexions at the same time (QNAM keeps the old connection open).
        httpResponse += "Connection: close\r\n";
        httpResponse += "\r\n";
        httpResponse += responseData;
        return httpResponse;
    }

private:
    QByteArray m_partialRequest;
    QSemaphore m_ready;
    QByteArray m_dataToSend;

    mutable QMutex m_mutex; // protects the 4 vars below
    QByteArray m_receivedData;
    QByteArray m_receivedHeaders;
    QMap<QByteArray, QByteArray> m_headers;
    int m_port;

    Features m_features;
    BlockingHttpServer *m_server;
    bool m_clientSendsActionInHttpHeader = true;
    QByteArray m_expectedSoapAction;
};

Q_DECLARE_OPERATORS_FOR_FLAGS(HttpServerThread::Features)

// KDSoap-server-side testing
// We need to do the listening and socket handling in a separate thread,
// so that the main thread can use synchronous calls. Note that this is
// really specific to unit tests and doesn't need to be done in a real
// KDSoap-based server.
template<class ServerObjectType>
class TestServerThread
{
public:
    TestServerThread()
        : m_thread(0)
        , m_pServer(0)
    {
    }
    ~TestServerThread()
    {
        if (m_thread) {
            m_thread->quit();
            m_thread->wait();
            delete m_thread;
        }
    }
    ServerObjectType *startThread()
    {
        m_pServer = new ServerObjectType;
        if (!m_pServer->listen()) {
            delete m_pServer;
            m_pServer = 0;
            return 0;
        }

        m_thread = new QThread;
        QObject::connect(m_thread, &QThread::finished, m_pServer, &ServerObjectType::deleteLater);

        m_pServer->moveToThread(m_thread);
        m_thread->start();
        return m_pServer;
    }

private:
    QThread *m_thread; // we could also use m_pServer->thread()
    ServerObjectType *m_pServer;
};

#endif /* HTTPSERVER_P_H */