aboutsummaryrefslogtreecommitdiffstats
path: root/src/modules/objects/qthttp
diff options
context:
space:
mode:
authorGravatar Alexey Sokolov2016-04-29 23:57:30 +0100
committerGravatar Alexey Sokolov2016-04-29 23:57:48 +0100
commit690dd7a33ddc90678367d73adf313533536e10f2 (patch)
tree2276fe7c384ebbc222b40a19c536d5c3c5606ce8 /src/modules/objects/qthttp
parentAdd config for clang-format. (diff)
downloadKVIrc-690dd7a33ddc90678367d73adf313533536e10f2.tar.gz
KVIrc-690dd7a33ddc90678367d73adf313533536e10f2.tar.bz2
KVIrc-690dd7a33ddc90678367d73adf313533536e10f2.zip
Apply clang-format
Diffstat (limited to 'src/modules/objects/qthttp')
-rw-r--r--src/modules/objects/qthttp/qhttp.cpp2714
-rw-r--r--src/modules/objects/qthttp/qhttp.h308
-rw-r--r--src/modules/objects/qthttp/qhttpauthenticator.cpp1545
-rw-r--r--src/modules/objects/qthttp/qhttpauthenticator_p.h114
-rw-r--r--src/modules/objects/qthttp/qringbuffer_p.h712
5 files changed, 2832 insertions, 2561 deletions
diff --git a/src/modules/objects/qthttp/qhttp.cpp b/src/modules/objects/qthttp/qhttp.cpp
index 33b885580..8dd437451 100644
--- a/src/modules/objects/qthttp/qhttp.cpp
+++ b/src/modules/objects/qthttp/qhttp.cpp
@@ -45,22 +45,22 @@
#include "qhttp.h"
#ifndef QT_NO_HTTP
-# include "qtcpsocket.h"
-# include "qsslsocket.h"
-# include "qtextstream.h"
-# include "qmap.h"
-# include "qlist.h"
-# include "qstring.h"
-# include "qstringlist.h"
-# include "qbuffer.h"
-# include "qringbuffer_p.h"
-# include "qcoreevent.h"
-# include "qurl.h"
-# include "qnetworkproxy.h"
-# include "qauthenticator.h"
-# include "qhttpauthenticator_p.h"
-# include "qdebug.h"
-# include "qtimer.h"
+#include "qtcpsocket.h"
+#include "qsslsocket.h"
+#include "qtextstream.h"
+#include "qmap.h"
+#include "qlist.h"
+#include "qstring.h"
+#include "qstringlist.h"
+#include "qbuffer.h"
+#include "qringbuffer_p.h"
+#include "qcoreevent.h"
+#include "qurl.h"
+#include "qnetworkproxy.h"
+#include "qauthenticator.h"
+#include "qhttpauthenticator_p.h"
+#include "qdebug.h"
+#include "qtimer.h"
#endif
#ifndef QT_NO_HTTP
@@ -71,125 +71,128 @@ class QHttpNormalRequest;
class QHttpRequest
{
public:
- QHttpRequest() : finished(false)
- { id = idCounter.fetchAndAddRelaxed(1); }
- virtual ~QHttpRequest()
- { }
+ QHttpRequest() : finished(false)
+ {
+ id = idCounter.fetchAndAddRelaxed(1);
+ }
+ virtual ~QHttpRequest()
+ {
+ }
- virtual void start(QHttp *) = 0;
- virtual bool hasRequestHeader();
- virtual QHttpRequestHeader requestHeader();
+ virtual void start(QHttp *) = 0;
+ virtual bool hasRequestHeader();
+ virtual QHttpRequestHeader requestHeader();
- virtual QIODevice *sourceDevice() = 0;
- virtual QIODevice *destinationDevice() = 0;
+ virtual QIODevice * sourceDevice() = 0;
+ virtual QIODevice * destinationDevice() = 0;
- int id;
- bool finished;
+ int id;
+ bool finished;
private:
- static QBasicAtomicInt idCounter;
+ static QBasicAtomicInt idCounter;
};
class QHttpPrivate
{
public:
- Q_DECLARE_PUBLIC(QHttp)
+ Q_DECLARE_PUBLIC(QHttp)
- inline QHttpPrivate(QHttp* parent)
- : socket(0), reconnectAttempts(2),
- deleteSocket(0), state(QHttp::Unconnected),
- error(QHttp::NoError), port(0), mode(QHttp::ConnectionModeHttp),
- toDevice(0), postDevice(0), bytesDone(0), chunkedSize(-1),
- repost(false), pendingPost(false), q_ptr(parent)
- {
- }
+ inline QHttpPrivate(QHttp * parent)
+ : socket(0), reconnectAttempts(2),
+ deleteSocket(0), state(QHttp::Unconnected),
+ error(QHttp::NoError), port(0), mode(QHttp::ConnectionModeHttp),
+ toDevice(0), postDevice(0), bytesDone(0), chunkedSize(-1),
+ repost(false), pendingPost(false), q_ptr(parent)
+ {
+ }
- inline ~QHttpPrivate()
- {
- while (!pending.isEmpty())
- delete pending.takeFirst();
+ inline ~QHttpPrivate()
+ {
+ while(!pending.isEmpty())
+ delete pending.takeFirst();
- if (deleteSocket)
- delete socket;
- }
+ if(deleteSocket)
+ delete socket;
+ }
- // private slots
- void _q_startNextRequest();
- void _q_slotReadyRead();
- void _q_slotConnected();
- void _q_slotError(QAbstractSocket::SocketError);
- void _q_slotClosed();
- void _q_slotBytesWritten(qint64 numBytes);
+ // private slots
+ void _q_startNextRequest();
+ void _q_slotReadyRead();
+ void _q_slotConnected();
+ void _q_slotError(QAbstractSocket::SocketError);
+ void _q_slotClosed();
+ void _q_slotBytesWritten(qint64 numBytes);
#ifndef QT_NO_OPENSSL
- void _q_slotEncryptedBytesWritten(qint64 numBytes);
+ void _q_slotEncryptedBytesWritten(qint64 numBytes);
#endif
- void _q_slotDoFinished();
- void _q_slotSendRequest();
- void _q_continuePost();
+ void _q_slotDoFinished();
+ void _q_slotSendRequest();
+ void _q_continuePost();
- int addRequest(QHttpNormalRequest *);
- int addRequest(QHttpRequest *);
- void finishedWithSuccess();
- void finishedWithError(const QString &detail, int errorCode);
+ int addRequest(QHttpNormalRequest *);
+ int addRequest(QHttpRequest *);
+ void finishedWithSuccess();
+ void finishedWithError(const QString & detail, int errorCode);
- void init();
- void setState(int);
- void closeConn();
- void setSock(QTcpSocket *sock);
+ void init();
+ void setState(int);
+ void closeConn();
+ void setSock(QTcpSocket * sock);
- void postMoreData();
+ void postMoreData();
- QTcpSocket *socket;
- int reconnectAttempts;
- bool deleteSocket;
- QList<QHttpRequest *> pending;
+ QTcpSocket * socket;
+ int reconnectAttempts;
+ bool deleteSocket;
+ QList<QHttpRequest *> pending;
- QHttp::State state;
- QHttp::Error error;
- QString errorString;
+ QHttp::State state;
+ QHttp::Error error;
+ QString errorString;
- QString hostName;
- quint16 port;
- QHttp::ConnectionMode mode;
+ QString hostName;
+ quint16 port;
+ QHttp::ConnectionMode mode;
- QByteArray buffer;
- QIODevice *toDevice;
- QIODevice *postDevice;
+ QByteArray buffer;
+ QIODevice * toDevice;
+ QIODevice * postDevice;
- qint64 bytesDone;
- qint64 bytesTotal;
- qint64 chunkedSize;
+ qint64 bytesDone;
+ qint64 bytesTotal;
+ qint64 chunkedSize;
- QHttpRequestHeader header;
+ QHttpRequestHeader header;
- bool readHeader;
- QString headerStr;
- QHttpResponseHeader response;
+ bool readHeader;
+ QString headerStr;
+ QHttpResponseHeader response;
- QRingBuffer rba;
+ QRingBuffer rba;
#ifndef QT_NO_NETWORKPROXY
- QNetworkProxy proxy;
- QHttpAuthenticator proxyAuthenticator;
+ QNetworkProxy proxy;
+ QHttpAuthenticator proxyAuthenticator;
#endif
- QHttpAuthenticator authenticator;
- bool repost;
- bool hasFinishedWithError;
- bool pendingPost;
- QTimer post100ContinueTimer;
- QHttp *q_ptr;
+ QHttpAuthenticator authenticator;
+ bool repost;
+ bool hasFinishedWithError;
+ bool pendingPost;
+ QTimer post100ContinueTimer;
+ QHttp * q_ptr;
};
QBasicAtomicInt QHttpRequest::idCounter = Q_BASIC_ATOMIC_INITIALIZER(1);
bool QHttpRequest::hasRequestHeader()
{
- return false;
+ return false;
}
QHttpRequestHeader QHttpRequest::requestHeader()
{
- return QHttpRequestHeader();
+ return QHttpRequestHeader();
}
/****************************************************
@@ -201,99 +204,104 @@ QHttpRequestHeader QHttpRequest::requestHeader()
class QHttpNormalRequest : public QHttpRequest
{
public:
- QHttpNormalRequest(const QHttpRequestHeader &h, QIODevice *d, QIODevice *t) :
- header(h), to(t)
- {
- is_ba = false;
- data.dev = d;
- }
+ QHttpNormalRequest(const QHttpRequestHeader & h, QIODevice * d, QIODevice * t) : header(h), to(t)
+ {
+ is_ba = false;
+ data.dev = d;
+ }
- QHttpNormalRequest(const QHttpRequestHeader &h, QByteArray *d, QIODevice *t) :
- header(h), to(t)
- {
- is_ba = true;
- data.ba = d;
- }
+ QHttpNormalRequest(const QHttpRequestHeader & h, QByteArray * d, QIODevice * t) : header(h), to(t)
+ {
+ is_ba = true;
+ data.ba = d;
+ }
- ~QHttpNormalRequest()
- {
- if (is_ba)
- delete data.ba;
- }
+ ~QHttpNormalRequest()
+ {
+ if(is_ba)
+ delete data.ba;
+ }
- void start(QHttp *);
- bool hasRequestHeader();
- QHttpRequestHeader requestHeader();
- inline void setRequestHeader(const QHttpRequestHeader &h) { header = h; }
+ void start(QHttp *);
+ bool hasRequestHeader();
+ QHttpRequestHeader requestHeader();
+ inline void setRequestHeader(const QHttpRequestHeader & h) { header = h; }
- QIODevice *sourceDevice();
- QIODevice *destinationDevice();
+ QIODevice * sourceDevice();
+ QIODevice * destinationDevice();
protected:
- QHttpRequestHeader header;
+ QHttpRequestHeader header;
private:
- union {
- QByteArray *ba;
- QIODevice *dev;
- } data;
- bool is_ba;
- QIODevice *to;
+ union
+ {
+ QByteArray * ba;
+ QIODevice * dev;
+ } data;
+ bool is_ba;
+ QIODevice * to;
};
-void QHttpNormalRequest::start(QHttp *http)
+void QHttpNormalRequest::start(QHttp * http)
{
- if (!http->d->socket)
- http->d->setSock(0);
- http->d->header = header;
+ if(!http->d->socket)
+ http->d->setSock(0);
+ http->d->header = header;
- if (is_ba) {
- http->d->buffer = *data.ba;
- if (http->d->buffer.size() >= 0)
- http->d->header.setContentLength(http->d->buffer.size());
+ if(is_ba)
+ {
+ http->d->buffer = *data.ba;
+ if(http->d->buffer.size() >= 0)
+ http->d->header.setContentLength(http->d->buffer.size());
- http->d->postDevice = 0;
- } else {
- http->d->buffer = QByteArray();
+ http->d->postDevice = 0;
+ }
+ else
+ {
+ http->d->buffer = QByteArray();
- if (data.dev && (data.dev->isOpen() || data.dev->open(QIODevice::ReadOnly))) {
- http->d->postDevice = data.dev;
- if (http->d->postDevice->size() >= 0)
- http->d->header.setContentLength(http->d->postDevice->size());
- } else {
- http->d->postDevice = 0;
- }
- }
+ if(data.dev && (data.dev->isOpen() || data.dev->open(QIODevice::ReadOnly)))
+ {
+ http->d->postDevice = data.dev;
+ if(http->d->postDevice->size() >= 0)
+ http->d->header.setContentLength(http->d->postDevice->size());
+ }
+ else
+ {
+ http->d->postDevice = 0;
+ }
+ }
- if (to && (to->isOpen() || to->open(QIODevice::WriteOnly)))
- http->d->toDevice = to;
- else
- http->d->toDevice = 0;
+ if(to && (to->isOpen() || to->open(QIODevice::WriteOnly)))
+ http->d->toDevice = to;
+ else
+ http->d->toDevice = 0;
- http->d->reconnectAttempts = 2;
- http->d->_q_slotSendRequest();
+ http->d->reconnectAttempts = 2;
+ http->d->_q_slotSendRequest();
}
bool QHttpNormalRequest::hasRequestHeader()
{
- return true;
+ return true;
}
QHttpRequestHeader QHttpNormalRequest::requestHeader()
{
- return header;
+ return header;
}
-QIODevice *QHttpNormalRequest::sourceDevice()
+QIODevice * QHttpNormalRequest::sourceDevice()
{
- if (is_ba)
- return 0;
- return data.dev;
+ if(is_ba)
+ return 0;
+ return data.dev;
}
-QIODevice *QHttpNormalRequest::destinationDevice()
+QIODevice * QHttpNormalRequest::destinationDevice()
{
- return to;
+ return to;
}
/****************************************************
@@ -309,27 +317,28 @@ QIODevice *QHttpNormalRequest::destinationDevice()
class QHttpPGHRequest : public QHttpNormalRequest
{
public:
- QHttpPGHRequest(const QHttpRequestHeader &h, QIODevice *d, QIODevice *t) :
- QHttpNormalRequest(h, d, t)
- { }
+ QHttpPGHRequest(const QHttpRequestHeader & h, QIODevice * d, QIODevice * t) : QHttpNormalRequest(h, d, t)
+ {
+ }
- QHttpPGHRequest(const QHttpRequestHeader &h, QByteArray *d, QIODevice *t) :
- QHttpNormalRequest(h, d, t)
- { }
+ QHttpPGHRequest(const QHttpRequestHeader & h, QByteArray * d, QIODevice * t) : QHttpNormalRequest(h, d, t)
+ {
+ }
- ~QHttpPGHRequest()
- { }
+ ~QHttpPGHRequest()
+ {
+ }
- void start(QHttp *);
+ void start(QHttp *);
};
-void QHttpPGHRequest::start(QHttp *http)
+void QHttpPGHRequest::start(QHttp * http)
{
- if (http->d->port && http->d->port != 80)
- header.setValue(QLatin1String("Host"), http->d->hostName + QLatin1Char(':') + QString::number(http->d->port));
- else
- header.setValue(QLatin1String("Host"), http->d->hostName);
- QHttpNormalRequest::start(http);
+ if(http->d->port && http->d->port != 80)
+ header.setValue(QLatin1String("Host"), http->d->hostName + QLatin1Char(':') + QString::number(http->d->port));
+ else
+ header.setValue(QLatin1String("Host"), http->d->hostName);
+ QHttpNormalRequest::start(http);
}
/****************************************************
@@ -341,39 +350,45 @@ void QHttpPGHRequest::start(QHttp *http)
class QHttpSetHostRequest : public QHttpRequest
{
public:
- QHttpSetHostRequest(const QString &h, quint16 p, QHttp::ConnectionMode m)
- : hostName(h), port(p), mode(m)
- { }
+ QHttpSetHostRequest(const QString & h, quint16 p, QHttp::ConnectionMode m)
+ : hostName(h), port(p), mode(m)
+ {
+ }
- void start(QHttp *);
+ void start(QHttp *);
- QIODevice *sourceDevice()
- { return 0; }
- QIODevice *destinationDevice()
- { return 0; }
+ QIODevice * sourceDevice()
+ {
+ return 0;
+ }
+ QIODevice * destinationDevice()
+ {
+ return 0;
+ }
private:
- QString hostName;
- quint16 port;
- QHttp::ConnectionMode mode;
+ QString hostName;
+ quint16 port;
+ QHttp::ConnectionMode mode;
};
-void QHttpSetHostRequest::start(QHttp *http)
+void QHttpSetHostRequest::start(QHttp * http)
{
- http->d->hostName = hostName;
- http->d->port = port;
- http->d->mode = mode;
+ http->d->hostName = hostName;
+ http->d->port = port;
+ http->d->mode = mode;
#ifdef QT_NO_OPENSSL
- if (mode == QHttp::ConnectionModeHttps) {
- // SSL requested but no SSL support compiled in
- http->d->finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "HTTPS connection requested but SSL support not compiled in")),
- QHttp::UnknownError);
- return;
- }
+ if(mode == QHttp::ConnectionModeHttps)
+ {
+ // SSL requested but no SSL support compiled in
+ http->d->finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "HTTPS connection requested but SSL support not compiled in")),
+ QHttp::UnknownError);
+ return;
+ }
#endif
- http->d->finishedWithSuccess();
+ http->d->finishedWithSuccess();
}
/****************************************************
@@ -385,27 +400,31 @@ void QHttpSetHostRequest::start(QHttp *http)
class QHttpSetUserRequest : public QHttpRequest
{
public:
- QHttpSetUserRequest(const QString &userName, const QString &password) :
- user(userName), pass(password)
- { }
+ QHttpSetUserRequest(const QString & userName, const QString & password) : user(userName), pass(password)
+ {
+ }
- void start(QHttp *);
+ void start(QHttp *);
- QIODevice *sourceDevice()
- { return 0; }
- QIODevice *destinationDevice()
- { return 0; }
+ QIODevice * sourceDevice()
+ {
+ return 0;
+ }
+ QIODevice * destinationDevice()
+ {
+ return 0;
+ }
private:
- QString user;
- QString pass;
+ QString user;
+ QString pass;
};
-void QHttpSetUserRequest::start(QHttp *http)
+void QHttpSetUserRequest::start(QHttp * http)
{
- http->d->authenticator.setUser(user);
- http->d->authenticator.setPassword(pass);
- http->d->finishedWithSuccess();
+ http->d->authenticator.setUser(user);
+ http->d->authenticator.setPassword(pass);
+ http->d->finishedWithSuccess();
}
#ifndef QT_NO_NETWORKPROXY
@@ -419,29 +438,34 @@ void QHttpSetUserRequest::start(QHttp *http)
class QHttpSetProxyRequest : public QHttpRequest
{
public:
- inline QHttpSetProxyRequest(const QNetworkProxy &proxy)
- {
- this->proxy = proxy;
- }
+ inline QHttpSetProxyRequest(const QNetworkProxy & proxy)
+ {
+ this->proxy = proxy;
+ }
- inline void start(QHttp *http)
- {
- http->d->proxy = proxy;
- QString user = proxy.user();
- if (!user.isEmpty())
- http->d->proxyAuthenticator.setUser(user);
- QString password = proxy.password();
- if (!password.isEmpty())
- http->d->proxyAuthenticator.setPassword(password);
- http->d->finishedWithSuccess();
- }
+ inline void start(QHttp * http)
+ {
+ http->d->proxy = proxy;
+ QString user = proxy.user();
+ if(!user.isEmpty())
+ http->d->proxyAuthenticator.setUser(user);
+ QString password = proxy.password();
+ if(!password.isEmpty())
+ http->d->proxyAuthenticator.setPassword(password);
+ http->d->finishedWithSuccess();
+ }
+
+ inline QIODevice * sourceDevice()
+ {
+ return 0;
+ }
+ inline QIODevice * destinationDevice()
+ {
+ return 0;
+ }
- inline QIODevice *sourceDevice()
- { return 0; }
- inline QIODevice *destinationDevice()
- { return 0; }
private:
- QNetworkProxy proxy;
+ QNetworkProxy proxy;
};
#endif // QT_NO_NETWORKPROXY
@@ -455,24 +479,29 @@ private:
class QHttpSetSocketRequest : public QHttpRequest
{
public:
- QHttpSetSocketRequest(QTcpSocket *s) : socket(s)
- { }
+ QHttpSetSocketRequest(QTcpSocket * s) : socket(s)
+ {
+ }
- void start(QHttp *);
+ void start(QHttp *);
- QIODevice *sourceDevice()
- { return 0; }
- QIODevice *destinationDevice()
- { return 0; }
+ QIODevice * sourceDevice()
+ {
+ return 0;
+ }
+ QIODevice * destinationDevice()
+ {
+ return 0;
+ }
private:
- QTcpSocket *socket;
+ QTcpSocket * socket;
};
-void QHttpSetSocketRequest::start(QHttp *http)
+void QHttpSetSocketRequest::start(QHttp * http)
{
- http->d->setSock(socket);
- http->d->finishedWithSuccess();
+ http->d->setSock(socket);
+ http->d->finishedWithSuccess();
}
/****************************************************
@@ -484,30 +513,35 @@ void QHttpSetSocketRequest::start(QHttp *http)
class QHttpCloseRequest : public QHttpRequest
{
public:
- QHttpCloseRequest()
- { }
- void start(QHttp *);
+ QHttpCloseRequest()
+ {
+ }
+ void start(QHttp *);
- QIODevice *sourceDevice()
- { return 0; }
- QIODevice *destinationDevice()
- { return 0; }
+ QIODevice * sourceDevice()
+ {
+ return 0;
+ }
+ QIODevice * destinationDevice()
+ {
+ return 0;
+ }
};
-void QHttpCloseRequest::start(QHttp *http)
+void QHttpCloseRequest::start(QHttp * http)
{
- http->d->closeConn();
+ http->d->closeConn();
}
class QHttpHeaderPrivate
{
- Q_DECLARE_PUBLIC(QHttpHeader)
+ Q_DECLARE_PUBLIC(QHttpHeader)
public:
- inline virtual ~QHttpHeaderPrivate() {}
+ inline virtual ~QHttpHeaderPrivate() {}
- QList<QPair<QString, QString> > values;
- bool valid;
- QHttpHeader *q_ptr;
+ QList<QPair<QString, QString>> values;
+ bool valid;
+ QHttpHeader * q_ptr;
};
/****************************************************
@@ -569,21 +603,21 @@ public:
QHttpHeader::QHttpHeader()
: d_ptr(new QHttpHeaderPrivate)
{
- Q_D(QHttpHeader);
- d->q_ptr = this;
- d->valid = true;
+ Q_D(QHttpHeader);
+ d->q_ptr = this;
+ d->valid = true;
}
/*!
Constructs a copy of \a header.
*/
-QHttpHeader::QHttpHeader(const QHttpHeader &header)
+QHttpHeader::QHttpHeader(const QHttpHeader & header)
: d_ptr(new QHttpHeaderPrivate)
{
- Q_D(QHttpHeader);
- d->q_ptr = this;
- d->valid = header.d_func()->valid;
- d->values = header.d_func()->values;
+ Q_D(QHttpHeader);
+ d->q_ptr = this;
+ d->valid = header.d_func()->valid;
+ d->values = header.d_func()->values;
}
/*!
@@ -594,36 +628,36 @@ QHttpHeader::QHttpHeader(const QHttpHeader &header)
"\r\n" delimited lines; each of these lines should have the format
key, colon, space, value.
*/
-QHttpHeader::QHttpHeader(const QString &str)
+QHttpHeader::QHttpHeader(const QString & str)
: d_ptr(new QHttpHeaderPrivate)
{
- Q_D(QHttpHeader);
- d->q_ptr = this;
- d->valid = true;
- parse(str);
+ Q_D(QHttpHeader);
+ d->q_ptr = this;
+ d->valid = true;
+ parse(str);
}
/*! \internal
*/
-QHttpHeader::QHttpHeader(QHttpHeaderPrivate &dd, const QString &str)
+QHttpHeader::QHttpHeader(QHttpHeaderPrivate & dd, const QString & str)
: d_ptr(&dd)
{
- Q_D(QHttpHeader);
- d->q_ptr = this;
- d->valid = true;
- if (!str.isEmpty())
- parse(str);
+ Q_D(QHttpHeader);
+ d->q_ptr = this;
+ d->valid = true;
+ if(!str.isEmpty())
+ parse(str);
}
/*! \internal
*/
-QHttpHeader::QHttpHeader(QHttpHeaderPrivate &dd, const QHttpHeader &header)
+QHttpHeader::QHttpHeader(QHttpHeaderPrivate & dd, const QHttpHeader & header)
: d_ptr(&dd)
{
- Q_D(QHttpHeader);
- d->q_ptr = this;
- d->valid = header.d_func()->valid;
- d->values = header.d_func()->values;
+ Q_D(QHttpHeader);
+ d->q_ptr = this;
+ d->valid = header.d_func()->valid;
+ d->values = header.d_func()->values;
}
/*!
Destructor.
@@ -635,12 +669,12 @@ QHttpHeader::~QHttpHeader()
/*!
Assigns \a h and returns a reference to this http header.
*/
-QHttpHeader &QHttpHeader::operator=(const QHttpHeader &h)
+QHttpHeader & QHttpHeader::operator=(const QHttpHeader & h)
{
- Q_D(QHttpHeader);
- d->values = h.d_func()->values;
- d->valid = h.d_func()->valid;
- return *this;
+ Q_D(QHttpHeader);
+ d->values = h.d_func()->values;
+ d->valid = h.d_func()->valid;
+ return *this;
}
/*!
@@ -650,8 +684,8 @@ QHttpHeader &QHttpHeader::operator=(const QHttpHeader &h)
*/
bool QHttpHeader::isValid() const
{
- Q_D(const QHttpHeader);
- return d->valid;
+ Q_D(const QHttpHeader);
+ return d->valid;
}
/*! \internal
@@ -663,52 +697,60 @@ bool QHttpHeader::isValid() const
\sa toString()
*/
-bool QHttpHeader::parse(const QString &str)
+bool QHttpHeader::parse(const QString & str)
{
- Q_D(QHttpHeader);
- QStringList lst;
- int pos = str.indexOf(QLatin1Char('\n'));
- if (pos > 0 && str.at(pos - 1) == QLatin1Char('\r'))
- lst = str.trimmed().split(QLatin1String("\r\n"));
- else
- lst = str.trimmed().split(QLatin1String("\n"));
- lst.removeAll(QString()); // No empties
+ Q_D(QHttpHeader);
+ QStringList lst;
+ int pos = str.indexOf(QLatin1Char('\n'));
+ if(pos > 0 && str.at(pos - 1) == QLatin1Char('\r'))
+ lst = str.trimmed().split(QLatin1String("\r\n"));
+ else
+ lst = str.trimmed().split(QLatin1String("\n"));
+ lst.removeAll(QString()); // No empties
- if (lst.isEmpty())
- return true;
+ if(lst.isEmpty())
+ return true;
- QStringList lines;
- QStringList::Iterator it = lst.begin();
- for (; it != lst.end(); ++it) {
- if (!(*it).isEmpty()) {
- if ((*it)[0].isSpace()) {
- if (!lines.isEmpty()) {
- lines.last() += QLatin1Char(' ');
- lines.last() += (*it).trimmed();
- }
- } else {
- lines.append((*it));
- }
- }
- }
+ QStringList lines;
+ QStringList::Iterator it = lst.begin();
+ for(; it != lst.end(); ++it)
+ {
+ if(!(*it).isEmpty())
+ {
+ if((*it)[0].isSpace())
+ {
+ if(!lines.isEmpty())
+ {
+ lines.last() += QLatin1Char(' ');
+ lines.last() += (*it).trimmed();
+ }
+ }
+ else
+ {
+ lines.append((*it));
+ }
+ }
+ }
- int number = 0;
- it = lines.begin();
- for (; it != lines.end(); ++it) {
- if (!parseLine(*it, number++)) {
- d->valid = false;
- return false;
- }
- }
- return true;
+ int number = 0;
+ it = lines.begin();
+ for(; it != lines.end(); ++it)
+ {
+ if(!parseLine(*it, number++))
+ {
+ d->valid = false;
+ return false;
+ }
+ }
+ return true;
}
/*! \internal
*/
void QHttpHeader::setValid(bool v)
{
- Q_D(QHttpHeader);
- d->valid = v;
+ Q_D(QHttpHeader);
+ d->valid = v;
}
/*!
@@ -717,35 +759,37 @@ void QHttpHeader::setValid(bool v)
\sa setValue() removeValue() hasKey() keys()
*/
-QString QHttpHeader::value(const QString &key) const
+QString QHttpHeader::value(const QString & key) const
{
- Q_D(const QHttpHeader);
- QString lowercaseKey = key.toLower();
- QList<QPair<QString, QString> >::ConstIterator it = d->values.constBegin();
- while (it != d->values.constEnd()) {
- if ((*it).first.toLower() == lowercaseKey)
- return (*it).second;
- ++it;
- }
- return QString();
+ Q_D(const QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QList<QPair<QString, QString>>::ConstIterator it = d->values.constBegin();
+ while(it != d->values.constEnd())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ return (*it).second;
+ ++it;
+ }
+ return QString();
}
/*!
Returns all the entries with the given \a key. If no entry
has this \a key, an empty string list is returned.
*/
-QStringList QHttpHeader::allValues(const QString &key) const
+QStringList QHttpHeader::allValues(const QString & key) const
{
- Q_D(const QHttpHeader);
- QString lowercaseKey = key.toLower();
- QStringList valueList;
- QList<QPair<QString, QString> >::ConstIterator it = d->values.constBegin();
- while (it != d->values.constEnd()) {
- if ((*it).first.toLower() == lowercaseKey)
- valueList.append((*it).second);
- ++it;
- }
- return valueList;
+ Q_D(const QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QStringList valueList;
+ QList<QPair<QString, QString>>::ConstIterator it = d->values.constBegin();
+ while(it != d->values.constEnd())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ valueList.append((*it).second);
+ ++it;
+ }
+ return valueList;
}
/*!
@@ -755,20 +799,22 @@ QStringList QHttpHeader::allValues(const QString &key) const
*/
QStringList QHttpHeader::keys() const
{
- Q_D(const QHttpHeader);
- QStringList keyList;
- QSet<QString> seenKeys;
- QList<QPair<QString, QString> >::ConstIterator it = d->values.constBegin();
- while (it != d->values.constEnd()) {
- const QString &key = (*it).first;
- QString lowercaseKey = key.toLower();
- if (!seenKeys.contains(lowercaseKey)) {
- keyList.append(key);
- seenKeys.insert(lowercaseKey);
- }
- ++it;
- }
- return keyList;
+ Q_D(const QHttpHeader);
+ QStringList keyList;
+ QSet<QString> seenKeys;
+ QList<QPair<QString, QString>>::ConstIterator it = d->values.constBegin();
+ while(it != d->values.constEnd())
+ {
+ const QString & key = (*it).first;
+ QString lowercaseKey = key.toLower();
+ if(!seenKeys.contains(lowercaseKey))
+ {
+ keyList.append(key);
+ seenKeys.insert(lowercaseKey);
+ }
+ ++it;
+ }
+ return keyList;
}
/*!
@@ -777,17 +823,18 @@ QStringList QHttpHeader::keys() const
\sa value() setValue() keys()
*/
-bool QHttpHeader::hasKey(const QString &key) const
+bool QHttpHeader::hasKey(const QString & key) const
{
- Q_D(const QHttpHeader);
- QString lowercaseKey = key.toLower();
- QList<QPair<QString, QString> >::ConstIterator it = d->values.constBegin();
- while (it != d->values.constEnd()) {
- if ((*it).first.toLower() == lowercaseKey)
- return true;
- ++it;
- }
- return false;
+ Q_D(const QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QList<QPair<QString, QString>>::ConstIterator it = d->values.constBegin();
+ while(it != d->values.constEnd())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ return true;
+ ++it;
+ }
+ return false;
}
/*!
@@ -800,47 +847,49 @@ bool QHttpHeader::hasKey(const QString &key) const
\sa value() hasKey() removeValue()
*/
-void QHttpHeader::setValue(const QString &key, const QString &value)
+void QHttpHeader::setValue(const QString & key, const QString & value)
{
- Q_D(QHttpHeader);
- QString lowercaseKey = key.toLower();
- QList<QPair<QString, QString> >::Iterator it = d->values.begin();
- while (it != d->values.end()) {
- if ((*it).first.toLower() == lowercaseKey) {
- (*it).second = value;
- return;
- }
- ++it;
- }
- // not found so add
- addValue(key, value);
+ Q_D(QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QList<QPair<QString, QString>>::Iterator it = d->values.begin();
+ while(it != d->values.end())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ {
+ (*it).second = value;
+ return;
+ }
+ ++it;
+ }
+ // not found so add
+ addValue(key, value);
}
/*!
Sets the header entries to be the list of key value pairs in \a values.
*/
-void QHttpHeader::setValues(const QList<QPair<QString, QString> > &values)
+void QHttpHeader::setValues(const QList<QPair<QString, QString>> & values)
{
- Q_D(QHttpHeader);
- d->values = values;
+ Q_D(QHttpHeader);
+ d->values = values;
}
/*!
Adds a new entry with the \a key and \a value.
*/
-void QHttpHeader::addValue(const QString &key, const QString &value)
+void QHttpHeader::addValue(const QString & key, const QString & value)
{
- Q_D(QHttpHeader);
- d->values.append(qMakePair(key, value));
+ Q_D(QHttpHeader);
+ d->values.append(qMakePair(key, value));
}
/*!
Returns all the entries in the header.
*/
-QList<QPair<QString, QString> > QHttpHeader::values() const
+QList<QPair<QString, QString>> QHttpHeader::values() const
{
- Q_D(const QHttpHeader);
- return d->values;
+ Q_D(const QHttpHeader);
+ return d->values;
}
/*!
@@ -848,35 +897,39 @@ QList<QPair<QString, QString> > QHttpHeader::values() const
\sa value() setValue()
*/
-void QHttpHeader::removeValue(const QString &key)
+void QHttpHeader::removeValue(const QString & key)
{
- Q_D(QHttpHeader);
- QString lowercaseKey = key.toLower();
- QList<QPair<QString, QString> >::Iterator it = d->values.begin();
- while (it != d->values.end()) {
- if ((*it).first.toLower() == lowercaseKey) {
- d->values.erase(it);
- return;
- }
- ++it;
- }
+ Q_D(QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QList<QPair<QString, QString>>::Iterator it = d->values.begin();
+ while(it != d->values.end())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ {
+ d->values.erase(it);
+ return;
+ }
+ ++it;
+ }
}
/*!
Removes all the entries with the key \a key from the HTTP header.
*/
-void QHttpHeader::removeAllValues(const QString &key)
+void QHttpHeader::removeAllValues(const QString & key)
{
- Q_D(QHttpHeader);
- QString lowercaseKey = key.toLower();
- QList<QPair<QString, QString> >::Iterator it = d->values.begin();
- while (it != d->values.end()) {
- if ((*it).first.toLower() == lowercaseKey) {
- it = d->values.erase(it);
- continue;
- }
- ++it;
- }
+ Q_D(QHttpHeader);
+ QString lowercaseKey = key.toLower();
+ QList<QPair<QString, QString>>::Iterator it = d->values.begin();
+ while(it != d->values.end())
+ {
+ if((*it).first.toLower() == lowercaseKey)
+ {
+ it = d->values.erase(it);
+ continue;
+ }
+ ++it;
+ }
}
/*! \internal
@@ -887,15 +940,15 @@ void QHttpHeader::removeAllValues(const QString &key)
\sa parse()
*/
-bool QHttpHeader::parseLine(const QString &line, int)
+bool QHttpHeader::parseLine(const QString & line, int)
{
- int i = line.indexOf(QLatin1Char(':'));
- if (i == -1)
- return false;
+ int i = line.indexOf(QLatin1Char(':'));
+ if(i == -1)
+ return false;
- addValue(line.left(i).trimmed(), line.mid(i + 1).trimmed());
+ addValue(line.left(i).trimmed(), line.mid(i + 1).trimmed());
- return true;
+ return true;
}
/*!
@@ -907,18 +960,19 @@ bool QHttpHeader::parseLine(const QString &line, int)
*/
QString QHttpHeader::toString() const
{
- Q_D(const QHttpHeader);
- if (!isValid())
- return QLatin1String("");
+ Q_D(const QHttpHeader);
+ if(!isValid())
+ return QLatin1String("");
- QString ret = QLatin1String("");
+ QString ret = QLatin1String("");
- QList<QPair<QString, QString> >::ConstIterator it = d->values.constBegin();
- while (it != d->values.constEnd()) {
- ret += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n");
- ++it;
- }
- return ret;
+ QList<QPair<QString, QString>>::ConstIterator it = d->values.constBegin();
+ while(it != d->values.constEnd())
+ {
+ ret += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n");
+ ++it;
+ }
+ return ret;
}
/*!
@@ -929,7 +983,7 @@ QString QHttpHeader::toString() const
*/
bool QHttpHeader::hasContentLength() const
{
- return hasKey(QLatin1String("content-length"));
+ return hasKey(QLatin1String("content-length"));
}
/*!
@@ -940,7 +994,7 @@ bool QHttpHeader::hasContentLength() const
*/
uint QHttpHeader::contentLength() const
{
- return value(QLatin1String("content-length")).toUInt();
+ return value(QLatin1String("content-length")).toUInt();
}
/*!
@@ -951,7 +1005,7 @@ uint QHttpHeader::contentLength() const
*/
void QHttpHeader::setContentLength(int len)
{
- setValue(QLatin1String("content-length"), QString::number(len));
+ setValue(QLatin1String("content-length"), QString::number(len));
}
/*!
@@ -962,7 +1016,7 @@ void QHttpHeader::setContentLength(int len)
*/
bool QHttpHeader::hasContentType() const
{
- return hasKey(QLatin1String("content-type"));
+ return hasKey(QLatin1String("content-type"));
}
/*!
@@ -972,15 +1026,15 @@ bool QHttpHeader::hasContentType() const
*/
QString QHttpHeader::contentType() const
{
- QString type = value(QLatin1String("content-type"));
- if (type.isEmpty())
- return QString();
+ QString type = value(QLatin1String("content-type"));
+ if(type.isEmpty())
+ return QString();
- int pos = type.indexOf(QLatin1Char(';'));
- if (pos == -1)
- return type;
+ int pos = type.indexOf(QLatin1Char(';'));
+ if(pos == -1)
+ return type;
- return type.left(pos).trimmed();
+ return type.left(pos).trimmed();
}
/*!
@@ -989,19 +1043,19 @@ QString QHttpHeader::contentType() const
\sa contentType() hasContentType()
*/
-void QHttpHeader::setContentType(const QString &type)
+void QHttpHeader::setContentType(const QString & type)
{
- setValue(QLatin1String("content-type"), type);
+ setValue(QLatin1String("content-type"), type);
}
class QHttpResponseHeaderPrivate : public QHttpHeaderPrivate
{
- Q_DECLARE_PUBLIC(QHttpResponseHeader)
+ Q_DECLARE_PUBLIC(QHttpResponseHeader)
public:
- int statCode;
- QString reasonPhr;
- int majVer;
- int minVer;
+ int statCode;
+ QString reasonPhr;
+ int majVer;
+ int minVer;
};
/****************************************************
@@ -1037,34 +1091,34 @@ public:
QHttpResponseHeader::QHttpResponseHeader()
: QHttpHeader(*new QHttpResponseHeaderPrivate)
{
- setValid(false);
+ setValid(false);
}
/*!
Constructs a copy of \a header.
*/
-QHttpResponseHeader::QHttpResponseHeader(const QHttpResponseHeader &header)
+QHttpResponseHeader::QHttpResponseHeader(const QHttpResponseHeader & header)
: QHttpHeader(*new QHttpResponseHeaderPrivate, header)
{
- Q_D(QHttpResponseHeader);
- d->statCode = header.d_func()->statCode;
- d->reasonPhr = header.d_func()->reasonPhr;
- d->majVer = header.d_func()->majVer;
- d->minVer = header.d_func()->minVer;
+ Q_D(QHttpResponseHeader);
+ d->statCode = header.d_func()->statCode;
+ d->reasonPhr = header.d_func()->reasonPhr;
+ d->majVer = header.d_func()->majVer;
+ d->minVer = header.d_func()->minVer;
}
/*!
Copies the contents of \a header into this QHttpResponseHeader.
*/
-QHttpResponseHeader &QHttpResponseHeader::operator=(const QHttpResponseHeader &header)
+QHttpResponseHeader & QHttpResponseHeader::operator=(const QHttpResponseHeader & header)
{
- Q_D(QHttpResponseHeader);
- QHttpHeader::operator=(header);
- d->statCode = header.d_func()->statCode;
- d->reasonPhr = header.d_func()->reasonPhr;
- d->majVer = header.d_func()->majVer;
- d->minVer = header.d_func()->minVer;
- return *this;
+ Q_D(QHttpResponseHeader);
+ QHttpHeader::operator=(header);
+ d->statCode = header.d_func()->statCode;
+ d->reasonPhr = header.d_func()->reasonPhr;
+ d->majVer = header.d_func()->majVer;
+ d->minVer = header.d_func()->minVer;
+ return *this;
}
/*!
@@ -1075,10 +1129,10 @@ QHttpResponseHeader &QHttpResponseHeader::operator=(const QHttpResponseHeader &h
reason-phrase); each of remaining lines should have the format key, colon,
space, value.
*/
-QHttpResponseHeader::QHttpResponseHeader(const QString &str)
+QHttpResponseHeader::QHttpResponseHeader(const QString & str)
: QHttpHeader(*new QHttpResponseHeaderPrivate)
{
- parse(str);
+ parse(str);
}
/*!
@@ -1090,10 +1144,10 @@ QHttpResponseHeader::QHttpResponseHeader(const QString &str)
\sa statusCode() reasonPhrase() majorVersion() minorVersion()
*/
-QHttpResponseHeader::QHttpResponseHeader(int code, const QString &text, int majorVer, int minorVer)
+QHttpResponseHeader::QHttpResponseHeader(int code, const QString & text, int majorVer, int minorVer)
: QHttpHeader(*new QHttpResponseHeaderPrivate)
{
- setStatusLine(code, text, majorVer, minorVer);
+ setStatusLine(code, text, majorVer, minorVer);
}
/*!
@@ -1104,14 +1158,14 @@ QHttpResponseHeader::QHttpResponseHeader(int code, const QString &text, int majo
\sa statusCode() reasonPhrase() majorVersion() minorVersion()
*/
-void QHttpResponseHeader::setStatusLine(int code, const QString &text, int majorVer, int minorVer)
+void QHttpResponseHeader::setStatusLine(int code, const QString & text, int majorVer, int minorVer)
{
- Q_D(QHttpResponseHeader);
- setValid(true);
- d->statCode = code;
- d->reasonPhr = text;
- d->majVer = majorVer;
- d->minVer = minorVer;
+ Q_D(QHttpResponseHeader);
+ setValid(true);
+ d->statCode = code;
+ d->reasonPhr = text;
+ d->majVer = majorVer;
+ d->minVer = minorVer;
}
/*!
@@ -1121,8 +1175,8 @@ void QHttpResponseHeader::setStatusLine(int code, const QString &text, int major
*/
int QHttpResponseHeader::statusCode() const
{
- Q_D(const QHttpResponseHeader);
- return d->statCode;
+ Q_D(const QHttpResponseHeader);
+ return d->statCode;
}
/*!
@@ -1132,8 +1186,8 @@ int QHttpResponseHeader::statusCode() const
*/
QString QHttpResponseHeader::reasonPhrase() const
{
- Q_D(const QHttpResponseHeader);
- return d->reasonPhr;
+ Q_D(const QHttpResponseHeader);
+ return d->reasonPhr;
}
/*!
@@ -1143,8 +1197,8 @@ QString QHttpResponseHeader::reasonPhrase() const
*/
int QHttpResponseHeader::majorVersion() const
{
- Q_D(const QHttpResponseHeader);
- return d->majVer;
+ Q_D(const QHttpResponseHeader);
+ return d->majVer;
}
/*!
@@ -1154,59 +1208,64 @@ int QHttpResponseHeader::majorVersion() const
*/
int QHttpResponseHeader::minorVersion() const
{
- Q_D(const QHttpResponseHeader);
- return d->minVer;
+ Q_D(const QHttpResponseHeader);
+ return d->minVer;
}
/*! \internal
*/
-bool QHttpResponseHeader::parseLine(const QString &line, int number)
+bool QHttpResponseHeader::parseLine(const QString & line, int number)
{
- Q_D(QHttpResponseHeader);
- if (number != 0)
- return QHttpHeader::parseLine(line, number);
+ Q_D(QHttpResponseHeader);
+ if(number != 0)
+ return QHttpHeader::parseLine(line, number);
- QString l = line.simplified();
- if (l.length() < 10)
- return false;
+ QString l = line.simplified();
+ if(l.length() < 10)
+ return false;
- if (l.left(5) == QLatin1String("HTTP/") && l[5].isDigit() && l[6] == QLatin1Char('.') &&
- l[7].isDigit() && l[8] == QLatin1Char(' ') && l[9].isDigit()) {
- d->majVer = l[5].toLatin1() - '0';
- d->minVer = l[7].toLatin1() - '0';
+ if(l.left(5) == QLatin1String("HTTP/") && l[5].isDigit() && l[6] == QLatin1Char('.') && l[7].isDigit() && l[8] == QLatin1Char(' ') && l[9].isDigit())
+ {
+ d->majVer = l[5].toLatin1() - '0';
+ d->minVer = l[7].toLatin1() - '0';
- int pos = l.indexOf(QLatin1Char(' '), 9);
- if (pos != -1) {
- d->reasonPhr = l.mid(pos + 1);
- d->statCode = l.mid(9, pos - 9).toInt();
- } else {
- d->statCode = l.mid(9).toInt();
- d->reasonPhr.clear();
- }
- } else {
- return false;
- }
+ int pos = l.indexOf(QLatin1Char(' '), 9);
+ if(pos != -1)
+ {
+ d->reasonPhr = l.mid(pos + 1);
+ d->statCode = l.mid(9, pos - 9).toInt();
+ }
+ else
+ {
+ d->statCode = l.mid(9).toInt();
+ d->reasonPhr.clear();
+ }
+ }
+ else
+ {
+ return false;
+ }
- return true;
+ return true;
}
/*! \reimp
*/
QString QHttpResponseHeader::toString() const
{
- Q_D(const QHttpResponseHeader);
- QString ret(QLatin1String("HTTP/%1.%2 %3 %4\r\n%5\r\n"));
- return ret.arg(d->majVer).arg(d->minVer).arg(d->statCode).arg(d->reasonPhr).arg(QHttpHeader::toString());
+ Q_D(const QHttpResponseHeader);
+ QString ret(QLatin1String("HTTP/%1.%2 %3 %4\r\n%5\r\n"));
+ return ret.arg(d->majVer).arg(d->minVer).arg(d->statCode).arg(d->reasonPhr).arg(QHttpHeader::toString());
}
class QHttpRequestHeaderPrivate : public QHttpHeaderPrivate
{
- Q_DECLARE_PUBLIC(QHttpRequestHeader)
+ Q_DECLARE_PUBLIC(QHttpRequestHeader)
public:
- QString m;
- QString p;
- int majVer;
- int minVer;
+ QString m;
+ QString p;
+ int majVer;
+ int minVer;
};
/****************************************************
@@ -1252,7 +1311,7 @@ public:
QHttpRequestHeader::QHttpRequestHeader()
: QHttpHeader(*new QHttpRequestHeaderPrivate)
{
- setValid(false);
+ setValid(false);
}
/*!
@@ -1261,41 +1320,41 @@ QHttpRequestHeader::QHttpRequestHeader()
minorVer. The \a path argument must be properly encoded for an
HTTP request.
*/
-QHttpRequestHeader::QHttpRequestHeader(const QString &method, const QString &path, int majorVer, int minorVer)
+QHttpRequestHeader::QHttpRequestHeader(const QString & method, const QString & path, int majorVer, int minorVer)
: QHttpHeader(*new QHttpRequestHeaderPrivate)
{
- Q_D(QHttpRequestHeader);
- d->m = method;
- d->p = path;
- d->majVer = majorVer;
- d->minVer = minorVer;
+ Q_D(QHttpRequestHeader);
+ d->m = method;
+ d->p = path;
+ d->majVer = majorVer;
+ d->minVer = minorVer;
}
/*!
Constructs a copy of \a header.
*/
-QHttpRequestHeader::QHttpRequestHeader(const QHttpRequestHeader &header)
+QHttpRequestHeader::QHttpRequestHeader(const QHttpRequestHeader & header)
: QHttpHeader(*new QHttpRequestHeaderPrivate, header)
{
- Q_D(QHttpRequestHeader);
- d->m = header.d_func()->m;
- d->p = header.d_func()->p;
- d->majVer = header.d_func()->majVer;
- d->minVer = header.d_func()->minVer;
+ Q_D(QHttpRequestHeader);
+ d->m = header.d_func()->m;
+ d->p = header.d_func()->p;
+ d->majVer = header.d_func()->majVer;
+ d->minVer = header.d_func()->minVer;
}
/*!
Copies the content of \a header into this QHttpRequestHeader
*/
-QHttpRequestHeader &QHttpRequestHeader::operator=(const QHttpRequestHeader &header)
+QHttpRequestHeader & QHttpRequestHeader::operator=(const QHttpRequestHeader & header)
{
- Q_D(QHttpRequestHeader);
- QHttpHeader::operator=(header);
- d->m = header.d_func()->m;
- d->p = header.d_func()->p;
- d->majVer = header.d_func()->majVer;
- d->minVer = header.d_func()->minVer;
- return *this;
+ Q_D(QHttpRequestHeader);
+ QHttpHeader::operator=(header);
+ d->m = header.d_func()->m;
+ d->p = header.d_func()->p;
+ d->majVer = header.d_func()->majVer;
+ d->minVer = header.d_func()->minVer;
+ return *this;
}
/*!
@@ -1305,10 +1364,10 @@ QHttpRequestHeader &QHttpRequestHeader::operator=(const QHttpRequestHeader &head
HTTP-version); each of the remaining lines should have the format key,
colon, space, value.
*/
-QHttpRequestHeader::QHttpRequestHeader(const QString &str)
+QHttpRequestHeader::QHttpRequestHeader(const QString & str)
: QHttpHeader(*new QHttpRequestHeaderPrivate)
{
- parse(str);
+ parse(str);
}
/*!
@@ -1319,14 +1378,14 @@ QHttpRequestHeader::QHttpRequestHeader(const QString &str)
\sa method() path() majorVersion() minorVersion()
*/
-void QHttpRequestHeader::setRequest(const QString &method, const QString &path, int majorVer, int minorVer)
+void QHttpRequestHeader::setRequest(const QString & method, const QString & path, int majorVer, int minorVer)
{
- Q_D(QHttpRequestHeader);
- setValid(true);
- d->m = method;
- d->p = path;
- d->majVer = majorVer;
- d->minVer = minorVer;
+ Q_D(QHttpRequestHeader);
+ setValid(true);
+ d->m = method;
+ d->p = path;
+ d->majVer = majorVer;
+ d->minVer = minorVer;
}
/*!
@@ -1336,8 +1395,8 @@ void QHttpRequestHeader::setRequest(const QString &method, const QString &path,
*/
QString QHttpRequestHeader::method() const
{
- Q_D(const QHttpRequestHeader);
- return d->m;
+ Q_D(const QHttpRequestHeader);
+ return d->m;
}
/*!
@@ -1347,8 +1406,8 @@ QString QHttpRequestHeader::method() const
*/
QString QHttpRequestHeader::path() const
{
- Q_D(const QHttpRequestHeader);
- return d->p;
+ Q_D(const QHttpRequestHeader);
+ return d->p;
}
/*!
@@ -1358,8 +1417,8 @@ QString QHttpRequestHeader::path() const
*/
int QHttpRequestHeader::majorVersion() const
{
- Q_D(const QHttpRequestHeader);
- return d->majVer;
+ Q_D(const QHttpRequestHeader);
+ return d->majVer;
}
/*!
@@ -1369,50 +1428,51 @@ int QHttpRequestHeader::majorVersion() const
*/
int QHttpRequestHeader::minorVersion() const
{
- Q_D(const QHttpRequestHeader);
- return d->minVer;
+ Q_D(const QHttpRequestHeader);
+ return d->minVer;
}
/*! \internal
*/
-bool QHttpRequestHeader::parseLine(const QString &line, int number)
+bool QHttpRequestHeader::parseLine(const QString & line, int number)
{
- Q_D(QHttpRequestHeader);
- if (number != 0)
- return QHttpHeader::parseLine(line, number);
+ Q_D(QHttpRequestHeader);
+ if(number != 0)
+ return QHttpHeader::parseLine(line, number);
- QStringList lst = line.simplified().split(QLatin1String(" "));
- if (lst.count() > 0) {
- d->m = lst[0];
- if (lst.count() > 1) {
- d->p = lst[1];
- if (lst.count() > 2) {
- QString v = lst[2];
- if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") &&
- v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit()) {
- d->majVer = v[5].toLatin1() - '0';
- d->minVer = v[7].toLatin1() - '0';
- return true;
- }
- }
- }
- }
+ QStringList lst = line.simplified().split(QLatin1String(" "));
+ if(lst.count() > 0)
+ {
+ d->m = lst[0];
+ if(lst.count() > 1)
+ {
+ d->p = lst[1];
+ if(lst.count() > 2)
+ {
+ QString v = lst[2];
+ if(v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") && v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit())
+ {
+ d->majVer = v[5].toLatin1() - '0';
+ d->minVer = v[7].toLatin1() - '0';
+ return true;
+ }
+ }
+ }
+ }
- return false;
+ return false;
}
/*! \reimp
*/
QString QHttpRequestHeader::toString() const
{
- Q_D(const QHttpRequestHeader);
- QString first(QLatin1String("%1 %2"));
- QString last(QLatin1String(" HTTP/%3.%4\r\n%5\r\n"));
- return first.arg(d->m).arg(d->p) +
- last.arg(d->majVer).arg(d->minVer).arg(QHttpHeader::toString());
+ Q_D(const QHttpRequestHeader);
+ QString first(QLatin1String("%1 %2"));
+ QString last(QLatin1String(" HTTP/%3.%4\r\n%5\r\n"));
+ return first.arg(d->m).arg(d->p) + last.arg(d->majVer).arg(d->minVer).arg(QHttpHeader::toString());
}
-
/****************************************************
*
* QHttp
@@ -1526,10 +1586,10 @@ QString QHttpRequestHeader::toString() const
Constructs a QHttp object. The \a parent parameter is passed on
to the QObject constructor.
*/
-QHttp::QHttp(QObject *parent)
+QHttp::QHttp(QObject * parent)
: QObject(parent), d(new QHttpPrivate(this))
{
- d->init();
+ d->init();
}
/*!
@@ -1540,13 +1600,13 @@ QHttp::QHttp(QObject *parent)
\sa setHost()
*/
-QHttp::QHttp(const QString &hostName, quint16 port, QObject *parent)
+QHttp::QHttp(const QString & hostName, quint16 port, QObject * parent)
: QObject(parent), d(new QHttpPrivate(this))
{
- d->init();
+ d->init();
- d->hostName = hostName;
- d->port = port;
+ d->hostName = hostName;
+ d->port = port;
}
/*!
@@ -1561,25 +1621,25 @@ QHttp::QHttp(const QString &hostName, quint16 port, QObject *parent)
\sa setHost()
*/
-QHttp::QHttp(const QString &hostName, ConnectionMode mode, quint16 port, QObject *parent)
+QHttp::QHttp(const QString & hostName, ConnectionMode mode, quint16 port, QObject * parent)
: QObject(parent), d(new QHttpPrivate(this))
{
- d->init();
+ d->init();
- d->hostName = hostName;
- if (port == 0)
- port = (mode == ConnectionModeHttp) ? 80 : 443;
- d->port = port;
- d->mode = mode;
+ d->hostName = hostName;
+ if(port == 0)
+ port = (mode == ConnectionModeHttp) ? 80 : 443;
+ d->port = port;
+ d->mode = mode;
}
void QHttpPrivate::init()
{
- Q_Q(QHttp);
- errorString = QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown error"));
- QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
- post100ContinueTimer.setSingleShot(true);
- QObject::connect(&post100ContinueTimer, SIGNAL(timeout()), q, SLOT(_q_continuePost()));
+ Q_Q(QHttp);
+ errorString = QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown error"));
+ QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
+ post100ContinueTimer.setSingleShot(true);
+ QObject::connect(&post100ContinueTimer, SIGNAL(timeout()), q, SLOT(_q_continuePost()));
}
/*!
@@ -1588,7 +1648,7 @@ void QHttpPrivate::init()
*/
QHttp::~QHttp()
{
- abort();
+ abort();
}
void QHttp::_q_startNextRequest()
@@ -1867,14 +1927,14 @@ void QHttp::_q_continuePost()
*/
void QHttp::abort()
{
- if (d->pending.isEmpty())
- return;
+ if(d->pending.isEmpty())
+ return;
- d->finishedWithError(tr("Request aborted"), Aborted);
- clearPendingRequests();
- if (d->socket)
- d->socket->abort();
- d->closeConn();
+ d->finishedWithError(tr("Request aborted"), Aborted);
+ clearPendingRequests();
+ if(d->socket)
+ d->socket->abort();
+ d->closeConn();
}
/*!
@@ -1886,9 +1946,9 @@ void QHttp::abort()
qint64 QHttp::bytesAvailable() const
{
#if defined(QHTTP_DEBUG)
- qDebug("QHttp::bytesAvailable(): %d bytes", (int)d->rba.size());
+ qDebug("QHttp::bytesAvailable(): %d bytes", (int)d->rba.size());
#endif
- return qint64(d->rba.size());
+ return qint64(d->rba.size());
}
/*! \fn qint64 QHttp::readBlock(char *data, quint64 maxlen)
@@ -1902,28 +1962,30 @@ qint64 QHttp::bytesAvailable() const
\sa get() post() request() readyRead() bytesAvailable() readAll()
*/
-qint64 QHttp::read(char *data, qint64 maxlen)
+qint64 QHttp::read(char * data, qint64 maxlen)
{
- if (data == 0 && maxlen != 0) {
- qWarning("QHttp::read: Null pointer error");
- return -1;
- }
- if (maxlen >= d->rba.size())
- maxlen = d->rba.size();
- int readSoFar = 0;
- while (!d->rba.isEmpty() && readSoFar < maxlen) {
- int nextBlockSize = d->rba.nextDataBlockSize();
- int bytesToRead = qMin<qint64>(maxlen - readSoFar, nextBlockSize);
- memcpy(data + readSoFar, d->rba.readPointer(), bytesToRead);
- d->rba.free(bytesToRead);
- readSoFar += bytesToRead;
- }
+ if(data == 0 && maxlen != 0)
+ {
+ qWarning("QHttp::read: Null pointer error");
+ return -1;
+ }
+ if(maxlen >= d->rba.size())
+ maxlen = d->rba.size();
+ int readSoFar = 0;
+ while(!d->rba.isEmpty() && readSoFar < maxlen)
+ {
+ int nextBlockSize = d->rba.nextDataBlockSize();
+ int bytesToRead = qMin<qint64>(maxlen - readSoFar, nextBlockSize);
+ memcpy(data + readSoFar, d->rba.readPointer(), bytesToRead);
+ d->rba.free(bytesToRead);
+ readSoFar += bytesToRead;
+ }
- d->bytesDone += maxlen;
+ d->bytesDone += maxlen;
#if defined(QHTTP_DEBUG)
- qDebug("QHttp::read(): read %lld bytes (%lld bytes done)", maxlen, d->bytesDone);
+ qDebug("QHttp::read(): read %lld bytes (%lld bytes done)", maxlen, d->bytesDone);
#endif
- return maxlen;
+ return maxlen;
}
/*!
@@ -1933,12 +1995,12 @@ qint64 QHttp::read(char *data, qint64 maxlen)
*/
QByteArray QHttp::readAll()
{
- qint64 avail = bytesAvailable();
- QByteArray tmp;
- tmp.resize(int(avail));
- qint64 got = read(tmp.data(), int(avail));
- tmp.resize(got);
- return tmp;
+ qint64 avail = bytesAvailable();
+ QByteArray tmp;
+ tmp.resize(int(avail));
+ qint64 got = read(tmp.data(), int(avail));
+ tmp.resize(got);
+ return tmp;
}
/*!
@@ -1949,9 +2011,9 @@ QByteArray QHttp::readAll()
*/
int QHttp::currentId() const
{
- if (d->pending.isEmpty())
- return 0;
- return d->pending.first()->id;
+ if(d->pending.isEmpty())
+ return 0;
+ return d->pending.first()->id;
}
/*!
@@ -1964,12 +2026,13 @@ int QHttp::currentId() const
*/
QHttpRequestHeader QHttp::currentRequest() const
{
- if (!d->pending.isEmpty()) {
- QHttpRequest *r = d->pending.first();
- if (r->hasRequestHeader())
- return r->requestHeader();
- }
- return QHttpRequestHeader();
+ if(!d->pending.isEmpty())
+ {
+ QHttpRequest * r = d->pending.first();
+ if(r->hasRequestHeader())
+ return r->requestHeader();
+ }
+ return QHttpRequestHeader();
}
/*!
@@ -1981,7 +2044,7 @@ QHttpRequestHeader QHttp::currentRequest() const
*/
QHttpResponseHeader QHttp::lastResponse() const
{
- return d->response;
+ return d->response;
}
/*!
@@ -1994,11 +2057,11 @@ QHttpResponseHeader QHttp::lastResponse() const
\sa currentDestinationDevice() post() request()
*/
-QIODevice *QHttp::currentSourceDevice() const
+QIODevice * QHttp::currentSourceDevice() const
{
- if (d->pending.isEmpty())
- return 0;
- return d->pending.first()->sourceDevice();
+ if(d->pending.isEmpty())
+ return 0;
+ return d->pending.first()->sourceDevice();
}
/*!
@@ -2011,11 +2074,11 @@ QIODevice *QHttp::currentSourceDevice() const
\sa currentSourceDevice() get() post() request()
*/
-QIODevice *QHttp::currentDestinationDevice() const
+QIODevice * QHttp::currentDestinationDevice() const
{
- if (d->pending.isEmpty())
- return 0;
- return d->pending.first()->destinationDevice();
+ if(d->pending.isEmpty())
+ return 0;
+ return d->pending.first()->destinationDevice();
}
/*!
@@ -2029,7 +2092,7 @@ QIODevice *QHttp::currentDestinationDevice() const
*/
bool QHttp::hasPendingRequests() const
{
- return d->pending.count() > 1;
+ return d->pending.count() > 1;
}
/*!
@@ -2041,9 +2104,9 @@ bool QHttp::hasPendingRequests() const
*/
void QHttp::clearPendingRequests()
{
- // delete all entires except the first one
- while (d->pending.count() > 1)
- delete d->pending.takeLast();
+ // delete all entires except the first one
+ while(d->pending.count() > 1)
+ delete d->pending.takeLast();
}
/*!
@@ -2061,9 +2124,9 @@ void QHttp::clearPendingRequests()
\sa get() post() head() request() requestStarted() requestFinished() done()
*/
-int QHttp::setHost(const QString &hostName, quint16 port)
+int QHttp::setHost(const QString & hostName, quint16 port)
{
- return d->addRequest(new QHttpSetHostRequest(hostName, port, ConnectionModeHttp));
+ return d->addRequest(new QHttpSetHostRequest(hostName, port, ConnectionModeHttp));
}
/*!
@@ -2084,15 +2147,15 @@ int QHttp::setHost(const QString &hostName, quint16 port)
\sa get() post() head() request() requestStarted() requestFinished() done()
*/
-int QHttp::setHost(const QString &hostName, ConnectionMode mode, quint16 port)
+int QHttp::setHost(const QString & hostName, ConnectionMode mode, quint16 port)
{
#ifdef QT_NO_OPENSSL
- if (mode == ConnectionModeHttps)
- qWarning("QHttp::setHost: HTTPS connection requested but SSL support not compiled in");
+ if(mode == ConnectionModeHttps)
+ qWarning("QHttp::setHost: HTTPS connection requested but SSL support not compiled in");
#endif
- if (port == 0)
- port = (mode == ConnectionModeHttp) ? 80 : 443;
- return d->addRequest(new QHttpSetHostRequest(hostName, port, mode));
+ if(port == 0)
+ port = (mode == ConnectionModeHttp) ? 80 : 443;
+ return d->addRequest(new QHttpSetHostRequest(hostName, port, mode));
}
/*!
@@ -2116,9 +2179,9 @@ int QHttp::setHost(const QString &hostName, ConnectionMode mode, quint16 port)
\sa QObject::moveToThread(), {Thread Support in Qt}
*/
-int QHttp::setSocket(QTcpSocket *socket)
+int QHttp::setSocket(QTcpSocket * socket)
{
- return d->addRequest(new QHttpSetSocketRequest(socket));
+ return d->addRequest(new QHttpSetSocketRequest(socket));
}
/*!
@@ -2134,9 +2197,9 @@ int QHttp::setSocket(QTcpSocket *socket)
emitted. When it is finished the requestFinished() signal is
emitted.
*/
-int QHttp::setUser(const QString &userName, const QString &password)
+int QHttp::setUser(const QString & userName, const QString & password)
{
- return d->addRequest(new QHttpSetUserRequest(userName, password));
+ return d->addRequest(new QHttpSetUserRequest(userName, password));
}
#ifndef QT_NO_NETWORKPROXY
@@ -2160,11 +2223,11 @@ int QHttp::setUser(const QString &userName, const QString &password)
\sa QFtp::setProxy()
*/
-int QHttp::setProxy(const QString &host, int port,
- const QString &username, const QString &password)
+int QHttp::setProxy(const QString & host, int port,
+ const QString & username, const QString & password)
{
- QNetworkProxy proxy(QNetworkProxy::HttpProxy, host, port, username, password);
- return d->addRequest(new QHttpSetProxyRequest(proxy));
+ QNetworkProxy proxy(QNetworkProxy::HttpProxy, host, port, username, password);
+ return d->addRequest(new QHttpSetProxyRequest(proxy));
}
/*!
@@ -2181,9 +2244,9 @@ int QHttp::setProxy(const QString &host, int port,
is, ConnectionModeHttp), QHttp will treat the proxy as a caching
proxy.
*/
-int QHttp::setProxy(const QNetworkProxy &proxy)
+int QHttp::setProxy(const QNetworkProxy & proxy)
{
- return d->addRequest(new QHttpSetProxyRequest(proxy));
+ return d->addRequest(new QHttpSetProxyRequest(proxy));
}
#endif
@@ -2219,11 +2282,11 @@ int QHttp::setProxy(const QNetworkProxy &proxy)
\sa setHost(), post(), head(), request(), requestStarted(),
requestFinished(), done()
*/
-int QHttp::get(const QString &path, QIODevice *to)
+int QHttp::get(const QString & path, QIODevice * to)
{
- QHttpRequestHeader header(QLatin1String("GET"), path);
- header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
- return d->addRequest(new QHttpPGHRequest(header, (QIODevice *) 0, to));
+ QHttpRequestHeader header(QLatin1String("GET"), path);
+ header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
+ return d->addRequest(new QHttpPGHRequest(header, (QIODevice *)0, to));
}
/*!
@@ -2256,11 +2319,11 @@ int QHttp::get(const QString &path, QIODevice *to)
\sa setHost() get() head() request() requestStarted() requestFinished() done()
*/
-int QHttp::post(const QString &path, QIODevice *data, QIODevice *to )
+int QHttp::post(const QString & path, QIODevice * data, QIODevice * to)
{
- QHttpRequestHeader header(QLatin1String("POST"), path);
- header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
- return d->addRequest(new QHttpPGHRequest(header, data, to));
+ QHttpRequestHeader header(QLatin1String("POST"), path);
+ header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
+ return d->addRequest(new QHttpPGHRequest(header, data, to));
}
/*!
@@ -2268,11 +2331,11 @@ int QHttp::post(const QString &path, QIODevice *data, QIODevice *to )
\a data is used as the content data of the HTTP request.
*/
-int QHttp::post(const QString &path, const QByteArray &data, QIODevice *to)
+int QHttp::post(const QString & path, const QByteArray & data, QIODevice * to)
{
- QHttpRequestHeader header(QLatin1String("POST"), path);
- header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
- return d->addRequest(new QHttpPGHRequest(header, new QByteArray(data), to));
+ QHttpRequestHeader header(QLatin1String("POST"), path);
+ header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
+ return d->addRequest(new QHttpPGHRequest(header, new QByteArray(data), to));
}
/*!
@@ -2293,11 +2356,11 @@ int QHttp::post(const QString &path, const QByteArray &data, QIODevice *to)
\sa setHost() get() post() request() requestStarted() requestFinished() done()
*/
-int QHttp::head(const QString &path)
+int QHttp::head(const QString & path)
{
- QHttpRequestHeader header(QLatin1String("HEAD"), path);
- header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
- return d->addRequest(new QHttpPGHRequest(header, (QIODevice*)0, 0));
+ QHttpRequestHeader header(QLatin1String("HEAD"), path);
+ header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
+ return d->addRequest(new QHttpPGHRequest(header, (QIODevice *)0, 0));
}
/*!
@@ -2327,9 +2390,9 @@ int QHttp::head(const QString &path)
\sa setHost() get() post() head() requestStarted() requestFinished() done()
*/
-int QHttp::request(const QHttpRequestHeader &header, QIODevice *data, QIODevice *to)
+int QHttp::request(const QHttpRequestHeader & header, QIODevice * data, QIODevice * to)
{
- return d->addRequest(new QHttpNormalRequest(header, data, to));
+ return d->addRequest(new QHttpNormalRequest(header, data, to));
}
/*!
@@ -2337,9 +2400,9 @@ int QHttp::request(const QHttpRequestHeader &header, QIODevice *data, QIODevice
\a data is used as the content data of the HTTP request.
*/
-int QHttp::request(const QHttpRequestHeader &header, const QByteArray &data, QIODevice *to )
+int QHttp::request(const QHttpRequestHeader & header, const QByteArray & data, QIODevice * to)
{
- return d->addRequest(new QHttpNormalRequest(header, new QByteArray(data), to));
+ return d->addRequest(new QHttpNormalRequest(header, new QByteArray(data), to));
}
/*!
@@ -2368,7 +2431,7 @@ int QHttp::request(const QHttpRequestHeader &header, const QByteArray &data, QIO
*/
int QHttp::close()
{
- return d->addRequest(new QHttpCloseRequest());
+ return d->addRequest(new QHttpCloseRequest());
}
/*!
@@ -2378,679 +2441,777 @@ int QHttp::close()
*/
int QHttp::closeConnection()
{
- return d->addRequest(new QHttpCloseRequest());
+ return d->addRequest(new QHttpCloseRequest());
}
-int QHttpPrivate::addRequest(QHttpNormalRequest *req)
+int QHttpPrivate::addRequest(QHttpNormalRequest * req)
{
- QHttpRequestHeader h = req->requestHeader();
- if (h.path().isEmpty()) {
- // note: the following qWarning is autotested. If you change it, change the test too.
- qWarning("QHttp: empty path requested is invalid -- using '/'");
- h.setRequest(h.method(), QLatin1String("/"), h.majorVersion(), h.minorVersion());
- req->setRequestHeader(h);
- }
+ QHttpRequestHeader h = req->requestHeader();
+ if(h.path().isEmpty())
+ {
+ // note: the following qWarning is autotested. If you change it, change the test too.
+ qWarning("QHttp: empty path requested is invalid -- using '/'");
+ h.setRequest(h.method(), QLatin1String("/"), h.majorVersion(), h.minorVersion());
+ req->setRequestHeader(h);
+ }
- // contine below
- return addRequest(static_cast<QHttpRequest *>(req));
+ // contine below
+ return addRequest(static_cast<QHttpRequest *>(req));
}
-int QHttpPrivate::addRequest(QHttpRequest *req)
+int QHttpPrivate::addRequest(QHttpRequest * req)
{
- Q_Q(QHttp);
- pending.append(req);
+ Q_Q(QHttp);
+ pending.append(req);
- if (pending.count() == 1) {
- // don't emit the requestStarted() signal before the id is returned
- QMetaObject::invokeMethod(q, "_q_startNextRequest", Qt::QueuedConnection);
- }
- return req->id;
+ if(pending.count() == 1)
+ {
+ // don't emit the requestStarted() signal before the id is returned
+ QMetaObject::invokeMethod(q, "_q_startNextRequest", Qt::QueuedConnection);
+ }
+ return req->id;
}
void QHttpPrivate::_q_startNextRequest()
{
- Q_Q(QHttp);
- if (pending.isEmpty())
- return;
- QHttpRequest *r = pending.first();
+ Q_Q(QHttp);
+ if(pending.isEmpty())
+ return;
+ QHttpRequest * r = pending.first();
- error = QHttp::NoError;
- errorString = QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown error"));
+ error = QHttp::NoError;
+ errorString = QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown error"));
- if (q->bytesAvailable() != 0)
- q->readAll(); // clear the data
- emit q->requestStarted(r->id);
- r->start(q);
+ if(q->bytesAvailable() != 0)
+ q->readAll(); // clear the data
+ emit q->requestStarted(r->id);
+ r->start(q);
}
void QHttpPrivate::_q_slotSendRequest()
{
- if (hostName.isNull()) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "No server set to connect to")),
- QHttp::UnknownError);
- return;
- }
+ if(hostName.isNull())
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "No server set to connect to")),
+ QHttp::UnknownError);
+ return;
+ }
- QString connectionHost = hostName;
- int connectionPort = port;
- bool sslInUse = false;
+ QString connectionHost = hostName;
+ int connectionPort = port;
+ bool sslInUse = false;
#ifndef QT_NO_OPENSSL
- QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
- if (mode == QHttp::ConnectionModeHttps || (sslSocket && sslSocket->isEncrypted()))
- sslInUse = true;
+ QSslSocket * sslSocket = qobject_cast<QSslSocket *>(socket);
+ if(mode == QHttp::ConnectionModeHttps || (sslSocket && sslSocket->isEncrypted()))
+ sslInUse = true;
#endif
#ifndef QT_NO_NETWORKPROXY
- bool cachingProxyInUse = false;
- bool transparentProxyInUse = false;
- if (proxy.type() == QNetworkProxy::DefaultProxy)
- proxy = QNetworkProxy::applicationProxy();
+ bool cachingProxyInUse = false;
+ bool transparentProxyInUse = false;
+ if(proxy.type() == QNetworkProxy::DefaultProxy)
+ proxy = QNetworkProxy::applicationProxy();
- if (proxy.type() == QNetworkProxy::HttpCachingProxy) {
- if (proxy.hostName().isEmpty())
- proxy.setType(QNetworkProxy::NoProxy);
- else
- cachingProxyInUse = true;
- } else if (proxy.type() == QNetworkProxy::HttpProxy) {
- // Compatibility behaviour: HttpProxy can be used to mean both
- // transparent and caching proxy
- if (proxy.hostName().isEmpty()) {
- proxy.setType(QNetworkProxy::NoProxy);
- } else if (sslInUse) {
- // Disallow use of caching proxy with HTTPS; instead fall back to
- // transparent HTTP CONNECT proxying.
- transparentProxyInUse = true;
- } else {
- proxy.setType(QNetworkProxy::HttpCachingProxy);
- cachingProxyInUse = true;
- }
- }
+ if(proxy.type() == QNetworkProxy::HttpCachingProxy)
+ {
+ if(proxy.hostName().isEmpty())
+ proxy.setType(QNetworkProxy::NoProxy);
+ else
+ cachingProxyInUse = true;
+ }
+ else if(proxy.type() == QNetworkProxy::HttpProxy)
+ {
+ // Compatibility behaviour: HttpProxy can be used to mean both
+ // transparent and caching proxy
+ if(proxy.hostName().isEmpty())
+ {
+ proxy.setType(QNetworkProxy::NoProxy);
+ }
+ else if(sslInUse)
+ {
+ // Disallow use of caching proxy with HTTPS; instead fall back to
+ // transparent HTTP CONNECT proxying.
+ transparentProxyInUse = true;
+ }
+ else
+ {
+ proxy.setType(QNetworkProxy::HttpCachingProxy);
+ cachingProxyInUse = true;
+ }
+ }
- // Proxy support. Insert the Proxy-Authorization item into the
- // header before it's sent off to the proxy.
- if (cachingProxyInUse) {
- QUrl proxyUrl;
- proxyUrl.setScheme(QLatin1String("http"));
- proxyUrl.setHost(hostName);
- if (port && port != 80)
- proxyUrl.setPort(port);
- QString request = QString::fromLatin1(proxyUrl.resolved(QUrl::fromEncoded(header.path().toLatin1())).toEncoded());
+ // Proxy support. Insert the Proxy-Authorization item into the
+ // header before it's sent off to the proxy.
+ if(cachingProxyInUse)
+ {
+ QUrl proxyUrl;
+ proxyUrl.setScheme(QLatin1String("http"));
+ proxyUrl.setHost(hostName);
+ if(port && port != 80)
+ proxyUrl.setPort(port);
+ QString request = QString::fromLatin1(proxyUrl.resolved(QUrl::fromEncoded(header.path().toLatin1())).toEncoded());
- header.setRequest(header.method(), request, header.majorVersion(), header.minorVersion());
- header.setValue(QLatin1String("Proxy-Connection"), QLatin1String("keep-alive"));
+ header.setRequest(header.method(), request, header.majorVersion(), header.minorVersion());
+ header.setValue(QLatin1String("Proxy-Connection"), QLatin1String("keep-alive"));
- QHttpAuthenticatorPrivate *auth = QHttpAuthenticatorPrivate::getPrivate(proxyAuthenticator);
- if (auth && auth->method != QHttpAuthenticatorPrivate::None) {
- QByteArray response = auth->calculateResponse(header.method().toLatin1(), header.path().toLatin1());
- header.setValue(QLatin1String("Proxy-Authorization"), QString::fromLatin1(response));
- }
+ QHttpAuthenticatorPrivate * auth = QHttpAuthenticatorPrivate::getPrivate(proxyAuthenticator);
+ if(auth && auth->method != QHttpAuthenticatorPrivate::None)
+ {
+ QByteArray response = auth->calculateResponse(header.method().toLatin1(), header.path().toLatin1());
+ header.setValue(QLatin1String("Proxy-Authorization"), QString::fromLatin1(response));
+ }
- connectionHost = proxy.hostName();
- connectionPort = proxy.port();
- }
+ connectionHost = proxy.hostName();
+ connectionPort = proxy.port();
+ }
- if (transparentProxyInUse || sslInUse) {
- socket->setProxy(proxy);
- }
+ if(transparentProxyInUse || sslInUse)
+ {
+ socket->setProxy(proxy);
+ }
#endif
- // Username support. Insert the user and password into the query
- // string.
- QHttpAuthenticatorPrivate *auth = QHttpAuthenticatorPrivate::getPrivate(authenticator);
- if (auth && auth->method != QHttpAuthenticatorPrivate::None) {
- QByteArray response = auth->calculateResponse(header.method().toLatin1(), header.path().toLatin1());
- header.setValue(QLatin1String("Authorization"), QString::fromLatin1(response));
- }
+ // Username support. Insert the user and password into the query
+ // string.
+ QHttpAuthenticatorPrivate * auth = QHttpAuthenticatorPrivate::getPrivate(authenticator);
+ if(auth && auth->method != QHttpAuthenticatorPrivate::None)
+ {
+ QByteArray response = auth->calculateResponse(header.method().toLatin1(), header.path().toLatin1());
+ header.setValue(QLatin1String("Authorization"), QString::fromLatin1(response));
+ }
- // Do we need to setup a new connection or can we reuse an
- // existing one?
- if (socket->peerName() != connectionHost || socket->peerPort() != connectionPort
- || socket->state() != QTcpSocket::ConnectedState
+ // Do we need to setup a new connection or can we reuse an
+ // existing one?
+ if(socket->peerName() != connectionHost || socket->peerPort() != connectionPort
+ || socket->state() != QTcpSocket::ConnectedState
#ifndef QT_NO_OPENSSL
- || (sslSocket && sslSocket->isEncrypted() != (mode == QHttp::ConnectionModeHttps))
+ || (sslSocket && sslSocket->isEncrypted() != (mode == QHttp::ConnectionModeHttps))
#endif
- ) {
- socket->blockSignals(true);
- socket->abort();
- socket->blockSignals(false);
+ )
+ {
+ socket->blockSignals(true);
+ socket->abort();
+ socket->blockSignals(false);
- setState(QHttp::Connecting);
+ setState(QHttp::Connecting);
#ifndef QT_NO_OPENSSL
- if (sslSocket && mode == QHttp::ConnectionModeHttps) {
- sslSocket->connectToHostEncrypted(hostName, port);
- } else
+ if(sslSocket && mode == QHttp::ConnectionModeHttps)
+ {
+ sslSocket->connectToHostEncrypted(hostName, port);
+ }
+ else
#endif
- {
- socket->connectToHost(connectionHost, connectionPort);
- }
- } else {
- _q_slotConnected();
- }
-
+ {
+ socket->connectToHost(connectionHost, connectionPort);
+ }
+ }
+ else
+ {
+ _q_slotConnected();
+ }
}
void QHttpPrivate::finishedWithSuccess()
{
- Q_Q(QHttp);
- if (pending.isEmpty())
- return;
- QHttpRequest *r = pending.first();
+ Q_Q(QHttp);
+ if(pending.isEmpty())
+ return;
+ QHttpRequest * r = pending.first();
- // did we recurse?
- if (r->finished)
- return;
- r->finished = true;
- hasFinishedWithError = false;
+ // did we recurse?
+ if(r->finished)
+ return;
+ r->finished = true;
+ hasFinishedWithError = false;
- emit q->requestFinished(r->id, false);
- if (hasFinishedWithError) {
- // we recursed and changed into an error. The finishedWithError function
- // below has emitted the done(bool) signal and cleared the queue by now.
- return;
- }
+ emit q->requestFinished(r->id, false);
+ if(hasFinishedWithError)
+ {
+ // we recursed and changed into an error. The finishedWithError function
+ // below has emitted the done(bool) signal and cleared the queue by now.
+ return;
+ }
- pending.removeFirst();
- delete r;
+ pending.removeFirst();
+ delete r;
- if (pending.isEmpty()) {
- emit q->done(false);
- } else {
- _q_startNextRequest();
- }
+ if(pending.isEmpty())
+ {
+ emit q->done(false);
+ }
+ else
+ {
+ _q_startNextRequest();
+ }
}
-void QHttpPrivate::finishedWithError(const QString &detail, int errorCode)
+void QHttpPrivate::finishedWithError(const QString & detail, int errorCode)
{
- Q_Q(QHttp);
- if (pending.isEmpty())
- return;
- QHttpRequest *r = pending.first();
- hasFinishedWithError = true;
+ Q_Q(QHttp);
+ if(pending.isEmpty())
+ return;
+ QHttpRequest * r = pending.first();
+ hasFinishedWithError = true;
- error = QHttp::Error(errorCode);
- errorString = detail;
+ error = QHttp::Error(errorCode);
+ errorString = detail;
- // did we recurse?
- if (!r->finished) {
- r->finished = true;
- emit q->requestFinished(r->id, true);
- }
+ // did we recurse?
+ if(!r->finished)
+ {
+ r->finished = true;
+ emit q->requestFinished(r->id, true);
+ }
- while (!pending.isEmpty())
- delete pending.takeFirst();
- emit q->done(hasFinishedWithError);
+ while(!pending.isEmpty())
+ delete pending.takeFirst();
+ emit q->done(hasFinishedWithError);
}
void QHttpPrivate::_q_slotClosed()
{
- Q_Q(QHttp);
+ Q_Q(QHttp);
- if (state == QHttp::Reading) {
- if (response.hasKey(QLatin1String("content-length"))) {
- // We got Content-Length, so did we get all bytes?
- if (bytesDone + q->bytesAvailable() != response.contentLength()) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Wrong content length")), QHttp::WrongContentLength);
- }
- }
- } else if (state == QHttp::Connecting || state == QHttp::Sending) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Server closed connection unexpectedly")), QHttp::UnexpectedClose);
- }
+ if(state == QHttp::Reading)
+ {
+ if(response.hasKey(QLatin1String("content-length")))
+ {
+ // We got Content-Length, so did we get all bytes?
+ if(bytesDone + q->bytesAvailable() != response.contentLength())
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Wrong content length")), QHttp::WrongContentLength);
+ }
+ }
+ }
+ else if(state == QHttp::Connecting || state == QHttp::Sending)
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Server closed connection unexpectedly")), QHttp::UnexpectedClose);
+ }
- postDevice = 0;
- if (state != QHttp::Closing)
- setState(QHttp::Closing);
- QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
+ postDevice = 0;
+ if(state != QHttp::Closing)
+ setState(QHttp::Closing);
+ QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
}
void QHttpPrivate::_q_continuePost()
{
- if (pendingPost) {
- pendingPost = false;
- setState(QHttp::Sending);
- _q_slotBytesWritten(0);
- }
+ if(pendingPost)
+ {
+ pendingPost = false;
+ setState(QHttp::Sending);
+ _q_slotBytesWritten(0);
+ }
}
void QHttpPrivate::_q_slotConnected()
{
- if (state != QHttp::Sending) {
- bytesDone = 0;
- setState(QHttp::Sending);
- }
+ if(state != QHttp::Sending)
+ {
+ bytesDone = 0;
+ setState(QHttp::Sending);
+ }
- QString str = header.toString();
- bytesTotal = str.length();
- socket->write(str.toLatin1(), bytesTotal);
+ QString str = header.toString();
+ bytesTotal = str.length();
+ socket->write(str.toLatin1(), bytesTotal);
#if defined(QHTTP_DEBUG)
- qDebug("QHttp: write request header %p:\n---{\n%s}---", &header, str.toLatin1().constData());
+ qDebug("QHttp: write request header %p:\n---{\n%s}---", &header, str.toLatin1().constData());
#endif
- if (postDevice) {
- postDevice->seek(0); // reposition the device
- bytesTotal += postDevice->size();
- //check for 100-continue
- if (header.value(QLatin1String("expect")).contains(QLatin1String("100-continue"), Qt::CaseInsensitive)) {
- //create a time out for 2 secs.
- pendingPost = true;
- post100ContinueTimer.start(2000);
- }
- } else {
- bytesTotal += buffer.size();
- socket->write(buffer, buffer.size());
- }
+ if(postDevice)
+ {
+ postDevice->seek(0); // reposition the device
+ bytesTotal += postDevice->size();
+ //check for 100-continue
+ if(header.value(QLatin1String("expect")).contains(QLatin1String("100-continue"), Qt::CaseInsensitive))
+ {
+ //create a time out for 2 secs.
+ pendingPost = true;
+ post100ContinueTimer.start(2000);
+ }
+ }
+ else
+ {
+ bytesTotal += buffer.size();
+ socket->write(buffer, buffer.size());
+ }
}
void QHttpPrivate::_q_slotError(QAbstractSocket::SocketError err)
{
- Q_Q(QHttp);
- postDevice = 0;
+ Q_Q(QHttp);
+ postDevice = 0;
- if (state == QHttp::Connecting || state == QHttp::Reading || state == QHttp::Sending) {
- switch (err) {
- case QTcpSocket::ConnectionRefusedError:
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Connection refused (or timed out)")), QHttp::ConnectionRefused);
- break;
- case QTcpSocket::HostNotFoundError:
- finishedWithError(QString::fromLatin1(QT_TRANSLATE_NOOP("QHttp", "Host %1 not found"))
- .arg(socket->peerName()), QHttp::HostNotFound);
- break;
- case QTcpSocket::RemoteHostClosedError:
- if (state == QHttp::Sending && reconnectAttempts--) {
- setState(QHttp::Closing);
- setState(QHttp::Unconnected);
- socket->blockSignals(true);
- socket->abort();
- socket->blockSignals(false);
- QMetaObject::invokeMethod(q, "_q_slotSendRequest", Qt::QueuedConnection);
- return;
- }
- break;
+ if(state == QHttp::Connecting || state == QHttp::Reading || state == QHttp::Sending)
+ {
+ switch(err)
+ {
+ case QTcpSocket::ConnectionRefusedError:
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Connection refused (or timed out)")), QHttp::ConnectionRefused);
+ break;
+ case QTcpSocket::HostNotFoundError:
+ finishedWithError(QString::fromLatin1(QT_TRANSLATE_NOOP("QHttp", "Host %1 not found"))
+ .arg(socket->peerName()),
+ QHttp::HostNotFound);
+ break;
+ case QTcpSocket::RemoteHostClosedError:
+ if(state == QHttp::Sending && reconnectAttempts--)
+ {
+ setState(QHttp::Closing);
+ setState(QHttp::Unconnected);
+ socket->blockSignals(true);
+ socket->abort();
+ socket->blockSignals(false);
+ QMetaObject::invokeMethod(q, "_q_slotSendRequest", Qt::QueuedConnection);
+ return;
+ }
+ break;
#ifndef QT_NO_NETWORKPROXY
- case QTcpSocket::ProxyAuthenticationRequiredError:
- finishedWithError(socket->errorString(), QHttp::ProxyAuthenticationRequiredError);
- break;
+ case QTcpSocket::ProxyAuthenticationRequiredError:
+ finishedWithError(socket->errorString(), QHttp::ProxyAuthenticationRequiredError);
+ break;
#endif
- default:
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "HTTP request failed")), QHttp::UnknownError);
- break;
- }
- }
+ default:
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "HTTP request failed")), QHttp::UnknownError);
+ break;
+ }
+ }
- closeConn();
+ closeConn();
}
#ifndef QT_NO_OPENSSL
void QHttpPrivate::_q_slotEncryptedBytesWritten(qint64 written)
{
- Q_UNUSED(written);
- postMoreData();
+ Q_UNUSED(written);
+ postMoreData();
}
#endif
void QHttpPrivate::_q_slotBytesWritten(qint64 written)
{
- Q_Q(QHttp);
- bytesDone += written;
- emit q->dataSendProgress(bytesDone, bytesTotal);
- postMoreData();
+ Q_Q(QHttp);
+ bytesDone += written;
+ emit q->dataSendProgress(bytesDone, bytesTotal);
+ postMoreData();
}
// Send the POST data
void QHttpPrivate::postMoreData()
{
- if (pendingPost)
- return;
+ if(pendingPost)
+ return;
- if (!postDevice)
- return;
+ if(!postDevice)
+ return;
- // the following is backported code from Qt 4.6 QNetworkAccessManager.
- // We also have to check the encryptedBytesToWrite() if it is an SSL socket.
+// the following is backported code from Qt 4.6 QNetworkAccessManager.
+// We also have to check the encryptedBytesToWrite() if it is an SSL socket.
#ifndef QT_NO_OPENSSL
- QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket);
- // if it is really an ssl socket, check more than just bytesToWrite()
- if ((socket->bytesToWrite() + (sslSocket ? sslSocket->encryptedBytesToWrite() : 0)) == 0) {
+ QSslSocket * sslSocket = qobject_cast<QSslSocket *>(socket);
+ // if it is really an ssl socket, check more than just bytesToWrite()
+ if((socket->bytesToWrite() + (sslSocket ? sslSocket->encryptedBytesToWrite() : 0)) == 0)
+ {
#else
- if (socket->bytesToWrite() == 0) {
+ if(socket->bytesToWrite() == 0)
+ {
#endif
- int max = qMin<qint64>(4096, postDevice->size() - postDevice->pos());
- QByteArray arr;
- arr.resize(max);
+ int max = qMin<qint64>(4096, postDevice->size() - postDevice->pos());
+ QByteArray arr;
+ arr.resize(max);
- int n = postDevice->read(arr.data(), max);
- if (n < 0) {
- qWarning("Could not read enough bytes from the device");
- closeConn();
- return;
- }
- if (postDevice->atEnd()) {
- postDevice = 0;
- }
+ int n = postDevice->read(arr.data(), max);
+ if(n < 0)
+ {
+ qWarning("Could not read enough bytes from the device");
+ closeConn();
+ return;
+ }
+ if(postDevice->atEnd())
+ {
+ postDevice = 0;
+ }
- socket->write(arr, n);
- }
+ socket->write(arr, n);
+ }
}
void QHttpPrivate::_q_slotReadyRead()
{
- Q_Q(QHttp);
- QHttp::State oldState = state;
- if (state != QHttp::Reading) {
- setState(QHttp::Reading);
- readHeader = true;
- headerStr = QLatin1String("");
- bytesDone = 0;
- chunkedSize = -1;
- repost = false;
- }
+ Q_Q(QHttp);
+ QHttp::State oldState = state;
+ if(state != QHttp::Reading)
+ {
+ setState(QHttp::Reading);
+ readHeader = true;
+ headerStr = QLatin1String("");
+ bytesDone = 0;
+ chunkedSize = -1;
+ repost = false;
+ }
- while (readHeader) {
- bool end = false;
- QString tmp;
- while (!end && socket->canReadLine()) {
- tmp = QString::fromLatin1(socket->readLine());
- if (tmp == QLatin1String("\r\n") || tmp == QLatin1String("\n") || tmp.isEmpty())
- end = true;
- else
- headerStr += tmp;
- }
+ while(readHeader)
+ {
+ bool end = false;
+ QString tmp;
+ while(!end && socket->canReadLine())
+ {
+ tmp = QString::fromLatin1(socket->readLine());
+ if(tmp == QLatin1String("\r\n") || tmp == QLatin1String("\n") || tmp.isEmpty())
+ end = true;
+ else
+ headerStr += tmp;
+ }
- if (!end)
- return;
+ if(!end)
+ return;
- response = QHttpResponseHeader(headerStr);
- headerStr = QLatin1String("");
+ response = QHttpResponseHeader(headerStr);
+ headerStr = QLatin1String("");
#if defined(QHTTP_DEBUG)
- qDebug("QHttp: read response header:\n---{\n%s}---", response.toString().toLatin1().constData());
+ qDebug("QHttp: read response header:\n---{\n%s}---", response.toString().toLatin1().constData());
#endif
- // Check header
- if (!response.isValid()) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP response header")),
- QHttp::InvalidResponseHeader);
- closeConn();
- return;
- }
+ // Check header
+ if(!response.isValid())
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP response header")),
+ QHttp::InvalidResponseHeader);
+ closeConn();
+ return;
+ }
- int statusCode = response.statusCode();
- if (statusCode == 401 || statusCode == 407) { // (Proxy) Authentication required
- QHttpAuthenticator *auth =
+ int statusCode = response.statusCode();
+ if(statusCode == 401 || statusCode == 407)
+ { // (Proxy) Authentication required
+ QHttpAuthenticator * auth =
#ifndef QT_NO_NETWORKPROXY
- statusCode == 407
- ? &proxyAuthenticator :
+ statusCode == 407
+ ? &proxyAuthenticator
+ :
#endif
- &authenticator;
- if (auth->isNull())
- auth->detach();
- QHttpAuthenticatorPrivate *priv = QHttpAuthenticatorPrivate::getPrivate(*auth);
- priv->parseHttpResponse(response, (statusCode == 407));
- if (priv->phase == QHttpAuthenticatorPrivate::Done) {
- socket->blockSignals(true);
+ &authenticator;
+ if(auth->isNull())
+ auth->detach();
+ QHttpAuthenticatorPrivate * priv = QHttpAuthenticatorPrivate::getPrivate(*auth);
+ priv->parseHttpResponse(response, (statusCode == 407));
+ if(priv->phase == QHttpAuthenticatorPrivate::Done)
+ {
+ socket->blockSignals(true);
#ifndef QT_NO_NETWORKPROXY
- if (statusCode == 407) {
- //need to emit a QAuthenticator to maintain source compatibility
- QAuthenticator qauthClean = auth->toQAuthenticator();
- QAuthenticator qauthToEmit = qauthClean;
- emit q->proxyAuthenticationRequired(proxy, &qauthToEmit);
- if (qauthClean != qauthToEmit) {
- //user changed something, copy back (which will reset our state)
- *auth = qauthToEmit;
- }
- } else
+ if(statusCode == 407)
+ {
+ //need to emit a QAuthenticator to maintain source compatibility
+ QAuthenticator qauthClean = auth->toQAuthenticator();
+ QAuthenticator qauthToEmit = qauthClean;
+ emit q->proxyAuthenticationRequired(proxy, &qauthToEmit);
+ if(qauthClean != qauthToEmit)
+ {
+ //user changed something, copy back (which will reset our state)
+ *auth = qauthToEmit;
+ }
+ }
+ else
#endif
- {
- //need to emit a QAuthenticator to maintain source compatibility
- QAuthenticator qauthClean = auth->toQAuthenticator();
- QAuthenticator qauthToEmit = qauthClean;
- emit q->authenticationRequired(hostName, port, &qauthToEmit);
- if (qauthClean != qauthToEmit) {
- //user changed something, copy back (which will reset our state)
- *auth = qauthToEmit;
- }
- }
- socket->blockSignals(false);
- } else if (priv->phase == QHttpAuthenticatorPrivate::Invalid) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown authentication method")),
- QHttp::AuthenticationRequiredError);
- closeConn();
- return;
- }
+ {
+ //need to emit a QAuthenticator to maintain source compatibility
+ QAuthenticator qauthClean = auth->toQAuthenticator();
+ QAuthenticator qauthToEmit = qauthClean;
+ emit q->authenticationRequired(hostName, port, &qauthToEmit);
+ if(qauthClean != qauthToEmit)
+ {
+ //user changed something, copy back (which will reset our state)
+ *auth = qauthToEmit;
+ }
+ }
+ socket->blockSignals(false);
+ }
+ else if(priv->phase == QHttpAuthenticatorPrivate::Invalid)
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown authentication method")),
+ QHttp::AuthenticationRequiredError);
+ closeConn();
+ return;
+ }
- // priv->phase will get reset to QHttpAuthenticatorPrivate::Start if the authenticator got modified in the signal above.
- if (priv->phase == QHttpAuthenticatorPrivate::Done) {
+ // priv->phase will get reset to QHttpAuthenticatorPrivate::Start if the authenticator got modified in the signal above.
+ if(priv->phase == QHttpAuthenticatorPrivate::Done)
+ {
#ifndef QT_NO_NETWORKPROXY
- if (statusCode == 407)
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Proxy authentication required")),
- QHttp::ProxyAuthenticationRequiredError);
- else
+ if(statusCode == 407)
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Proxy authentication required")),
+ QHttp::ProxyAuthenticationRequiredError);
+ else
#endif
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Authentication required")),
- QHttp::AuthenticationRequiredError);
- closeConn();
- return;
- } else {
- // close the connection if it isn't already and reconnect using the chosen authentication method
- bool willClose = (response.value(QLatin1String("proxy-connection")).toLower() == QLatin1String("close"))
- || (response.value(QLatin1String("connection")).toLower() == QLatin1String("close"));
- if (willClose) {
- if (socket) {
- setState(QHttp::Closing);
- socket->blockSignals(true);
- socket->close();
- socket->blockSignals(false);
- socket->readAll();
- }
- _q_slotSendRequest();
- return;
- } else {
- repost = true;
- }
- }
- } else {
- buffer.clear();
- }
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Authentication required")),
+ QHttp::AuthenticationRequiredError);
+ closeConn();
+ return;
+ }
+ else
+ {
+ // close the connection if it isn't already and reconnect using the chosen authentication method
+ bool willClose = (response.value(QLatin1String("proxy-connection")).toLower() == QLatin1String("close"))
+ || (response.value(QLatin1String("connection")).toLower() == QLatin1String("close"));
+ if(willClose)
+ {
+ if(socket)
+ {
+ setState(QHttp::Closing);
+ socket->blockSignals(true);
+ socket->close();
+ socket->blockSignals(false);
+ socket->readAll();
+ }
+ _q_slotSendRequest();
+ return;
+ }
+ else
+ {
+ repost = true;
+ }
+ }
+ }
+ else
+ {
+ buffer.clear();
+ }
- if (response.statusCode() == 100 && pendingPost) {
- // if we have pending POST, start sending data otherwise ignore
- post100ContinueTimer.stop();
- QMetaObject::invokeMethod(q, "_q_continuePost", Qt::QueuedConnection);
- return;
- }
+ if(response.statusCode() == 100 && pendingPost)
+ {
+ // if we have pending POST, start sending data otherwise ignore
+ post100ContinueTimer.stop();
+ QMetaObject::invokeMethod(q, "_q_continuePost", Qt::QueuedConnection);
+ return;
+ }
- // The 100-continue header is ignored (in case of no 'expect:100-continue' header),
- // because when using the POST method, we send both the request header and data in
- // one chunk.
- if (response.statusCode() != 100) {
- post100ContinueTimer.stop();
- pendingPost = false;
- readHeader = false;
- if (response.hasKey(QLatin1String("transfer-encoding")) &&
- response.value(QLatin1String("transfer-encoding")).toLower().contains(QLatin1String("chunked")))
- chunkedSize = 0;
+ // The 100-continue header is ignored (in case of no 'expect:100-continue' header),
+ // because when using the POST method, we send both the request header and data in
+ // one chunk.
+ if(response.statusCode() != 100)
+ {
+ post100ContinueTimer.stop();
+ pendingPost = false;
+ readHeader = false;
+ if(response.hasKey(QLatin1String("transfer-encoding")) && response.value(QLatin1String("transfer-encoding")).toLower().contains(QLatin1String("chunked")))
+ chunkedSize = 0;
- if (!repost)
- emit q->responseHeaderReceived(response);
- if (state == QHttp::Unconnected || state == QHttp::Closing)
- return;
- } else {
- // Restore the state, the next incoming data will be treated as if
- // we never say the 100 response.
- state = oldState;
- }
- }
+ if(!repost)
+ emit q->responseHeaderReceived(response);
+ if(state == QHttp::Unconnected || state == QHttp::Closing)
+ return;
+ }
+ else
+ {
+ // Restore the state, the next incoming data will be treated as if
+ // we never say the 100 response.
+ state = oldState;
+ }
+ }
- bool everythingRead = false;
+ bool everythingRead = false;
- if (q->currentRequest().method() == QLatin1String("HEAD") ||
- response.statusCode() == 304 || response.statusCode() == 204 ||
- response.statusCode() == 205) {
- // HEAD requests have only headers as replies
- // These status codes never have a body:
- // 304 Not Modified
- // 204 No Content
- // 205 Reset Content
- everythingRead = true;
- } else {
- qint64 n = socket->bytesAvailable();
- QByteArray *arr = 0;
- if (chunkedSize != -1) {
- // transfer-encoding is chunked
- for (;;) {
- // get chunk size
- if (chunkedSize == 0) {
- if (!socket->canReadLine())
- break;
- QString sizeString = QString::fromLatin1(socket->readLine());
- int tPos = sizeString.indexOf(QLatin1Char(';'));
- if (tPos != -1)
- sizeString.truncate(tPos);
- bool ok;
- chunkedSize = sizeString.toInt(&ok, 16);
- if (!ok) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP chunked body")),
- QHttp::WrongContentLength);
- closeConn();
- delete arr;
- return;
- }
- if (chunkedSize == 0) // last-chunk
- chunkedSize = -2;
- }
+ if(q->currentRequest().method() == QLatin1String("HEAD") || response.statusCode() == 304 || response.statusCode() == 204 || response.statusCode() == 205)
+ {
+ // HEAD requests have only headers as replies
+ // These status codes never have a body:
+ // 304 Not Modified
+ // 204 No Content
+ // 205 Reset Content
+ everythingRead = true;
+ }
+ else
+ {
+ qint64 n = socket->bytesAvailable();
+ QByteArray * arr = 0;
+ if(chunkedSize != -1)
+ {
+ // transfer-encoding is chunked
+ for(;;)
+ {
+ // get chunk size
+ if(chunkedSize == 0)
+ {
+ if(!socket->canReadLine())
+ break;
+ QString sizeString = QString::fromLatin1(socket->readLine());
+ int tPos = sizeString.indexOf(QLatin1Char(';'));
+ if(tPos != -1)
+ sizeString.truncate(tPos);
+ bool ok;
+ chunkedSize = sizeString.toInt(&ok, 16);
+ if(!ok)
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP chunked body")),
+ QHttp::WrongContentLength);
+ closeConn();
+ delete arr;
+ return;
+ }
+ if(chunkedSize == 0) // last-chunk
+ chunkedSize = -2;
+ }
- // read trailer
- while (chunkedSize == -2 && socket->canReadLine()) {
- QString read = QString::fromLatin1(socket->readLine());
- if (read == QLatin1String("\r\n") || read == QLatin1String("\n"))
- chunkedSize = -1;
- }
- if (chunkedSize == -1) {
- everythingRead = true;
- break;
- }
+ // read trailer
+ while(chunkedSize == -2 && socket->canReadLine())
+ {
+ QString read = QString::fromLatin1(socket->readLine());
+ if(read == QLatin1String("\r\n") || read == QLatin1String("\n"))
+ chunkedSize = -1;
+ }
+ if(chunkedSize == -1)
+ {
+ everythingRead = true;
+ break;
+ }
- // make sure that you can read the terminating CRLF,
- // otherwise wait until next time...
- n = socket->bytesAvailable();
- if (n == 0)
- break;
- if (n == chunkedSize || n == chunkedSize+1) {
- n = chunkedSize - 1;
- if (n == 0)
- break;
- }
+ // make sure that you can read the terminating CRLF,
+ // otherwise wait until next time...
+ n = socket->bytesAvailable();
+ if(n == 0)
+ break;
+ if(n == chunkedSize || n == chunkedSize + 1)
+ {
+ n = chunkedSize - 1;
+ if(n == 0)
+ break;
+ }
- // read data
- qint64 toRead = chunkedSize < 0 ? n : qMin(n, chunkedSize);
- if (!arr)
- arr = new QByteArray;
- uint oldArrSize = arr->size();
- arr->resize(oldArrSize + toRead);
- qint64 read = socket->read(arr->data()+oldArrSize, toRead);
- arr->resize(oldArrSize + read);
+ // read data
+ qint64 toRead = chunkedSize < 0 ? n : qMin(n, chunkedSize);
+ if(!arr)
+ arr = new QByteArray;
+ uint oldArrSize = arr->size();
+ arr->resize(oldArrSize + toRead);
+ qint64 read = socket->read(arr->data() + oldArrSize, toRead);
+ arr->resize(oldArrSize + read);
- chunkedSize -= read;
+ chunkedSize -= read;
- if (chunkedSize == 0 && n - read >= 2) {
- // read terminating CRLF
- char tmp[2];
- socket->read(tmp, 2);
- if (tmp[0] != '\r' || tmp[1] != '\n') {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP chunked body")),
- QHttp::WrongContentLength);
- closeConn();
- delete arr;
- return;
- }
- }
- }
- } else if (response.hasContentLength()) {
- if (repost && (n < response.contentLength())) {
- // wait for the content to be available fully
- // if repost is required, the content is ignored
- return;
- }
- n = qMin(qint64(response.contentLength() - bytesDone), n);
- if (n > 0) {
- arr = new QByteArray;
- arr->resize(n);
- qint64 read = socket->read(arr->data(), n);
- arr->resize(read);
- }
- if (bytesDone + q->bytesAvailable() + n == response.contentLength())
- everythingRead = true;
- } else if (n > 0) {
- // workaround for VC++ bug
- QByteArray temp = socket->readAll();
- arr = new QByteArray(temp);
- }
+ if(chunkedSize == 0 && n - read >= 2)
+ {
+ // read terminating CRLF
+ char tmp[2];
+ socket->read(tmp, 2);
+ if(tmp[0] != '\r' || tmp[1] != '\n')
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Invalid HTTP chunked body")),
+ QHttp::WrongContentLength);
+ closeConn();
+ delete arr;
+ return;
+ }
+ }
+ }
+ }
+ else if(response.hasContentLength())
+ {
+ if(repost && (n < response.contentLength()))
+ {
+ // wait for the content to be available fully
+ // if repost is required, the content is ignored
+ return;
+ }
+ n = qMin(qint64(response.contentLength() - bytesDone), n);
+ if(n > 0)
+ {
+ arr = new QByteArray;
+ arr->resize(n);
+ qint64 read = socket->read(arr->data(), n);
+ arr->resize(read);
+ }
+ if(bytesDone + q->bytesAvailable() + n == response.contentLength())
+ everythingRead = true;
+ }
+ else if(n > 0)
+ {
+ // workaround for VC++ bug
+ QByteArray temp = socket->readAll();
+ arr = new QByteArray(temp);
+ }
- if (arr && !repost) {
- n = arr->size();
- if (toDevice) {
- qint64 bytesWritten;
- bytesWritten = toDevice->write(*arr, n);
- delete arr;
- arr = 0;
- // if writing to the device does not succeed, quit with error
- if (bytesWritten == -1 || bytesWritten < n) {
- finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Error writing response to device")), QHttp::UnknownError);
- } else {
- bytesDone += bytesWritten;
+ if(arr && !repost)
+ {
+ n = arr->size();
+ if(toDevice)
+ {
+ qint64 bytesWritten;
+ bytesWritten = toDevice->write(*arr, n);
+ delete arr;
+ arr = 0;
+ // if writing to the device does not succeed, quit with error
+ if(bytesWritten == -1 || bytesWritten < n)
+ {
+ finishedWithError(QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Error writing response to device")), QHttp::UnknownError);
+ }
+ else
+ {
+ bytesDone += bytesWritten;
#if defined(QHTTP_DEBUG)
- qDebug("QHttp::_q_slotReadyRead(): read %lld bytes (%lld bytes done)", n, bytesDone);
+ qDebug("QHttp::_q_slotReadyRead(): read %lld bytes (%lld bytes done)", n, bytesDone);
#endif
- }
- if (response.hasContentLength())
- emit q->dataReadProgress(bytesDone, response.contentLength());
- else
- emit q->dataReadProgress(bytesDone, 0);
- } else {
- char *ptr = rba.reserve(arr->size());
- memcpy(ptr, arr->data(), arr->size());
- delete arr;
- arr = 0;
+ }
+ if(response.hasContentLength())
+ emit q->dataReadProgress(bytesDone, response.contentLength());
+ else
+ emit q->dataReadProgress(bytesDone, 0);
+ }
+ else
+ {
+ char * ptr = rba.reserve(arr->size());
+ memcpy(ptr, arr->data(), arr->size());
+ delete arr;
+ arr = 0;
#if defined(QHTTP_DEBUG)
- qDebug("QHttp::_q_slotReadyRead(): read %lld bytes (%lld bytes done)", n, bytesDone + q->bytesAvailable());
+ qDebug("QHttp::_q_slotReadyRead(): read %lld bytes (%lld bytes done)", n, bytesDone + q->bytesAvailable());
#endif
- if (response.hasContentLength())
- emit q->dataReadProgress(bytesDone + q->bytesAvailable(), response.contentLength());
- else
- emit q->dataReadProgress(bytesDone + q->bytesAvailable(), 0);
- emit q->readyRead(response);
- }
- }
+ if(response.hasContentLength())
+ emit q->dataReadProgress(bytesDone + q->bytesAvailable(), response.contentLength());
+ else
+ emit q->dataReadProgress(bytesDone + q->bytesAvailable(), 0);
+ emit q->readyRead(response);
+ }
+ }
- delete arr;
- }
+ delete arr;
+ }
- if (everythingRead) {
- if (repost) {
- _q_slotSendRequest();
- return;
- }
- // Handle "Connection: close"
- if (response.value(QLatin1String("connection")).toLower() == QLatin1String("close")) {
- closeConn();
- } else {
- setState(QHttp::Connected);
- // Start a timer, so that we emit the keep alive signal
- // "after" this method returned.
- QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
- }
- }
+ if(everythingRead)
+ {
+ if(repost)
+ {
+ _q_slotSendRequest();
+ return;
+ }
+ // Handle "Connection: close"
+ if(response.value(QLatin1String("connection")).toLower() == QLatin1String("close"))
+ {
+ closeConn();
+ }
+ else
+ {
+ setState(QHttp::Connected);
+ // Start a timer, so that we emit the keep alive signal
+ // "after" this method returned.
+ QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
+ }
+ }
}
void QHttpPrivate::_q_slotDoFinished()
{
- if (state == QHttp::Connected) {
- finishedWithSuccess();
- } else if (state != QHttp::Unconnected) {
- setState(QHttp::Unconnected);
- finishedWithSuccess();
- }
+ if(state == QHttp::Connected)
+ {
+ finishedWithSuccess();
+ }
+ else if(state != QHttp::Unconnected)
+ {
+ setState(QHttp::Unconnected);
+ finishedWithSuccess();
+ }
}
-
/*!
Returns the current state of the object. When the state changes,
the stateChanged() signal is emitted.
@@ -3059,7 +3220,7 @@ void QHttpPrivate::_q_slotDoFinished()
*/
QHttp::State QHttp::state() const
{
- return d->state;
+ return d->state;
}
/*!
@@ -3071,7 +3232,7 @@ QHttp::State QHttp::state() const
*/
QHttp::Error QHttp::error() const
{
- return d->error;
+ return d->error;
}
/*!
@@ -3082,79 +3243,84 @@ QHttp::Error QHttp::error() const
*/
QString QHttp::errorString() const
{
- return d->errorString;
+ return d->errorString;
}
void QHttpPrivate::setState(int s)
{
- Q_Q(QHttp);
+ Q_Q(QHttp);
#if defined(QHTTP_DEBUG)
- qDebug("QHttp state changed %d -> %d", state, s);
+ qDebug("QHttp state changed %d -> %d", state, s);
#endif
- state = QHttp::State(s);
- emit q->stateChanged(s);
+ state = QHttp::State(s);
+ emit q->stateChanged(s);
}
void QHttpPrivate::closeConn()
{
- Q_Q(QHttp);
- // If no connection is open -> ignore
- if (state == QHttp::Closing || state == QHttp::Unconnected)
- return;
+ Q_Q(QHttp);
+ // If no connection is open -> ignore
+ if(state == QHttp::Closing || state == QHttp::Unconnected)
+ return;
- postDevice = 0;
- setState(QHttp::Closing);
+ postDevice = 0;
+ setState(QHttp::Closing);
- // Already closed ?
- if (!socket || !socket->isOpen()) {
- QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
- } else {
- // Close now.
- socket->close();
- }
+ // Already closed ?
+ if(!socket || !socket->isOpen())
+ {
+ QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);
+ }
+ else
+ {
+ // Close now.
+ socket->close();
+ }
}
-void QHttpPrivate::setSock(QTcpSocket *sock)
+void QHttpPrivate::setSock(QTcpSocket * sock)
{
- Q_Q(const QHttp);
+ Q_Q(const QHttp);
- // disconnect all existing signals
- if (socket)
- socket->disconnect();
- if (deleteSocket)
- delete socket;
+ // disconnect all existing signals
+ if(socket)
+ socket->disconnect();
+ if(deleteSocket)
+ delete socket;
- // use the new QTcpSocket socket, or create one if socket is 0.
- deleteSocket = (sock == 0);
- socket = sock;
- if (!socket) {
+ // use the new QTcpSocket socket, or create one if socket is 0.
+ deleteSocket = (sock == 0);
+ socket = sock;
+ if(!socket)
+ {
#ifndef QT_NO_OPENSSL
- if (QSslSocket::supportsSsl())
- socket = new QSslSocket();
- else
+ if(QSslSocket::supportsSsl())
+ socket = new QSslSocket();
+ else
#endif
- socket = new QTcpSocket();
- }
+ socket = new QTcpSocket();
+ }
- // connect all signals
- QObject::connect(socket, SIGNAL(connected()), q, SLOT(_q_slotConnected()));
- QObject::connect(socket, SIGNAL(disconnected()), q, SLOT(_q_slotClosed()));
- QObject::connect(socket, SIGNAL(readyRead()), q, SLOT(_q_slotReadyRead()));
- QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), q, SLOT(_q_slotError(QAbstractSocket::SocketError)));
- QObject::connect(socket, SIGNAL(bytesWritten(qint64)),
- q, SLOT(_q_slotBytesWritten(qint64)));
+ // connect all signals
+ QObject::connect(socket, SIGNAL(connected()), q, SLOT(_q_slotConnected()));
+ QObject::connect(socket, SIGNAL(disconnected()), q, SLOT(_q_slotClosed()));
+ QObject::connect(socket, SIGNAL(readyRead()), q, SLOT(_q_slotReadyRead()));
+ QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), q, SLOT(_q_slotError(QAbstractSocket::SocketError)));
+ QObject::connect(socket, SIGNAL(bytesWritten(qint64)),
+ q, SLOT(_q_slotBytesWritten(qint64)));
#ifndef QT_NO_NETWORKPROXY
- QObject::connect(socket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
- q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+ QObject::connect(socket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)),
+ q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)));
#endif
#ifndef QT_NO_OPENSSL
- if (qobject_cast<QSslSocket *>(socket)) {
- QObject::connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
- q, SIGNAL(sslErrors(QList<QSslError>)));
- QObject::connect(socket, SIGNAL(encryptedBytesWritten(qint64)),
- q, SLOT(_q_slotEncryptedBytesWritten(qint64)));
- }
+ if(qobject_cast<QSslSocket *>(socket))
+ {
+ QObject::connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
+ q, SIGNAL(sslErrors(QList<QSslError>)));
+ QObject::connect(socket, SIGNAL(encryptedBytesWritten(qint64)),
+ q, SLOT(_q_slotEncryptedBytesWritten(qint64)));
+ }
#endif
}
@@ -3170,9 +3336,9 @@ void QHttpPrivate::setSock(QTcpSocket *sock)
#ifndef QT_NO_OPENSSL
void QHttp::ignoreSslErrors()
{
- QSslSocket *sslSocket = qobject_cast<QSslSocket *>(d->socket);
- if (sslSocket)
- sslSocket->ignoreSslErrors();
+ QSslSocket * sslSocket = qobject_cast<QSslSocket *>(d->socket);
+ if(sslSocket)
+ sslSocket->ignoreSslErrors();
}
#endif
diff --git a/src/modules/objects/qthttp/qhttp.h b/src/modules/objects/qthttp/qhttp.h
index f8fe7614c..f40361656 100644
--- a/src/modules/objects/qthttp/qhttp.h
+++ b/src/modules/objects/qthttp/qhttp.h
@@ -64,237 +64,239 @@ class QHttpHeaderPrivate;
class QHttpHeader
{
public:
- QHttpHeader();
- QHttpHeader(const QHttpHeader &header);
- QHttpHeader(const QString &str);
- virtual ~QHttpHeader();
+ QHttpHeader();
+ QHttpHeader(const QHttpHeader & header);
+ QHttpHeader(const QString & str);
+ virtual ~QHttpHeader();
- QHttpHeader &operator=(const QHttpHeader &h);
+ QHttpHeader & operator=(const QHttpHeader & h);
- void setValue(const QString &key, const QString &value);
- void setValues(const QList<QPair<QString, QString> > &values);
- void addValue(const QString &key, const QString &value);
- QList<QPair<QString, QString> > values() const;
- bool hasKey(const QString &key) const;
- QStringList keys() const;
- QString value(const QString &key) const;
- QStringList allValues(const QString &key) const;
- void removeValue(const QString &key);
- void removeAllValues(const QString &key);
+ void setValue(const QString & key, const QString & value);
+ void setValues(const QList<QPair<QString, QString>> & values);
+ void addValue(const QString & key, const QString & value);
+ QList<QPair<QString, QString>> values() const;
+ bool hasKey(const QString & key) const;
+ QStringList keys() const;
+ QString value(const QString & key) const;
+ QStringList allValues(const QString & key) const;
+ void removeValue(const QString & key);
+ void removeAllValues(const QString & key);
- // ### Qt 5: change to qint64
- bool hasContentLength() const;
- uint contentLength() const;
- void setContentLength(int len);
+ // ### Qt 5: change to qint64
+ bool hasContentLength() const;
+ uint contentLength() const;
+ void setContentLength(int len);
- bool hasContentType() const;
- QString contentType() const;
- void setContentType(const QString &type);
+ bool hasContentType() const;
+ QString contentType() const;
+ void setContentType(const QString & type);
- virtual QString toString() const;
- bool isValid() const;
+ virtual QString toString() const;
+ bool isValid() const;
- virtual int majorVersion() const = 0;
- virtual int minorVersion() const = 0;
+ virtual int majorVersion() const = 0;
+ virtual int minorVersion() const = 0;
protected:
- virtual bool parseLine(const QString &line, int number);
- bool parse(const QString &str);
- void setValid(bool);
+ virtual bool parseLine(const QString & line, int number);
+ bool parse(const QString & str);
+ void setValid(bool);
- QHttpHeader(QHttpHeaderPrivate &dd, const QString &str = QString());
- QHttpHeader(QHttpHeaderPrivate &dd, const QHttpHeader &header);
- QScopedPointer<QHttpHeaderPrivate> d_ptr;
+ QHttpHeader(QHttpHeaderPrivate & dd, const QString & str = QString());
+ QHttpHeader(QHttpHeaderPrivate & dd, const QHttpHeader & header);
+ QScopedPointer<QHttpHeaderPrivate> d_ptr;
private:
- Q_DECLARE_PRIVATE(QHttpHeader)
+ Q_DECLARE_PRIVATE(QHttpHeader)
};
class QHttpResponseHeaderPrivate;
class QHttpResponseHeader : public QHttpHeader
{
public:
- QHttpResponseHeader();
- QHttpResponseHeader(const QHttpResponseHeader &header);
- QHttpResponseHeader(const QString &str);
- QHttpResponseHeader(int code, const QString &text = QString(), int majorVer = 1, int minorVer = 1);
- QHttpResponseHeader &operator=(const QHttpResponseHeader &header);
+ QHttpResponseHeader();
+ QHttpResponseHeader(const QHttpResponseHeader & header);
+ QHttpResponseHeader(const QString & str);
+ QHttpResponseHeader(int code, const QString & text = QString(), int majorVer = 1, int minorVer = 1);
+ QHttpResponseHeader & operator=(const QHttpResponseHeader & header);
- void setStatusLine(int code, const QString &text = QString(), int majorVer = 1, int minorVer = 1);
+ void setStatusLine(int code, const QString & text = QString(), int majorVer = 1, int minorVer = 1);
- int statusCode() const;
- QString reasonPhrase() const;
+ int statusCode() const;
+ QString reasonPhrase() const;
- int majorVersion() const;
- int minorVersion() const;
+ int majorVersion() const;
+ int minorVersion() const;
- QString toString() const;
+ QString toString() const;
protected:
- bool parseLine(const QString &line, int number);
+ bool parseLine(const QString & line, int number);
private:
- Q_DECLARE_PRIVATE(QHttpResponseHeader)
- friend class QHttpPrivate;
+ Q_DECLARE_PRIVATE(QHttpResponseHeader)
+ friend class QHttpPrivate;
};
class QHttpRequestHeaderPrivate;
class QHttpRequestHeader : public QHttpHeader
{
public:
- QHttpRequestHeader();
- QHttpRequestHeader(const QString &method, const QString &path, int majorVer = 1, int minorVer = 1);
- QHttpRequestHeader(const QHttpRequestHeader &header);
- QHttpRequestHeader(const QString &str);
- QHttpRequestHeader &operator=(const QHttpRequestHeader &header);
+ QHttpRequestHeader();
+ QHttpRequestHeader(const QString & method, const QString & path, int majorVer = 1, int minorVer = 1);
+ QHttpRequestHeader(const QHttpRequestHeader & header);
+ QHttpRequestHeader(const QString & str);
+ QHttpRequestHeader & operator=(const QHttpRequestHeader & header);
- void setRequest(const QString &method, const QString &path, int majorVer = 1, int minorVer = 1);
+ void setRequest(const QString & method, const QString & path, int majorVer = 1, int minorVer = 1);
- QString method() const;
- QString path() const;
+ QString method() const;
+ QString path() const;
- int majorVersion() const;
- int minorVersion() const;
+ int majorVersion() const;
+ int minorVersion() const;
- QString toString() const;
+ QString toString() const;
protected:
- bool parseLine(const QString &line, int number);
+ bool parseLine(const QString & line, int number);
private:
- Q_DECLARE_PRIVATE(QHttpRequestHeader)
+ Q_DECLARE_PRIVATE(QHttpRequestHeader)
};
class QHttp : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum ConnectionMode {
- ConnectionModeHttp,
- ConnectionModeHttps
- };
+ enum ConnectionMode
+ {
+ ConnectionModeHttp,
+ ConnectionModeHttps
+ };
- explicit QHttp(QObject *parent = 0);
- QHttp(const QString &hostname, quint16 port = 80, QObject *parent = 0);
- QHttp(const QString &hostname, ConnectionMode mode, quint16 port = 0, QObject *parent = 0);
- virtual ~QHttp();
+ explicit QHttp(QObject * parent = 0);
+ QHttp(const QString & hostname, quint16 port = 80, QObject * parent = 0);
+ QHttp(const QString & hostname, ConnectionMode mode, quint16 port = 0, QObject * parent = 0);
+ virtual ~QHttp();
- enum State {
- Unconnected,
- HostLookup,
- Connecting,
- Sending,
- Reading,
- Connected,
- Closing
- };
- enum Error {
- NoError,
- UnknownError,
- HostNotFound,
- ConnectionRefused,
- UnexpectedClose,
- InvalidResponseHeader,
- WrongContentLength,
- Aborted,
- AuthenticationRequiredError,
- ProxyAuthenticationRequiredError
- };
+ enum State
+ {
+ Unconnected,
+ HostLookup,
+ Connecting,
+ Sending,
+ Reading,
+ Connected,
+ Closing
+ };
+ enum Error
+ {
+ NoError,
+ UnknownError,
+ HostNotFound,
+ ConnectionRefused,
+ UnexpectedClose,
+ InvalidResponseHeader,
+ WrongContentLength,
+ Aborted,
+ AuthenticationRequiredError,
+ ProxyAuthenticationRequiredError
+ };
- int setHost(const QString &hostname, quint16 port = 80);
- int setHost(const QString &hostname, ConnectionMode mode, quint16 port = 0);
+ int setHost(const QString & hostname, quint16 port = 80);
+ int setHost(const QString & hostname, ConnectionMode mode, quint16 port = 0);
- int setSocket(QTcpSocket *socket);
- int setUser(const QString &username, const QString &password = QString());
+ int setSocket(QTcpSocket * socket);
+ int setUser(const QString & username, const QString & password = QString());
#ifndef QT_NO_NETWORKPROXY
- int setProxy(const QString &host, int port,
- const QString &username = QString(),
- const QString &password = QString());
- int setProxy(const QNetworkProxy &proxy);
+ int setProxy(const QString & host, int port,
+ const QString & username = QString(),
+ const QString & password = QString());
+ int setProxy(const QNetworkProxy & proxy);
#endif
- int get(const QString &path, QIODevice *to=0);
- int post(const QString &path, QIODevice *data, QIODevice *to=0 );
- int post(const QString &path, const QByteArray &data, QIODevice *to=0);
- int head(const QString &path);
- int request(const QHttpRequestHeader &header, QIODevice *device=0, QIODevice *to=0);
- int request(const QHttpRequestHeader &header, const QByteArray &data, QIODevice *to=0);
+ int get(const QString & path, QIODevice * to = 0);
+ int post(const QString & path, QIODevice * data, QIODevice * to = 0);
+ int post(const QString & path, const QByteArray & data, QIODevice * to = 0);
+ int head(const QString & path);
+ int request(const QHttpRequestHeader & header, QIODevice * device = 0, QIODevice * to = 0);
+ int request(const QHttpRequestHeader & header, const QByteArray & data, QIODevice * to = 0);
- int closeConnection();
- int close();
+ int closeConnection();
+ int close();
- qint64 bytesAvailable() const;
- qint64 read(char *data, qint64 maxlen);
- QByteArray readAll();
+ qint64 bytesAvailable() const;
+ qint64 read(char * data, qint64 maxlen);
+ QByteArray readAll();
- int currentId() const;
- QIODevice *currentSourceDevice() const;
- QIODevice *currentDestinationDevice() const;
- QHttpRequestHeader currentRequest() const;
- QHttpResponseHeader lastResponse() const;
- bool hasPendingRequests() const;
- void clearPendingRequests();
+ int currentId() const;
+ QIODevice * currentSourceDevice() const;
+ QIODevice * currentDestinationDevice() const;
+ QHttpRequestHeader currentRequest() const;
+ QHttpResponseHeader lastResponse() const;
+ bool hasPendingRequests() const;
+ void clearPendingRequests();
- State state() const;
+ State state() const;
- Error error() const;
- QString errorString() const;
+ Error error() const;
+ QString errorString() const;
public Q_SLOTS:
- void abort();
+ void abort();
#ifndef QT_NO_OPENSSL
- void ignoreSslErrors();
+ void ignoreSslErrors();
#endif
-Q_SIGNALS:
- void stateChanged(int);
- void responseHeaderReceived(const QHttpResponseHeader &resp);
- void readyRead(const QHttpResponseHeader &resp);
+ Q_SIGNALS : void stateChanged(int);
+ void responseHeaderReceived(const QHttpResponseHeader & resp);
+ void readyRead(const QHttpResponseHeader & resp);
- // ### Qt 5: change to qint64
- void dataSendProgress(int, int);
- void dataReadProgress(int, int);
+ // ### Qt 5: change to qint64
+ void dataSendProgress(int, int);
+ void dataReadProgress(int, int);
- void requestStarted(int);
- void requestFinished(int, bool);
- void done(bool);
+ void requestStarted(int);
+ void requestFinished(int, bool);
+ void done(bool);
#ifndef QT_NO_NETWORKPROXY
- void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *);
+ void proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator *);
#endif
- void authenticationRequired(const QString &hostname, quint16 port, QAuthenticator *);
+ void authenticationRequired(const QString & hostname, quint16 port, QAuthenticator *);
#ifndef QT_NO_OPENSSL
- void sslErrors(const QList<QSslError> &errors);
+ void sslErrors(const QList<QSslError> & errors);
#endif
private:
- Q_DISABLE_COPY(QHttp)
- QScopedPointer<QHttpPrivate> d;
+ Q_DISABLE_COPY(QHttp)
+ QScopedPointer<QHttpPrivate> d;
- void _q_startNextRequest();
- void _q_slotReadyRead();
- void _q_slotConnected();
- void _q_slotError(QAbstractSocket::SocketError e);
- void _q_slotClosed();
- void _q_slotBytesWritten(qint64 numBytes);
+ void _q_startNextRequest();
+ void _q_slotReadyRead();
+ void _q_slotConnected();
+ void _q_slotError(QAbstractSocket::SocketError e);
+ void _q_slotClosed();
+ void _q_slotBytesWritten(qint64 numBytes);
#ifndef QT_NO_OPENSSL
- void _q_slotEncryptedBytesWritten(qint64 numBytes);
+ void _q_slotEncryptedBytesWritten(qint64 numBytes);
#endif
- void _q_slotDoFinished();
- void _q_slotSendRequest();
- void _q_continuePost();
+ void _q_slotDoFinished();
+ void _q_slotSendRequest();
+ void _q_continuePost();
- friend class QHttpNormalRequest;
- friend class QHttpSetHostRequest;
- friend class QHttpSetSocketRequest;
- friend class QHttpSetUserRequest;
- friend class QHttpSetProxyRequest;
- friend class QHttpCloseRequest;
- friend class QHttpPGHRequest;
+ friend class QHttpNormalRequest;
+ friend class QHttpSetHostRequest;
+ friend class QHttpSetSocketRequest;
+ friend class QHttpSetUserRequest;
+ friend class QHttpSetProxyRequest;
+ friend class QHttpCloseRequest;
+ friend class QHttpPGHRequest;
};
QT_END_HEADER
diff --git a/src/modules/objects/qthttp/qhttpauthenticator.cpp b/src/modules/objects/qthttp/qhttpauthenticator.cpp
index ad622a2a7..afe462a98 100644
--- a/src/modules/objects/qthttp/qhttpauthenticator.cpp
+++ b/src/modules/objects/qthttp/qhttpauthenticator.cpp
@@ -60,7 +60,7 @@ QT_BEGIN_NAMESPACE
#endif
static QByteArray qNtlmPhase1();
-static QByteArray qNtlmPhase3(QHttpAuthenticatorPrivate *ctx, const QByteArray& phase2data);
+static QByteArray qNtlmPhase3(QHttpAuthenticatorPrivate * ctx, const QByteArray & phase2data);
/*!
\class QHttpAuthenticator
@@ -128,7 +128,6 @@ static QByteArray qNtlmPhase3(QHttpAuthenticatorPrivate *ctx, const QByteArray&
\sa QSslSocket
*/
-
/*!
Constructs an empty authentication object
*/
@@ -142,72 +141,71 @@ QHttpAuthenticator::QHttpAuthenticator()
*/
QHttpAuthenticator::~QHttpAuthenticator()
{
- if (d && !d->ref.deref())
- delete d;
+ if(d && !d->ref.deref())
+ delete d;
}
/*!
Constructs a copy of \a other.
*/
-QHttpAuthenticator::QHttpAuthenticator(const QHttpAuthenticator &other)
+QHttpAuthenticator::QHttpAuthenticator(const QHttpAuthenticator & other)
: d(other.d)
{
- if (d)
- d->ref.ref();
+ if(d)
+ d->ref.ref();
}
/*!
Assigns the contents of \a other to this authenticator.
*/
-QHttpAuthenticator &QHttpAuthenticator::operator=(const QHttpAuthenticator &other)
+QHttpAuthenticator & QHttpAuthenticator::operator=(const QHttpAuthenticator & other)
{
- if (d == other.d)
- return *this;
+ if(d == other.d)
+ return *this;
- if (d && !d->ref.deref())
- delete d;
+ if(d && !d->ref.deref())
+ delete d;
- d = other.d;
- if (d)
- d->ref.ref();
- return *this;
+ d = other.d;
+ if(d)
+ d->ref.ref();
+ return *this;
}
/*!
Returns true if this authenticator is identical to \a other; otherwise
returns false.
*/
-bool QHttpAuthenticator::operator==(const QHttpAuthenticator &other) const
+bool QHttpAuthenticator::operator==(const QHttpAuthenticator & other) const
{
- if (d == other.d)
- return true;
- return d->user == other.d->user
- && d->password == other.d->password
- && d->realm == other.d->realm
- && d->method == other.d->method
- && d->options == other.d->options;
+ if(d == other.d)
+ return true;
+ return d->user == other.d->user
+ && d->password == other.d->password
+ && d->realm == other.d->realm
+ && d->method == other.d->method
+ && d->options == other.d->options;
}
-QHttpAuthenticator &QHttpAuthenticator::operator=(const QAuthenticator& auth)
+QHttpAuthenticator & QHttpAuthenticator::operator=(const QAuthenticator & auth)
{
- detach();
- d->user = auth.user();
- d->password = auth.password();
- d->options = auth.options();
- return *this;
+ detach();
+ d->user = auth.user();
+ d->password = auth.password();
+ d->options = auth.options();
+ return *this;
}
QAuthenticator QHttpAuthenticator::toQAuthenticator()
{
- QAuthenticator rv;
- rv.setUser(d->user);
- rv.setPassword(d->password);
- foreach (const QString& option, d->options.keys())
- rv.setOption(option, d->options.value(option));
- return rv;
+ QAuthenticator rv;
+ rv.setUser(d->user);
+ rv.setPassword(d->password);
+ foreach(const QString & option, d->options.keys())
+ rv.setOption(option, d->options.value(option));
+ return rv;
}
-
/*!
\fn bool QHttpAuthenticator::operator!=(const QHttpAuthenticator &other) const
@@ -220,7 +218,7 @@ QAuthenticator QHttpAuthenticator::toQAuthenticator()
*/
QString QHttpAuthenticator::user() const
{
- return d ? d->user : QString();
+ return d ? d->user : QString();
}
/*!
@@ -228,31 +226,35 @@ QString QHttpAuthenticator::user() const
\sa QNetworkAccessManager::authenticationRequired()
*/
-void QHttpAuthenticator::setUser(const QString &user)
+void QHttpAuthenticator::setUser(const QString & user)
{
- detach();
- int separatorPosn = 0;
+ detach();
+ int separatorPosn = 0;
- switch(d->method) {
- case QHttpAuthenticatorPrivate::Ntlm:
- if((separatorPosn = user.indexOf(QLatin1String("\\"))) != -1) {
- //domain name is present
- d->realm.clear();
- d->userDomain = user.left(separatorPosn);
- d->extractedUser = user.mid(separatorPosn + 1);
- d->user = user;
- } else {
- d->extractedUser = user;
- d->user = user;
- d->realm.clear();
- d->userDomain.clear();
- }
- break;
- default:
- d->user = user;
- d->userDomain.clear();
- break;
- }
+ switch(d->method)
+ {
+ case QHttpAuthenticatorPrivate::Ntlm:
+ if((separatorPosn = user.indexOf(QLatin1String("\\"))) != -1)
+ {
+ //domain name is present
+ d->realm.clear();
+ d->userDomain = user.left(separatorPosn);
+ d->extractedUser = user.mid(separatorPosn + 1);
+ d->user = user;
+ }
+ else
+ {
+ d->extractedUser = user;
+ d->user = user;
+ d->realm.clear();
+ d->userDomain.clear();
+ }
+ break;
+ default:
+ d->user = user;
+ d->userDomain.clear();
+ break;
+ }
}
/*!
@@ -260,7 +262,7 @@ void QHttpAuthenticator::setUser(const QString &user)
*/
QString QHttpAuthenticator::password() const
{
- return d ? d->password : QString();
+ return d ? d->password : QString();
}
/*!
@@ -268,10 +270,10 @@ QString QHttpAuthenticator::password() const
\sa QNetworkAccessManager::authenticationRequired()
*/
-void QHttpAuthenticator::setPassword(const QString &password)
+void QHttpAuthenticator::setPassword(const QString & password)
{
- detach();
- d->password = password;
+ detach();
+ d->password = password;
}
/*!
@@ -279,14 +281,15 @@ void QHttpAuthenticator::setPassword(const QString &password)
*/
void QHttpAuthenticator::detach()
{
- if (!d) {
- d = new QHttpAuthenticatorPrivate;
- d->ref.store(1);
- return;
- }
+ if(!d)
+ {
+ d = new QHttpAuthenticatorPrivate;
+ d->ref.store(1);
+ return;
+ }
- qAtomicDetach(d);
- d->phase = QHttpAuthenticatorPrivate::Start;
+ qAtomicDetach(d);
+ d->phase = QHttpAuthenticatorPrivate::Start;
}
/*!
@@ -294,7 +297,7 @@ void QHttpAuthenticator::detach()
*/
QString QHttpAuthenticator::realm() const
{
- return d ? d->realm : QString();
+ return d ? d->realm : QString();
}
/*!
@@ -305,9 +308,9 @@ QString QHttpAuthenticator::realm() const
\sa options(), QHttpAuthenticator#Options
*/
-QVariant QHttpAuthenticator::option(const QString &opt) const
+QVariant QHttpAuthenticator::option(const QString & opt) const
{
- return d ? d->options.value(opt) : QVariant();
+ return d ? d->options.value(opt) : QVariant();
}
/*!
@@ -320,7 +323,7 @@ QVariant QHttpAuthenticator::option(const QString &opt) const
*/
QVariantHash QHttpAuthenticator::options() const
{
- return d ? d->options : QVariantHash();
+ return d ? d->options : QVariantHash();
}
/*!
@@ -331,54 +334,50 @@ QVariantHash QHttpAuthenticator::options() const
\sa options(), option(), QHttpAuthenticator#Options
*/
-void QHttpAuthenticator::setOption(const QString &opt, const QVariant &value)
+void QHttpAuthenticator::setOption(const QString & opt, const QVariant & value)
{
- detach();
- d->options.insert(opt, value);
+ detach();
+ d->options.insert(opt, value);
}
-
/*!
Returns true if the authenticator is null.
*/
bool QHttpAuthenticator::isNull() const
{
- return !d;
+ return !d;
}
QHttpAuthenticatorPrivate::QHttpAuthenticatorPrivate()
- : ref(0)
- , method(None)
- , hasFailed(false)
- , phase(Start)
- , nonceCount(0)
+ : ref(0), method(None), hasFailed(false), phase(Start), nonceCount(0)
{
- cnonce = QCryptographicHash::hash(QByteArray::number(qrand(), 16) + QByteArray::number(qrand(), 16),
- QCryptographicHash::Md5).toHex();
- nonceCount = 0;
+ cnonce = QCryptographicHash::hash(QByteArray::number(qrand(), 16) + QByteArray::number(qrand(), 16),
+ QCryptographicHash::Md5)
+ .toHex();
+ nonceCount = 0;
}
#ifndef QT_NO_HTTP
-void QHttpAuthenticatorPrivate::parseHttpResponse(const QHttpResponseHeader &header, bool isProxy)
+void QHttpAuthenticatorPrivate::parseHttpResponse(const QHttpResponseHeader & header, bool isProxy)
{
- const QList<QPair<QString, QString> > values = header.values();
- QList<QPair<QByteArray, QByteArray> > rawValues;
+ const QList<QPair<QString, QString>> values = header.values();
+ QList<QPair<QByteArray, QByteArray>> rawValues;
- QList<QPair<QString, QString> >::const_iterator it, end;
- for (it = values.constBegin(), end = values.constEnd(); it != end; ++it)
- rawValues.append(qMakePair(it->first.toLatin1(), it->second.toUtf8()));
+ QList<QPair<QString, QString>>::const_iterator it, end;
+ for(it = values.constBegin(), end = values.constEnd(); it != end; ++it)
+ rawValues.append(qMakePair(it->first.toLatin1(), it->second.toUtf8()));
- // continue in byte array form
- parseHttpResponse(rawValues, isProxy);
+ // continue in byte array form
+ parseHttpResponse(rawValues, isProxy);
}
#endif
-void QHttpAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByteArray> > &values, bool isProxy)
+void QHttpAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByteArray>> & values, bool isProxy)
{
- const char *search = isProxy ? "proxy-authenticate" : "www-authenticate";
+ const char * search = isProxy ? "proxy-authenticate" : "www-authenticate";
- method = None;
- /*
+ method = None;
+ /*
Fun from the HTTP 1.1 specs, that we currently ignore:
User agents are advised to take special care in parsing the WWW-
@@ -388,170 +387,192 @@ void QHttpAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray,
authentication parameters.
*/
- QByteArray headerVal;
- for (int i = 0; i < values.size(); ++i) {
- const QPair<QByteArray, QByteArray> &current = values.at(i);
- if (current.first.toLower() != search)
- continue;
- QByteArray str = current.second.toLower();
- if (method < Basic && str.startsWith("basic")) {
- method = Basic;
- headerVal = current.second.mid(6);
- } else if (method < Ntlm && str.startsWith("ntlm")) {
- method = Ntlm;
- headerVal = current.second.mid(5);
- } else if (method < DigestMd5 && str.startsWith("digest")) {
- method = DigestMd5;
- headerVal = current.second.mid(7);
- }
- }
+ QByteArray headerVal;
+ for(int i = 0; i < values.size(); ++i)
+ {
+ const QPair<QByteArray, QByteArray> & current = values.at(i);
+ if(current.first.toLower() != search)
+ continue;
+ QByteArray str = current.second.toLower();
+ if(method < Basic && str.startsWith("basic"))
+ {
+ method = Basic;
+ headerVal = current.second.mid(6);
+ }
+ else if(method < Ntlm && str.startsWith("ntlm"))
+ {
+ method = Ntlm;
+ headerVal = current.second.mid(5);
+ }
+ else if(method < DigestMd5 && str.startsWith("digest"))
+ {
+ method = DigestMd5;
+ headerVal = current.second.mid(7);
+ }
+ }
- challenge = headerVal.trimmed();
- QHash<QByteArray, QByteArray> options = parseDigestAuthenticationChallenge(challenge);
+ challenge = headerVal.trimmed();
+ QHash<QByteArray, QByteArray> options = parseDigestAuthenticationChallenge(challenge);
- switch(method) {
- case Basic:
- this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
- if (user.isEmpty() && password.isEmpty())
- phase = Done;
- break;
- case Ntlm:
- // #### extract from header
- break;
- case DigestMd5: {
- this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
- if (options.value("stale").toLower() == "true")
- phase = Start;
- if (user.isEmpty() && password.isEmpty())
- phase = Done;
- break;
- }
- default:
- realm.clear();
- challenge = QByteArray();
- phase = Invalid;
- }
+ switch(method)
+ {
+ case Basic:
+ this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
+ if(user.isEmpty() && password.isEmpty())
+ phase = Done;
+ break;
+ case Ntlm:
+ // #### extract from header
+ break;
+ case DigestMd5:
+ {
+ this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
+ if(options.value("stale").toLower() == "true")
+ phase = Start;
+ if(user.isEmpty() && password.isEmpty())
+ phase = Done;
+ break;
+ }
+ default:
+ realm.clear();
+ challenge = QByteArray();
+ phase = Invalid;
+ }
}
-QByteArray QHttpAuthenticatorPrivate::calculateResponse(const QByteArray &requestMethod, const QByteArray &path)
+QByteArray QHttpAuthenticatorPrivate::calculateResponse(const QByteArray & requestMethod, const QByteArray & path)
{
- QByteArray response;
- const char *methodString = 0;
- switch(method) {
- case QHttpAuthenticatorPrivate::None:
- methodString = "";
- phase = Done;
- break;
- case QHttpAuthenticatorPrivate::Plain:
- response = '\0' + user.toUtf8() + '\0' + password.toUtf8();
- phase = Done;
- break;
- case QHttpAuthenticatorPrivate::Basic:
- methodString = "Basic ";
- response = user.toLatin1() + ':' + password.toLatin1();
- response = response.toBase64();
- phase = Done;
- break;
- case QHttpAuthenticatorPrivate::Login:
- if (challenge.contains("VXNlciBOYW1lAA==")) {
- response = user.toUtf8().toBase64();
- phase = Phase2;
- } else if (challenge.contains("UGFzc3dvcmQA")) {
- response = password.toUtf8().toBase64();
- phase = Done;
- }
- break;
- case QHttpAuthenticatorPrivate::CramMd5:
- break;
- case QHttpAuthenticatorPrivate::DigestMd5:
- methodString = "Digest ";
- response = digestMd5Response(challenge, requestMethod, path);
- phase = Done;
- break;
- case QHttpAuthenticatorPrivate::Ntlm:
- methodString = "NTLM ";
- if (challenge.isEmpty()) {
- response = qNtlmPhase1().toBase64();
- if (user.isEmpty())
- phase = Done;
- else
- phase = Phase2;
- } else {
- response = qNtlmPhase3(this, QByteArray::fromBase64(challenge)).toBase64();
- phase = Done;
- }
+ QByteArray response;
+ const char * methodString = 0;
+ switch(method)
+ {
+ case QHttpAuthenticatorPrivate::None:
+ methodString = "";
+ phase = Done;
+ break;
+ case QHttpAuthenticatorPrivate::Plain:
+ response = '\0' + user.toUtf8() + '\0' + password.toUtf8();
+ phase = Done;
+ break;
+ case QHttpAuthenticatorPrivate::Basic:
+ methodString = "Basic ";
+ response = user.toLatin1() + ':' + password.toLatin1();
+ response = response.toBase64();
+ phase = Done;
+ break;
+ case QHttpAuthenticatorPrivate::Login:
+ if(challenge.contains("VXNlciBOYW1lAA=="))
+ {
+ response = user.toUtf8().toBase64();
+ phase = Phase2;
+ }
+ else if(challenge.contains("UGFzc3dvcmQA"))
+ {
+ response = password.toUtf8().toBase64();
+ phase = Done;
+ }
+ break;
+ case QHttpAuthenticatorPrivate::CramMd5:
+ break;
+ case QHttpAuthenticatorPrivate::DigestMd5:
+ methodString = "Digest ";
+ response = digestMd5Response(challenge, requestMethod, path);
+ phase = Done;
+ break;
+ case QHttpAuthenticatorPrivate::Ntlm:
+ methodString = "NTLM ";
+ if(challenge.isEmpty())
+ {
+ response = qNtlmPhase1().toBase64();
+ if(user.isEmpty())
+ phase = Done;
+ else
+ phase = Phase2;
+ }
+ else
+ {
+ response = qNtlmPhase3(this, QByteArray::fromBase64(challenge)).toBase64();
+ phase = Done;
+ }
- break;
- }
- return QByteArray(methodString) + response;
+ break;
+ }
+ return QByteArray(methodString) + response;
}
-
// ---------------------------- Digest Md5 code ----------------------------------------
-QHash<QByteArray, QByteArray> QHttpAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
+QHash<QByteArray, QByteArray> QHttpAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray & challenge)
{
- QHash<QByteArray, QByteArray> options;
- // parse the challenge
- const char *d = challenge.constData();
- const char *end = d + challenge.length();
- while (d < end) {
- while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
- ++d;
- const char *start = d;
- while (d < end && *d != '=')
- ++d;
- QByteArray key = QByteArray(start, d - start);
- ++d;
- if (d >= end)
- break;
- bool quote = (*d == '"');
- if (quote)
- ++d;
- if (d >= end)
- break;
- start = d;
- QByteArray value;
- while (d < end) {
- bool backslash = false;
- if (*d == '\\' && d < end - 1) {
- ++d;
- backslash = true;
- }
- if (!backslash) {
- if (quote) {
- if (*d == '"')
- break;
- } else {
- if (*d == ',')
- break;
- }
- }
- value += *d;
- ++d;
- }
- while (d < end && *d != ',')
- ++d;
- ++d;
- options[key] = value;
- }
+ QHash<QByteArray, QByteArray> options;
+ // parse the challenge
+ const char * d = challenge.constData();
+ const char * end = d + challenge.length();
+ while(d < end)
+ {
+ while(d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
+ ++d;
+ const char * start = d;
+ while(d < end && *d != '=')
+ ++d;
+ QByteArray key = QByteArray(start, d - start);
+ ++d;
+ if(d >= end)
+ break;
+ bool quote = (*d == '"');
+ if(quote)
+ ++d;
+ if(d >= end)
+ break;
+ start = d;
+ QByteArray value;
+ while(d < end)
+ {
+ bool backslash = false;
+ if(*d == '\\' && d < end - 1)
+ {
+ ++d;
+ backslash = true;
+ }
+ if(!backslash)
+ {
+ if(quote)
+ {
+ if(*d == '"')
+ break;
+ }
+ else
+ {
+ if(*d == ',')
+ break;
+ }
+ }
+ value += *d;
+ ++d;
+ }
+ while(d < end && *d != ',')
+ ++d;
+ ++d;
+ options[key] = value;
+ }
- QByteArray qop = options.value("qop");
- if (!qop.isEmpty()) {
- QList<QByteArray> qopoptions = qop.split(',');
- if (!qopoptions.contains("auth"))
- return QHash<QByteArray, QByteArray>();
- // #### can't do auth-int currently
-// if (qop.contains("auth-int"))
-// qop = "auth-int";
-// else if (qop.contains("auth"))
-// qop = "auth";
-// else
-// qop = QByteArray();
- options["qop"] = "auth";
- }
+ QByteArray qop = options.value("qop");
+ if(!qop.isEmpty())
+ {
+ QList<QByteArray> qopoptions = qop.split(',');
+ if(!qopoptions.contains("auth"))
+ return QHash<QByteArray, QByteArray>();
+ // #### can't do auth-int currently
+ // if (qop.contains("auth-int"))
+ // qop = "auth-int";
+ // else if (qop.contains("auth"))
+ // qop = "auth";
+ // else
+ // qop = QByteArray();
+ options["qop"] = "auth";
+ }
- return options;
+ return options;
}
/*
@@ -562,117 +583,117 @@ QHash<QByteArray, QByteArray> QHttpAuthenticatorPrivate::parseDigestAuthenticati
Currently we don't support the full SASL authentication mechanism (which includes cyphers)
*/
-
/* calculate request-digest/response-digest as per HTTP Digest spec */
static QByteArray digestMd5ResponseHelper(
- const QByteArray &alg,
- const QByteArray &userName,
- const QByteArray &realm,
- const QByteArray &password,
- const QByteArray &nonce, /* nonce from server */
- const QByteArray &nonceCount, /* 8 hex digits */
- const QByteArray &cNonce, /* client nonce */
- const QByteArray &qop, /* qop-value: "", "auth", "auth-int" */
- const QByteArray &method, /* method from the request */
- const QByteArray &digestUri, /* requested URL */
- const QByteArray &hEntity /* H(entity body) if qop="auth-int" */
+ const QByteArray & alg,
+ const QByteArray & userName,
+ const QByteArray & realm,
+ const QByteArray & password,
+ const QByteArray & nonce, /* nonce from server */
+ const QByteArray & nonceCount, /* 8 hex digits */
+ const QByteArray & cNonce, /* client nonce */
+ const QByteArray & qop, /* qop-value: "", "auth", "auth-int" */
+ const QByteArray & method, /* method from the request */
+ const QByteArray & digestUri, /* requested URL */
+ const QByteArray & hEntity /* H(entity body) if qop="auth-int" */
)
{
- QCryptographicHash hash(QCryptographicHash::Md5);
- hash.addData(userName);
- hash.addData(":", 1);
- hash.addData(realm);
- hash.addData(":", 1);
- hash.addData(password);
- QByteArray ha1 = hash.result();
- if (alg.toLower() == "md5-sess") {
- hash.reset();
- // RFC 2617 contains an error, it was:
- // hash.addData(ha1);
- // but according to the errata page at http://www.rfc-editor.org/errata_list.php, ID 1649, it
- // must be the following line:
- hash.addData(ha1.toHex());
- hash.addData(":", 1);
- hash.addData(nonce);
- hash.addData(":", 1);
- hash.addData(cNonce);
- ha1 = hash.result();
- };
- ha1 = ha1.toHex();
+ QCryptographicHash hash(QCryptographicHash::Md5);
+ hash.addData(userName);
+ hash.addData(":", 1);
+ hash.addData(realm);
+ hash.addData(":", 1);
+ hash.addData(password);
+ QByteArray ha1 = hash.result();
+ if(alg.toLower() == "md5-sess")
+ {
+ hash.reset();
+ // RFC 2617 contains an error, it was:
+ // hash.addData(ha1);
+ // but according to the errata page at http://www.rfc-editor.org/errata_list.php, ID 1649, it
+ // must be the following line:
+ hash.addData(ha1.toHex());
+ hash.addData(":", 1);
+ hash.addData(nonce);
+ hash.addData(":", 1);
+ hash.addData(cNonce);
+ ha1 = hash.result();
+ };
+ ha1 = ha1.toHex();
- // calculate H(A2)
- hash.reset();
- hash.addData(method);
- hash.addData(":", 1);
- hash.addData(digestUri);
- if (qop.toLower() == "auth-int") {
- hash.addData(":", 1);
- hash.addData(hEntity);
- }
- QByteArray ha2hex = hash.result().toHex();
+ // calculate H(A2)
+ hash.reset();
+ hash.addData(method);
+ hash.addData(":", 1);
+ hash.addData(digestUri);
+ if(qop.toLower() == "auth-int")
+ {
+ hash.addData(":", 1);
+ hash.addData(hEntity);
+ }
+ QByteArray ha2hex = hash.result().toHex();
- // calculate response
- hash.reset();
- hash.addData(ha1);
- hash.addData(":", 1);
- hash.addData(nonce);
- hash.addData(":", 1);
- if (!qop.isNull()) {
- hash.addData(nonceCount);
- hash.addData(":", 1);
- hash.addData(cNonce);
- hash.addData(":", 1);
- hash.addData(qop);
- hash.addData(":", 1);
- }
- hash.addData(ha2hex);
- return hash.result().toHex();
+ // calculate response
+ hash.reset();
+ hash.addData(ha1);
+ hash.addData(":", 1);
+ hash.addData(nonce);
+ hash.addData(":", 1);
+ if(!qop.isNull())
+ {
+ hash.addData(nonceCount);
+ hash.addData(":", 1);
+ hash.addData(cNonce);
+ hash.addData(":", 1);
+ hash.addData(qop);
+ hash.addData(":", 1);
+ }
+ hash.addData(ha2hex);
+ return hash.result().toHex();
}
-QByteArray QHttpAuthenticatorPrivate::digestMd5Response(const QByteArray &challenge, const QByteArray &method, const QByteArray &path)
+QByteArray QHttpAuthenticatorPrivate::digestMd5Response(const QByteArray & challenge, const QByteArray & method, const QByteArray & path)
{
- QHash<QByteArray,QByteArray> options = parseDigestAuthenticationChallenge(challenge);
+ QHash<QByteArray, QByteArray> options = parseDigestAuthenticationChallenge(challenge);
- ++nonceCount;
- QByteArray nonceCountString = QByteArray::number(nonceCount, 16);
- while (nonceCountString.length() < 8)
- nonceCountString.prepend('0');
+ ++nonceCount;
+ QByteArray nonceCountString = QByteArray::number(nonceCount, 16);
+ while(nonceCountString.length() < 8)
+ nonceCountString.prepend('0');
- QByteArray nonce = options.value("nonce");
- QByteArray opaque = options.value("opaque");
- QByteArray qop = options.value("qop");
+ QByteArray nonce = options.value("nonce");
+ QByteArray opaque = options.value("opaque");
+ QByteArray qop = options.value("qop");
-// qDebug() << "calculating digest: method=" << method << "path=" << path;
- QByteArray response = digestMd5ResponseHelper(options.value("algorithm"), user.toLatin1(),
- realm.toLatin1(), password.toLatin1(),
- nonce, nonceCountString,
- cnonce, qop, method,
- path, QByteArray());
+ // qDebug() << "calculating digest: method=" << method << "path=" << path;
+ QByteArray response = digestMd5ResponseHelper(options.value("algorithm"), user.toLatin1(),
+ realm.toLatin1(), password.toLatin1(),
+ nonce, nonceCountString,
+ cnonce, qop, method,
+ path, QByteArray());
+ QByteArray credentials;
+ credentials += "username=\"" + user.toLatin1() + "\", ";
+ credentials += "realm=\"" + realm.toLatin1() + "\", ";
+ credentials += "nonce=\"" + nonce + "\", ";
+ credentials += "uri=\"" + path + "\", ";
+ if(!opaque.isEmpty())
+ credentials += "opaque=\"" + opaque + "\", ";
+ credentials += "response=\"" + response + '\"';
+ if(!options.value("algorithm").isEmpty())
+ credentials += ", algorithm=" + options.value("algorithm");
+ if(!options.value("qop").isEmpty())
+ {
+ credentials += ", qop=" + qop + ", ";
+ credentials += "nc=" + nonceCountString + ", ";
+ credentials += "cnonce=\"" + cnonce + '\"';
+ }
- QByteArray credentials;
- credentials += "username=\"" + user.toLatin1() + "\", ";
- credentials += "realm=\"" + realm.toLatin1() + "\", ";
- credentials += "nonce=\"" + nonce + "\", ";
- credentials += "uri=\"" + path + "\", ";
- if (!opaque.isEmpty())
- credentials += "opaque=\"" + opaque + "\", ";
- credentials += "response=\"" + response + '\"';
- if (!options.value("algorithm").isEmpty())
- credentials += ", algorithm=" + options.value("algorithm");
- if (!options.value("qop").isEmpty()) {
- credentials += ", qop=" + qop + ", ";
- credentials += "nc=" + nonceCountString + ", ";
- credentials += "cnonce=\"" + cnonce + '\"';
- }
-
- return credentials;
+ return credentials;
}
// ---------------------------- Digest Md5 code ----------------------------------------
-
-
/*
* NTLM message flags.
*
@@ -813,10 +834,9 @@ QByteArray QHttpAuthenticatorPrivate::digestMd5Response(const QByteArray &challe
//#define NTLMV1_CLIENT
-
//************************Global variables***************************
-const int blockSize = 64; //As per RFC2104 Block-size is 512 bits
+const int blockSize = 64; //As per RFC2104 Block-size is 512 bits
const int nDigestLen = 16; //Trunctaion Length of the Hmac-Md5 digest
const quint8 respversion = 1;
const quint8 hirespversion = 1;
@@ -838,269 +858,276 @@ const quint8 hirespversion = 1;
- add v2 handling
*/
-class QNtlmBuffer {
+class QNtlmBuffer
+{
public:
- QNtlmBuffer() : len(0), maxLen(0), offset(0) {}
- quint16 len;
- quint16 maxLen;
- quint32 offset;
- enum { Size = 8 };
+ QNtlmBuffer() : len(0), maxLen(0), offset(0) {}
+ quint16 len;
+ quint16 maxLen;
+ quint32 offset;
+ enum
+ {
+ Size = 8
+ };
};
class QNtlmPhase1BlockBase
{
public:
- char magic[8];
- quint32 type;
- quint32 flags;
- QNtlmBuffer domain;
- QNtlmBuffer workstation;
- enum { Size = 32 };
+ char magic[8];
+ quint32 type;
+ quint32 flags;
+ QNtlmBuffer domain;
+ QNtlmBuffer workstation;
+ enum
+ {
+ Size = 32
+ };
};
// ################# check paddings
class QNtlmPhase2BlockBase
{
public:
- char magic[8];
- quint32 type;
- QNtlmBuffer targetName;
- quint32 flags;
- unsigned char challenge[8];
- quint32 context[2];
- QNtlmBuffer targetInfo;
- enum { Size = 48 };
+ char magic[8];
+ quint32 type;
+ QNtlmBuffer targetName;
+ quint32 flags;
+ unsigned char challenge[8];
+ quint32 context[2];
+ QNtlmBuffer targetInfo;
+ enum
+ {
+ Size = 48
+ };
};
-class QNtlmPhase3BlockBase {
+class QNtlmPhase3BlockBase
+{
public:
- char magic[8];
- quint32 type;
- QNtlmBuffer lmResponse;
- QNtlmBuffer ntlmResponse;
- QNtlmBuffer domain;
- QNtlmBuffer user;
- QNtlmBuffer workstation;
- QNtlmBuffer sessionKey;
- quint32 flags;
- enum { Size = 64 };
+ char magic[8];
+ quint32 type;
+ QNtlmBuffer lmResponse;
+ QNtlmBuffer ntlmResponse;
+ QNtlmBuffer domain;
+ QNtlmBuffer user;
+ QNtlmBuffer workstation;
+ QNtlmBuffer sessionKey;
+ quint32 flags;
+ enum
+ {
+ Size = 64
+ };
};
-static void qStreamNtlmBuffer(QDataStream& ds, const QByteArray& s)
+static void qStreamNtlmBuffer(QDataStream & ds, const QByteArray & s)
{
- ds.writeRawData(s.constData(), s.size());
+ ds.writeRawData(s.constData(), s.size());
}
-
-static void qStreamNtlmString(QDataStream& ds, const QString& s, bool unicode)
+static void qStreamNtlmString(QDataStream & ds, const QString & s, bool unicode)
{
- if (!unicode) {
- qStreamNtlmBuffer(ds, s.toLatin1());
- return;
- }
- const ushort *d = s.utf16();
- for (int i = 0; i < s.length(); ++i)
- ds << d[i];
+ if(!unicode)
+ {
+ qStreamNtlmBuffer(ds, s.toLatin1());
+ return;
+ }
+ const ushort * d = s.utf16();
+ for(int i = 0; i < s.length(); ++i)
+ ds << d[i];
}
-
-
-static int qEncodeNtlmBuffer(QNtlmBuffer& buf, int offset, const QByteArray& s)
+static int qEncodeNtlmBuffer(QNtlmBuffer & buf, int offset, const QByteArray & s)
{
- buf.len = s.size();
- buf.maxLen = buf.len;
- buf.offset = (offset + 1) & ~1;
- return buf.offset + buf.len;
+ buf.len = s.size();
+ buf.maxLen = buf.len;
+ buf.offset = (offset + 1) & ~1;
+ return buf.offset + buf.len;
}
-
-static int qEncodeNtlmString(QNtlmBuffer& buf, int offset, const QString& s, bool unicode)
+static int qEncodeNtlmString(QNtlmBuffer & buf, int offset, const QString & s, bool unicode)
{
- if (!unicode)
- return qEncodeNtlmBuffer(buf, offset, s.toLatin1());
- buf.len = 2 * s.length();
- buf.maxLen = buf.len;
- buf.offset = (offset + 1) & ~1;
- return buf.offset + buf.len;
+ if(!unicode)
+ return qEncodeNtlmBuffer(buf, offset, s.toLatin1());
+ buf.len = 2 * s.length();
+ buf.maxLen = buf.len;
+ buf.offset = (offset + 1) & ~1;
+ return buf.offset + buf.len;
}
-
-static QDataStream& operator<<(QDataStream& s, const QNtlmBuffer& b)
+static QDataStream & operator<<(QDataStream & s, const QNtlmBuffer & b)
{
- s << b.len << b.maxLen << b.offset;
- return s;
+ s << b.len << b.maxLen << b.offset;
+ return s;
}
-static QDataStream& operator>>(QDataStream& s, QNtlmBuffer& b)
+static QDataStream & operator>>(QDataStream & s, QNtlmBuffer & b)
{
- s >> b.len >> b.maxLen >> b.offset;
- return s;
+ s >> b.len >> b.maxLen >> b.offset;
+ return s;
}
-
class QNtlmPhase1Block : public QNtlmPhase1BlockBase
-{ // request
+{ // request
public:
- QNtlmPhase1Block() {
- qstrncpy(magic, "NTLMSSP", 8);
- type = 1;
- flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_REQUEST_TARGET;
- }
+ QNtlmPhase1Block()
+ {
+ qstrncpy(magic, "NTLMSSP", 8);
+ type = 1;
+ flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_REQUEST_TARGET;
+ }
- // extracted
- QString domainStr, workstationStr;
+ // extracted
+ QString domainStr, workstationStr;
};
-
class QNtlmPhase2Block : public QNtlmPhase2BlockBase
-{ // challenge
+{ // challenge
public:
- QNtlmPhase2Block() {
- magic[0] = 0;
- type = 0xffffffff;
- }
+ QNtlmPhase2Block()
+ {
+ magic[0] = 0;
+ type = 0xffffffff;
+ }
- // extracted
- QString targetNameStr, targetInfoStr;
- QByteArray targetInfoBuff;
+ // extracted
+ QString targetNameStr, targetInfoStr;
+ QByteArray targetInfoBuff;
};
-
-
-class QNtlmPhase3Block : public QNtlmPhase3BlockBase { // response
+class QNtlmPhase3Block : public QNtlmPhase3BlockBase
+{ // response
public:
- QNtlmPhase3Block() {
- qstrncpy(magic, "NTLMSSP", 8);
- type = 3;
- flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_TARGET_INFO;
- }
+ QNtlmPhase3Block()
+ {
+ qstrncpy(magic, "NTLMSSP", 8);
+ type = 3;
+ flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_TARGET_INFO;
+ }
- // extracted
- QByteArray lmResponseBuf, ntlmResponseBuf;
- QString domainStr, userStr, workstationStr, sessionKeyStr;
- QByteArray v2Hash;
+ // extracted
+ QByteArray lmResponseBuf, ntlmResponseBuf;
+ QString domainStr, userStr, workstationStr, sessionKeyStr;
+ QByteArray v2Hash;
};
+static QDataStream & operator<<(QDataStream & s, const QNtlmPhase1Block & b)
+{
+ bool unicode = (b.flags & NTLMSSP_NEGOTIATE_UNICODE);
-static QDataStream& operator<<(QDataStream& s, const QNtlmPhase1Block& b) {
- bool unicode = (b.flags & NTLMSSP_NEGOTIATE_UNICODE);
-
- s.writeRawData(b.magic, sizeof(b.magic));
- s << b.type;
- s << b.flags;
- s << b.domain;
- s << b.workstation;
- if (!b.domainStr.isEmpty())
- qStreamNtlmString(s, b.domainStr, unicode);
- if (!b.workstationStr.isEmpty())
- qStreamNtlmString(s, b.workstationStr, unicode);
- return s;
+ s.writeRawData(b.magic, sizeof(b.magic));
+ s << b.type;
+ s << b.flags;
+ s << b.domain;
+ s << b.workstation;
+ if(!b.domainStr.isEmpty())
+ qStreamNtlmString(s, b.domainStr, unicode);
+ if(!b.workstationStr.isEmpty())
+ qStreamNtlmString(s, b.workstationStr, unicode);
+ return s;
}
+static QDataStream & operator<<(QDataStream & s, const QNtlmPhase3Block & b)
+{
+ bool unicode = (b.flags & NTLMSSP_NEGOTIATE_UNICODE);
+ s.writeRawData(b.magic, sizeof(b.magic));
+ s << b.type;
+ s << b.lmResponse;
+ s << b.ntlmResponse;
+ s << b.domain;
+ s << b.user;
+ s << b.workstation;
+ s << b.sessionKey;
+ s << b.flags;
-static QDataStream& operator<<(QDataStream& s, const QNtlmPhase3Block& b) {
- bool unicode = (b.flags & NTLMSSP_NEGOTIATE_UNICODE);
- s.writeRawData(b.magic, sizeof(b.magic));
- s << b.type;
- s << b.lmResponse;
- s << b.ntlmResponse;
- s << b.domain;
- s << b.user;
- s << b.workstation;
- s << b.sessionKey;
- s << b.flags;
-
- if (!b.domainStr.isEmpty())
- qStreamNtlmString(s, b.domainStr, unicode);
-
- qStreamNtlmString(s, b.userStr, unicode);
+ if(!b.domainStr.isEmpty())
+ qStreamNtlmString(s, b.domainStr, unicode);
- if (!b.workstationStr.isEmpty())
- qStreamNtlmString(s, b.workstationStr, unicode);
+ qStreamNtlmString(s, b.userStr, unicode);
- // Send auth info
- qStreamNtlmBuffer(s, b.lmResponseBuf);
- qStreamNtlmBuffer(s, b.ntlmResponseBuf);
+ if(!b.workstationStr.isEmpty())
+ qStreamNtlmString(s, b.workstationStr, unicode);
+ // Send auth info
+ qStreamNtlmBuffer(s, b.lmResponseBuf);
+ qStreamNtlmBuffer(s, b.ntlmResponseBuf);
- return s;
+ return s;
}
-
static QByteArray qNtlmPhase1()
{
- QByteArray rc;
- QDataStream ds(&rc, QIODevice::WriteOnly);
- ds.setByteOrder(QDataStream::LittleEndian);
- QNtlmPhase1Block pb;
- ds << pb;
- return rc;
+ QByteArray rc;
+ QDataStream ds(&rc, QIODevice::WriteOnly);
+ ds.setByteOrder(QDataStream::LittleEndian);
+ QNtlmPhase1Block pb;
+ ds << pb;
+ return rc;
}
-
-static QByteArray qStringAsUcs2Le(const QString& src)
+static QByteArray qStringAsUcs2Le(const QString & src)
{
- QByteArray rc(2*src.length(), 0);
- const unsigned short *s = src.utf16();
- unsigned short *d = (unsigned short*)rc.data();
- for (int i = 0; i < src.length(); ++i) {
- d[i] = qToLittleEndian(s[i]);
- }
- return rc;
+ QByteArray rc(2 * src.length(), 0);
+ const unsigned short * s = src.utf16();
+ unsigned short * d = (unsigned short *)rc.data();
+ for(int i = 0; i < src.length(); ++i)
+ {
+ d[i] = qToLittleEndian(s[i]);
+ }
+ return rc;
}
-
-static QString qStringFromUcs2Le(const QByteArray& src)
+static QString qStringFromUcs2Le(const QByteArray & src)
{
- Q_ASSERT(src.size() % 2 == 0);
- unsigned short *d = (unsigned short*)src.data();
- for (int i = 0; i < src.length() / 2; ++i) {
- d[i] = qFromLittleEndian(d[i]);
- }
- return QString((const QChar *)src.data(), src.size()/2);
+ Q_ASSERT(src.size() % 2 == 0);
+ unsigned short * d = (unsigned short *)src.data();
+ for(int i = 0; i < src.length() / 2; ++i)
+ {
+ d[i] = qFromLittleEndian(d[i]);
+ }
+ return QString((const QChar *)src.data(), src.size() / 2);
}
#ifdef NTLMV1_CLIENT
-static QByteArray qEncodeNtlmResponse(const QHttpAuthenticatorPrivate *ctx, const QNtlmPhase2Block& ch)
+static QByteArray qEncodeNtlmResponse(const QHttpAuthenticatorPrivate * ctx, const QNtlmPhase2Block & ch)
{
- QCryptographicHash md4(QCryptographicHash::Md4);
- QByteArray asUcs2Le = qStringAsUcs2Le(ctx->password);
- md4.addData(asUcs2Le.data(), asUcs2Le.size());
+ QCryptographicHash md4(QCryptographicHash::Md4);
+ QByteArray asUcs2Le = qStringAsUcs2Le(ctx->password);
+ md4.addData(asUcs2Le.data(), asUcs2Le.size());
- unsigned char md4hash[22];
- memset(md4hash, 0, sizeof(md4hash));
- QByteArray hash = md4.result();
- Q_ASSERT(hash.size() == 16);
- memcpy(md4hash, hash.constData(), 16);
+ unsigned char md4hash[22];
+ memset(md4hash, 0, sizeof(md4hash));
+ QByteArray hash = md4.result();
+ Q_ASSERT(hash.size() == 16);
+ memcpy(md4hash, hash.constData(), 16);
- QByteArray rc(24, 0);
- deshash((unsigned char *)rc.data(), md4hash, (unsigned char *)ch.challenge);
- deshash((unsigned char *)rc.data() + 8, md4hash + 7, (unsigned char *)ch.challenge);
- deshash((unsigned char *)rc.data() + 16, md4hash + 14, (unsigned char *)ch.challenge);
+ QByteArray rc(24, 0);
+ deshash((unsigned char *)rc.data(), md4hash, (unsigned char *)ch.challenge);
+ deshash((unsigned char *)rc.data() + 8, md4hash + 7, (unsigned char *)ch.challenge);
+ deshash((unsigned char *)rc.data() + 16, md4hash + 14, (unsigned char *)ch.challenge);
- hash.fill(0);
- return rc;
+ hash.fill(0);
+ return rc;
}
-
-static QByteArray qEncodeLmResponse(const QHttpAuthenticatorPrivate *ctx, const QNtlmPhase2Block& ch)
+static QByteArray qEncodeLmResponse(const QHttpAuthenticatorPrivate * ctx, const QNtlmPhase2Block & ch)
{
- QByteArray hash(21, 0);
- QByteArray key(14, 0);
- qstrncpy(key.data(), ctx->password.toUpper().toLatin1(), 14);
- const char *block = "KGS!@#$%";
+ QByteArray hash(21, 0);
+ QByteArray key(14, 0);
+ qstrncpy(key.data(), ctx->password.toUpper().toLatin1(), 14);
+ const char * block = "KGS!@#$%";
- deshash((unsigned char *)hash.data(), (unsigned char *)key.data(), (unsigned char *)block);
- deshash((unsigned char *)hash.data() + 8, (unsigned char *)key.data() + 7, (unsigned char *)block);
- key.fill(0);
+ deshash((unsigned char *)hash.data(), (unsigned char *)key.data(), (unsigned char *)block);
+ deshash((unsigned char *)hash.data() + 8, (unsigned char *)key.data() + 7, (unsigned char *)block);
+ key.fill(0);
- QByteArray rc(24, 0);
- deshash((unsigned char *)rc.data(), (unsigned char *)hash.data(), ch.challenge);
- deshash((unsigned char *)rc.data() + 8, (unsigned char *)hash.data() + 7, ch.challenge);
- deshash((unsigned char *)rc.data() + 16, (unsigned char *)hash.data() + 14, ch.challenge);
+ QByteArray rc(24, 0);
+ deshash((unsigned char *)rc.data(), (unsigned char *)hash.data(), ch.challenge);
+ deshash((unsigned char *)rc.data() + 8, (unsigned char *)hash.data() + 7, ch.challenge);
+ deshash((unsigned char *)rc.data() + 16, (unsigned char *)hash.data() + 14, ch.challenge);
- hash.fill(0);
- return rc;
+ hash.fill(0);
+ return rc;
}
#endif
@@ -1126,320 +1153,330 @@ static QByteArray qEncodeLmResponse(const QHttpAuthenticatorPrivate *ctx, const
* ---------------------------------------
*
*********************************************************************/
-QByteArray qEncodeHmacMd5(QByteArray &key, const QByteArray &message)
+QByteArray qEncodeHmacMd5(QByteArray & key, const QByteArray & message)
{
- Q_ASSERT_X(!(message.isEmpty()),"qEncodeHmacMd5", "Empty message check");
- Q_ASSERT_X(!(key.isEmpty()),"qEncodeHmacMd5", "Empty key check");
+ Q_ASSERT_X(!(message.isEmpty()), "qEncodeHmacMd5", "Empty message check");
+ Q_ASSERT_X(!(key.isEmpty()), "qEncodeHmacMd5", "Empty key check");
- QCryptographicHash hash(QCryptographicHash::Md5);
- QByteArray hMsg;
+ QCryptographicHash hash(QCryptographicHash::Md5);
+ QByteArray hMsg;
- QByteArray iKeyPad(blockSize, 0x36);
- QByteArray oKeyPad(blockSize, 0x5c);
+ QByteArray iKeyPad(blockSize, 0x36);
+ QByteArray oKeyPad(blockSize, 0x5c);
- hash.reset();
- // Adjust the key length to blockSize
+ hash.reset();
+ // Adjust the key length to blockSize
- if(blockSize < key.length()) {
- hash.addData(key);
- key = hash.result(); //MD5 will always return 16 bytes length output
- }
+ if(blockSize < key.length())
+ {
+ hash.addData(key);
+ key = hash.result(); //MD5 will always return 16 bytes length output
+ }
- //Key will be <= 16 or 20 bytes as hash function (MD5 or SHA hash algorithms)
- //key size can be max of Block size only
- key = key.leftJustified(blockSize,0,true);
+ //Key will be <= 16 or 20 bytes as hash function (MD5 or SHA hash algorithms)
+ //key size can be max of Block size only
+ key = key.leftJustified(blockSize, 0, true);
- //iKeyPad, oKeyPad and key are all of same size "blockSize"
+ //iKeyPad, oKeyPad and key are all of same size "blockSize"
- //xor of iKeyPad with Key and store the result into iKeyPad
- for(int i = 0; i<key.size();i++) {
- iKeyPad[i] = key[i]^iKeyPad[i];
- }
+ //xor of iKeyPad with Key and store the result into iKeyPad
+ for(int i = 0; i < key.size(); i++)
+ {
+ iKeyPad[i] = key[i] ^ iKeyPad[i];
+ }
- //xor of oKeyPad with Key and store the result into oKeyPad
- for(int i = 0; i<key.size();i++) {
- oKeyPad[i] = key[i]^oKeyPad[i];
- }
+ //xor of oKeyPad with Key and store the result into oKeyPad
+ for(int i = 0; i < key.size(); i++)
+ {
+ oKeyPad[i] = key[i] ^ oKeyPad[i];
+ }
- iKeyPad.append(message); // (K0 xor ipad) || text
+ iKeyPad.append(message); // (K0 xor ipad) || text
- hash.reset();
- hash.addData(iKeyPad);
- hMsg = hash.result();
- //Digest gen after pass-1: H((K0 xor ipad)||text)
+ hash.reset();
+ hash.addData(iKeyPad);
+ hMsg = hash.result();
+ //Digest gen after pass-1: H((K0 xor ipad)||text)
- QByteArray hmacDigest;
- oKeyPad.append(hMsg);
- hash.reset();
- hash.addData(oKeyPad);
- hmacDigest = hash.result();
- // H((K0 xor opad )|| H((K0 xor ipad) || text))
+ QByteArray hmacDigest;
+ oKeyPad.append(hMsg);
+ hash.reset();
+ hash.addData(oKeyPad);
+ hmacDigest = hash.result();
+ // H((K0 xor opad )|| H((K0 xor ipad) || text))
- /*hmacDigest should not be less than half the length of the HMAC output
+ /*hmacDigest should not be less than half the length of the HMAC output
(to match the birthday attack bound) and not less than 80 bits
(a suitable lower bound on the number of bits that need to be
predicted by an attacker).
Refer RFC 2104 for more details on truncation part */
- /*MD5 hash always returns 16 byte digest only and HMAC-MD5 spec
+ /*MD5 hash always returns 16 byte digest only and HMAC-MD5 spec
(RFC 2104) also says digest length should be 16 bytes*/
- return hmacDigest;
+ return hmacDigest;
}
-static QByteArray qCreatev2Hash(const QHttpAuthenticatorPrivate *ctx,
- QNtlmPhase3Block *phase3)
+static QByteArray qCreatev2Hash(const QHttpAuthenticatorPrivate * ctx,
+ QNtlmPhase3Block * phase3)
{
- Q_ASSERT(phase3 != 0);
- // since v2 Hash is need for both NTLMv2 and LMv2 it is calculated
- // only once and stored and reused
- if(phase3->v2Hash.size() == 0) {
- QCryptographicHash md4(QCryptographicHash::Md4);
- QByteArray passUnicode = qStringAsUcs2Le(ctx->password);
- md4.addData(passUnicode.data(), passUnicode.size());
+ Q_ASSERT(phase3 != 0);
+ // since v2 Hash is need for both NTLMv2 and LMv2 it is calculated
+ // only once and stored and reused
+ if(phase3->v2Hash.size() == 0)
+ {
+ QCryptographicHash md4(QCryptographicHash::Md4);
+ QByteArray passUnicode = qStringAsUcs2Le(ctx->password);
+ md4.addData(passUnicode.data(), passUnicode.size());
- QByteArray hashKey = md4.result();
- Q_ASSERT(hashKey.size() == 16);
- // Assuming the user and domain is always unicode in challenge
- QByteArray message =
- qStringAsUcs2Le(ctx->extractedUser.toUpper()) +
- qStringAsUcs2Le(phase3->domainStr);
+ QByteArray hashKey = md4.result();
+ Q_ASSERT(hashKey.size() == 16);
+ // Assuming the user and domain is always unicode in challenge
+ QByteArray message = qStringAsUcs2Le(ctx->extractedUser.toUpper()) + qStringAsUcs2Le(phase3->domainStr);
- phase3->v2Hash = qEncodeHmacMd5(hashKey, message);
- }
- return phase3->v2Hash;
+ phase3->v2Hash = qEncodeHmacMd5(hashKey, message);
+ }
+ return phase3->v2Hash;
}
-static QByteArray clientChallenge(const QHttpAuthenticatorPrivate *ctx)
+static QByteArray clientChallenge(const QHttpAuthenticatorPrivate * ctx)
{
- Q_ASSERT(ctx->cnonce.size() >= 8);
- QByteArray clientCh = ctx->cnonce.right(8);
- return clientCh;
+ Q_ASSERT(ctx->cnonce.size() >= 8);
+ QByteArray clientCh = ctx->cnonce.right(8);
+ return clientCh;
}
// caller has to ensure a valid targetInfoBuff
-static QByteArray qExtractServerTime(const QByteArray& targetInfoBuff)
+static QByteArray qExtractServerTime(const QByteArray & targetInfoBuff)
{
- QByteArray timeArray;
- QDataStream ds(targetInfoBuff);
- ds.setByteOrder(QDataStream::LittleEndian);
+ QByteArray timeArray;
+ QDataStream ds(targetInfoBuff);
+ ds.setByteOrder(QDataStream::LittleEndian);
- quint16 avId;
- quint16 avLen;
+ quint16 avId;
+ quint16 avLen;
- ds >> avId;
- ds >> avLen;
- while(avId != 0) {
- if(avId == AVTIMESTAMP) {
- timeArray.resize(avLen);
- //avLen size of QByteArray is allocated
- ds.readRawData(timeArray.data(), avLen);
- break;
- }
- ds.skipRawData(avLen);
- ds >> avId;
- ds >> avLen;
- }
- return timeArray;
+ ds >> avId;
+ ds >> avLen;
+ while(avId != 0)
+ {
+ if(avId == AVTIMESTAMP)
+ {
+ timeArray.resize(avLen);
+ //avLen size of QByteArray is allocated
+ ds.readRawData(timeArray.data(), avLen);
+ break;
+ }
+ ds.skipRawData(avLen);
+ ds >> avId;
+ ds >> avLen;
+ }
+ return timeArray;
}
-static QByteArray qEncodeNtlmv2Response(const QHttpAuthenticatorPrivate *ctx,
- const QNtlmPhase2Block& ch,
- QNtlmPhase3Block *phase3)
+static QByteArray qEncodeNtlmv2Response(const QHttpAuthenticatorPrivate * ctx,
+ const QNtlmPhase2Block & ch,
+ QNtlmPhase3Block * phase3)
{
- Q_ASSERT(phase3 != 0);
- // return value stored in phase3
- qCreatev2Hash(ctx, phase3);
+ Q_ASSERT(phase3 != 0);
+ // return value stored in phase3
+ qCreatev2Hash(ctx, phase3);
- QByteArray temp;
- QDataStream ds(&temp, QIODevice::WriteOnly);
- ds.setByteOrder(QDataStream::LittleEndian);
+ QByteArray temp;
+ QDataStream ds(&temp, QIODevice::WriteOnly);
+ ds.setByteOrder(QDataStream::LittleEndian);
- ds << respversion;
- ds << hirespversion;
+ ds << respversion;
+ ds << hirespversion;
- //Reserved
- QByteArray reserved1(6, 0);
- ds.writeRawData(reserved1.constData(), reserved1.size());
+ //Reserved
+ QByteArray reserved1(6, 0);
+ ds.writeRawData(reserved1.constData(), reserved1.size());
- quint64 time = 0;
- QByteArray timeArray;
+ quint64 time = 0;
+ QByteArray timeArray;
- if(ch.targetInfo.len)
- {
- timeArray = qExtractServerTime(ch.targetInfoBuff);
- }
+ if(ch.targetInfo.len)
+ {
+ timeArray = qExtractServerTime(ch.targetInfoBuff);
+ }
- //if server sends time, use it instead of current time
- if(timeArray.size()) {
- ds.writeRawData(timeArray.constData(), timeArray.size());
- } else {
- QDateTime currentTime(QDate::currentDate(),
- QTime::currentTime(), Qt::UTC);
+ //if server sends time, use it instead of current time
+ if(timeArray.size())
+ {
+ ds.writeRawData(timeArray.constData(), timeArray.size());
+ }
+ else
+ {
+ QDateTime currentTime(QDate::currentDate(),
+ QTime::currentTime(), Qt::UTC);
- // number of seconds between 1601 and epoc(1970)
- // 369 years, 89 leap years
- // ((369 * 365) + 89) * 24 * 3600 = 11644473600
+ // number of seconds between 1601 and epoc(1970)
+ // 369 years, 89 leap years
+ // ((369 * 365) + 89) * 24 * 3600 = 11644473600
- time = Q_UINT64_C(currentTime.toTime_t() + 11644473600);
+ time = Q_UINT64_C(currentTime.toTime_t() + 11644473600);
- // represented as 100 nano seconds
- time = Q_UINT64_C(time * 10000000);
- ds << time;
- }
+ // represented as 100 nano seconds
+ time = Q_UINT64_C(time * 10000000);
+ ds << time;
+ }
- //8 byte client challenge
- QByteArray clientCh = clientChallenge(ctx);
- ds.writeRawData(clientCh.constData(), clientCh.size());
+ //8 byte client challenge
+ QByteArray clientCh = clientChallenge(ctx);
+ ds.writeRawData(clientCh.constData(), clientCh.size());
- //Reserved
- QByteArray reserved2(4, 0);
- ds.writeRawData(reserved2.constData(), reserved2.size());
+ //Reserved
+ QByteArray reserved2(4, 0);
+ ds.writeRawData(reserved2.constData(), reserved2.size());
- if (ch.targetInfo.len > 0) {
- ds.writeRawData(ch.targetInfoBuff.constData(),
- ch.targetInfoBuff.size());
- }
+ if(ch.targetInfo.len > 0)
+ {
+ ds.writeRawData(ch.targetInfoBuff.constData(),
+ ch.targetInfoBuff.size());
+ }
- //Reserved
- QByteArray reserved3(4, 0);
- ds.writeRawData(reserved3.constData(), reserved3.size());
+ //Reserved
+ QByteArray reserved3(4, 0);
+ ds.writeRawData(reserved3.constData(), reserved3.size());
- QByteArray message((const char*)ch.challenge, sizeof(ch.challenge));
- message.append(temp);
+ QByteArray message((const char *)ch.challenge, sizeof(ch.challenge));
+ message.append(temp);
- QByteArray ntChallengeResp = qEncodeHmacMd5(phase3->v2Hash, message);
- ntChallengeResp.append(temp);
+ QByteArray ntChallengeResp = qEncodeHmacMd5(phase3->v2Hash, message);
+ ntChallengeResp.append(temp);
- return ntChallengeResp;
+ return ntChallengeResp;
}
-static QByteArray qEncodeLmv2Response(const QHttpAuthenticatorPrivate *ctx,
- const QNtlmPhase2Block& ch,
- QNtlmPhase3Block *phase3)
+static QByteArray qEncodeLmv2Response(const QHttpAuthenticatorPrivate * ctx,
+ const QNtlmPhase2Block & ch,
+ QNtlmPhase3Block * phase3)
{
- Q_ASSERT(phase3 != 0);
- // return value stored in phase3
- qCreatev2Hash(ctx, phase3);
+ Q_ASSERT(phase3 != 0);
+ // return value stored in phase3
+ qCreatev2Hash(ctx, phase3);
- QByteArray message((const char*)ch.challenge, sizeof(ch.challenge));
- QByteArray clientCh = clientChallenge(ctx);
+ QByteArray message((const char *)ch.challenge, sizeof(ch.challenge));
+ QByteArray clientCh = clientChallenge(ctx);
- message.append(clientCh);
+ message.append(clientCh);
- QByteArray lmChallengeResp = qEncodeHmacMd5(phase3->v2Hash, message);
- lmChallengeResp.append(clientCh);
+ QByteArray lmChallengeResp = qEncodeHmacMd5(phase3->v2Hash, message);
+ lmChallengeResp.append(clientCh);
- return lmChallengeResp;
+ return lmChallengeResp;
}
-static bool qNtlmDecodePhase2(const QByteArray& data, QNtlmPhase2Block& ch)
+static bool qNtlmDecodePhase2(const QByteArray & data, QNtlmPhase2Block & ch)
{
- Q_ASSERT(QNtlmPhase2BlockBase::Size == sizeof(QNtlmPhase2BlockBase));
- if (data.size() < QNtlmPhase2BlockBase::Size)
- return false;
+ Q_ASSERT(QNtlmPhase2BlockBase::Size == sizeof(QNtlmPhase2BlockBase));
+ if(data.size() < QNtlmPhase2BlockBase::Size)
+ return false;
+ QDataStream ds(data);
+ ds.setByteOrder(QDataStream::LittleEndian);
+ if(ds.readRawData(ch.magic, 8) < 8)
+ return false;
+ if(strncmp(ch.magic, "NTLMSSP", 8) != 0)
+ return false;
- QDataStream ds(data);
- ds.setByteOrder(QDataStream::LittleEndian);
- if (ds.readRawData(ch.magic, 8) < 8)
- return false;
- if (strncmp(ch.magic, "NTLMSSP", 8) != 0)
- return false;
+ ds >> ch.type;
+ if(ch.type != 2)
+ return false;
- ds >> ch.type;
- if (ch.type != 2)
- return false;
+ ds >> ch.targetName;
+ ds >> ch.flags;
+ if(ds.readRawData((char *)ch.challenge, 8) < 8)
+ return false;
+ ds >> ch.context[0] >> ch.context[1];
+ ds >> ch.targetInfo;
- ds >> ch.targetName;
- ds >> ch.flags;
- if (ds.readRawData((char *)ch.challenge, 8) < 8)
- return false;
- ds >> ch.context[0] >> ch.context[1];
- ds >> ch.targetInfo;
+ if(ch.targetName.len > 0)
+ {
+ if(ch.targetName.len + ch.targetName.offset >= (unsigned)data.size())
+ return false;
- if (ch.targetName.len > 0) {
- if (ch.targetName.len + ch.targetName.offset >= (unsigned)data.size())
- return false;
+ ch.targetNameStr = qStringFromUcs2Le(data.mid(ch.targetName.offset, ch.targetName.len));
+ }
- ch.targetNameStr = qStringFromUcs2Le(data.mid(ch.targetName.offset, ch.targetName.len));
- }
+ if(ch.targetInfo.len > 0)
+ {
+ if(ch.targetInfo.len + ch.targetInfo.offset > (unsigned)data.size())
+ return false;
- if (ch.targetInfo.len > 0) {
- if (ch.targetInfo.len + ch.targetInfo.offset > (unsigned)data.size())
- return false;
+ ch.targetInfoBuff = data.mid(ch.targetInfo.offset, ch.targetInfo.len);
+ }
- ch.targetInfoBuff = data.mid(ch.targetInfo.offset, ch.targetInfo.len);
- }
-
- return true;
+ return true;
}
-
-static QByteArray qNtlmPhase3(QHttpAuthenticatorPrivate *ctx, const QByteArray& phase2data)
+static QByteArray qNtlmPhase3(QHttpAuthenticatorPrivate * ctx, const QByteArray & phase2data)
{
- QNtlmPhase2Block ch;
- if (!qNtlmDecodePhase2(phase2data, ch))
- return QByteArray();
+ QNtlmPhase2Block ch;
+ if(!qNtlmDecodePhase2(phase2data, ch))
+ return QByteArray();
- QByteArray rc;
- QDataStream ds(&rc, QIODevice::WriteOnly);
- ds.setByteOrder(QDataStream::LittleEndian);
- QNtlmPhase3Block pb;
+ QByteArray rc;
+ QDataStream ds(&rc, QIODevice::WriteOnly);
+ ds.setByteOrder(QDataStream::LittleEndian);
+ QNtlmPhase3Block pb;
- bool unicode = ch.flags & NTLMSSP_NEGOTIATE_UNICODE;
+ bool unicode = ch.flags & NTLMSSP_NEGOTIATE_UNICODE;
- pb.flags = NTLMSSP_NEGOTIATE_NTLM;
- if (unicode)
- pb.flags |= NTLMSSP_NEGOTIATE_UNICODE;
- else
- pb.flags |= NTLMSSP_NEGOTIATE_OEM;
+ pb.flags = NTLMSSP_NEGOTIATE_NTLM;
+ if(unicode)
+ pb.flags |= NTLMSSP_NEGOTIATE_UNICODE;
+ else
+ pb.flags |= NTLMSSP_NEGOTIATE_OEM;
+ int offset = QNtlmPhase3BlockBase::Size;
+ Q_ASSERT(QNtlmPhase3BlockBase::Size == sizeof(QNtlmPhase3BlockBase));
- int offset = QNtlmPhase3BlockBase::Size;
- Q_ASSERT(QNtlmPhase3BlockBase::Size == sizeof(QNtlmPhase3BlockBase));
+ // for kerberos style user@domain logins, NTLM domain string should be left empty
+ if(ctx->userDomain.isEmpty() && !ctx->extractedUser.contains(QLatin1Char('@')))
+ {
+ offset = qEncodeNtlmString(pb.domain, offset, ch.targetNameStr, unicode);
+ pb.domainStr = ch.targetNameStr;
+ }
+ else
+ {
+ offset = qEncodeNtlmString(pb.domain, offset, ctx->userDomain, unicode);
+ pb.domainStr = ctx->userDomain;
+ }
- // for kerberos style user@domain logins, NTLM domain string should be left empty
- if (ctx->userDomain.isEmpty() && !ctx->extractedUser.contains(QLatin1Char('@'))) {
- offset = qEncodeNtlmString(pb.domain, offset, ch.targetNameStr, unicode);
- pb.domainStr = ch.targetNameStr;
- } else {
- offset = qEncodeNtlmString(pb.domain, offset, ctx->userDomain, unicode);
- pb.domainStr = ctx->userDomain;
- }
+ offset = qEncodeNtlmString(pb.user, offset, ctx->extractedUser, unicode);
+ pb.userStr = ctx->extractedUser;
- offset = qEncodeNtlmString(pb.user, offset, ctx->extractedUser, unicode);
- pb.userStr = ctx->extractedUser;
+ offset = qEncodeNtlmString(pb.workstation, offset, ctx->workstation, unicode);
+ pb.workstationStr = ctx->workstation;
- offset = qEncodeNtlmString(pb.workstation, offset, ctx->workstation, unicode);
- pb.workstationStr = ctx->workstation;
-
- // Get LM response
+// Get LM response
#ifdef NTLMV1_CLIENT
- pb.lmResponseBuf = qEncodeLmResponse(ctx, ch);
+ pb.lmResponseBuf = qEncodeLmResponse(ctx, ch);
#else
- if (ch.targetInfo.len > 0) {
- pb.lmResponseBuf = QByteArray();
- } else {
- pb.lmResponseBuf = qEncodeLmv2Response(ctx, ch, &pb);
- }
+ if(ch.targetInfo.len > 0)
+ {
+ pb.lmResponseBuf = QByteArray();
+ }
+ else
+ {
+ pb.lmResponseBuf = qEncodeLmv2Response(ctx, ch, &pb);
+ }
#endif
- offset = qEncodeNtlmBuffer(pb.lmResponse, offset, pb.lmResponseBuf);
+ offset = qEncodeNtlmBuffer(pb.lmResponse, offset, pb.lmResponseBuf);
- // Get NTLM response
+// Get NTLM response
#ifdef NTLMV1_CLIENT
- pb.ntlmResponseBuf = qEncodeNtlmResponse(ctx, ch);
+ pb.ntlmResponseBuf = qEncodeNtlmResponse(ctx, ch);
#else
- pb.ntlmResponseBuf = qEncodeNtlmv2Response(ctx, ch, &pb);
+ pb.ntlmResponseBuf = qEncodeNtlmv2Response(ctx, ch, &pb);
#endif
- offset = qEncodeNtlmBuffer(pb.ntlmResponse, offset, pb.ntlmResponseBuf);
-
+ offset = qEncodeNtlmBuffer(pb.ntlmResponse, offset, pb.ntlmResponseBuf);
- // Encode and send
- ds << pb;
+ // Encode and send
+ ds << pb;
- return rc;
+ return rc;
}
-
-
QT_END_NAMESPACE
diff --git a/src/modules/objects/qthttp/qhttpauthenticator_p.h b/src/modules/objects/qthttp/qhttpauthenticator_p.h
index 54b4c3536..1c9a26b76 100644
--- a/src/modules/objects/qthttp/qhttpauthenticator_p.h
+++ b/src/modules/objects/qthttp/qhttpauthenticator_p.h
@@ -67,82 +67,92 @@ class QUrl;
class QHttpAuthenticator
{
public:
- QHttpAuthenticator();
- ~QHttpAuthenticator();
+ QHttpAuthenticator();
+ ~QHttpAuthenticator();
- QHttpAuthenticator(const QHttpAuthenticator &other);
- QHttpAuthenticator &operator=(const QHttpAuthenticator &other);
+ QHttpAuthenticator(const QHttpAuthenticator & other);
+ QHttpAuthenticator & operator=(const QHttpAuthenticator & other);
- bool operator==(const QHttpAuthenticator &other) const;
- inline bool operator!=(const QHttpAuthenticator &other) const { return !operator==(other); }
+ bool operator==(const QHttpAuthenticator & other) const;
+ inline bool operator!=(const QHttpAuthenticator & other) const { return !operator==(other); }
- QString user() const;
- void setUser(const QString &user);
+ QString user() const;
+ void setUser(const QString & user);
- QString password() const;
- void setPassword(const QString &password);
+ QString password() const;
+ void setPassword(const QString & password);
- QString realm() const;
+ QString realm() const;
- QVariant option(const QString &opt) const;
- QVariantHash options() const;
- void setOption(const QString &opt, const QVariant &value);
+ QVariant option(const QString & opt) const;
+ QVariantHash options() const;
+ void setOption(const QString & opt, const QVariant & value);
- bool isNull() const;
- void detach();
+ bool isNull() const;
+ void detach();
+
+ QHttpAuthenticator & operator=(const QAuthenticator & auth);
+ QAuthenticator toQAuthenticator();
- QHttpAuthenticator &operator=(const QAuthenticator& auth);
- QAuthenticator toQAuthenticator();
private:
- friend class QHttpAuthenticatorPrivate;
- QHttpAuthenticatorPrivate *d;
+ friend class QHttpAuthenticatorPrivate;
+ QHttpAuthenticatorPrivate * d;
};
class QHttpAuthenticatorPrivate
{
public:
- enum Method { None, Basic, Plain, Login, Ntlm, CramMd5, DigestMd5 };
- QHttpAuthenticatorPrivate();
+ enum Method
+ {
+ None,
+ Basic,
+ Plain,
+ Login,
+ Ntlm,
+ CramMd5,
+ DigestMd5
+ };
+ QHttpAuthenticatorPrivate();
- QAtomicInt ref;
- QString user;
- QString extractedUser;
- QString password;
- QVariantHash options;
- Method method;
- QString realm;
- QByteArray challenge;
- bool hasFailed; //credentials have been tried but rejected by server.
+ QAtomicInt ref;
+ QString user;
+ QString extractedUser;
+ QString password;
+ QVariantHash options;
+ Method method;
+ QString realm;
+ QByteArray challenge;
+ bool hasFailed; //credentials have been tried but rejected by server.
- enum Phase {
- Start,
- Phase2,
- Done,
- Invalid
- };
- Phase phase;
+ enum Phase
+ {
+ Start,
+ Phase2,
+ Done,
+ Invalid
+ };
+ Phase phase;
- // digest specific
- QByteArray cnonce;
- int nonceCount;
+ // digest specific
+ QByteArray cnonce;
+ int nonceCount;
- // ntlm specific
- QString workstation;
- QString userDomain;
+ // ntlm specific
+ QString workstation;
+ QString userDomain;
- QByteArray calculateResponse(const QByteArray &method, const QByteArray &path);
+ QByteArray calculateResponse(const QByteArray & method, const QByteArray & path);
- inline static QHttpAuthenticatorPrivate *getPrivate(QHttpAuthenticator &auth) { return auth.d; }
- inline static const QHttpAuthenticatorPrivate *getPrivate(const QHttpAuthenticator &auth) { return auth.d; }
+ inline static QHttpAuthenticatorPrivate * getPrivate(QHttpAuthenticator & auth) { return auth.d; }
+ inline static const QHttpAuthenticatorPrivate * getPrivate(const QHttpAuthenticator & auth) { return auth.d; }
- QByteArray digestMd5Response(const QByteArray &challenge, const QByteArray &method, const QByteArray &path);
- static QHash<QByteArray, QByteArray> parseDigestAuthenticationChallenge(const QByteArray &challenge);
+ QByteArray digestMd5Response(const QByteArray & challenge, const QByteArray & method, const QByteArray & path);
+ static QHash<QByteArray, QByteArray> parseDigestAuthenticationChallenge(const QByteArray & challenge);
#ifndef QT_NO_HTTP
- void parseHttpResponse(const QHttpResponseHeader &, bool isProxy);
+ void parseHttpResponse(const QHttpResponseHeader &, bool isProxy);
#endif
- void parseHttpResponse(const QList<QPair<QByteArray, QByteArray> >&, bool isProxy);
-
+ void parseHttpResponse(const QList<QPair<QByteArray, QByteArray>> &, bool isProxy);
};
#endif
diff --git a/src/modules/objects/qthttp/qringbuffer_p.h b/src/modules/objects/qthttp/qringbuffer_p.h
index ff762fab2..b1690af52 100644
--- a/src/modules/objects/qthttp/qringbuffer_p.h
+++ b/src/modules/objects/qthttp/qringbuffer_p.h
@@ -59,389 +59,445 @@
class QRingBuffer
{
public:
- inline QRingBuffer(int growth = 4096) : basicBlockSize(growth) {
- buffers << QByteArray();
- clear();
- }
+ inline QRingBuffer(int growth = 4096) : basicBlockSize(growth)
+ {
+ buffers << QByteArray();
+ clear();
+ }
- inline int nextDataBlockSize() const {
- return (tailBuffer == 0 ? tail : buffers.first().size()) - head;
- }
+ inline int nextDataBlockSize() const
+ {
+ return (tailBuffer == 0 ? tail : buffers.first().size()) - head;
+ }
- inline const char *readPointer() const {
- return buffers.isEmpty() ? 0 : (buffers.first().constData() + head);
- }
+ inline const char * readPointer() const
+ {
+ return buffers.isEmpty() ? 0 : (buffers.first().constData() + head);
+ }
- // access the bytes at a specified position
- // the out-variable length will contain the amount of bytes readable
- // from there, e.g. the amount still the same QByteArray
- inline const char *readPointerAtPosition(qint64 pos, qint64 &length) const {
- if (buffers.isEmpty()) {
- length = 0;
- return 0;
- }
+ // access the bytes at a specified position
+ // the out-variable length will contain the amount of bytes readable
+ // from there, e.g. the amount still the same QByteArray
+ inline const char * readPointerAtPosition(qint64 pos, qint64 & length) const
+ {
+ if(buffers.isEmpty())
+ {
+ length = 0;
+ return 0;
+ }
- if (pos >= bufferSize) {
- length = 0;
- return 0;
- }
+ if(pos >= bufferSize)
+ {
+ length = 0;
+ return 0;
+ }
- // special case: it is in the first buffer
- int nextDataBlockSizeValue = nextDataBlockSize();
- if (pos - head < nextDataBlockSizeValue) {
- length = nextDataBlockSizeValue - pos;
- return buffers.at(0).constData() + head + pos;
- }
+ // special case: it is in the first buffer
+ int nextDataBlockSizeValue = nextDataBlockSize();
+ if(pos - head < nextDataBlockSizeValue)
+ {
+ length = nextDataBlockSizeValue - pos;
+ return buffers.at(0).constData() + head + pos;
+ }
- // special case: we only had one buffer and tried to read over it
- if (buffers.length() == 1) {
- length = 0;
- return 0;
- }
+ // special case: we only had one buffer and tried to read over it
+ if(buffers.length() == 1)
+ {
+ length = 0;
+ return 0;
+ }
- // skip the first
- pos -= nextDataBlockSizeValue;
+ // skip the first
+ pos -= nextDataBlockSizeValue;
- // normal case: it is somewhere in the second to the-one-before-the-tailBuffer
- for (int i = 1; i < tailBuffer; i++) {
- if (pos >= buffers[i].size()) {
- pos -= buffers[i].size();
- continue;
- }
+ // normal case: it is somewhere in the second to the-one-before-the-tailBuffer
+ for(int i = 1; i < tailBuffer; i++)
+ {
+ if(pos >= buffers[i].size())
+ {
+ pos -= buffers[i].size();
+ continue;
+ }
- length = buffers[i].length() - pos;
- return buffers[i].constData() + pos;
- }
+ length = buffers[i].length() - pos;
+ return buffers[i].constData() + pos;
+ }
- // it is in the tail buffer
- length = tail - pos;
- return buffers[tailBuffer].constData() + pos;
- }
+ // it is in the tail buffer
+ length = tail - pos;
+ return buffers[tailBuffer].constData() + pos;
+ }
- inline void free(int bytes) {
- bufferSize -= bytes;
- if (bufferSize < 0)
- bufferSize = 0;
+ inline void free(int bytes)
+ {
+ bufferSize -= bytes;
+ if(bufferSize < 0)
+ bufferSize = 0;
- for (;;) {
- int nextBlockSize = nextDataBlockSize();
- if (bytes < nextBlockSize) {
- head += bytes;
- if (head == tail && tailBuffer == 0)
- head = tail = 0;
- break;
- }
+ for(;;)
+ {
+ int nextBlockSize = nextDataBlockSize();
+ if(bytes < nextBlockSize)
+ {
+ head += bytes;
+ if(head == tail && tailBuffer == 0)
+ head = tail = 0;
+ break;
+ }
- bytes -= nextBlockSize;
- if (buffers.count() == 1) {
- if (buffers.at(0).size() != basicBlockSize)
- buffers[0].resize(basicBlockSize);
- head = tail = 0;
- tailBuffer = 0;
- break;
- }
+ bytes -= nextBlockSize;
+ if(buffers.count() == 1)
+ {
+ if(buffers.at(0).size() != basicBlockSize)
+ buffers[0].resize(basicBlockSize);
+ head = tail = 0;
+ tailBuffer = 0;
+ break;
+ }
- buffers.removeAt(0);
- --tailBuffer;
- head = 0;
- }
+ buffers.removeAt(0);
+ --tailBuffer;
+ head = 0;
+ }
- if (isEmpty())
- clear(); // try to minify/squeeze us
- }
+ if(isEmpty())
+ clear(); // try to minify/squeeze us
+ }
- inline char *reserve(int bytes) {
- // if this is a fresh empty QRingBuffer
- if (bufferSize == 0) {
- buffers[0].resize(qMax(basicBlockSize, bytes));
- bufferSize += bytes;
- tail = bytes;
- return buffers[tailBuffer].data();
- }
+ inline char * reserve(int bytes)
+ {
+ // if this is a fresh empty QRingBuffer
+ if(bufferSize == 0)
+ {
+ buffers[0].resize(qMax(basicBlockSize, bytes));
+ bufferSize += bytes;
+ tail = bytes;
+ return buffers[tailBuffer].data();
+ }
- bufferSize += bytes;
+ bufferSize += bytes;
- // if there is already enough space, simply return.
- if (tail + bytes <= buffers.at(tailBuffer).size()) {
- char *writePtr = buffers[tailBuffer].data() + tail;
- tail += bytes;
- return writePtr;
- }
+ // if there is already enough space, simply return.
+ if(tail + bytes <= buffers.at(tailBuffer).size())
+ {
+ char * writePtr = buffers[tailBuffer].data() + tail;
+ tail += bytes;
+ return writePtr;
+ }
- // if our buffer isn't half full yet, simply resize it.
- if (tail < buffers.at(tailBuffer).size() / 2) {
- buffers[tailBuffer].resize(tail + bytes);
- char *writePtr = buffers[tailBuffer].data() + tail;
- tail += bytes;
- return writePtr;
- }
+ // if our buffer isn't half full yet, simply resize it.
+ if(tail < buffers.at(tailBuffer).size() / 2)
+ {
+ buffers[tailBuffer].resize(tail + bytes);
+ char * writePtr = buffers[tailBuffer].data() + tail;
+ tail += bytes;
+ return writePtr;
+ }
- // shrink this buffer to its current size
- buffers[tailBuffer].resize(tail);
+ // shrink this buffer to its current size
+ buffers[tailBuffer].resize(tail);
- // create a new QByteArray with the right size
- buffers << QByteArray();
- ++tailBuffer;
- buffers[tailBuffer].resize(qMax(basicBlockSize, bytes));
- tail = bytes;
- return buffers[tailBuffer].data();
- }
+ // create a new QByteArray with the right size
+ buffers << QByteArray();
+ ++tailBuffer;
+ buffers[tailBuffer].resize(qMax(basicBlockSize, bytes));
+ tail = bytes;
+ return buffers[tailBuffer].data();
+ }
- inline void truncate(int pos) {
- if (pos < size())
- chop(size() - pos);
- }
+ inline void truncate(int pos)
+ {
+ if(pos < size())
+ chop(size() - pos);
+ }
- inline void chop(int bytes) {
- bufferSize -= bytes;
- if (bufferSize < 0)
- bufferSize = 0;
+ inline void chop(int bytes)
+ {
+ bufferSize -= bytes;
+ if(bufferSize < 0)
+ bufferSize = 0;
- for (;;) {
- // special case: head and tail are in the same buffer
- if (tailBuffer == 0) {
- tail -= bytes;
- if (tail <= head)
- tail = head = 0;
- return;
- }
+ for(;;)
+ {
+ // special case: head and tail are in the same buffer
+ if(tailBuffer == 0)
+ {
+ tail -= bytes;
+ if(tail <= head)
+ tail = head = 0;
+ return;
+ }
- if (bytes <= tail) {
- tail -= bytes;
- return;
- }
+ if(bytes <= tail)
+ {
+ tail -= bytes;
+ return;
+ }
- bytes -= tail;
- buffers.removeAt(tailBuffer);
+ bytes -= tail;
+ buffers.removeAt(tailBuffer);
- --tailBuffer;
- tail = buffers.at(tailBuffer).size();
- }
+ --tailBuffer;
+ tail = buffers.at(tailBuffer).size();
+ }
- if (isEmpty())
- clear(); // try to minify/squeeze us
- }
+ if(isEmpty())
+ clear(); // try to minify/squeeze us
+ }
- inline bool isEmpty() const {
- return tailBuffer == 0 && tail == 0;
- }
+ inline bool isEmpty() const
+ {
+ return tailBuffer == 0 && tail == 0;
+ }
- inline int getChar() {
- if (isEmpty())
- return -1;
- char c = *readPointer();
- free(1);
- return int(uchar(c));
- }
+ inline int getChar()
+ {
+ if(isEmpty())
+ return -1;
+ char c = *readPointer();
+ free(1);
+ return int(uchar(c));
+ }
- inline void putChar(char c) {
- char *ptr = reserve(1);
- *ptr = c;
- }
+ inline void putChar(char c)
+ {
+ char * ptr = reserve(1);
+ *ptr = c;
+ }
- inline void ungetChar(char c) {
- --head;
- if (head < 0) {
- buffers.prepend(QByteArray());
- buffers[0].resize(basicBlockSize);
- head = basicBlockSize - 1;
- ++tailBuffer;
- }
- buffers[0][head] = c;
- ++bufferSize;
- }
+ inline void ungetChar(char c)
+ {
+ --head;
+ if(head < 0)
+ {
+ buffers.prepend(QByteArray());
+ buffers[0].resize(basicBlockSize);
+ head = basicBlockSize - 1;
+ ++tailBuffer;
+ }
+ buffers[0][head] = c;
+ ++bufferSize;
+ }
- inline int size() const {
- return bufferSize;
- }
+ inline int size() const
+ {
+ return bufferSize;
+ }
- inline void clear() {
- buffers.erase(buffers.begin() + 1, buffers.end());
- buffers[0].resize(0);
- buffers[0].squeeze();
+ inline void clear()
+ {
+ buffers.erase(buffers.begin() + 1, buffers.end());
+ buffers[0].resize(0);
+ buffers[0].squeeze();
- head = tail = 0;
- tailBuffer = 0;
- bufferSize = 0;
- }
+ head = tail = 0;
+ tailBuffer = 0;
+ bufferSize = 0;
+ }
- inline int indexOf(char c) const {
- int index = 0;
- for (int i = 0; i < buffers.size(); ++i) {
- int start = 0;
- int end = buffers.at(i).size();
+ inline int indexOf(char c) const
+ {
+ int index = 0;
+ for(int i = 0; i < buffers.size(); ++i)
+ {
+ int start = 0;
+ int end = buffers.at(i).size();
- if (i == 0)
- start = head;
- if (i == tailBuffer)
- end = tail;
- const char *ptr = buffers.at(i).data() + start;
- for (int j = start; j < end; ++j) {
- if (*ptr++ == c)
- return index;
- ++index;
- }
- }
- return -1;
- }
+ if(i == 0)
+ start = head;
+ if(i == tailBuffer)
+ end = tail;
+ const char * ptr = buffers.at(i).data() + start;
+ for(int j = start; j < end; ++j)
+ {
+ if(*ptr++ == c)
+ return index;
+ ++index;
+ }
+ }
+ return -1;
+ }
- inline int indexOf(char c, int maxLength) const {
- int index = 0;
- int remain = qMin(size(), maxLength);
- for (int i = 0; remain && i < buffers.size(); ++i) {
- int start = 0;
- int end = buffers.at(i).size();
+ inline int indexOf(char c, int maxLength) const
+ {
+ int index = 0;
+ int remain = qMin(size(), maxLength);
+ for(int i = 0; remain && i < buffers.size(); ++i)
+ {
+ int start = 0;
+ int end = buffers.at(i).size();
- if (i == 0)
- start = head;
- if (i == tailBuffer)
- end = tail;
- if (remain < end - start) {
- end = start + remain;
- remain = 0;
- } else {
- remain -= end - start;
- }
- const char *ptr = buffers.at(i).data() + start;
- for (int j = start; j < end; ++j) {
- if (*ptr++ == c)
- return index;
- ++index;
- }
- }
- return -1;
- }
+ if(i == 0)
+ start = head;
+ if(i == tailBuffer)
+ end = tail;
+ if(remain < end - start)
+ {
+ end = start + remain;
+ remain = 0;
+ }
+ else
+ {
+ remain -= end - start;
+ }
+ const char * ptr = buffers.at(i).data() + start;
+ for(int j = start; j < end; ++j)
+ {
+ if(*ptr++ == c)
+ return index;
+ ++index;
+ }
+ }
+ return -1;
+ }
- inline int read(char *data, int maxLength) {
- int bytesToRead = qMin(size(), maxLength);
- int readSoFar = 0;
- while (readSoFar < bytesToRead) {
- const char *ptr = readPointer();
- int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar, nextDataBlockSize());
- if (data)
- memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
- readSoFar += bytesToReadFromThisBlock;
- free(bytesToReadFromThisBlock);
- }
- return readSoFar;
- }
+ inline int read(char * data, int maxLength)
+ {
+ int bytesToRead = qMin(size(), maxLength);
+ int readSoFar = 0;
+ while(readSoFar < bytesToRead)
+ {
+ const char * ptr = readPointer();
+ int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar, nextDataBlockSize());
+ if(data)
+ memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
+ readSoFar += bytesToReadFromThisBlock;
+ free(bytesToReadFromThisBlock);
+ }
+ return readSoFar;
+ }
- inline QByteArray read(int maxLength) {
- QByteArray tmp;
- tmp.resize(qMin(maxLength, size()));
- read(tmp.data(), tmp.size());
- return tmp;
- }
+ inline QByteArray read(int maxLength)
+ {
+ QByteArray tmp;
+ tmp.resize(qMin(maxLength, size()));
+ read(tmp.data(), tmp.size());
+ return tmp;
+ }
- inline QByteArray readAll() {
- return read(size());
- }
+ inline QByteArray readAll()
+ {
+ return read(size());
+ }
- // read an unspecified amount (will read the first buffer)
- inline QByteArray read() {
- if (bufferSize == 0)
- return QByteArray();
+ // read an unspecified amount (will read the first buffer)
+ inline QByteArray read()
+ {
+ if(bufferSize == 0)
+ return QByteArray();
- // multiple buffers, just take the first one
- if (head == 0 && tailBuffer != 0) {
- QByteArray qba = buffers.takeFirst();
- --tailBuffer;
- bufferSize -= qba.length();
- return qba;
- }
+ // multiple buffers, just take the first one
+ if(head == 0 && tailBuffer != 0)
+ {
+ QByteArray qba = buffers.takeFirst();
+ --tailBuffer;
+ bufferSize -= qba.length();
+ return qba;
+ }
- // one buffer with good value for head. Just take it.
- if (head == 0 && tailBuffer == 0) {
- QByteArray qba = buffers.takeFirst();
- qba.resize(tail);
- buffers << QByteArray();
- bufferSize = 0;
- tail = 0;
- return qba;
- }
+ // one buffer with good value for head. Just take it.
+ if(head == 0 && tailBuffer == 0)
+ {
+ QByteArray qba = buffers.takeFirst();
+ qba.resize(tail);
+ buffers << QByteArray();
+ bufferSize = 0;
+ tail = 0;
+ return qba;
+ }
- // Bad case: We have to memcpy.
- // We can avoid by initializing the QRingBuffer with basicBlockSize of 0
- // and only using this read() function.
- QByteArray qba(readPointer(), nextDataBlockSize());
- buffers.removeFirst();
- head = 0;
- if (tailBuffer == 0) {
- buffers << QByteArray();
- tail = 0;
- } else {
- --tailBuffer;
- }
- bufferSize -= qba.length();
- return qba;
- }
+ // Bad case: We have to memcpy.
+ // We can avoid by initializing the QRingBuffer with basicBlockSize of 0
+ // and only using this read() function.
+ QByteArray qba(readPointer(), nextDataBlockSize());
+ buffers.removeFirst();
+ head = 0;
+ if(tailBuffer == 0)
+ {
+ buffers << QByteArray();
+ tail = 0;
+ }
+ else
+ {
+ --tailBuffer;
+ }
+ bufferSize -= qba.length();
+ return qba;
+ }
- // append a new buffer to the end
- inline void append(const QByteArray &qba) {
- buffers[tailBuffer].resize(tail);
- buffers << qba;
- ++tailBuffer;
- tail = qba.length();
- bufferSize += qba.length();
- }
+ // append a new buffer to the end
+ inline void append(const QByteArray & qba)
+ {
+ buffers[tailBuffer].resize(tail);
+ buffers << qba;
+ ++tailBuffer;
+ tail = qba.length();
+ bufferSize += qba.length();
+ }
- inline QByteArray peek(int maxLength) const {
- int bytesToRead = qMin(size(), maxLength);
- if(maxLength <= 0)
- return QByteArray();
- QByteArray ret;
- ret.resize(bytesToRead);
- int readSoFar = 0;
- for (int i = 0; readSoFar < bytesToRead && i < buffers.size(); ++i) {
- int start = 0;
- int end = buffers.at(i).size();
- if (i == 0)
- start = head;
- if (i == tailBuffer)
- end = tail;
- const int len = qMin(ret.size()-readSoFar, end-start);
- memcpy(ret.data()+readSoFar, buffers.at(i).constData()+start, len);
- readSoFar += len;
- }
- Q_ASSERT(readSoFar == ret.size());
- return ret;
- }
+ inline QByteArray peek(int maxLength) const
+ {
+ int bytesToRead = qMin(size(), maxLength);
+ if(maxLength <= 0)
+ return QByteArray();
+ QByteArray ret;
+ ret.resize(bytesToRead);
+ int readSoFar = 0;
+ for(int i = 0; readSoFar < bytesToRead && i < buffers.size(); ++i)
+ {
+ int start = 0;
+ int end = buffers.at(i).size();
+ if(i == 0)
+ start = head;
+ if(i == tailBuffer)
+ end = tail;
+ const int len = qMin(ret.size() - readSoFar, end - start);
+ memcpy(ret.data() + readSoFar, buffers.at(i).constData() + start, len);
+ readSoFar += len;
+ }
+ Q_ASSERT(readSoFar == ret.size());
+ return ret;
+ }
- inline int skip(int length) {
- return read(0, length);
- }
+ inline int skip(int length)
+ {
+ return read(0, length);
+ }
- inline int readLine(char *data, int maxLength) {
- int index = indexOf('\n');
- if (index == -1)
- return read(data, maxLength);
- if (maxLength <= 0)
- return -1;
+ inline int readLine(char * data, int maxLength)
+ {
+ int index = indexOf('\n');
+ if(index == -1)
+ return read(data, maxLength);
+ if(maxLength <= 0)
+ return -1;
- int readSoFar = 0;
- while (readSoFar < index + 1 && readSoFar < maxLength - 1) {
- int bytesToRead = qMin((index + 1) - readSoFar, nextDataBlockSize());
- bytesToRead = qMin(bytesToRead, (maxLength - 1) - readSoFar);
- memcpy(data + readSoFar, readPointer(), bytesToRead);
- readSoFar += bytesToRead;
- free(bytesToRead);
- }
+ int readSoFar = 0;
+ while(readSoFar < index + 1 && readSoFar < maxLength - 1)
+ {
+ int bytesToRead = qMin((index + 1) - readSoFar, nextDataBlockSize());
+ bytesToRead = qMin(bytesToRead, (maxLength - 1) - readSoFar);
+ memcpy(data + readSoFar, readPointer(), bytesToRead);
+ readSoFar += bytesToRead;
+ free(bytesToRead);
+ }
- // Terminate it.
- data[readSoFar] = '\0';
- return readSoFar;
- }
+ // Terminate it.
+ data[readSoFar] = '\0';
+ return readSoFar;
+ }
- inline bool canReadLine() const {
- return indexOf('\n') != -1;
- }
+ inline bool canReadLine() const
+ {
+ return indexOf('\n') != -1;
+ }
private:
- QList<QByteArray> buffers;
- int head, tail;
- int tailBuffer; // always buffers.size() - 1
- int basicBlockSize;
- int bufferSize;
+ QList<QByteArray> buffers;
+ int head, tail;
+ int tailBuffer; // always buffers.size() - 1
+ int basicBlockSize;
+ int bufferSize;
};
#endif // QRINGBUFFER_P_H