Rename most classes to remove the 'Q' prefix.

This commit is contained in:
Nathan Osman
2017-07-07 18:29:50 -07:00
parent 0197444a83
commit e68c0b0f11
56 changed files with 468 additions and 468 deletions

View File

@@ -37,7 +37,7 @@ int main(int argc, char * argv[])
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
// Attempt to open the local file and read from it // Attempt to open the local file and read from it
QLocalFile file; LocalFile file;
if (!file.open()) { if (!file.open()) {
qCritical("Unable to open local file - is server running?"); qCritical("Unable to open local file - is server running?");
return 1; return 1;

View File

@@ -27,7 +27,7 @@
#include "apihandler.h" #include "apihandler.h"
void ApiHandler::messages(QHttpSocket *socket) void ApiHandler::messages(HttpSocket *socket)
{ {
QJsonObject object; QJsonObject object;
object.insert("messages", QJsonArray::fromStringList(mMessages)); object.insert("messages", QJsonArray::fromStringList(mMessages));
@@ -35,7 +35,7 @@ void ApiHandler::messages(QHttpSocket *socket)
} }
void ApiHandler::messagesNew(QHttpSocket *socket) void ApiHandler::messagesNew(HttpSocket *socket)
{ {
QJsonDocument document; QJsonDocument document;
if (socket->readJson(document)) { if (socket->readJson(document)) {
@@ -49,5 +49,5 @@ void ApiHandler::messagesNew(QHttpSocket *socket)
} }
// If execution reaches this point, malformed data was supplied // If execution reaches this point, malformed data was supplied
socket->writeError(QHttpSocket::BadRequest); socket->writeError(HttpSocket::BadRequest);
} }

View File

@@ -34,8 +34,8 @@ class ApiHandler : public QObject
public Q_SLOTS: public Q_SLOTS:
void messages(QHttpSocket *socket); void messages(HttpSocket *socket);
void messagesNew(QHttpSocket *socket); void messagesNew(HttpSocket *socket);
private: private:

View File

@@ -64,7 +64,7 @@ int main(int argc, char * argv[])
quint16 port = parser.value(portOption).toInt(); quint16 port = parser.value(portOption).toInt();
// Build the hierarchy of handlers // Build the hierarchy of handlers
QFilesystemHandler handler(":/static"); FilesystemHandler handler(":/static");
handler.addRedirect(QRegExp("^$"), "/index.html"); handler.addRedirect(QRegExp("^$"), "/index.html");
ApiHandler renameMe; ApiHandler renameMe;
@@ -73,7 +73,7 @@ int main(int argc, char * argv[])
apiHandler.registerMethod("messages/new", &renameMe, &ApiHandler::messagesNew); apiHandler.registerMethod("messages/new", &renameMe, &ApiHandler::messagesNew);
handler.addSubHandler(QRegExp("api/"), &apiHandler); handler.addSubHandler(QRegExp("api/"), &apiHandler);
QHttpServer server(&handler); HttpServer server(&handler);
// Attempt to listen on the specified port // Attempt to listen on the specified port
if (!server.listen(address, port)) { if (!server.listen(address, port)) {

View File

@@ -68,8 +68,8 @@ int main(int argc, char * argv[])
QString dir = parser.value(dirOption); QString dir = parser.value(dirOption);
// Create the filesystem handler and server // Create the filesystem handler and server
QFilesystemHandler handler(dir); FilesystemHandler handler(dir);
QHttpServer server(&handler); HttpServer server(&handler);
// Attempt to listen on the specified port // Attempt to listen on the specified port
if (!server.listen(address, port)) { if (!server.listen(address, port)) {

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QFilesystemHandlerPrivate; class QHTTPENGINE_EXPORT FilesystemHandlerPrivate;
/** /**
* @brief Handler for filesystem requests * @brief Handler for filesystem requests
@@ -45,7 +45,7 @@ class QHTTPENGINE_EXPORT QFilesystemHandlerPrivate;
* can be modified after initialization. It is possible to use a resource * can be modified after initialization. It is possible to use a resource
* directory for the document root. * directory for the document root.
*/ */
class QHTTPENGINE_EXPORT QFilesystemHandler : public QHttpHandler class QHTTPENGINE_EXPORT FilesystemHandler : public HttpHandler
{ {
Q_OBJECT Q_OBJECT
@@ -54,12 +54,12 @@ public:
/** /**
* @brief Create a new filesystem handler * @brief Create a new filesystem handler
*/ */
explicit QFilesystemHandler(QObject *parent = 0); explicit FilesystemHandler(QObject *parent = 0);
/** /**
* @brief Create a new filesystem handler from the specified directory * @brief Create a new filesystem handler from the specified directory
*/ */
QFilesystemHandler(const QString &documentRoot, QObject *parent = 0); FilesystemHandler(const QString &documentRoot, QObject *parent = 0);
/** /**
* @brief Set the document root * @brief Set the document root
@@ -74,12 +74,12 @@ protected:
/** /**
* @brief Reimplementation of QHttpHandler::process() * @brief Reimplementation of QHttpHandler::process()
*/ */
virtual void process(QHttpSocket *socket, const QString &path); virtual void process(HttpSocket *socket, const QString &path);
private: private:
QFilesystemHandlerPrivate *const d; FilesystemHandlerPrivate *const d;
friend class QFilesystemHandlerPrivate; friend class FilesystemHandlerPrivate;
}; };
#endif // QHTTPENGINE_QFILESYSTEMHANDLER_H #endif // QHTTPENGINE_QFILESYSTEMHANDLER_H

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QHttpBasicAuthPrivate; class QHTTPENGINE_EXPORT HttpBasicAuthPrivate;
/** /**
* @brief Middleware for HTTP basic authentication * @brief Middleware for HTTP basic authentication
@@ -38,7 +38,7 @@ class QHTTPENGINE_EXPORT QHttpBasicAuthPrivate;
* different method of authentication, override the verify() method in a * different method of authentication, override the verify() method in a
* derived class. * derived class.
*/ */
class QHTTPENGINE_EXPORT QHttpBasicAuth : public QHttpMiddleware class QHTTPENGINE_EXPORT HttpBasicAuth : public HttpMiddleware
{ {
Q_OBJECT Q_OBJECT
@@ -49,7 +49,7 @@ public:
* *
* The realm string is shown to a client when credentials are requested. * The realm string is shown to a client when credentials are requested.
*/ */
QHttpBasicAuth(const QString &realm, QObject *parent = Q_NULLPTR); HttpBasicAuth(const QString &realm, QObject *parent = Q_NULLPTR);
/** /**
* @brief Add credentials to the list * @brief Add credentials to the list
@@ -65,7 +65,7 @@ public:
* If the verify() method returns true, the client will be granted access * If the verify() method returns true, the client will be granted access
* to the resources. Otherwise, 401 Unauthorized will be returned. * to the resources. Otherwise, 401 Unauthorized will be returned.
*/ */
virtual bool process(QHttpSocket *socket); virtual bool process(HttpSocket *socket);
protected: protected:
@@ -76,7 +76,7 @@ protected:
private: private:
QHttpBasicAuthPrivate *const d; HttpBasicAuthPrivate *const d;
}; };
#endif // QHTTPENGINE_QHTTPBASICAUTH_H #endif // QHTTPENGINE_QHTTPBASICAUTH_H

View File

@@ -28,9 +28,9 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QRegExp; class QRegExp;
class QHttpMiddleware; class HttpMiddleware;
class QHttpSocket; class HttpSocket;
class QHTTPENGINE_EXPORT QHttpHandlerPrivate; class QHTTPENGINE_EXPORT HttpHandlerPrivate;
/** /**
* @brief Base class for HTTP handlers * @brief Base class for HTTP handlers
@@ -68,7 +68,7 @@ class QHTTPENGINE_EXPORT QHttpHandlerPrivate;
* the request or write an error to the socket. The default implementation of * the request or write an error to the socket. The default implementation of
* process() simply returns an HTTP 404 error. * process() simply returns an HTTP 404 error.
*/ */
class QHTTPENGINE_EXPORT QHttpHandler : public QObject class QHTTPENGINE_EXPORT HttpHandler : public QObject
{ {
Q_OBJECT Q_OBJECT
@@ -77,12 +77,12 @@ public:
/** /**
* @brief Base constructor for a handler * @brief Base constructor for a handler
*/ */
explicit QHttpHandler(QObject *parent = 0); explicit HttpHandler(QObject *parent = 0);
/** /**
* @brief Add middleware to the handler * @brief Add middleware to the handler
*/ */
void addMiddleware(QHttpMiddleware *middleware); void addMiddleware(HttpMiddleware *middleware);
/** /**
* @brief Add a redirect for a specific pattern * @brief Add a redirect for a specific pattern
@@ -103,12 +103,12 @@ public:
* used when the route() method is invoked to determine whether the * used when the route() method is invoked to determine whether the
* request matches any patterns. The order of the list is preserved. * request matches any patterns. The order of the list is preserved.
*/ */
void addSubHandler(const QRegExp &pattern, QHttpHandler *handler); void addSubHandler(const QRegExp &pattern, HttpHandler *handler);
/** /**
* @brief Route an incoming request * @brief Route an incoming request
*/ */
void route(QHttpSocket *socket, const QString &path); void route(HttpSocket *socket, const QString &path);
protected: protected:
@@ -119,12 +119,12 @@ protected:
* a redirect with QHttpSocket::writeRedirect(), or writing an error to * a redirect with QHttpSocket::writeRedirect(), or writing an error to
* the socket using QHttpSocket::writeError(). * the socket using QHttpSocket::writeError().
*/ */
virtual void process(QHttpSocket *socket, const QString &path); virtual void process(HttpSocket *socket, const QString &path);
private: private:
QHttpHandlerPrivate *const d; HttpHandlerPrivate *const d;
friend class QHttpHandlerPrivate; friend class HttpHandlerPrivate;
}; };
#endif // QHTTPENGINE_QHTTPHANDLER_H #endif // QHTTPENGINE_QHTTPHANDLER_H

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHttpSocket; class HttpSocket;
/** /**
* @brief Pre-handler request processor * @brief Pre-handler request processor
@@ -35,7 +35,7 @@ class QHttpSocket;
* Middleware sits between the server and the final request handler, * Middleware sits between the server and the final request handler,
* determining whether the request should be passed on to the handler. * determining whether the request should be passed on to the handler.
*/ */
class QHTTPENGINE_EXPORT QHttpMiddleware : public QObject class QHTTPENGINE_EXPORT HttpMiddleware : public QObject
{ {
Q_OBJECT Q_OBJECT
@@ -44,7 +44,7 @@ public:
/** /**
* @brief Base constructor for middleware * @brief Base constructor for middleware
*/ */
explicit QHttpMiddleware(QObject *parent = Q_NULLPTR) : QObject(parent) {} explicit HttpMiddleware(QObject *parent = Q_NULLPTR) : QObject(parent) {}
/** /**
* @brief Determine if request processing should continue * @brief Determine if request processing should continue
@@ -53,7 +53,7 @@ public:
* returned, processing continues. Otherwise, it is assumed that an * returned, processing continues. Otherwise, it is assumed that an
* appropriate error was written to the socket. * appropriate error was written to the socket.
*/ */
virtual bool process(QHttpSocket *socket) = 0; virtual bool process(HttpSocket *socket) = 0;
}; };
#endif // QHTTPENGINE_QHTTPMIDDLEWARE_H #endif // QHTTPENGINE_QHTTPMIDDLEWARE_H

View File

@@ -36,7 +36,7 @@
* response headers. Functionality is broken up into smaller methods in order * response headers. Functionality is broken up into smaller methods in order
* to make the unit tests simpler. * to make the unit tests simpler.
*/ */
class QHTTPENGINE_EXPORT QHttpParser class QHTTPENGINE_EXPORT HttpParser
{ {
public: public:
@@ -56,7 +56,7 @@ public:
/** /**
* @brief Parse and remove the query string from a path * @brief Parse and remove the query string from a path
*/ */
static bool parsePath(const QByteArray &rawPath, QString &path, QHttpSocket::QueryStringMap &queryString); static bool parsePath(const QByteArray &rawPath, QString &path, HttpSocket::QueryStringMap &queryString);
/** /**
* @brief Parse a list of lines containing HTTP headers * @brief Parse a list of lines containing HTTP headers
@@ -64,7 +64,7 @@ public:
* Each line is expected to be in the format "name: value". Parsing is * Each line is expected to be in the format "name: value". Parsing is
* immediately aborted if an invalid line is encountered. * immediately aborted if an invalid line is encountered.
*/ */
static bool parseHeaderList(const QList<QByteArray> &lines, QHttpSocket::HeaderMap &headers); static bool parseHeaderList(const QList<QByteArray> &lines, HttpSocket::HeaderMap &headers);
/** /**
* @brief Parse HTTP headers * @brief Parse HTTP headers
@@ -73,17 +73,17 @@ public:
* into a status line and HTTP headers. The parts list will contain the * into a status line and HTTP headers. The parts list will contain the
* parts from the status line. * parts from the status line.
*/ */
static bool parseHeaders(const QByteArray &data, QList<QByteArray> &parts, QHttpSocket::HeaderMap &headers); static bool parseHeaders(const QByteArray &data, QList<QByteArray> &parts, HttpSocket::HeaderMap &headers);
/** /**
* @brief Parse HTTP request headers * @brief Parse HTTP request headers
*/ */
static bool parseRequestHeaders(const QByteArray &data, QHttpSocket::Method &method, QByteArray &path, QHttpSocket::HeaderMap &headers); static bool parseRequestHeaders(const QByteArray &data, HttpSocket::Method &method, QByteArray &path, HttpSocket::HeaderMap &headers);
/** /**
* @brief Parse HTTP response headers * @brief Parse HTTP response headers
*/ */
static bool parseResponseHeaders(const QByteArray &data, int &statusCode, QByteArray &statusReason, QHttpSocket::HeaderMap &headers); static bool parseResponseHeaders(const QByteArray &data, int &statusCode, QByteArray &statusReason, HttpSocket::HeaderMap &headers);
}; };
#endif // QHTTPENGINE_QHTTPPARSER_H #endif // QHTTPENGINE_QHTTPPARSER_H

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QHttpRangePrivate; class QHTTPENGINE_EXPORT HttpRangePrivate;
/** /**
* @brief HTTP range representation * @brief HTTP range representation
@@ -61,7 +61,7 @@ class QHTTPENGINE_EXPORT QHttpRangePrivate;
* @endcode * @endcode
* *
*/ */
class QHTTPENGINE_EXPORT QHttpRange class QHTTPENGINE_EXPORT HttpRange
{ {
public: public:
@@ -70,7 +70,7 @@ public:
* *
* An empty QHttpRange is considered invalid. * An empty QHttpRange is considered invalid.
*/ */
QHttpRange(); HttpRange();
/** /**
* @brief Construct QHttpRange by parsing range * @brief Construct QHttpRange by parsing range
@@ -80,7 +80,7 @@ public:
* constructor. dataSize may be supplied so that relative ranges could be * constructor. dataSize may be supplied so that relative ranges could be
* represented as absolute values. * represented as absolute values.
*/ */
QHttpRange(const QString &range, qint64 dataSize = -1); HttpRange(const QString &range, qint64 dataSize = -1);
/** /**
* @brief Construct QHttpRange, using from and to values * @brief Construct QHttpRange, using from and to values
@@ -89,7 +89,7 @@ public:
* supplied so that relative ranges could be represented as * supplied so that relative ranges could be represented as
* absolute values. * absolute values.
*/ */
QHttpRange(qint64 from, qint64 to, qint64 dataSize = -1); HttpRange(qint64 from, qint64 to, qint64 dataSize = -1);
/** /**
* @brief Construct QHttpRange from other QHttpRange and dataSize * @brief Construct QHttpRange from other QHttpRange and dataSize
@@ -97,17 +97,17 @@ public:
* Initialises a new QHttpRange with from and to values of other * Initialises a new QHttpRange with from and to values of other
* QHttpRequest. Supplied dataSize is used instead of other dataSize. * QHttpRequest. Supplied dataSize is used instead of other dataSize.
*/ */
QHttpRange(const QHttpRange &other, qint64 dataSize); HttpRange(const HttpRange &other, qint64 dataSize);
/** /**
* @brief Destroy the range * @brief Destroy the range
*/ */
~QHttpRange(); ~HttpRange();
/** /**
* @brief Assignment operator * @brief Assignment operator
*/ */
QHttpRange& operator=(const QHttpRange &other); HttpRange& operator=(const HttpRange &other);
/** /**
* @brief Return starting position of range * @brief Return starting position of range
@@ -263,7 +263,7 @@ public:
private: private:
QHttpRangePrivate *const d; HttpRangePrivate *const d;
}; };
#endif // QHTTPENGINE_QHTTPRANGE_H #endif // QHTTPENGINE_QHTTPRANGE_H

View File

@@ -33,8 +33,8 @@
class QSslConfiguration; class QSslConfiguration;
#endif #endif
class QHttpHandler; class HttpHandler;
class QHTTPENGINE_EXPORT QHttpServerPrivate; class QHTTPENGINE_EXPORT HttpServerPrivate;
/** /**
* @brief TCP server for HTTP requests * @brief TCP server for HTTP requests
@@ -60,7 +60,7 @@ class QHTTPENGINE_EXPORT QHttpServerPrivate;
* signal is connected to the QHttpSocket's deleteLater() slot to ensure that * signal is connected to the QHttpSocket's deleteLater() slot to ensure that
* the socket is deleted when the client disconnects. * the socket is deleted when the client disconnects.
*/ */
class QHTTPENGINE_EXPORT QHttpServer : public QTcpServer class QHTTPENGINE_EXPORT HttpServer : public QTcpServer
{ {
Q_OBJECT Q_OBJECT
@@ -69,17 +69,17 @@ public:
/** /**
* @brief Create an HTTP server * @brief Create an HTTP server
*/ */
explicit QHttpServer(QObject *parent = 0); explicit HttpServer(QObject *parent = 0);
/** /**
* @brief Create an HTTP server with the specified handler * @brief Create an HTTP server with the specified handler
*/ */
QHttpServer(QHttpHandler *handler, QObject *parent = 0); HttpServer(HttpHandler *handler, QObject *parent = 0);
/** /**
* @brief Set the root handler for all new requests * @brief Set the root handler for all new requests
*/ */
void setHandler(QHttpHandler *handler); void setHandler(HttpHandler *handler);
#if !defined(QT_NO_SSL) #if !defined(QT_NO_SSL)
/** /**
@@ -100,8 +100,8 @@ protected:
private: private:
QHttpServerPrivate *const d; HttpServerPrivate *const d;
friend class QHttpServerPrivate; friend class HttpServerPrivate;
}; };
#endif // QHTTPENGINE_QHTTPSERVER_H #endif // QHTTPENGINE_QHTTPSERVER_H

View File

@@ -33,7 +33,7 @@
class QJsonDocument; class QJsonDocument;
class QTcpSocket; class QTcpSocket;
class QHTTPENGINE_EXPORT QHttpSocketPrivate; class QHTTPENGINE_EXPORT HttpSocketPrivate;
/** /**
* @brief Implementation of the HTTP protocol * @brief Implementation of the HTTP protocol
@@ -89,7 +89,7 @@ class QHTTPENGINE_EXPORT QHttpSocketPrivate;
* status code to the writeError() method. Both methods will close the socket * status code to the writeError() method. Both methods will close the socket
* once the response is written. * once the response is written.
*/ */
class QHTTPENGINE_EXPORT QHttpSocket : public QIODevice class QHTTPENGINE_EXPORT HttpSocket : public QIODevice
{ {
Q_OBJECT Q_OBJECT
@@ -106,7 +106,7 @@ public:
* The key used for the map is the QIByteArray class, which allows for * The key used for the map is the QIByteArray class, which allows for
* case-insensitive comparison. * case-insensitive comparison.
*/ */
typedef QMultiMap<QIByteArray, QByteArray> HeaderMap; typedef QMultiMap<IByteArray, QByteArray> HeaderMap;
/** /**
* HTTP methods * HTTP methods
@@ -177,7 +177,7 @@ public:
* This instance will assume ownership of the socket. That is, it will * This instance will assume ownership of the socket. That is, it will
* make itself the parent of the socket. * make itself the parent of the socket.
*/ */
QHttpSocket(QTcpSocket *socket, QObject *parent = 0); HttpSocket(QTcpSocket *socket, QObject *parent = 0);
/** /**
* @brief Retrieve the number of bytes available for reading * @brief Retrieve the number of bytes available for reading
@@ -354,8 +354,8 @@ protected:
private: private:
QHttpSocketPrivate *const d; HttpSocketPrivate *const d;
friend class QHttpSocketPrivate; friend class HttpSocketPrivate;
}; };
#endif // QHTTPENGINE_QHTTPSOCKET_H #endif // QHTTPENGINE_QHTTPSOCKET_H

View File

@@ -35,15 +35,15 @@
* The QIByteArray is identical to the QByteArray class in all aspects except * The QIByteArray is identical to the QByteArray class in all aspects except
* that it performs comparisons in a case-insensitive manner. * that it performs comparisons in a case-insensitive manner.
*/ */
class QHTTPENGINE_EXPORT QIByteArray : public QByteArray class QHTTPENGINE_EXPORT IByteArray : public QByteArray
{ {
public: public:
/// \{ /// \{
QIByteArray() {} IByteArray() {}
QIByteArray(const QByteArray &other) : QByteArray(other) {} IByteArray(const QByteArray &other) : QByteArray(other) {}
QIByteArray(const QIByteArray &other) : QByteArray(other) {} IByteArray(const IByteArray &other) : QByteArray(other) {}
QIByteArray(const char *data, int size = -1) : QByteArray(data, size) {} IByteArray(const char *data, int size = -1) : QByteArray(data, size) {}
inline bool operator==(const QString &s2) const { return toLower() == s2.toLower(); } inline bool operator==(const QString &s2) const { return toLower() == s2.toLower(); }
inline bool operator!=(const QString &s2) const { return toLower() != s2.toLower(); } inline bool operator!=(const QString &s2) const { return toLower() != s2.toLower(); }
@@ -58,40 +58,40 @@ public:
/// \} /// \}
}; };
inline bool operator==(const QIByteArray &a1, const char *a2) { return a1.toLower() == QByteArray(a2).toLower(); } inline bool operator==(const IByteArray &a1, const char *a2) { return a1.toLower() == QByteArray(a2).toLower(); }
inline bool operator==(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() == a2.toLower(); } inline bool operator==(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() == a2.toLower(); }
inline bool operator==(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() == a2.toLower(); } inline bool operator==(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() == a2.toLower(); }
inline bool operator==(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() == a2.toLower(); } inline bool operator==(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() == a2.toLower(); }
inline bool operator==(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() == a2.toLower(); } inline bool operator==(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() == a2.toLower(); }
inline bool operator!=(const QIByteArray &a1, const char *a2) { return a1.toLower() != QByteArray(a2).toLower(); } inline bool operator!=(const IByteArray &a1, const char *a2) { return a1.toLower() != QByteArray(a2).toLower(); }
inline bool operator!=(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() != a2.toLower(); } inline bool operator!=(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() != a2.toLower(); }
inline bool operator!=(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() != a2.toLower(); } inline bool operator!=(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() != a2.toLower(); }
inline bool operator!=(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() != a2.toLower(); } inline bool operator!=(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() != a2.toLower(); }
inline bool operator!=(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() != a2.toLower(); } inline bool operator!=(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() != a2.toLower(); }
inline bool operator<(const QIByteArray &a1, const char *a2) { return a1.toLower() < QByteArray(a2).toLower(); } inline bool operator<(const IByteArray &a1, const char *a2) { return a1.toLower() < QByteArray(a2).toLower(); }
inline bool operator<(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() < a2.toLower(); } inline bool operator<(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() < a2.toLower(); }
inline bool operator<(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() < a2.toLower(); } inline bool operator<(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() < a2.toLower(); }
inline bool operator<(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() < a2.toLower(); } inline bool operator<(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() < a2.toLower(); }
inline bool operator<(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() < a2.toLower(); } inline bool operator<(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() < a2.toLower(); }
inline bool operator>(const QIByteArray &a1, const char *a2) { return a1.toLower() > QByteArray(a2).toLower(); } inline bool operator>(const IByteArray &a1, const char *a2) { return a1.toLower() > QByteArray(a2).toLower(); }
inline bool operator>(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() > a2.toLower(); } inline bool operator>(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() > a2.toLower(); }
inline bool operator>(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() > a2.toLower(); } inline bool operator>(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() > a2.toLower(); }
inline bool operator>(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() > a2.toLower(); } inline bool operator>(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() > a2.toLower(); }
inline bool operator>(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() > a2.toLower(); } inline bool operator>(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() > a2.toLower(); }
inline bool operator<=(const QIByteArray &a1, const char *a2) { return a1.toLower() <= QByteArray(a2).toLower(); } inline bool operator<=(const IByteArray &a1, const char *a2) { return a1.toLower() <= QByteArray(a2).toLower(); }
inline bool operator<=(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() <= a2.toLower(); } inline bool operator<=(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() <= a2.toLower(); }
inline bool operator<=(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() <= a2.toLower(); } inline bool operator<=(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() <= a2.toLower(); }
inline bool operator<=(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() <= a2.toLower(); } inline bool operator<=(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() <= a2.toLower(); }
inline bool operator<=(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() <= a2.toLower(); } inline bool operator<=(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() <= a2.toLower(); }
inline bool operator>=(const QIByteArray &a1, const char *a2) { return a1.toLower() >= QByteArray(a2).toLower(); } inline bool operator>=(const IByteArray &a1, const char *a2) { return a1.toLower() >= QByteArray(a2).toLower(); }
inline bool operator>=(const char *a1, const QIByteArray &a2) { return QByteArray(a1).toLower() >= a2.toLower(); } inline bool operator>=(const char *a1, const IByteArray &a2) { return QByteArray(a1).toLower() >= a2.toLower(); }
inline bool operator>=(const QIByteArray &a1, const QByteArray &a2) { return a1.toLower() >= a2.toLower(); } inline bool operator>=(const IByteArray &a1, const QByteArray &a2) { return a1.toLower() >= a2.toLower(); }
inline bool operator>=(const QByteArray &a1, const QIByteArray &a2) { return a1.toLower() >= a2.toLower(); } inline bool operator>=(const QByteArray &a1, const IByteArray &a2) { return a1.toLower() >= a2.toLower(); }
inline bool operator>=(const QIByteArray &a1, const QIByteArray &a2) { return a1.toLower() >= a2.toLower(); } inline bool operator>=(const IByteArray &a1, const IByteArray &a2) { return a1.toLower() >= a2.toLower(); }
#endif // QHTTPENGINE_QIBYTEARRAY_H #endif // QHTTPENGINE_QIBYTEARRAY_H

View File

@@ -29,7 +29,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QLocalAuthPrivate; class QHTTPENGINE_EXPORT LocalAuthPrivate;
/** /**
* @brief Middleware for local file-based authentication * @brief Middleware for local file-based authentication
@@ -49,7 +49,7 @@ class QHTTPENGINE_EXPORT QLocalAuthPrivate;
* *
* Additional data can be added to the object using the setData() method. * Additional data can be added to the object using the setData() method.
*/ */
class QHTTPENGINE_EXPORT QLocalAuth : public QHttpMiddleware class QHTTPENGINE_EXPORT LocalAuth : public HttpMiddleware
{ {
Q_OBJECT Q_OBJECT
@@ -61,7 +61,7 @@ public:
* To determine whether the local file was created successfully, call the * To determine whether the local file was created successfully, call the
* exists() method. * exists() method.
*/ */
explicit QLocalAuth(QObject *parent = Q_NULLPTR); explicit LocalAuth(QObject *parent = Q_NULLPTR);
/** /**
* @brief Determine whether the file exists * @brief Determine whether the file exists
@@ -91,11 +91,11 @@ public:
* If the token supplied by the client matches, the request is allowed. * If the token supplied by the client matches, the request is allowed.
* Otherwise, an HTTP 403 error is returned. * Otherwise, an HTTP 403 error is returned.
*/ */
virtual bool process(QHttpSocket *socket); virtual bool process(HttpSocket *socket);
private: private:
QLocalAuthPrivate *const d; LocalAuthPrivate *const d;
}; };
#endif // QHTTPENGINE_QLOCALAUTH_H #endif // QHTTPENGINE_QLOCALAUTH_H

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QLocalFilePrivate; class QHTTPENGINE_EXPORT LocalFilePrivate;
/** /**
* @brief Locally accessible file * @brief Locally accessible file
@@ -49,7 +49,7 @@ class QHTTPENGINE_EXPORT QLocalFilePrivate;
* For example, if the application name was "test" and the user's home * For example, if the application name was "test" and the user's home
* directory was `/home/bob`, the absolute path would be `/home/bob/.test`. * directory was `/home/bob`, the absolute path would be `/home/bob/.test`.
*/ */
class QHTTPENGINE_EXPORT QLocalFile : public QFile class QHTTPENGINE_EXPORT LocalFile : public QFile
{ {
Q_OBJECT Q_OBJECT
@@ -58,7 +58,7 @@ public:
/** /**
* @brief Create a new local file * @brief Create a new local file
*/ */
explicit QLocalFile(QObject *parent = 0); explicit LocalFile(QObject *parent = 0);
/** /**
* @brief Attempt to open the file * @brief Attempt to open the file
@@ -71,8 +71,8 @@ public:
private: private:
QLocalFilePrivate *const d; LocalFilePrivate *const d;
friend class QLocalFilePrivate; friend class LocalFilePrivate;
}; };
#endif // QHTTPENGINE_QLOCALFILE_H #endif // QHTTPENGINE_QLOCALFILE_H

View File

@@ -27,7 +27,7 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHttpSocket; class HttpSocket;
class QHTTPENGINE_EXPORT QObjectHandlerPrivate; class QHTTPENGINE_EXPORT QObjectHandlerPrivate;
/** /**
@@ -67,7 +67,7 @@ class QHTTPENGINE_EXPORT QObjectHandlerPrivate;
* }); * });
* @endcode * @endcode
*/ */
class QHTTPENGINE_EXPORT QObjectHandler : public QHttpHandler class QHTTPENGINE_EXPORT QObjectHandler : public HttpHandler
{ {
Q_OBJECT Q_OBJECT
@@ -123,7 +123,7 @@ public:
"The slot must have exactly one argument."); "The slot must have exactly one argument.");
// Ensure the argument is of the correct type // Ensure the argument is of the correct type
Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<QHttpSocket*, typename QtPrivate::List_Select<typename SlotType::Arguments, 0>::Value>::value), Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<HttpSocket*, typename QtPrivate::List_Select<typename SlotType::Arguments, 0>::Value>::value),
"The slot parameters do not match"); "The slot parameters do not match");
// Invoke the implementation // Invoke the implementation
@@ -157,7 +157,7 @@ protected:
/** /**
* @brief Reimplementation of QHttpHandler::process() * @brief Reimplementation of QHttpHandler::process()
*/ */
virtual void process(QHttpSocket *socket, const QString &path); virtual void process(HttpSocket *socket, const QString &path);
private: private:
@@ -171,7 +171,7 @@ private:
"The slot must have exactly one argument."); "The slot must have exactly one argument.");
// Ensure the argument is of the correct type // Ensure the argument is of the correct type
Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<QHttpSocket*, typename QtPrivate::List_Select<typename SlotType::Arguments, 0>::Value>::value), Q_STATIC_ASSERT_X((QtPrivate::AreArgumentsCompatible<HttpSocket*, typename QtPrivate::List_Select<typename SlotType::Arguments, 0>::Value>::value),
"The slot parameters do not match"); "The slot parameters do not match");
registerMethodImpl(name, context, registerMethodImpl(name, context,

View File

@@ -29,12 +29,12 @@
#include "qhttpengine_global.h" #include "qhttpengine_global.h"
class QHTTPENGINE_EXPORT QProxyHandlerPrivate; class QHTTPENGINE_EXPORT ProxyHandlerPrivate;
/** /**
* @brief Handler that routes HTTP requests to an upstream server * @brief Handler that routes HTTP requests to an upstream server
*/ */
class QHTTPENGINE_EXPORT QProxyHandler : public QHttpHandler class QHTTPENGINE_EXPORT ProxyHandler : public HttpHandler
{ {
Q_OBJECT Q_OBJECT
@@ -43,18 +43,18 @@ public:
/** /**
* @brief Create a new proxy handler * @brief Create a new proxy handler
*/ */
QProxyHandler(const QHostAddress &address, quint16 port, QObject *parent = 0); ProxyHandler(const QHostAddress &address, quint16 port, QObject *parent = 0);
protected: protected:
/** /**
* @brief Reimplementation of QHttpHandler::process() * @brief Reimplementation of QHttpHandler::process()
*/ */
virtual void process(QHttpSocket *socket, const QString &path); virtual void process(HttpSocket *socket, const QString &path);
private: private:
QProxyHandlerPrivate *const d; ProxyHandlerPrivate *const d;
}; };
#endif // QHTTPENGINE_QPROXYHANDLER_H #endif // QHTTPENGINE_QPROXYHANDLER_H

View File

@@ -48,12 +48,12 @@ const QString ListTemplate =
"</body>" "</body>"
"</html>"; "</html>";
QFilesystemHandlerPrivate::QFilesystemHandlerPrivate(QFilesystemHandler *handler) FilesystemHandlerPrivate::FilesystemHandlerPrivate(FilesystemHandler *handler)
: QObject(handler) : QObject(handler)
{ {
} }
bool QFilesystemHandlerPrivate::absolutePath(const QString &path, QString &absolutePath) bool FilesystemHandlerPrivate::absolutePath(const QString &path, QString &absolutePath)
{ {
// Resolve the path according to the document root // Resolve the path according to the document root
absolutePath = documentRoot.absoluteFilePath(path); absolutePath = documentRoot.absoluteFilePath(path);
@@ -64,20 +64,20 @@ bool QFilesystemHandlerPrivate::absolutePath(const QString &path, QString &absol
return documentRoot.exists(absolutePath) && !documentRoot.relativeFilePath(path).startsWith("../"); return documentRoot.exists(absolutePath) && !documentRoot.relativeFilePath(path).startsWith("../");
} }
QByteArray QFilesystemHandlerPrivate::mimeType(const QString &absolutePath) QByteArray FilesystemHandlerPrivate::mimeType(const QString &absolutePath)
{ {
// Query the MIME database based on the filename and its contents // Query the MIME database based on the filename and its contents
return database.mimeTypeForFile(absolutePath).name().toUtf8(); return database.mimeTypeForFile(absolutePath).name().toUtf8();
} }
void QFilesystemHandlerPrivate::processFile(QHttpSocket *socket, const QString &absolutePath) void FilesystemHandlerPrivate::processFile(HttpSocket *socket, const QString &absolutePath)
{ {
// Attempt to open the file for reading // Attempt to open the file for reading
QFile *file = new QFile(absolutePath); QFile *file = new QFile(absolutePath);
if (!file->open(QIODevice::ReadOnly)) { if (!file->open(QIODevice::ReadOnly)) {
delete file; delete file;
socket->writeError(QHttpSocket::Forbidden); socket->writeError(HttpSocket::Forbidden);
return; return;
} }
@@ -93,7 +93,7 @@ void QFilesystemHandlerPrivate::processFile(QHttpSocket *socket, const QString &
// Checking for partial content request // Checking for partial content request
QByteArray rangeHeader = socket->headers().value("Range"); QByteArray rangeHeader = socket->headers().value("Range");
QHttpRange range; HttpRange range;
if (!rangeHeader.isEmpty() && rangeHeader.startsWith("bytes=")) { if (!rangeHeader.isEmpty() && rangeHeader.startsWith("bytes=")) {
// Skiping 'bytes=' - first 6 chars and spliting ranges by comma // Skiping 'bytes=' - first 6 chars and spliting ranges by comma
@@ -101,12 +101,12 @@ void QFilesystemHandlerPrivate::processFile(QHttpSocket *socket, const QString &
// Taking only first range, as multiple ranges require multipart // Taking only first range, as multiple ranges require multipart
// reply support // reply support
range = QHttpRange(QString(rangeList.at(0)), fileSize); range = HttpRange(QString(rangeList.at(0)), fileSize);
} }
// If range is valid, send partial content // If range is valid, send partial content
if (range.isValid()) { if (range.isValid()) {
socket->setStatusCode(QHttpSocket::PartialContent); socket->setStatusCode(HttpSocket::PartialContent);
socket->setHeader("Content-Length", QByteArray::number(range.length())); socket->setHeader("Content-Length", QByteArray::number(range.length()));
socket->setHeader("Content-Range", QByteArray("bytes ") + range.contentRange().toLatin1()); socket->setHeader("Content-Range", QByteArray("bytes ") + range.contentRange().toLatin1());
copier->setRange(range.from(), range.to()); copier->setRange(range.from(), range.to());
@@ -124,7 +124,7 @@ void QFilesystemHandlerPrivate::processFile(QHttpSocket *socket, const QString &
copier->start(); copier->start();
} }
void QFilesystemHandlerPrivate::processDirectory(QHttpSocket *socket, const QString &path, const QString &absolutePath) void FilesystemHandlerPrivate::processDirectory(HttpSocket *socket, const QString &path, const QString &absolutePath)
{ {
// Add entries for each of the files // Add entries for each of the files
QString listing; QString listing;
@@ -148,29 +148,29 @@ void QFilesystemHandlerPrivate::processDirectory(QHttpSocket *socket, const QStr
socket->close(); socket->close();
} }
QFilesystemHandler::QFilesystemHandler(QObject *parent) FilesystemHandler::FilesystemHandler(QObject *parent)
: QHttpHandler(parent), : HttpHandler(parent),
d(new QFilesystemHandlerPrivate(this)) d(new FilesystemHandlerPrivate(this))
{ {
} }
QFilesystemHandler::QFilesystemHandler(const QString &documentRoot, QObject *parent) FilesystemHandler::FilesystemHandler(const QString &documentRoot, QObject *parent)
: QHttpHandler(parent), : HttpHandler(parent),
d(new QFilesystemHandlerPrivate(this)) d(new FilesystemHandlerPrivate(this))
{ {
setDocumentRoot(documentRoot); setDocumentRoot(documentRoot);
} }
void QFilesystemHandler::setDocumentRoot(const QString &documentRoot) void FilesystemHandler::setDocumentRoot(const QString &documentRoot)
{ {
d->documentRoot.setPath(documentRoot); d->documentRoot.setPath(documentRoot);
} }
void QFilesystemHandler::process(QHttpSocket *socket, const QString &path) void FilesystemHandler::process(HttpSocket *socket, const QString &path)
{ {
// If a document root is not set, an error has occurred // If a document root is not set, an error has occurred
if (d->documentRoot.path().isNull()) { if (d->documentRoot.path().isNull()) {
socket->writeError(QHttpSocket::InternalServerError); socket->writeError(HttpSocket::InternalServerError);
return; return;
} }
@@ -180,7 +180,7 @@ void QFilesystemHandler::process(QHttpSocket *socket, const QString &path)
// Attempt to retrieve the absolute path // Attempt to retrieve the absolute path
QString absolutePath; QString absolutePath;
if (!d->absolutePath(decodedPath, absolutePath)) { if (!d->absolutePath(decodedPath, absolutePath)) {
socket->writeError(QHttpSocket::NotFound); socket->writeError(HttpSocket::NotFound);
return; return;
} }

View File

@@ -30,19 +30,19 @@
#include <qhttpengine/qfilesystemhandler.h> #include <qhttpengine/qfilesystemhandler.h>
#include <qhttpengine/qhttpsocket.h> #include <qhttpengine/qhttpsocket.h>
class QFilesystemHandlerPrivate : public QObject class FilesystemHandlerPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
QFilesystemHandlerPrivate(QFilesystemHandler *handler); FilesystemHandlerPrivate(FilesystemHandler *handler);
bool absolutePath(const QString &path, QString &absolutePath); bool absolutePath(const QString &path, QString &absolutePath);
QByteArray mimeType(const QString &path); QByteArray mimeType(const QString &path);
void processFile(QHttpSocket *socket, const QString &absolutePath); void processFile(HttpSocket*socket, const QString &absolutePath);
void processDirectory(QHttpSocket *socket, const QString &path, const QString &absolutePath); void processDirectory(HttpSocket*socket, const QString &path, const QString &absolutePath);
QDir documentRoot; QDir documentRoot;
QMimeDatabase database; QMimeDatabase database;

View File

@@ -27,37 +27,37 @@
#include "qhttpbasicauth_p.h" #include "qhttpbasicauth_p.h"
QHttpBasicAuthPrivate::QHttpBasicAuthPrivate(QObject *parent, const QString &realm) HttpBasicAuthPrivate::HttpBasicAuthPrivate(QObject *parent, const QString &realm)
: QObject(parent), : QObject(parent),
realm(realm) realm(realm)
{ {
} }
QHttpBasicAuth::QHttpBasicAuth(const QString &realm, QObject *parent) HttpBasicAuth::HttpBasicAuth(const QString &realm, QObject *parent)
: QHttpMiddleware(parent), : HttpMiddleware(parent),
d(new QHttpBasicAuthPrivate(this, realm)) d(new HttpBasicAuthPrivate(this, realm))
{ {
} }
void QHttpBasicAuth::add(const QString &username, const QString &password) void HttpBasicAuth::add(const QString &username, const QString &password)
{ {
d->map.insert(username, password); d->map.insert(username, password);
} }
bool QHttpBasicAuth::verify(const QString &username, const QString &password) bool HttpBasicAuth::verify(const QString &username, const QString &password)
{ {
return d->map.contains(username) && d->map.value(username) == password; return d->map.contains(username) && d->map.value(username) == password;
} }
bool QHttpBasicAuth::process(QHttpSocket *socket) bool HttpBasicAuth::process(HttpSocket *socket)
{ {
// Attempt to extract credentials from the header // Attempt to extract credentials from the header
QByteArrayList headerParts = socket->headers().value("Authorization").split(' '); QByteArrayList headerParts = socket->headers().value("Authorization").split(' ');
if (headerParts.count() == 2 && headerParts.at(0) == QIByteArray("Basic")) { if (headerParts.count() == 2 && headerParts.at(0) == IByteArray("Basic")) {
// Decode the credentials and split into username/password // Decode the credentials and split into username/password
QByteArrayList parts; QByteArrayList parts;
QHttpParser::split( HttpParser::split(
QByteArray::fromBase64(headerParts.at(1)), QByteArray::fromBase64(headerParts.at(1)),
":", 1, parts ":", 1, parts
); );
@@ -70,6 +70,6 @@ bool QHttpBasicAuth::process(QHttpSocket *socket)
// Otherwise, inform the client that valid credentials are required // Otherwise, inform the client that valid credentials are required
socket->setHeader("WWW-Authenticate", QString("Basic realm=\"%1\"").arg(d->realm).toUtf8()); socket->setHeader("WWW-Authenticate", QString("Basic realm=\"%1\"").arg(d->realm).toUtf8());
socket->writeError(QHttpSocket::Unauthorized); socket->writeError(HttpSocket::Unauthorized);
return false; return false;
} }

View File

@@ -26,13 +26,13 @@
#include <QMap> #include <QMap>
#include <QObject> #include <QObject>
class QHttpBasicAuthPrivate : public QObject class HttpBasicAuthPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit QHttpBasicAuthPrivate(QObject *parent, const QString &realm); explicit HttpBasicAuthPrivate(QObject *parent, const QString &realm);
const QString realm; const QString realm;
QMap<QString, QString> map; QMap<QString, QString> map;

View File

@@ -26,37 +26,37 @@
#include "qhttphandler_p.h" #include "qhttphandler_p.h"
QHttpHandlerPrivate::QHttpHandlerPrivate(QHttpHandler *handler) HttpHandlerPrivate::HttpHandlerPrivate(HttpHandler *handler)
: QObject(handler), : QObject(handler),
q(handler) q(handler)
{ {
} }
QHttpHandler::QHttpHandler(QObject *parent) HttpHandler::HttpHandler(QObject *parent)
: QObject(parent), : QObject(parent),
d(new QHttpHandlerPrivate(this)) d(new HttpHandlerPrivate(this))
{ {
} }
void QHttpHandler::addMiddleware(QHttpMiddleware *middleware) void HttpHandler::addMiddleware(HttpMiddleware *middleware)
{ {
d->middleware.append(middleware); d->middleware.append(middleware);
} }
void QHttpHandler::addRedirect(const QRegExp &pattern, const QString &path) void HttpHandler::addRedirect(const QRegExp &pattern, const QString &path)
{ {
d->redirects.append(Redirect(pattern, path)); d->redirects.append(Redirect(pattern, path));
} }
void QHttpHandler::addSubHandler(const QRegExp &pattern, QHttpHandler *handler) void HttpHandler::addSubHandler(const QRegExp &pattern, HttpHandler *handler)
{ {
d->subHandlers.append(SubHandler(pattern, handler)); d->subHandlers.append(SubHandler(pattern, handler));
} }
void QHttpHandler::route(QHttpSocket *socket, const QString &path) void HttpHandler::route(HttpSocket *socket, const QString &path)
{ {
// Run through each of the middleware // Run through each of the middleware
foreach (QHttpMiddleware *middleware, d->middleware) { foreach (HttpMiddleware *middleware, d->middleware) {
if (!middleware->process(socket)) { if (!middleware->process(socket)) {
return; return;
} }
@@ -86,9 +86,9 @@ void QHttpHandler::route(QHttpSocket *socket, const QString &path)
process(socket, path); process(socket, path);
} }
void QHttpHandler::process(QHttpSocket *socket, const QString &) void HttpHandler::process(HttpSocket *socket, const QString &)
{ {
// The default response is simply a 404 error // The default response is simply a 404 error
socket->writeError(QHttpSocket::NotFound); socket->writeError(HttpSocket::NotFound);
socket->close(); socket->close();
} }

View File

@@ -31,23 +31,23 @@
#include <qhttpengine/qhttphandler.h> #include <qhttpengine/qhttphandler.h>
typedef QPair<QRegExp, QString> Redirect; typedef QPair<QRegExp, QString> Redirect;
typedef QPair<QRegExp, QHttpHandler*> SubHandler; typedef QPair<QRegExp, HttpHandler*> SubHandler;
class QHttpHandlerPrivate : public QObject class HttpHandlerPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit QHttpHandlerPrivate(QHttpHandler *handler); explicit HttpHandlerPrivate(HttpHandler *handler);
QList<Redirect> redirects; QList<Redirect> redirects;
QList<SubHandler> subHandlers; QList<SubHandler> subHandlers;
QList<QHttpMiddleware*> middleware; QList<HttpMiddleware*> middleware;
private: private:
QHttpHandler *const q; HttpHandler*const q;
}; };
#endif // QHTTPENGINE_QHTTPHANDLERPRIVATE_H #endif // QHTTPENGINE_QHTTPHANDLERPRIVATE_H

View File

@@ -26,7 +26,7 @@
#include <qhttpengine/qhttpparser.h> #include <qhttpengine/qhttpparser.h>
void QHttpParser::split(const QByteArray &data, const QByteArray &delim, int maxSplit, QByteArrayList &parts) void HttpParser::split(const QByteArray &data, const QByteArray &delim, int maxSplit, QByteArrayList &parts)
{ {
int index = 0; int index = 0;
@@ -45,7 +45,7 @@ void QHttpParser::split(const QByteArray &data, const QByteArray &delim, int max
parts.append(data.mid(index)); parts.append(data.mid(index));
} }
bool QHttpParser::parsePath(const QByteArray &rawPath, QString &path, QHttpSocket::QueryStringMap &queryString) bool HttpParser::parsePath(const QByteArray &rawPath, QString &path, HttpSocket::QueryStringMap &queryString)
{ {
QUrl url(rawPath); QUrl url(rawPath);
if (!url.isValid()) { if (!url.isValid()) {
@@ -61,7 +61,7 @@ bool QHttpParser::parsePath(const QByteArray &rawPath, QString &path, QHttpSocke
return true; return true;
} }
bool QHttpParser::parseHeaderList(const QList<QByteArray> &lines, QHttpSocket::HeaderMap &headers) bool HttpParser::parseHeaderList(const QList<QByteArray> &lines, HttpSocket::HeaderMap &headers)
{ {
foreach (const QByteArray &line, lines) { foreach (const QByteArray &line, lines) {
@@ -80,7 +80,7 @@ bool QHttpParser::parseHeaderList(const QList<QByteArray> &lines, QHttpSocket::H
return true; return true;
} }
bool QHttpParser::parseHeaders(const QByteArray &data, QList<QByteArray> &parts, QHttpSocket::HeaderMap &headers) bool HttpParser::parseHeaders(const QByteArray &data, QList<QByteArray> &parts, HttpSocket::HeaderMap &headers)
{ {
// Split the data into individual lines // Split the data into individual lines
QList<QByteArray> lines; QList<QByteArray> lines;
@@ -95,7 +95,7 @@ bool QHttpParser::parseHeaders(const QByteArray &data, QList<QByteArray> &parts,
return parseHeaderList(lines, headers); return parseHeaderList(lines, headers);
} }
bool QHttpParser::parseRequestHeaders(const QByteArray &data, QHttpSocket::Method &method, QByteArray &path, QHttpSocket::HeaderMap &headers) bool HttpParser::parseRequestHeaders(const QByteArray &data, HttpSocket::Method &method, QByteArray &path, HttpSocket::HeaderMap &headers)
{ {
QList<QByteArray> parts; QList<QByteArray> parts;
if (!parseHeaders(data, parts, headers)) { if (!parseHeaders(data, parts, headers)) {
@@ -108,21 +108,21 @@ bool QHttpParser::parseRequestHeaders(const QByteArray &data, QHttpSocket::Metho
} }
if (parts[0] == "OPTIONS") { if (parts[0] == "OPTIONS") {
method = QHttpSocket::OPTIONS; method = HttpSocket::OPTIONS;
} else if (parts[0] == "GET") { } else if (parts[0] == "GET") {
method = QHttpSocket::GET; method = HttpSocket::GET;
} else if (parts[0] == "HEAD") { } else if (parts[0] == "HEAD") {
method = QHttpSocket::HEAD; method = HttpSocket::HEAD;
} else if (parts[0] == "POST") { } else if (parts[0] == "POST") {
method = QHttpSocket::POST; method = HttpSocket::POST;
} else if (parts[0] == "PUT") { } else if (parts[0] == "PUT") {
method = QHttpSocket::PUT; method = HttpSocket::PUT;
} else if (parts[0] == "DELETE") { } else if (parts[0] == "DELETE") {
method = QHttpSocket::DELETE; method = HttpSocket::DELETE;
} else if (parts[0] == "TRACE") { } else if (parts[0] == "TRACE") {
method = QHttpSocket::TRACE; method = HttpSocket::TRACE;
} else if (parts[0] == "CONNECT") { } else if (parts[0] == "CONNECT") {
method = QHttpSocket::CONNECT; method = HttpSocket::CONNECT;
} else { } else {
return false; return false;
} }
@@ -132,7 +132,7 @@ bool QHttpParser::parseRequestHeaders(const QByteArray &data, QHttpSocket::Metho
return true; return true;
} }
bool QHttpParser::parseResponseHeaders(const QByteArray &data, int &statusCode, QByteArray &statusReason, QHttpSocket::HeaderMap &headers) bool HttpParser::parseResponseHeaders(const QByteArray &data, int &statusCode, QByteArray &statusReason, HttpSocket::HeaderMap &headers)
{ {
QList<QByteArray> parts; QList<QByteArray> parts;
if (!parseHeaders(data, parts, headers)) { if (!parseHeaders(data, parts, headers)) {

View File

@@ -26,21 +26,21 @@
#include "qhttprange_p.h" #include "qhttprange_p.h"
QHttpRangePrivate::QHttpRangePrivate(QHttpRange *range) HttpRangePrivate::HttpRangePrivate(HttpRange *range)
: q(range) : q(range)
{ {
} }
QHttpRange::QHttpRange() HttpRange::HttpRange()
: d(new QHttpRangePrivate(this)) : d(new HttpRangePrivate(this))
{ {
d->from = 1; d->from = 1;
d->to = 0; d->to = 0;
d->dataSize = -1; d->dataSize = -1;
} }
QHttpRange::QHttpRange(const QString &range, qint64 dataSize) HttpRange::HttpRange(const QString &range, qint64 dataSize)
: d(new QHttpRangePrivate(this)) : d(new HttpRangePrivate(this))
{ {
QRegExp regExp("^(\\d*)-(\\d*)$"); QRegExp regExp("^(\\d*)-(\\d*)$");
@@ -101,28 +101,28 @@ QHttpRange::QHttpRange(const QString &range, qint64 dataSize)
d->dataSize = dataSize; d->dataSize = dataSize;
} }
QHttpRange::QHttpRange(qint64 from, qint64 to, qint64 dataSize) HttpRange::HttpRange(qint64 from, qint64 to, qint64 dataSize)
: d(new QHttpRangePrivate(this)) : d(new HttpRangePrivate(this))
{ {
d->from = from; d->from = from;
d->to = to < 0 ? -1 : to; d->to = to < 0 ? -1 : to;
d->dataSize = dataSize < 0 ? -1 : dataSize; d->dataSize = dataSize < 0 ? -1 : dataSize;
} }
QHttpRange::QHttpRange(const QHttpRange &other, qint64 dataSize) HttpRange::HttpRange(const HttpRange &other, qint64 dataSize)
: d(new QHttpRangePrivate(this)) : d(new HttpRangePrivate(this))
{ {
d->from = other.d->from; d->from = other.d->from;
d->to = other.d->to; d->to = other.d->to;
d->dataSize = dataSize; d->dataSize = dataSize;
} }
QHttpRange::~QHttpRange() HttpRange::~HttpRange()
{ {
delete d; delete d;
} }
QHttpRange& QHttpRange::operator=(const QHttpRange &other) HttpRange& HttpRange::operator=(const HttpRange &other)
{ {
if (&other != this) { if (&other != this) {
d->from = other.d->from; d->from = other.d->from;
@@ -133,7 +133,7 @@ QHttpRange& QHttpRange::operator=(const QHttpRange &other)
return *this; return *this;
} }
qint64 QHttpRange::from() const qint64 HttpRange::from() const
{ {
// Last N bytes requested // Last N bytes requested
if (d->from < 0 && d->dataSize != -1) { if (d->from < 0 && d->dataSize != -1) {
@@ -153,7 +153,7 @@ qint64 QHttpRange::from() const
return d->from; return d->from;
} }
qint64 QHttpRange::to() const qint64 HttpRange::to() const
{ {
// Last N bytes requested // Last N bytes requested
if (d->from < 0 && d->dataSize != -1) { if (d->from < 0 && d->dataSize != -1) {
@@ -178,7 +178,7 @@ qint64 QHttpRange::to() const
return d->to; return d->to;
} }
qint64 QHttpRange::length() const qint64 HttpRange::length() const
{ {
if (!isValid()) { if (!isValid()) {
return -1; return -1;
@@ -202,12 +202,12 @@ qint64 QHttpRange::length() const
return -1; return -1;
} }
qint64 QHttpRange::dataSize() const qint64 HttpRange::dataSize() const
{ {
return d->dataSize; return d->dataSize;
} }
bool QHttpRange::isValid() const bool HttpRange::isValid() const
{ {
// Valid cases: // Valid cases:
// 1. "-500/1000" => from: -500, to: -1; dataSize: 1000 // 1. "-500/1000" => from: -500, to: -1; dataSize: 1000
@@ -253,7 +253,7 @@ bool QHttpRange::isValid() const
return false; return false;
} }
QString QHttpRange::contentRange() const QString HttpRange::contentRange() const
{ {
QString fromStr, toStr, sizeStr = "*"; QString fromStr, toStr, sizeStr = "*";

View File

@@ -25,11 +25,11 @@
#include <qhttpengine/qhttprange.h> #include <qhttpengine/qhttprange.h>
class QHttpRangePrivate class HttpRangePrivate
{ {
public: public:
explicit QHttpRangePrivate(QHttpRange *range); explicit HttpRangePrivate(HttpRange *range);
qint64 from; qint64 from;
qint64 to; qint64 to;
@@ -37,7 +37,7 @@ public:
private: private:
QHttpRange *const q; HttpRange *const q;
}; };
#endif // QHTTPENGINE_QHTTPRANGEPRIVATE_H #endif // QHTTPENGINE_QHTTPRANGEPRIVATE_H

View File

@@ -29,56 +29,56 @@
#include "qhttpserver_p.h" #include "qhttpserver_p.h"
QHttpServerPrivate::QHttpServerPrivate(QHttpServer *httpServer) HttpServerPrivate::HttpServerPrivate(HttpServer *httpServer)
: QObject(httpServer), : QObject(httpServer),
q(httpServer), q(httpServer),
handler(0) handler(0)
{ {
} }
void QHttpServerPrivate::process(QTcpSocket *socket) void HttpServerPrivate::process(QTcpSocket *socket)
{ {
QHttpSocket *httpSocket = new QHttpSocket(socket, this); HttpSocket *httpSocket = new HttpSocket(socket, this);
// Wait until the socket finishes reading the HTTP headers before routing // Wait until the socket finishes reading the HTTP headers before routing
connect(httpSocket, &QHttpSocket::headersParsed, [this, httpSocket]() { connect(httpSocket, &HttpSocket::headersParsed, [this, httpSocket]() {
if (handler) { if (handler) {
handler->route(httpSocket, QString(httpSocket->path().mid(1))); handler->route(httpSocket, QString(httpSocket->path().mid(1)));
} else { } else {
httpSocket->writeError(QHttpSocket::InternalServerError); httpSocket->writeError(HttpSocket::InternalServerError);
} }
}); });
// Destroy the socket once the client is disconnected // Destroy the socket once the client is disconnected
connect(socket, &QTcpSocket::disconnected, httpSocket, &QHttpSocket::deleteLater); connect(socket, &QTcpSocket::disconnected, httpSocket, &HttpSocket::deleteLater);
} }
QHttpServer::QHttpServer(QObject *parent) HttpServer::HttpServer(QObject *parent)
: QTcpServer(parent), : QTcpServer(parent),
d(new QHttpServerPrivate(this)) d(new HttpServerPrivate(this))
{ {
} }
QHttpServer::QHttpServer(QHttpHandler *handler, QObject *parent) HttpServer::HttpServer(HttpHandler *handler, QObject *parent)
: QTcpServer(parent), : QTcpServer(parent),
d(new QHttpServerPrivate(this)) d(new HttpServerPrivate(this))
{ {
setHandler(handler); setHandler(handler);
} }
void QHttpServer::setHandler(QHttpHandler *handler) void HttpServer::setHandler(HttpHandler *handler)
{ {
d->handler = handler; d->handler = handler;
} }
#if !defined(QT_NO_SSL) #if !defined(QT_NO_SSL)
void QHttpServer::setSslConfiguration(const QSslConfiguration &configuration) void HttpServer::setSslConfiguration(const QSslConfiguration &configuration)
{ {
d->configuration = configuration; d->configuration = configuration;
} }
#endif #endif
void QHttpServer::incomingConnection(qintptr socketDescriptor) void HttpServer::incomingConnection(qintptr socketDescriptor)
{ {
#if !defined(QT_NO_SSL) #if !defined(QT_NO_SSL)
if (!d->configuration.isNull()) { if (!d->configuration.isNull()) {

View File

@@ -32,19 +32,19 @@
#include <qhttpengine/qhttpserver.h> #include <qhttpengine/qhttpserver.h>
class QHttpHandler; class HttpHandler;
class QHttpServerPrivate : public QObject class HttpServerPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit QHttpServerPrivate(QHttpServer *httpServer); explicit HttpServerPrivate(HttpServer *httpServer);
void process(QTcpSocket *socket); void process(QTcpSocket *socket);
QHttpHandler *handler; HttpHandler*handler;
#if !defined(QT_NO_SSL) #if !defined(QT_NO_SSL)
QSslConfiguration configuration; QSslConfiguration configuration;
@@ -52,7 +52,7 @@ public:
private: private:
QHttpServer *const q; HttpServer*const q;
}; };
#endif // QHTTPENGINE_QHTTPSERVERPRIVATE_H #endif // QHTTPENGINE_QHTTPSERVERPRIVATE_H

View File

@@ -51,7 +51,7 @@ const QString ErrorTemplate =
"</body>" "</body>"
"</html>"; "</html>";
QHttpSocketPrivate::QHttpSocketPrivate(QHttpSocket *httpSocket, QTcpSocket *tcpSocket) HttpSocketPrivate::HttpSocketPrivate(HttpSocket *httpSocket, QTcpSocket *tcpSocket)
: QObject(httpSocket), : QObject(httpSocket),
q(httpSocket), q(httpSocket),
socket(tcpSocket), socket(tcpSocket),
@@ -64,38 +64,38 @@ QHttpSocketPrivate::QHttpSocketPrivate(QHttpSocket *httpSocket, QTcpSocket *tcpS
{ {
socket->setParent(this); socket->setParent(this);
connect(socket, &QTcpSocket::readyRead, this, &QHttpSocketPrivate::onReadyRead); connect(socket, &QTcpSocket::readyRead, this, &HttpSocketPrivate::onReadyRead);
connect(socket, &QTcpSocket::bytesWritten, this, &QHttpSocketPrivate::onBytesWritten); connect(socket, &QTcpSocket::bytesWritten, this, &HttpSocketPrivate::onBytesWritten);
connect(socket, &QTcpSocket::readChannelFinished, q, &QHttpSocket::readChannelFinished); connect(socket, &QTcpSocket::readChannelFinished, q, &HttpSocket::readChannelFinished);
// Process anything already received by the socket // Process anything already received by the socket
onReadyRead(); onReadyRead();
} }
QByteArray QHttpSocketPrivate::statusReason(int statusCode) const QByteArray HttpSocketPrivate::statusReason(int statusCode) const
{ {
switch (statusCode) { switch (statusCode) {
case QHttpSocket::OK: return "OK"; case HttpSocket::OK: return "OK";
case QHttpSocket::Created: return "CREATED"; case HttpSocket::Created: return "CREATED";
case QHttpSocket::Accepted: return "ACCEPTED"; case HttpSocket::Accepted: return "ACCEPTED";
case QHttpSocket::PartialContent: return "PARTIAL CONTENT"; case HttpSocket::PartialContent: return "PARTIAL CONTENT";
case QHttpSocket::MovedPermanently: return "MOVED PERMANENTLY"; case HttpSocket::MovedPermanently: return "MOVED PERMANENTLY";
case QHttpSocket::Found: return "FOUND"; case HttpSocket::Found: return "FOUND";
case QHttpSocket::BadRequest: return "BAD REQUEST"; case HttpSocket::BadRequest: return "BAD REQUEST";
case QHttpSocket::Unauthorized: return "UNAUTHORIZED"; case HttpSocket::Unauthorized: return "UNAUTHORIZED";
case QHttpSocket::Forbidden: return "FORBIDDEN"; case HttpSocket::Forbidden: return "FORBIDDEN";
case QHttpSocket::NotFound: return "NOT FOUND"; case HttpSocket::NotFound: return "NOT FOUND";
case QHttpSocket::MethodNotAllowed: return "METHOD NOT ALLOWED"; case HttpSocket::MethodNotAllowed: return "METHOD NOT ALLOWED";
case QHttpSocket::Conflict: return "CONFLICT"; case HttpSocket::Conflict: return "CONFLICT";
case QHttpSocket::BadGateway: return "BAD GATEWAY"; case HttpSocket::BadGateway: return "BAD GATEWAY";
case QHttpSocket::ServiceUnavailable: return "SERVICE UNAVAILABLE"; case HttpSocket::ServiceUnavailable: return "SERVICE UNAVAILABLE";
case QHttpSocket::InternalServerError: return "INTERNAL SERVER ERROR"; case HttpSocket::InternalServerError: return "INTERNAL SERVER ERROR";
case QHttpSocket::HttpVersionNotSupported: return "HTTP VERSION NOT SUPPORTED"; case HttpSocket::HttpVersionNotSupported: return "HTTP VERSION NOT SUPPORTED";
default: return "UNKNOWN ERROR"; default: return "UNKNOWN ERROR";
} }
} }
void QHttpSocketPrivate::onReadyRead() void HttpSocketPrivate::onReadyRead()
{ {
// Append all of the new data to the read buffer // Append all of the new data to the read buffer
readBuffer.append(socket->readAll()); readBuffer.append(socket->readAll());
@@ -116,7 +116,7 @@ void QHttpSocketPrivate::onReadyRead()
} }
} }
void QHttpSocketPrivate::onBytesWritten(qint64 bytes) void HttpSocketPrivate::onBytesWritten(qint64 bytes)
{ {
// Check to see if all of the response header was written // Check to see if all of the response header was written
if (writeState == WriteHeaders) { if (writeState == WriteHeaders) {
@@ -134,7 +134,7 @@ void QHttpSocketPrivate::onBytesWritten(qint64 bytes)
} }
} }
bool QHttpSocketPrivate::readHeaders() bool HttpSocketPrivate::readHeaders()
{ {
// Check for the double CRLF that signals the end of the headers and // Check for the double CRLF that signals the end of the headers and
// if it is not found, wait until the next time readyRead is emitted // if it is not found, wait until the next time readyRead is emitted
@@ -145,9 +145,9 @@ bool QHttpSocketPrivate::readHeaders()
// Attempt to parse the headers and if a problem is encountered, abort // Attempt to parse the headers and if a problem is encountered, abort
// the connection (so that no more data is read or written) and return // the connection (so that no more data is read or written) and return
if (!QHttpParser::parseRequestHeaders(readBuffer.left(index), requestMethod, requestRawPath, requestHeaders) || if (!HttpParser::parseRequestHeaders(readBuffer.left(index), requestMethod, requestRawPath, requestHeaders) ||
!QHttpParser::parsePath(requestRawPath, requestPath, requestQueryString)) { !HttpParser::parsePath(requestRawPath, requestPath, requestQueryString)) {
q->writeError(QHttpSocket::BadRequest); q->writeError(HttpSocket::BadRequest);
return false; return false;
} }
@@ -168,7 +168,7 @@ bool QHttpSocketPrivate::readHeaders()
return true; return true;
} }
void QHttpSocketPrivate::readData() void HttpSocketPrivate::readData()
{ {
// Emit the readyRead() signal if any data is available in the buffer // Emit the readyRead() signal if any data is available in the buffer
if (readBuffer.size()) { if (readBuffer.size()) {
@@ -184,99 +184,99 @@ void QHttpSocketPrivate::readData()
} }
} }
QHttpSocket::QHttpSocket(QTcpSocket *socket, QObject *parent) HttpSocket::HttpSocket(QTcpSocket *socket, QObject *parent)
: QIODevice(parent), : QIODevice(parent),
d(new QHttpSocketPrivate(this, socket)) d(new HttpSocketPrivate(this, socket))
{ {
// The device is initially open for both reading and writing // The device is initially open for both reading and writing
setOpenMode(QIODevice::ReadWrite); setOpenMode(QIODevice::ReadWrite);
} }
qint64 QHttpSocket::bytesAvailable() const qint64 HttpSocket::bytesAvailable() const
{ {
if (d->readState > QHttpSocketPrivate::ReadHeaders) { if (d->readState > HttpSocketPrivate::ReadHeaders) {
return d->readBuffer.size() + QIODevice::bytesAvailable(); return d->readBuffer.size() + QIODevice::bytesAvailable();
} else { } else {
return 0; return 0;
} }
} }
bool QHttpSocket::isSequential() const bool HttpSocket::isSequential() const
{ {
return true; return true;
} }
void QHttpSocket::close() void HttpSocket::close()
{ {
// Invoke the parent method // Invoke the parent method
QIODevice::close(); QIODevice::close();
d->readState = QHttpSocketPrivate::ReadFinished; d->readState = HttpSocketPrivate::ReadFinished;
d->writeState = QHttpSocketPrivate::WriteFinished; d->writeState = HttpSocketPrivate::WriteFinished;
d->socket->close(); d->socket->close();
} }
QHostAddress QHttpSocket::peerAddress() const QHostAddress HttpSocket::peerAddress() const
{ {
return d->socket->peerAddress(); return d->socket->peerAddress();
} }
bool QHttpSocket::isHeadersParsed() const bool HttpSocket::isHeadersParsed() const
{ {
return d->readState > QHttpSocketPrivate::ReadHeaders; return d->readState > HttpSocketPrivate::ReadHeaders;
} }
QHttpSocket::Method QHttpSocket::method() const HttpSocket::Method HttpSocket::method() const
{ {
return d->requestMethod; return d->requestMethod;
} }
QByteArray QHttpSocket::rawPath() const QByteArray HttpSocket::rawPath() const
{ {
return d->requestRawPath; return d->requestRawPath;
} }
QString QHttpSocket::path() const QString HttpSocket::path() const
{ {
return d->requestPath; return d->requestPath;
} }
QHttpSocket::QueryStringMap QHttpSocket::queryString() const HttpSocket::QueryStringMap HttpSocket::queryString() const
{ {
return d->requestQueryString; return d->requestQueryString;
} }
QHttpSocket::HeaderMap QHttpSocket::headers() const HttpSocket::HeaderMap HttpSocket::headers() const
{ {
return d->requestHeaders; return d->requestHeaders;
} }
qint64 QHttpSocket::contentLength() const qint64 HttpSocket::contentLength() const
{ {
return d->requestDataTotal; return d->requestDataTotal;
} }
bool QHttpSocket::readJson(QJsonDocument &document) bool HttpSocket::readJson(QJsonDocument &document)
{ {
QJsonParseError error; QJsonParseError error;
document = QJsonDocument::fromJson(readAll(), &error); document = QJsonDocument::fromJson(readAll(), &error);
if (error.error != QJsonParseError::NoError) { if (error.error != QJsonParseError::NoError) {
writeError(QHttpSocket::BadRequest); writeError(HttpSocket::BadRequest);
return false; return false;
} }
return true; return true;
} }
void QHttpSocket::setStatusCode(int statusCode, const QByteArray &statusReason) void HttpSocket::setStatusCode(int statusCode, const QByteArray &statusReason)
{ {
d->responseStatusCode = statusCode; d->responseStatusCode = statusCode;
d->responseStatusReason = statusReason.isNull() ? d->statusReason(statusCode) : statusReason; d->responseStatusReason = statusReason.isNull() ? d->statusReason(statusCode) : statusReason;
} }
void QHttpSocket::setHeader(const QByteArray &name, const QByteArray &value, bool replace) void HttpSocket::setHeader(const QByteArray &name, const QByteArray &value, bool replace)
{ {
if (replace || d->responseHeaders.count(name)) { if (replace || d->responseHeaders.count(name)) {
d->responseHeaders.replace(name, value); d->responseHeaders.replace(name, value);
@@ -285,12 +285,12 @@ void QHttpSocket::setHeader(const QByteArray &name, const QByteArray &value, boo
} }
} }
void QHttpSocket::setHeaders(const HeaderMap &headers) void HttpSocket::setHeaders(const HeaderMap &headers)
{ {
d->responseHeaders = headers; d->responseHeaders = headers;
} }
void QHttpSocket::writeHeaders() void HttpSocket::writeHeaders()
{ {
// Use a QByteArray for building the header so that we can later determine // Use a QByteArray for building the header so that we can later determine
// exactly how many bytes were written // exactly how many bytes were written
@@ -312,14 +312,14 @@ void QHttpSocket::writeHeaders()
// Append an extra CRLF // Append an extra CRLF
header.append("\r\n"); header.append("\r\n");
d->writeState = QHttpSocketPrivate::WriteHeaders; d->writeState = HttpSocketPrivate::WriteHeaders;
d->responseHeaderRemaining = header.length(); d->responseHeaderRemaining = header.length();
// Write the header // Write the header
d->socket->write(header); d->socket->write(header);
} }
void QHttpSocket::writeRedirect(const QByteArray &path, bool permanent) void HttpSocket::writeRedirect(const QByteArray &path, bool permanent)
{ {
setStatusCode(permanent ? MovedPermanently : Found); setStatusCode(permanent ? MovedPermanently : Found);
setHeader("Location", path); setHeader("Location", path);
@@ -327,7 +327,7 @@ void QHttpSocket::writeRedirect(const QByteArray &path, bool permanent)
close(); close();
} }
void QHttpSocket::writeError(int statusCode, const QByteArray &statusReason) void HttpSocket::writeError(int statusCode, const QByteArray &statusReason)
{ {
setStatusCode(statusCode, statusReason); setStatusCode(statusCode, statusReason);
@@ -346,7 +346,7 @@ void QHttpSocket::writeError(int statusCode, const QByteArray &statusReason)
close(); close();
} }
void QHttpSocket::writeJson(const QJsonDocument &document, int statusCode) void HttpSocket::writeJson(const QJsonDocument &document, int statusCode)
{ {
QByteArray data = document.toJson(); QByteArray data = document.toJson();
setStatusCode(statusCode); setStatusCode(statusCode);
@@ -356,10 +356,10 @@ void QHttpSocket::writeJson(const QJsonDocument &document, int statusCode)
close(); close();
} }
qint64 QHttpSocket::readData(char *data, qint64 maxlen) qint64 HttpSocket::readData(char *data, qint64 maxlen)
{ {
// Ensure the connection is in the correct state for reading data // Ensure the connection is in the correct state for reading data
if (d->readState == QHttpSocketPrivate::ReadHeaders) { if (d->readState == HttpSocketPrivate::ReadHeaders) {
return 0; return 0;
} }
@@ -374,11 +374,11 @@ qint64 QHttpSocket::readData(char *data, qint64 maxlen)
return size; return size;
} }
qint64 QHttpSocket::writeData(const char *data, qint64 len) qint64 HttpSocket::writeData(const char *data, qint64 len)
{ {
// If the response headers have not yet been written, they must // If the response headers have not yet been written, they must
// immediately be written before the data can be // immediately be written before the data can be
if (d->writeState == QHttpSocketPrivate::WriteNone) { if (d->writeState == HttpSocketPrivate::WriteNone) {
writeHeaders(); writeHeaders();
} }

View File

@@ -27,13 +27,13 @@
class QTcpSocket; class QTcpSocket;
class QHttpSocketPrivate : public QObject class HttpSocketPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
QHttpSocketPrivate(QHttpSocket *httpSocket, QTcpSocket *tcpSocket); HttpSocketPrivate(HttpSocket *httpSocket, QTcpSocket *tcpSocket);
QByteArray statusReason(int statusCode) const; QByteArray statusReason(int statusCode) const;
@@ -46,11 +46,11 @@ public:
ReadFinished ReadFinished
} readState; } readState;
QHttpSocket::Method requestMethod; HttpSocket::Method requestMethod;
QByteArray requestRawPath; QByteArray requestRawPath;
QString requestPath; QString requestPath;
QHttpSocket::QueryStringMap requestQueryString; HttpSocket::QueryStringMap requestQueryString;
QHttpSocket::HeaderMap requestHeaders; HttpSocket::HeaderMap requestHeaders;
qint64 requestDataRead; qint64 requestDataRead;
qint64 requestDataTotal; qint64 requestDataTotal;
@@ -63,7 +63,7 @@ public:
int responseStatusCode; int responseStatusCode;
QByteArray responseStatusReason; QByteArray responseStatusReason;
QHttpSocket::HeaderMap responseHeaders; HttpSocket::HeaderMap responseHeaders;
qint64 responseHeaderRemaining; qint64 responseHeaderRemaining;
private Q_SLOTS: private Q_SLOTS:
@@ -76,7 +76,7 @@ private:
bool readHeaders(); bool readHeaders();
void readData(); void readData();
QHttpSocket *const q; HttpSocket*const q;
}; };
#endif // QHTTPENGINE_QHTTPSOCKETPRIVATE_H #endif // QHTTPENGINE_QHTTPSOCKETPRIVATE_H

View File

@@ -29,7 +29,7 @@
#include "qlocalauth_p.h" #include "qlocalauth_p.h"
QLocalAuthPrivate::QLocalAuthPrivate(QObject *parent) LocalAuthPrivate::LocalAuthPrivate(QObject *parent)
: QObject(parent), : QObject(parent),
tokenHeader("X-Auth-Token"), tokenHeader("X-Auth-Token"),
token(QUuid::createUuid().toString()) token(QUuid::createUuid().toString())
@@ -37,7 +37,7 @@ QLocalAuthPrivate::QLocalAuthPrivate(QObject *parent)
updateFile(); updateFile();
} }
void QLocalAuthPrivate::updateFile() void LocalAuthPrivate::updateFile()
{ {
if (file.open()) { if (file.open()) {
file.write(QJsonDocument(QJsonObject::fromVariantMap(data)).toJson()); file.write(QJsonDocument(QJsonObject::fromVariantMap(data)).toJson());
@@ -45,38 +45,38 @@ void QLocalAuthPrivate::updateFile()
} }
} }
QLocalAuth::QLocalAuth(QObject *parent) LocalAuth::LocalAuth(QObject *parent)
: QHttpMiddleware(parent), : HttpMiddleware(parent),
d(new QLocalAuthPrivate(this)) d(new LocalAuthPrivate(this))
{ {
} }
bool QLocalAuth::exists() const bool LocalAuth::exists() const
{ {
return d->file.exists(); return d->file.exists();
} }
QString QLocalAuth::filename() const QString LocalAuth::filename() const
{ {
return d->file.fileName(); return d->file.fileName();
} }
void QLocalAuth::setData(const QVariantMap &data) void LocalAuth::setData(const QVariantMap &data)
{ {
d->data = data; d->data = data;
d->data.insert("token", d->token); d->data.insert("token", d->token);
d->updateFile(); d->updateFile();
} }
void QLocalAuth::setHeaderName(const QByteArray &name) void LocalAuth::setHeaderName(const QByteArray &name)
{ {
d->tokenHeader = name; d->tokenHeader = name;
} }
bool QLocalAuth::process(QHttpSocket *socket) bool LocalAuth::process(HttpSocket *socket)
{ {
if (socket->headers().value(d->tokenHeader) != d->token) { if (socket->headers().value(d->tokenHeader) != d->token) {
socket->writeError(QHttpSocket::Forbidden); socket->writeError(HttpSocket::Forbidden);
return false; return false;
} }

View File

@@ -28,17 +28,17 @@
#include <qhttpengine/qlocalfile.h> #include <qhttpengine/qlocalfile.h>
class QLocalAuthPrivate : public QObject class LocalAuthPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit QLocalAuthPrivate(QObject *parent); explicit LocalAuthPrivate(QObject *parent);
void updateFile(); void updateFile();
QLocalFile file; LocalFile file;
QVariantMap data; QVariantMap data;
QByteArray tokenHeader; QByteArray tokenHeader;
QString token; QString token;

View File

@@ -34,7 +34,7 @@
#include "qlocalfile_p.h" #include "qlocalfile_p.h"
QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile) LocalFilePrivate::LocalFilePrivate(LocalFile *localFile)
: QObject(localFile), : QObject(localFile),
q(localFile) q(localFile)
{ {
@@ -43,7 +43,7 @@ QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile)
q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName())); q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName()));
} }
bool QLocalFilePrivate::setPermission() bool LocalFilePrivate::setPermission()
{ {
#if defined(Q_OS_UNIX) #if defined(Q_OS_UNIX)
return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0; return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0;
@@ -87,7 +87,7 @@ bool QLocalFilePrivate::setPermission()
#endif #endif
} }
bool QLocalFilePrivate::setHidden() bool LocalFilePrivate::setHidden()
{ {
#if defined(Q_OS_UNIX) #if defined(Q_OS_UNIX)
// On Unix, anything beginning with a "." is hidden // On Unix, anything beginning with a "." is hidden
@@ -100,13 +100,13 @@ bool QLocalFilePrivate::setHidden()
#endif #endif
} }
QLocalFile::QLocalFile(QObject *parent) LocalFile::LocalFile(QObject *parent)
: QFile(parent), : QFile(parent),
d(new QLocalFilePrivate(this)) d(new LocalFilePrivate(this))
{ {
} }
bool QLocalFile::open() bool LocalFile::open()
{ {
return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden(); return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden();
} }

View File

@@ -25,22 +25,22 @@
#include <QObject> #include <QObject>
class QLocalFile; class LocalFile;
class QLocalFilePrivate : public QObject class LocalFilePrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit QLocalFilePrivate(QLocalFile *localFile); explicit LocalFilePrivate(LocalFile *localFile);
bool setPermission(); bool setPermission();
bool setHidden(); bool setHidden();
private: private:
QLocalFile *const q; LocalFile*const q;
}; };
#endif // QHTTPENGINE_QLOCALFILEPRIVATE_H #endif // QHTTPENGINE_QLOCALFILEPRIVATE_H

View File

@@ -35,12 +35,12 @@ QObjectHandlerPrivate::QObjectHandlerPrivate(QObjectHandler *handler)
} }
QObjectHandler::QObjectHandler(QObject *parent) QObjectHandler::QObjectHandler(QObject *parent)
: QHttpHandler(parent), : HttpHandler(parent),
d(new QObjectHandlerPrivate(this)) d(new QObjectHandlerPrivate(this))
{ {
} }
void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, Method m) void QObjectHandlerPrivate::invokeSlot(HttpSocket *socket, Method m)
{ {
// Invoke the slot // Invoke the slot
if (m.oldSlot) { if (m.oldSlot) {
@@ -48,7 +48,7 @@ void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, Method m)
// Obtain the slot index // Obtain the slot index
int index = m.receiver->metaObject()->indexOfSlot(m.slot.method + 1); int index = m.receiver->metaObject()->indexOfSlot(m.slot.method + 1);
if (index == -1) { if (index == -1) {
socket->writeError(QHttpSocket::InternalServerError); socket->writeError(HttpSocket::InternalServerError);
return; return;
} }
@@ -57,14 +57,14 @@ void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, Method m)
// Ensure the parameter is correct // Ensure the parameter is correct
QList<QByteArray> params = method.parameterTypes(); QList<QByteArray> params = method.parameterTypes();
if (params.count() != 1 || params.at(0) != "QHttpSocket*") { if (params.count() != 1 || params.at(0) != "QHttpSocket*") {
socket->writeError(QHttpSocket::InternalServerError); socket->writeError(HttpSocket::InternalServerError);
return; return;
} }
// Invoke the method // Invoke the method
if (!m.receiver->metaObject()->method(index).invoke( if (!m.receiver->metaObject()->method(index).invoke(
m.receiver, Q_ARG(QHttpSocket*, socket))) { m.receiver, Q_ARG(HttpSocket*, socket))) {
socket->writeError(QHttpSocket::InternalServerError); socket->writeError(HttpSocket::InternalServerError);
return; return;
} }
} else { } else {
@@ -76,11 +76,11 @@ void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, Method m)
} }
} }
void QObjectHandler::process(QHttpSocket *socket, const QString &path) void QObjectHandler::process(HttpSocket *socket, const QString &path)
{ {
// Ensure the method has been registered // Ensure the method has been registered
if (!d->map.contains(path)) { if (!d->map.contains(path)) {
socket->writeError(QHttpSocket::NotFound); socket->writeError(HttpSocket::NotFound);
return; return;
} }
@@ -92,7 +92,7 @@ void QObjectHandler::process(QHttpSocket *socket, const QString &path)
d->invokeSlot(socket, m); d->invokeSlot(socket, m);
socket->close(); socket->close();
} else { } else {
connect(socket, &QHttpSocket::readChannelFinished, [this, socket, m]() { connect(socket, &HttpSocket::readChannelFinished, [this, socket, m]() {
d->invokeSlot(socket, m); d->invokeSlot(socket, m);
socket->close(); socket->close();
}); });

View File

@@ -26,7 +26,7 @@
#include <QMap> #include <QMap>
#include <QObject> #include <QObject>
class QHttpSocket; class HttpSocket;
class QObjectHandler; class QObjectHandler;
class QObjectHandlerPrivate : public QObject class QObjectHandlerPrivate : public QObject
@@ -60,7 +60,7 @@ public:
bool readAll; bool readAll;
}; };
void invokeSlot(QHttpSocket *socket, Method m); void invokeSlot(HttpSocket*socket, Method m);
QMap<QString, Method> map; QMap<QString, Method> map;

View File

@@ -25,20 +25,20 @@
#include "qproxyhandler_p.h" #include "qproxyhandler_p.h"
#include "qproxysocket.h" #include "qproxysocket.h"
QProxyHandlerPrivate::QProxyHandlerPrivate(QObject *parent, const QHostAddress &address, quint16 port) ProxyHandlerPrivate::ProxyHandlerPrivate(QObject *parent, const QHostAddress &address, quint16 port)
: QObject(parent), : QObject(parent),
address(address), address(address),
port(port) port(port)
{ {
} }
QProxyHandler::QProxyHandler(const QHostAddress &address, quint16 port, QObject *parent) ProxyHandler::ProxyHandler(const QHostAddress &address, quint16 port, QObject *parent)
: QHttpHandler(parent), : HttpHandler(parent),
d(new QProxyHandlerPrivate(this, address, port)) d(new ProxyHandlerPrivate(this, address, port))
{ {
} }
void QProxyHandler::process(QHttpSocket *socket, const QString &path) void ProxyHandler::process(HttpSocket *socket, const QString &path)
{ {
// Parent the socket to the proxy // Parent the socket to the proxy
socket->setParent(this); socket->setParent(this);

View File

@@ -28,13 +28,13 @@
#include <qhttpengine/qhttpsocket.h> #include <qhttpengine/qhttpsocket.h>
class QProxyHandlerPrivate : public QObject class ProxyHandlerPrivate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
QProxyHandlerPrivate(QObject *parent, const QHostAddress &address, quint16 port); ProxyHandlerPrivate(QObject *parent, const QHostAddress &address, quint16 port);
QHostAddress address; QHostAddress address;
quint16 port; quint16 port;

View File

@@ -24,13 +24,13 @@
#include "qproxysocket.h" #include "qproxysocket.h"
QProxySocket::QProxySocket(QHttpSocket *socket, const QString &path, const QHostAddress &address, quint16 port) QProxySocket::QProxySocket(HttpSocket *socket, const QString &path, const QHostAddress &address, quint16 port)
: QObject(socket), : QObject(socket),
mDownstreamSocket(socket), mDownstreamSocket(socket),
mPath(path), mPath(path),
mHeadersParsed(false) mHeadersParsed(false)
{ {
connect(mDownstreamSocket, &QHttpSocket::readyRead, this, &QProxySocket::onDownstreamReadyRead); connect(mDownstreamSocket, &HttpSocket::readyRead, this, &QProxySocket::onDownstreamReadyRead);
connect(&mUpstreamSocket, &QTcpSocket::connected, this, &QProxySocket::onUpstreamConnected); connect(&mUpstreamSocket, &QTcpSocket::connected, this, &QProxySocket::onUpstreamConnected);
connect(&mUpstreamSocket, &QTcpSocket::readyRead, this, &QProxySocket::onUpstreamReadyRead); connect(&mUpstreamSocket, &QTcpSocket::readyRead, this, &QProxySocket::onUpstreamReadyRead);
@@ -60,7 +60,7 @@ void QProxySocket::onUpstreamConnected()
); );
// Use the existing headers but insert proxy-related ones // Use the existing headers but insert proxy-related ones
QHttpSocket::HeaderMap headers = mDownstreamSocket->headers(); HttpSocket::HeaderMap headers = mDownstreamSocket->headers();
QByteArray peerIP = mDownstreamSocket->peerAddress().toString().toUtf8(); QByteArray peerIP = mDownstreamSocket->peerAddress().toString().toUtf8();
QByteArray origFwd = headers.value("X-Forwarded-For"); QByteArray origFwd = headers.value("X-Forwarded-For");
if (origFwd.isNull()) { if (origFwd.isNull()) {
@@ -94,9 +94,9 @@ void QProxySocket::onUpstreamReadyRead()
// Parse the headers // Parse the headers
int statusCode; int statusCode;
QByteArray statusReason; QByteArray statusReason;
QHttpSocket::HeaderMap headers; HttpSocket::HeaderMap headers;
if (!QHttpParser::parseResponseHeaders(mBuffer.left(index), statusCode, statusReason, headers)) { if (!HttpParser::parseResponseHeaders(mBuffer.left(index), statusCode, statusReason, headers)) {
mDownstreamSocket->writeError(QHttpSocket::BadGateway); mDownstreamSocket->writeError(HttpSocket::BadGateway);
return; return;
} }
@@ -120,20 +120,20 @@ void QProxySocket::onUpstreamError(QAbstractSocket::SocketError socketError)
if (mHeadersParsed) { if (mHeadersParsed) {
mDownstreamSocket->close(); mDownstreamSocket->close();
} else { } else {
mDownstreamSocket->writeError(QHttpSocket::BadGateway); mDownstreamSocket->writeError(HttpSocket::BadGateway);
} }
} }
QString QProxySocket::methodToString(QHttpSocket::Method method) const QString QProxySocket::methodToString(HttpSocket::Method method) const
{ {
switch (method) { switch (method) {
case QHttpSocket::OPTIONS: return "OPTIONS"; case HttpSocket::OPTIONS: return "OPTIONS";
case QHttpSocket::GET: return "GET"; case HttpSocket::GET: return "GET";
case QHttpSocket::HEAD: return "HEAD"; case HttpSocket::HEAD: return "HEAD";
case QHttpSocket::POST: return "POST"; case HttpSocket::POST: return "POST";
case QHttpSocket::PUT: return "PUT"; case HttpSocket::PUT: return "PUT";
case QHttpSocket::DELETE: return "DELETE"; case HttpSocket::DELETE: return "DELETE";
case QHttpSocket::TRACE: return "TRACE"; case HttpSocket::TRACE: return "TRACE";
case QHttpSocket::CONNECT: return "CONNECT"; case HttpSocket::CONNECT: return "CONNECT";
} }
} }

View File

@@ -38,7 +38,7 @@ class QProxySocket : public QObject
public: public:
explicit QProxySocket(QHttpSocket *socket, const QString &path, const QHostAddress &address, quint16 port); explicit QProxySocket(HttpSocket *socket, const QString &path, const QHostAddress &address, quint16 port);
private Q_SLOTS: private Q_SLOTS:
@@ -50,9 +50,9 @@ private Q_SLOTS:
private: private:
QString methodToString(QHttpSocket::Method method) const; QString methodToString(HttpSocket::Method method) const;
QHttpSocket *mDownstreamSocket; HttpSocket *mDownstreamSocket;
QTcpSocket mUpstreamSocket; QTcpSocket mUpstreamSocket;
QString mPath; QString mPath;

View File

@@ -72,22 +72,22 @@ void TestQFilesystemHandler::testRequests_data()
QTest::newRow("nonexistent resource") QTest::newRow("nonexistent resource")
<< "nonexistent" << "nonexistent"
<< static_cast<int>(QHttpSocket::NotFound) << static_cast<int>(HttpSocket::NotFound)
<< QByteArray(); << QByteArray();
QTest::newRow("outside document root") QTest::newRow("outside document root")
<< "../outside" << "../outside"
<< static_cast<int>(QHttpSocket::NotFound) << static_cast<int>(HttpSocket::NotFound)
<< QByteArray(); << QByteArray();
QTest::newRow("inside document root") QTest::newRow("inside document root")
<< "inside" << "inside"
<< static_cast<int>(QHttpSocket::OK) << static_cast<int>(HttpSocket::OK)
<< Data; << Data;
QTest::newRow("directory listing") QTest::newRow("directory listing")
<< "" << ""
<< static_cast<int>(QHttpSocket::OK) << static_cast<int>(HttpSocket::OK)
<< QByteArray(); << QByteArray();
} }
@@ -97,13 +97,13 @@ void TestQFilesystemHandler::testRequests()
QFETCH(int, statusCode); QFETCH(int, statusCode);
QFETCH(QByteArray, data); QFETCH(QByteArray, data);
QFilesystemHandler handler(QDir(dir.path()).absoluteFilePath("root")); FilesystemHandler handler(QDir(dir.path()).absoluteFilePath("root"));
QSocketPair pair; QSocketPair pair;
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
handler.route(&socket, path); handler.route(&socket, path);
@@ -124,37 +124,37 @@ void TestQFilesystemHandler::testRangeRequests_data()
QTest::newRow("full file") QTest::newRow("full file")
<< "inside" << "" << "inside" << ""
<< static_cast<int>(QHttpSocket::OK) << static_cast<int>(HttpSocket::OK)
<< "" << ""
<< Data; << Data;
QTest::newRow("range 0-2") QTest::newRow("range 0-2")
<< "inside" << "0-2" << "inside" << "0-2"
<< static_cast<int>(QHttpSocket::PartialContent) << static_cast<int>(HttpSocket::PartialContent)
<< "bytes 0-2/4" << "bytes 0-2/4"
<< Data.mid(0, 3); << Data.mid(0, 3);
QTest::newRow("range 1-2") QTest::newRow("range 1-2")
<< "inside" << "1-2" << "inside" << "1-2"
<< static_cast<int>(QHttpSocket::PartialContent) << static_cast<int>(HttpSocket::PartialContent)
<< "bytes 1-2/4" << "bytes 1-2/4"
<< Data.mid(1, 2); << Data.mid(1, 2);
QTest::newRow("skip first 1 byte") QTest::newRow("skip first 1 byte")
<< "inside" << "1-" << "inside" << "1-"
<< static_cast<int>(QHttpSocket::PartialContent) << static_cast<int>(HttpSocket::PartialContent)
<< "bytes 1-3/4" << "bytes 1-3/4"
<< Data.mid(1); << Data.mid(1);
QTest::newRow("last 2 bytes") QTest::newRow("last 2 bytes")
<< "inside" << "-2" << "inside" << "-2"
<< static_cast<int>(QHttpSocket::PartialContent) << static_cast<int>(HttpSocket::PartialContent)
<< "bytes 2-3/4" << "bytes 2-3/4"
<< Data.mid(2); << Data.mid(2);
QTest::newRow("bad range request") QTest::newRow("bad range request")
<< "inside" << "abcd" << "inside" << "abcd"
<< static_cast<int>(QHttpSocket::OK) << static_cast<int>(HttpSocket::OK)
<< "" << ""
<< Data; << Data;
} }
@@ -167,16 +167,16 @@ void TestQFilesystemHandler::testRangeRequests()
QFETCH(QString, contentRange); QFETCH(QString, contentRange);
QFETCH(QByteArray, data); QFETCH(QByteArray, data);
QFilesystemHandler handler(QDir(dir.path()).absoluteFilePath("root")); FilesystemHandler handler(QDir(dir.path()).absoluteFilePath("root"));
QSocketPair pair; QSocketPair pair;
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
if (!range.isEmpty()) { if (!range.isEmpty()) {
QHttpSocket::HeaderMap inHeaders; HttpSocket::HeaderMap inHeaders;
inHeaders.insert("Range", QByteArray("bytes=") + range.toUtf8()); inHeaders.insert("Range", QByteArray("bytes=") + range.toUtf8());
client.sendHeaders("GET", path.toUtf8(), inHeaders); client.sendHeaders("GET", path.toUtf8(), inHeaders);
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());

View File

@@ -49,7 +49,7 @@ private Q_SLOTS:
private: private:
QHttpBasicAuth auth; HttpBasicAuth auth;
}; };
void TestQHttpBasicAuth::initTestCase() void TestQHttpBasicAuth::initTestCase()
@@ -68,19 +68,19 @@ void TestQHttpBasicAuth::testProcess_data()
<< false << false
<< QString() << QString()
<< QString() << QString()
<< static_cast<int>(QHttpSocket::Unauthorized); << static_cast<int>(HttpSocket::Unauthorized);
QTest::newRow("invalid credentials") QTest::newRow("invalid credentials")
<< true << true
<< Username << Username
<< QString() << QString()
<< static_cast<int>(QHttpSocket::Unauthorized); << static_cast<int>(HttpSocket::Unauthorized);
QTest::newRow("valid credentials") QTest::newRow("valid credentials")
<< true << true
<< Username << Username
<< Password << Password
<< static_cast<int>(QHttpSocket::NotFound); << static_cast<int>(HttpSocket::NotFound);
} }
void TestQHttpBasicAuth::testProcess() void TestQHttpBasicAuth::testProcess()
@@ -94,9 +94,9 @@ void TestQHttpBasicAuth::testProcess()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
QHttpSocket::HeaderMap headers; HttpSocket::HeaderMap headers;
if (header) { if (header) {
headers.insert( headers.insert(
@@ -108,7 +108,7 @@ void TestQHttpBasicAuth::testProcess()
client.sendHeaders("GET", "/", headers); client.sendHeaders("GET", "/", headers);
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
QHttpHandler handler; HttpHandler handler;
handler.addMiddleware(&auth); handler.addMiddleware(&auth);
handler.route(&socket, "/"); handler.route(&socket, "/");

View File

@@ -29,13 +29,13 @@
#include "common/qsimplehttpclient.h" #include "common/qsimplehttpclient.h"
#include "common/qsocketpair.h" #include "common/qsocketpair.h"
class DummyHandler : public QHttpHandler class DummyHandler : public HttpHandler
{ {
Q_OBJECT Q_OBJECT
public: public:
virtual void process(QHttpSocket *socket, const QString &path) { virtual void process(HttpSocket *socket, const QString &path) {
mPathRemainder = path; mPathRemainder = path;
socket->writeHeaders(); socket->writeHeaders();
socket->close(); socket->close();
@@ -69,20 +69,20 @@ void TestQHttpHandler::testRedirect_data()
<< QRegExp("\\w+") << QRegExp("\\w+")
<< QString("/two") << QString("/two")
<< QByteArray("one") << QByteArray("one")
<< static_cast<int>(QHttpSocket::Found) << static_cast<int>(HttpSocket::Found)
<< QByteArray("/two"); << QByteArray("/two");
QTest::newRow("no match") QTest::newRow("no match")
<< QRegExp("\\d+") << QRegExp("\\d+")
<< QString("") << QString("")
<< QByteArray("test") << QByteArray("test")
<< static_cast<int>(QHttpSocket::NotFound); << static_cast<int>(HttpSocket::NotFound);
QTest::newRow("captured texts") QTest::newRow("captured texts")
<< QRegExp("(\\d+)") << QRegExp("(\\d+)")
<< QString("/path/%1") << QString("/path/%1")
<< QByteArray("123") << QByteArray("123")
<< static_cast<int>(QHttpSocket::Found) << static_cast<int>(HttpSocket::Found)
<< QByteArray("/path/123"); << QByteArray("/path/123");
} }
@@ -97,18 +97,18 @@ void TestQHttpHandler::testRedirect()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
client.sendHeaders("GET", path); client.sendHeaders("GET", path);
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
QHttpHandler handler; HttpHandler handler;
handler.addRedirect(pattern, destination); handler.addRedirect(pattern, destination);
handler.route(&socket, socket.path()); handler.route(&socket, socket.path());
QTRY_COMPARE(client.statusCode(), statusCode); QTRY_COMPARE(client.statusCode(), statusCode);
if (statusCode == QHttpSocket::Found) { if (statusCode == HttpSocket::Found) {
QFETCH(QByteArray, location); QFETCH(QByteArray, location);
QCOMPARE(client.headers().value("Location"), location); QCOMPARE(client.headers().value("Location"), location);
} }
@@ -125,19 +125,19 @@ void TestQHttpHandler::testSubHandler_data()
<< QRegExp("\\w+") << QRegExp("\\w+")
<< QByteArray("test") << QByteArray("test")
<< QString("") << QString("")
<< static_cast<int>(QHttpSocket::OK); << static_cast<int>(HttpSocket::OK);
QTest::newRow("no match") QTest::newRow("no match")
<< QRegExp("\\d+") << QRegExp("\\d+")
<< QByteArray("test") << QByteArray("test")
<< QString("") << QString("")
<< static_cast<int>(QHttpSocket::NotFound); << static_cast<int>(HttpSocket::NotFound);
QTest::newRow("path") QTest::newRow("path")
<< QRegExp("one/") << QRegExp("one/")
<< QByteArray("one/two") << QByteArray("one/two")
<< QString("two") << QString("two")
<< static_cast<int>(QHttpSocket::OK); << static_cast<int>(HttpSocket::OK);
} }
void TestQHttpHandler::testSubHandler() void TestQHttpHandler::testSubHandler()
@@ -151,13 +151,13 @@ void TestQHttpHandler::testSubHandler()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
client.sendHeaders("GET", path); client.sendHeaders("GET", path);
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
DummyHandler subHandler; DummyHandler subHandler;
QHttpHandler handler; HttpHandler handler;
handler.addSubHandler(pattern, &subHandler); handler.addSubHandler(pattern, &subHandler);
handler.route(&socket, socket.path()); handler.route(&socket, socket.path());

View File

@@ -29,15 +29,15 @@
#include "common/qsimplehttpclient.h" #include "common/qsimplehttpclient.h"
#include "common/qsocketpair.h" #include "common/qsocketpair.h"
class DummyMiddleware : public QHttpMiddleware class DummyMiddleware : public HttpMiddleware
{ {
Q_OBJECT Q_OBJECT
public: public:
virtual bool process(QHttpSocket *socket) virtual bool process(HttpSocket *socket)
{ {
socket->writeError(QHttpSocket::Forbidden); socket->writeError(HttpSocket::Forbidden);
return false; return false;
} }
}; };
@@ -57,17 +57,17 @@ void TestQHttpMiddleware::testProcess()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
client.sendHeaders("GET", "/"); client.sendHeaders("GET", "/");
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
DummyMiddleware middleware; DummyMiddleware middleware;
QHttpHandler handler; HttpHandler handler;
handler.addMiddleware(&middleware); handler.addMiddleware(&middleware);
handler.route(&socket, "/"); handler.route(&socket, "/");
QTRY_COMPARE(client.statusCode(), static_cast<int>(QHttpSocket::Forbidden)); QTRY_COMPARE(client.statusCode(), static_cast<int>(HttpSocket::Forbidden));
} }
QTEST_MAIN(TestQHttpMiddleware) QTEST_MAIN(TestQHttpMiddleware)

View File

@@ -30,15 +30,15 @@
typedef QList<QByteArray> QByteArrayList; typedef QList<QByteArray> QByteArrayList;
Q_DECLARE_METATYPE(QHttpSocket::Method) Q_DECLARE_METATYPE(HttpSocket::Method)
Q_DECLARE_METATYPE(QHttpSocket::QueryStringMap) Q_DECLARE_METATYPE(HttpSocket::QueryStringMap)
Q_DECLARE_METATYPE(QHttpSocket::HeaderMap) Q_DECLARE_METATYPE(HttpSocket::HeaderMap)
const QIByteArray Key1 = "a"; const IByteArray Key1 = "a";
const QByteArray Value1 = "b"; const QByteArray Value1 = "b";
const QByteArray Line1 = Key1 + ": " + Value1; const QByteArray Line1 = Key1 + ": " + Value1;
const QIByteArray Key2 = "c"; const IByteArray Key2 = "c";
const QByteArray Value2 = "d"; const QByteArray Value2 = "d";
const QByteArray Line2 = Key2 + ": " + Value2; const QByteArray Line2 = Key2 + ": " + Value2;
@@ -72,7 +72,7 @@ private Q_SLOTS:
private: private:
QHttpSocket::HeaderMap headers; HttpSocket::HeaderMap headers;
}; };
TestQHttpParser::TestQHttpParser() TestQHttpParser::TestQHttpParser()
@@ -127,7 +127,7 @@ void TestQHttpParser::testSplit()
QFETCH(QByteArrayList, parts); QFETCH(QByteArrayList, parts);
QByteArrayList outParts; QByteArrayList outParts;
QHttpParser::split(data, delim, maxSplit, outParts); HttpParser::split(data, delim, maxSplit, outParts);
QCOMPARE(outParts, parts); QCOMPARE(outParts, parts);
} }
@@ -136,29 +136,29 @@ void TestQHttpParser::testParsePath_data()
{ {
QTest::addColumn<QByteArray>("rawPath"); QTest::addColumn<QByteArray>("rawPath");
QTest::addColumn<QString>("path"); QTest::addColumn<QString>("path");
QTest::addColumn<QHttpSocket::QueryStringMap>("map"); QTest::addColumn<HttpSocket::QueryStringMap>("map");
QTest::newRow("no query string") QTest::newRow("no query string")
<< QByteArray("/path") << QByteArray("/path")
<< QString("/path") << QString("/path")
<< QHttpSocket::QueryStringMap(); << HttpSocket::QueryStringMap();
QTest::newRow("single parameter") QTest::newRow("single parameter")
<< QByteArray("/path?a=b") << QByteArray("/path?a=b")
<< QString("/path") << QString("/path")
<< QHttpSocket::QueryStringMap{{"a", "b"}}; << HttpSocket::QueryStringMap{{"a", "b"}};
} }
void TestQHttpParser::testParsePath() void TestQHttpParser::testParsePath()
{ {
QFETCH(QByteArray, rawPath); QFETCH(QByteArray, rawPath);
QFETCH(QString, path); QFETCH(QString, path);
QFETCH(QHttpSocket::QueryStringMap, map); QFETCH(HttpSocket::QueryStringMap, map);
QString outPath; QString outPath;
QHttpSocket::QueryStringMap outMap; HttpSocket::QueryStringMap outMap;
QVERIFY(QHttpParser::parsePath(rawPath, outPath, outMap)); QVERIFY(HttpParser::parsePath(rawPath, outPath, outMap));
QCOMPARE(path, outPath); QCOMPARE(path, outPath);
QCOMPARE(map, outMap); QCOMPARE(map, outMap);
@@ -168,7 +168,7 @@ void TestQHttpParser::testParseHeaderList_data()
{ {
QTest::addColumn<bool>("success"); QTest::addColumn<bool>("success");
QTest::addColumn<QByteArrayList>("lines"); QTest::addColumn<QByteArrayList>("lines");
QTest::addColumn<QHttpSocket::HeaderMap>("headers"); QTest::addColumn<HttpSocket::HeaderMap>("headers");
QTest::newRow("empty line") QTest::newRow("empty line")
<< false << false
@@ -185,11 +185,11 @@ void TestQHttpParser::testParseHeaderList()
QFETCH(bool, success); QFETCH(bool, success);
QFETCH(QByteArrayList, lines); QFETCH(QByteArrayList, lines);
QHttpSocket::HeaderMap outHeaders; HttpSocket::HeaderMap outHeaders;
QCOMPARE(QHttpParser::parseHeaderList(lines, outHeaders), success); QCOMPARE(HttpParser::parseHeaderList(lines, outHeaders), success);
if (success) { if (success) {
QFETCH(QHttpSocket::HeaderMap, headers); QFETCH(HttpSocket::HeaderMap, headers);
QCOMPARE(outHeaders, headers); QCOMPARE(outHeaders, headers);
} }
} }
@@ -216,9 +216,9 @@ void TestQHttpParser::testParseHeaders()
QFETCH(QByteArray, data); QFETCH(QByteArray, data);
QByteArrayList outParts; QByteArrayList outParts;
QHttpSocket::HeaderMap outHeaders; HttpSocket::HeaderMap outHeaders;
QCOMPARE(QHttpParser::parseHeaders(data, outParts, outHeaders), success); QCOMPARE(HttpParser::parseHeaders(data, outParts, outHeaders), success);
if (success) { if (success) {
QFETCH(QByteArrayList, parts); QFETCH(QByteArrayList, parts);
@@ -230,7 +230,7 @@ void TestQHttpParser::testParseRequestHeaders_data()
{ {
QTest::addColumn<bool>("success"); QTest::addColumn<bool>("success");
QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArray>("data");
QTest::addColumn<QHttpSocket::Method>("method"); QTest::addColumn<HttpSocket::Method>("method");
QTest::addColumn<QByteArray>("path"); QTest::addColumn<QByteArray>("path");
QTest::newRow("bad HTTP version") QTest::newRow("bad HTTP version")
@@ -240,7 +240,7 @@ void TestQHttpParser::testParseRequestHeaders_data()
QTest::newRow("GET request") QTest::newRow("GET request")
<< true << true
<< QByteArray("GET / HTTP/1.0") << QByteArray("GET / HTTP/1.0")
<< QHttpSocket::GET << HttpSocket::GET
<< QByteArray("/"); << QByteArray("/");
} }
@@ -249,14 +249,14 @@ void TestQHttpParser::testParseRequestHeaders()
QFETCH(bool, success); QFETCH(bool, success);
QFETCH(QByteArray, data); QFETCH(QByteArray, data);
QHttpSocket::Method outMethod; HttpSocket::Method outMethod;
QByteArray outPath; QByteArray outPath;
QHttpSocket::HeaderMap outHeaders; HttpSocket::HeaderMap outHeaders;
QCOMPARE(QHttpParser::parseRequestHeaders(data, outMethod, outPath, outHeaders), success); QCOMPARE(HttpParser::parseRequestHeaders(data, outMethod, outPath, outHeaders), success);
if (success) { if (success) {
QFETCH(QHttpSocket::Method, method); QFETCH(HttpSocket::Method, method);
QFETCH(QByteArray, path); QFETCH(QByteArray, path);
QCOMPARE(method, outMethod); QCOMPARE(method, outMethod);
@@ -289,9 +289,9 @@ void TestQHttpParser::testParseResponseHeaders()
int outStatusCode; int outStatusCode;
QByteArray outStatusReason; QByteArray outStatusReason;
QHttpSocket::HeaderMap outHeaders; HttpSocket::HeaderMap outHeaders;
QCOMPARE(QHttpParser::parseResponseHeaders(data, outStatusCode, outStatusReason, outHeaders), success); QCOMPARE(HttpParser::parseResponseHeaders(data, outStatusCode, outStatusReason, outHeaders), success);
if (success) { if (success) {
QFETCH(int, statusCode); QFETCH(int, statusCode);

View File

@@ -58,15 +58,15 @@ TestQHttpRange::TestQHttpRange()
void TestQHttpRange::testDefaultConstructor() void TestQHttpRange::testDefaultConstructor()
{ {
QHttpRange range; HttpRange range;
QCOMPARE(range.isValid(), false); QCOMPARE(range.isValid(), false);
} }
void TestQHttpRange::testAssignmentOperator() void TestQHttpRange::testAssignmentOperator()
{ {
QHttpRange range; HttpRange range;
QHttpRange otherRange(100, 200, -1); HttpRange otherRange(100, 200, -1);
range = otherRange; range = otherRange;
@@ -110,7 +110,7 @@ void TestQHttpRange::testFromToLength()
QFETCH(int, to); QFETCH(int, to);
QFETCH(int, length); QFETCH(int, length);
QHttpRange range(inFrom, inTo, inDataSize); HttpRange range(inFrom, inTo, inDataSize);
QCOMPARE(range.from(), from); QCOMPARE(range.from(), from);
QCOMPARE(range.to(), to); QCOMPARE(range.to(), to);
@@ -162,7 +162,7 @@ void TestQHttpRange::testIsValid()
QFETCH(int, dataSize); QFETCH(int, dataSize);
QFETCH(bool, valid); QFETCH(bool, valid);
QHttpRange range(from, to, dataSize); HttpRange range(from, to, dataSize);
QCOMPARE(range.isValid(), valid); QCOMPARE(range.isValid(), valid);
} }
@@ -235,7 +235,7 @@ void TestQHttpRange::testParseFromString()
QFETCH(int, dataSize); QFETCH(int, dataSize);
QFETCH(bool, valid); QFETCH(bool, valid);
QHttpRange range(data, dataSize); HttpRange range(data, dataSize);
QCOMPARE(range.isValid(), valid); QCOMPARE(range.isValid(), valid);
@@ -281,7 +281,7 @@ void TestQHttpRange::testContentRange()
QFETCH(int, dataSize); QFETCH(int, dataSize);
QFETCH(QString, contentRange); QFETCH(QString, contentRange);
QHttpRange range(from, to, dataSize); HttpRange range(from, to, dataSize);
QCOMPARE(range.contentRange(), contentRange); QCOMPARE(range.contentRange(), contentRange);
} }

View File

@@ -37,7 +37,7 @@
#include "common/qsimplehttpclient.h" #include "common/qsimplehttpclient.h"
class TestHandler : public QHttpHandler class TestHandler : public HttpHandler
{ {
Q_OBJECT Q_OBJECT
@@ -45,12 +45,12 @@ public:
TestHandler() : mSocket(0) {} TestHandler() : mSocket(0) {}
virtual void process(QHttpSocket *socket, const QString &path) { virtual void process(HttpSocket *socket, const QString &path) {
mSocket = socket; mSocket = socket;
mPath = path; mPath = path;
} }
QHttpSocket *mSocket; HttpSocket *mSocket;
QString mPath; QString mPath;
}; };
@@ -70,7 +70,7 @@ private Q_SLOTS:
void TestQHttpServer::testServer() void TestQHttpServer::testServer()
{ {
TestHandler handler; TestHandler handler;
QHttpServer server(&handler); HttpServer server(&handler);
QVERIFY(server.listen(QHostAddress::LocalHost)); QVERIFY(server.listen(QHostAddress::LocalHost));
@@ -102,7 +102,7 @@ void TestQHttpServer::testSsl()
config.setPrivateKey(key); config.setPrivateKey(key);
config.setLocalCertificateChain(certs); config.setLocalCertificateChain(certs);
QHttpServer server; HttpServer server;
server.setSslConfiguration(config); server.setSslConfiguration(config);
QVERIFY(server.listen(QHostAddress::LocalHost)); QVERIFY(server.listen(QHostAddress::LocalHost));

View File

@@ -32,7 +32,7 @@
#include "common/qsimplehttpclient.h" #include "common/qsimplehttpclient.h"
#include "common/qsocketpair.h" #include "common/qsocketpair.h"
Q_DECLARE_METATYPE(QHttpSocket::QueryStringMap) Q_DECLARE_METATYPE(HttpSocket::QueryStringMap)
// Utility macro (avoids duplication) that creates a pair of connected // Utility macro (avoids duplication) that creates a pair of connected
// sockets, a QSimpleHttpClient for the client and a QHttpSocket for the // sockets, a QSimpleHttpClient for the client and a QHttpSocket for the
@@ -41,7 +41,7 @@ Q_DECLARE_METATYPE(QHttpSocket::QueryStringMap)
QSocketPair pair; \ QSocketPair pair; \
QTRY_VERIFY(pair.isConnected()); \ QTRY_VERIFY(pair.isConnected()); \
QSimpleHttpClient client(pair.client()); \ QSimpleHttpClient client(pair.client()); \
QHttpSocket server(pair.server()) HttpSocket server(pair.server())
const QByteArray Method = "POST"; const QByteArray Method = "POST";
const QByteArray Path = "/test"; const QByteArray Path = "/test";
@@ -67,7 +67,7 @@ private Q_SLOTS:
private: private:
QHttpSocket::HeaderMap headers; HttpSocket::HeaderMap headers;
}; };
TestQHttpSocket::TestQHttpSocket() TestQHttpSocket::TestQHttpSocket()
@@ -82,7 +82,7 @@ void TestQHttpSocket::testProperties()
client.sendHeaders(Method, Path, headers); client.sendHeaders(Method, Path, headers);
QTRY_COMPARE(server.method(), QHttpSocket::POST); QTRY_COMPARE(server.method(), HttpSocket::POST);
QCOMPARE(server.rawPath(), Path); QCOMPARE(server.rawPath(), Path);
QCOMPARE(server.headers(), headers); QCOMPARE(server.headers(), headers);
@@ -120,7 +120,7 @@ void TestQHttpSocket::testRedirect()
server.writeRedirect(Path, true); server.writeRedirect(Path, true);
QTRY_COMPARE(client.statusCode(), static_cast<int>(QHttpSocket::MovedPermanently)); QTRY_COMPARE(client.statusCode(), static_cast<int>(HttpSocket::MovedPermanently));
QCOMPARE(client.headers().value("Location"), Path); QCOMPARE(client.headers().value("Location"), Path);
QTRY_COMPARE(disconnectedSpy.count(), 1); QTRY_COMPARE(disconnectedSpy.count(), 1);
} }
@@ -170,7 +170,7 @@ void TestQHttpSocket::testJson()
QJsonObject object{{"a", "b"}, {"c", 123}}; QJsonObject object{{"a", "b"}, {"c", 123}};
QByteArray data = QJsonDocument(object).toJson(); QByteArray data = QJsonDocument(object).toJson();
client.sendHeaders(Method, Path, QHttpSocket::HeaderMap{ client.sendHeaders(Method, Path, HttpSocket::HeaderMap{
{"Content-Length", QByteArray::number(data.length())}, {"Content-Length", QByteArray::number(data.length())},
{"Content-Type", "application/json"} {"Content-Type", "application/json"}
}); });

View File

@@ -31,8 +31,8 @@ const char *Value2 = "TEST";
// Helpful macros to cut down on the amount of duplicated code // Helpful macros to cut down on the amount of duplicated code
#define TEST_OPERATOR(tn,t,on,o,v) void test##tn##on() \ #define TEST_OPERATOR(tn,t,on,o,v) void test##tn##on() \
{ \ { \
QCOMPARE(QIByteArray(Value1) o static_cast<t>(Value2), v); \ QCOMPARE(IByteArray(Value1) o static_cast<t>(Value2), v); \
QCOMPARE(static_cast<t>(Value1) o QIByteArray(Value1), v); \ QCOMPARE(static_cast<t>(Value1) o IByteArray(Value1), v); \
} }
#define TEST_TYPE(tn,t) \ #define TEST_TYPE(tn,t) \
TEST_OPERATOR(tn, t, Equals, ==, true) \ TEST_OPERATOR(tn, t, Equals, ==, true) \
@@ -50,7 +50,7 @@ private Q_SLOTS:
TEST_TYPE(ConstChar, const char *) TEST_TYPE(ConstChar, const char *)
TEST_TYPE(QByteArray, QByteArray) TEST_TYPE(QByteArray, QByteArray)
TEST_TYPE(QIByteArray, QIByteArray) TEST_TYPE(IByteArray, IByteArray)
TEST_TYPE(QString, QString) TEST_TYPE(QString, QString)
void testContains(); void testContains();
@@ -58,7 +58,7 @@ private Q_SLOTS:
void TestQIByteArray::testContains() void TestQIByteArray::testContains()
{ {
QIByteArray v(Value1); IByteArray v(Value1);
QVERIFY(v.contains('t')); QVERIFY(v.contains('t'));
QVERIFY(v.contains(Value2)); QVERIFY(v.contains(Value2));

View File

@@ -51,9 +51,9 @@ void TestQLocalAuth::testAuth()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
QLocalAuth localAuth; LocalAuth localAuth;
localAuth.setData(QVariantMap{ localAuth.setData(QVariantMap{
{CustomName, CustomData} {CustomName, CustomData}
}); });
@@ -67,7 +67,7 @@ void TestQLocalAuth::testAuth()
QVERIFY(data.contains("token")); QVERIFY(data.contains("token"));
QCOMPARE(data.value(CustomName).toByteArray(), CustomData); QCOMPARE(data.value(CustomName).toByteArray(), CustomData);
client.sendHeaders("GET", "/", QHttpSocket::HeaderMap{ client.sendHeaders("GET", "/", HttpSocket::HeaderMap{
{HeaderName, data.value("token").toByteArray()} {HeaderName, data.value("token").toByteArray()}
}); });
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());

View File

@@ -46,7 +46,7 @@ void TestQLocalFile::initTestCase()
void TestQLocalFile::testOpen() void TestQLocalFile::testOpen()
{ {
QLocalFile file; LocalFile file;
QVERIFY(file.open()); QVERIFY(file.open());
QVERIFY(file.remove()); QVERIFY(file.remove());
} }

View File

@@ -37,8 +37,8 @@ public Q_SLOTS:
void wrongArgumentCount() {} void wrongArgumentCount() {}
void wrongArgumentType(int) {} void wrongArgumentType(int) {}
void valid(QHttpSocket *socket) { void valid(HttpSocket *socket) {
socket->writeError(QHttpSocket::OK); socket->writeError(HttpSocket::OK);
} }
}; };
@@ -60,19 +60,19 @@ void TestQObjectHandler::testOldConnection_data()
QTest::newRow("invalid slot") QTest::newRow("invalid slot")
<< QByteArray(SLOT(invalid())) << QByteArray(SLOT(invalid()))
<< static_cast<int>(QHttpSocket::InternalServerError); << static_cast<int>(HttpSocket::InternalServerError);
QTest::newRow("wrong argument count") QTest::newRow("wrong argument count")
<< QByteArray(SLOT(wrongArgumentCount())) << QByteArray(SLOT(wrongArgumentCount()))
<< static_cast<int>(QHttpSocket::InternalServerError); << static_cast<int>(HttpSocket::InternalServerError);
QTest::newRow("wrong argument type") QTest::newRow("wrong argument type")
<< QByteArray(SLOT(wrongArgumentType(int))) << QByteArray(SLOT(wrongArgumentType(int)))
<< static_cast<int>(QHttpSocket::InternalServerError); << static_cast<int>(HttpSocket::InternalServerError);
QTest::newRow("valid") QTest::newRow("valid")
<< QByteArray(SLOT(valid(QHttpSocket*))) << QByteArray(SLOT(valid(HttpSocket*)))
<< static_cast<int>(QHttpSocket::OK); << static_cast<int>(HttpSocket::OK);
} }
void TestQObjectHandler::testOldConnection() void TestQObjectHandler::testOldConnection()
@@ -89,7 +89,7 @@ void TestQObjectHandler::testOldConnection()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
client.sendHeaders("GET", "test"); client.sendHeaders("GET", "test");
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
@@ -107,11 +107,11 @@ void TestQObjectHandler::testNewConnection()
handler.registerMethod("0", &api, &DummyAPI::valid); handler.registerMethod("0", &api, &DummyAPI::valid);
// Connect to functor // Connect to functor
handler.registerMethod("1", [](QHttpSocket *socket) { handler.registerMethod("1", [](HttpSocket *socket) {
socket->writeError(QHttpSocket::OK); socket->writeError(HttpSocket::OK);
}); });
handler.registerMethod("2", &api, [](QHttpSocket *socket) { handler.registerMethod("2", &api, [](HttpSocket *socket) {
socket->writeError(QHttpSocket::OK); socket->writeError(HttpSocket::OK);
}); });
for (int i = 0; i < 3; ++i) { for (int i = 0; i < 3; ++i) {
@@ -119,13 +119,13 @@ void TestQObjectHandler::testNewConnection()
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server(), &pair);
client.sendHeaders("GET", QByteArray::number(i)); client.sendHeaders("GET", QByteArray::number(i));
QTRY_VERIFY(socket.isHeadersParsed()); QTRY_VERIFY(socket.isHeadersParsed());
handler.route(&socket, socket.path()); handler.route(&socket, socket.path());
QTRY_COMPARE(client.statusCode(), static_cast<int>(QHttpSocket::OK)); QTRY_COMPARE(client.statusCode(), static_cast<int>(HttpSocket::OK));
} }
} }

View File

@@ -48,26 +48,26 @@ void TestQProxyHandler::testDataPassthrough()
{ {
// Create the upstream handler (simple echo) // Create the upstream handler (simple echo)
QObjectHandler upstreamHandler; QObjectHandler upstreamHandler;
upstreamHandler.registerMethod(Path, [](QHttpSocket *socket) { upstreamHandler.registerMethod(Path, [](HttpSocket *socket) {
socket->write(socket->readAll()); socket->write(socket->readAll());
socket->close(); socket->close();
}, true); }, true);
// Create the upstream server and begin listening // Create the upstream server and begin listening
QHttpServer upstreamServer(&upstreamHandler); HttpServer upstreamServer(&upstreamHandler);
QVERIFY(upstreamServer.listen(QHostAddress::LocalHost)); QVERIFY(upstreamServer.listen(QHostAddress::LocalHost));
// Create the proxy handler // Create the proxy handler
QProxyHandler handler(upstreamServer.serverAddress(), upstreamServer.serverPort()); ProxyHandler handler(upstreamServer.serverAddress(), upstreamServer.serverPort());
QSocketPair pair; QSocketPair pair;
QTRY_VERIFY(pair.isConnected()); QTRY_VERIFY(pair.isConnected());
QSimpleHttpClient client(pair.client()); QSimpleHttpClient client(pair.client());
QHttpSocket socket(pair.server(), &pair); HttpSocket socket(pair.server());
// Send the headers and wait for them to be parsed // Send the headers and wait for them to be parsed
QHttpSocket::HeaderMap headers{ HttpSocket::HeaderMap headers{
{"Content-Length", QByteArray::number(Data.length())} {"Content-Length", QByteArray::number(Data.length())}
}; };
client.sendHeaders("POST", QString("/%1").arg(Path).toUtf8(), headers); client.sendHeaders("POST", QString("/%1").arg(Path).toUtf8(), headers);

View File

@@ -33,7 +33,7 @@ QSimpleHttpClient::QSimpleHttpClient(QTcpSocket *socket)
onReadyRead(); onReadyRead();
} }
void QSimpleHttpClient::sendHeaders(const QByteArray &method, const QByteArray &path, const QHttpSocket::HeaderMap &headers) void QSimpleHttpClient::sendHeaders(const QByteArray &method, const QByteArray &path, const HttpSocket::HeaderMap &headers)
{ {
QByteArray data = method + " " + path + " HTTP/1.0\r\n"; QByteArray data = method + " " + path + " HTTP/1.0\r\n";
for (auto i = headers.constBegin(); i != headers.constEnd(); ++i) { for (auto i = headers.constBegin(); i != headers.constEnd(); ++i) {
@@ -59,7 +59,7 @@ void QSimpleHttpClient::onReadyRead()
// Parse the headers if the double CRLF sequence was found // Parse the headers if the double CRLF sequence was found
int index = mBuffer.indexOf("\r\n\r\n"); int index = mBuffer.indexOf("\r\n\r\n");
if (index != -1) { if (index != -1) {
QHttpParser::parseResponseHeaders(mBuffer.left(index), mStatusCode, mStatusReason, mHeaders); HttpParser::parseResponseHeaders(mBuffer.left(index), mStatusCode, mStatusReason, mHeaders);
mHeadersParsed = true; mHeadersParsed = true;
mData.append(mBuffer.mid(index + 4)); mData.append(mBuffer.mid(index + 4));

View File

@@ -45,7 +45,7 @@ public:
QSimpleHttpClient(QTcpSocket *socket); QSimpleHttpClient(QTcpSocket *socket);
void sendHeaders(const QByteArray &method, const QByteArray &path, const QHttpSocket::HeaderMap &headers=QHttpSocket::HeaderMap()); void sendHeaders(const QByteArray &method, const QByteArray &path, const HttpSocket::HeaderMap &headers=HttpSocket::HeaderMap());
void sendData(const QByteArray &data); void sendData(const QByteArray &data);
int statusCode() const { int statusCode() const {
@@ -56,7 +56,7 @@ public:
return mStatusReason; return mStatusReason;
} }
QHttpSocket::HeaderMap headers() const { HttpSocket::HeaderMap headers() const {
return mHeaders; return mHeaders;
} }
@@ -79,7 +79,7 @@ private:
int mStatusCode; int mStatusCode;
QByteArray mStatusReason; QByteArray mStatusReason;
QHttpSocket::HeaderMap mHeaders; HttpSocket::HeaderMap mHeaders;
QByteArray mData; QByteArray mData;
}; };