summaryrefslogtreecommitdiffstats
path: root/src/network
diff options
context:
space:
mode:
Diffstat (limited to 'src/network')
-rw-r--r--src/network/access/qabstractnetworkcache.h7
-rw-r--r--src/network/access/qftp.cpp1
-rw-r--r--src/network/access/qhttpmultipart.h9
-rw-r--r--src/network/access/qhttpnetworkconnection.cpp57
-rw-r--r--src/network/access/qhttpnetworkconnection_p.h1
-rw-r--r--src/network/access/qhttpnetworkconnectionchannel.cpp18
-rw-r--r--src/network/access/qhttpnetworkheader.cpp12
-rw-r--r--src/network/access/qhttpnetworkreply.cpp30
-rw-r--r--src/network/access/qhttpnetworkreply_p.h10
-rw-r--r--src/network/access/qhttpnetworkrequest.cpp24
-rw-r--r--src/network/access/qhttpnetworkrequest_p.h8
-rw-r--r--src/network/access/qhttpthreaddelegate.cpp7
-rw-r--r--src/network/access/qhttpthreaddelegate_p.h2
-rw-r--r--src/network/access/qnetworkaccessauthenticationmanager_p.h2
-rw-r--r--src/network/access/qnetworkaccessbackend.cpp1
-rw-r--r--src/network/access/qnetworkaccesscache.cpp6
-rw-r--r--src/network/access/qnetworkaccessmanager.cpp7
-rw-r--r--src/network/access/qnetworkaccessmanager.h6
-rw-r--r--src/network/access/qnetworkaccessmanager_p.h2
-rw-r--r--src/network/access/qnetworkcookie.cpp2
-rw-r--r--src/network/access/qnetworkcookie.h5
-rw-r--r--src/network/access/qnetworkcookiejar.cpp4
-rw-r--r--src/network/access/qnetworkcookiejar.h2
-rw-r--r--src/network/access/qnetworkdiskcache.h2
-rw-r--r--src/network/access/qnetworkreply.cpp32
-rw-r--r--src/network/access/qnetworkreply.h5
-rw-r--r--src/network/access/qnetworkreply_p.h1
-rw-r--r--src/network/access/qnetworkreplyfileimpl.cpp7
-rw-r--r--src/network/access/qnetworkreplyhttpimpl.cpp201
-rw-r--r--src/network/access/qnetworkreplyhttpimpl_p.h13
-rw-r--r--src/network/access/qnetworkreplyimpl.cpp21
-rw-r--r--src/network/access/qnetworkreplyimpl_p.h3
-rw-r--r--src/network/access/qnetworkrequest.cpp45
-rw-r--r--src/network/access/qnetworkrequest.h10
-rw-r--r--src/network/access/qspdyprotocolhandler.cpp41
-rw-r--r--src/network/bearer/qnetworkconfigmanager.h4
-rw-r--r--src/network/bearer/qnetworkconfigmanager_p.cpp15
-rw-r--r--src/network/bearer/qnetworkconfiguration.cpp14
-rw-r--r--src/network/bearer/qnetworkconfiguration.h5
-rw-r--r--src/network/bearer/qnetworksession.h2
-rw-r--r--src/network/doc/qtnetwork.qdocconf2
-rw-r--r--src/network/doc/snippets/code/src_network_bearer_qnetworkconfigmanager.cpp6
-rw-r--r--src/network/doc/snippets/code/src_network_ssl_qsslsocket.cpp3
-rw-r--r--src/network/kernel/kernel.pri9
-rw-r--r--src/network/kernel/qauthenticator.cpp4
-rw-r--r--src/network/kernel/qdnslookup.cpp3
-rw-r--r--src/network/kernel/qdnslookup.h46
-rw-r--r--src/network/kernel/qdnslookup_android.cpp2
-rw-r--r--src/network/kernel/qdnslookup_p.h2
-rw-r--r--src/network/kernel/qdnslookup_unix.cpp4
-rw-r--r--src/network/kernel/qdnslookup_win.cpp4
-rw-r--r--src/network/kernel/qdnslookup_winrt.cpp45
-rw-r--r--src/network/kernel/qhostaddress.cpp138
-rw-r--r--src/network/kernel/qhostaddress.h9
-rw-r--r--src/network/kernel/qhostinfo.cpp16
-rw-r--r--src/network/kernel/qhostinfo_unix.cpp9
-rw-r--r--src/network/kernel/qhostinfo_win.cpp34
-rw-r--r--src/network/kernel/qhostinfo_winrt.cpp174
-rw-r--r--src/network/kernel/qnetworkinterface.cpp16
-rw-r--r--src/network/kernel/qnetworkinterface.h13
-rw-r--r--src/network/kernel/qnetworkinterface_unix.cpp90
-rw-r--r--src/network/kernel/qnetworkinterface_win.cpp140
-rw-r--r--src/network/kernel/qnetworkinterface_win_p.h262
-rw-r--r--src/network/kernel/qnetworkinterface_winrt.cpp149
-rw-r--r--src/network/kernel/qnetworkproxy.cpp5
-rw-r--r--src/network/kernel/qnetworkproxy.h14
-rw-r--r--src/network/kernel/qnetworkproxy_generic.cpp2
-rw-r--r--src/network/kernel/qnetworkproxy_mac.cpp1
-rw-r--r--src/network/socket/qabstractsocket.cpp137
-rw-r--r--src/network/socket/qabstractsocket.h4
-rw-r--r--src/network/socket/qabstractsocket_p.h5
-rw-r--r--src/network/socket/qabstractsocketengine_p.h48
-rw-r--r--src/network/socket/qhttpsocketengine.cpp13
-rw-r--r--src/network/socket/qhttpsocketengine_p.h7
-rw-r--r--src/network/socket/qlocalserver.h4
-rw-r--r--src/network/socket/qlocalserver_unix.cpp2
-rw-r--r--src/network/socket/qlocalsocket.h2
-rw-r--r--src/network/socket/qnativesocketengine.cpp76
-rw-r--r--src/network/socket/qnativesocketengine_p.h126
-rw-r--r--src/network/socket/qnativesocketengine_unix.cpp334
-rw-r--r--src/network/socket/qnativesocketengine_win.cpp333
-rw-r--r--src/network/socket/qnativesocketengine_winrt.cpp321
-rw-r--r--src/network/socket/qnativesocketengine_winrt_p.h9
-rw-r--r--src/network/socket/qnet_unix_p.h35
-rw-r--r--src/network/socket/qsocks5socketengine.cpp32
-rw-r--r--src/network/socket/qsocks5socketengine_p.h7
-rw-r--r--src/network/socket/qtcpserver.cpp42
-rw-r--r--src/network/socket/qtcpserver.h6
-rw-r--r--src/network/socket/qtcpserver_p.h2
-rw-r--r--src/network/socket/qtcpsocket.cpp9
-rw-r--r--src/network/socket/qtcpsocket.h6
-rw-r--r--src/network/socket/qudpsocket.cpp28
-rw-r--r--src/network/socket/qudpsocket.h4
-rw-r--r--src/network/ssl/qssl.cpp4
-rw-r--r--src/network/ssl/qssl.h3
-rw-r--r--src/network/ssl/qsslcertificate.h9
-rw-r--r--src/network/ssl/qsslcertificate_openssl.cpp3
-rw-r--r--src/network/ssl/qsslcertificateextension.h8
-rw-r--r--src/network/ssl/qsslcipher.h7
-rw-r--r--src/network/ssl/qsslconfiguration.h5
-rw-r--r--src/network/ssl/qsslcontext_openssl.cpp4
-rw-r--r--src/network/ssl/qsslellipticcurve.cpp2
-rw-r--r--src/network/ssl/qsslellipticcurve.h3
-rw-r--r--src/network/ssl/qsslerror.h5
-rw-r--r--src/network/ssl/qsslkey.h7
-rw-r--r--src/network/ssl/qsslkey_openssl.cpp49
-rw-r--r--src/network/ssl/qsslkey_p.h19
-rw-r--r--src/network/ssl/qsslpresharedkeyauthenticator.h8
-rw-r--r--src/network/ssl/qsslpresharedkeyauthenticator_p.h11
-rw-r--r--src/network/ssl/qsslsocket.cpp42
-rw-r--r--src/network/ssl/qsslsocket.h2
-rw-r--r--src/network/ssl/qsslsocket_mac.cpp70
-rw-r--r--src/network/ssl/qsslsocket_mac_p.h7
-rw-r--r--src/network/ssl/qsslsocket_openssl.cpp120
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols.cpp105
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols_p.h25
-rw-r--r--src/network/ssl/qsslsocket_winrt.cpp30
117 files changed, 2226 insertions, 1760 deletions
diff --git a/src/network/access/qabstractnetworkcache.h b/src/network/access/qabstractnetworkcache.h
index 352daa9700..326891b3dc 100644
--- a/src/network/access/qabstractnetworkcache.h
+++ b/src/network/access/qabstractnetworkcache.h
@@ -60,9 +60,12 @@ public:
QNetworkCacheMetaData(const QNetworkCacheMetaData &other);
~QNetworkCacheMetaData();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkCacheMetaData &operator=(QNetworkCacheMetaData &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkCacheMetaData &operator=(const QNetworkCacheMetaData &other);
- void swap(QNetworkCacheMetaData &other)
+ void swap(QNetworkCacheMetaData &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QNetworkCacheMetaData &other) const;
@@ -121,7 +124,7 @@ public Q_SLOTS:
virtual void clear() = 0;
protected:
- explicit QAbstractNetworkCache(QObject *parent = 0);
+ explicit QAbstractNetworkCache(QObject *parent = Q_NULLPTR);
QAbstractNetworkCache(QAbstractNetworkCachePrivate &dd, QObject *parent);
private:
diff --git a/src/network/access/qftp.cpp b/src/network/access/qftp.cpp
index a83d56f31f..74c95ecd5e 100644
--- a/src/network/access/qftp.cpp
+++ b/src/network/access/qftp.cpp
@@ -46,7 +46,6 @@
#include "qregexp.h"
#include "qtimer.h"
#include "qfileinfo.h"
-#include "qhash.h"
#include "qtcpserver.h"
#include "qlocale.h"
diff --git a/src/network/access/qhttpmultipart.h b/src/network/access/qhttpmultipart.h
index 2e08a3d6f8..5f865c059b 100644
--- a/src/network/access/qhttpmultipart.h
+++ b/src/network/access/qhttpmultipart.h
@@ -51,9 +51,12 @@ public:
QHttpPart();
QHttpPart(const QHttpPart &other);
~QHttpPart();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QHttpPart &operator=(QHttpPart &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QHttpPart &operator=(const QHttpPart &other);
- void swap(QHttpPart &other) { qSwap(d, other.d); }
+ void swap(QHttpPart &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QHttpPart &other) const;
inline bool operator!=(const QHttpPart &other) const
@@ -88,8 +91,8 @@ public:
AlternativeType
};
- explicit QHttpMultiPart(QObject *parent = 0);
- explicit QHttpMultiPart(ContentType contentType, QObject *parent = 0);
+ explicit QHttpMultiPart(QObject *parent = Q_NULLPTR);
+ explicit QHttpMultiPart(ContentType contentType, QObject *parent = Q_NULLPTR);
~QHttpMultiPart();
void append(const QHttpPart &httpPart);
diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp
index f810df5711..c4cb8e65c0 100644
--- a/src/network/access/qhttpnetworkconnection.cpp
+++ b/src/network/access/qhttpnetworkconnection.cpp
@@ -326,7 +326,7 @@ void QHttpNetworkConnectionPrivate::prepareRequest(HttpMessagePair &messagePair)
QByteArray host;
if (add.setAddress(hostName)) {
if (add.protocol() == QAbstractSocket::IPv6Protocol)
- host = "[" + hostName.toLatin1() + "]";//format the ipv6 in the standard way
+ host = '[' + hostName.toLatin1() + ']'; //format the ipv6 in the standard way
else
host = hostName.toLatin1();
@@ -506,6 +506,53 @@ bool QHttpNetworkConnectionPrivate::handleAuthenticateChallenge(QAbstractSocket
return false;
}
+QUrl QHttpNetworkConnectionPrivate::parseRedirectResponse(QAbstractSocket *socket, QHttpNetworkReply *reply)
+{
+ if (!reply->request().isFollowRedirects())
+ return QUrl();
+
+ QUrl rUrl;
+ QList<QPair<QByteArray, QByteArray> > fields = reply->header();
+ foreach (const QNetworkReply::RawHeaderPair &header, fields) {
+ if (header.first.toLower() == "location") {
+ rUrl = QUrl::fromEncoded(header.second);
+ break;
+ }
+ }
+
+ // If the location url is invalid/empty, we emit ProtocolUnknownError
+ if (!rUrl.isValid()) {
+ emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
+ return QUrl();
+ }
+
+ // Check if we have exceeded max redirects allowed
+ if (reply->request().redirectCount() <= 0) {
+ emitReplyError(socket, reply, QNetworkReply::TooManyRedirectsError);
+ return QUrl();
+ }
+
+ // Resolve the URL if it's relative
+ if (rUrl.isRelative())
+ rUrl = reply->request().url().resolved(rUrl);
+
+ // Check redirect url protocol
+ QString scheme = rUrl.scheme();
+ if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) {
+ QString previousUrlScheme = reply->request().url().scheme();
+ // Check if we're doing an unsecure redirect (https -> http)
+ if (previousUrlScheme == QLatin1String("https")
+ && scheme == QLatin1String("http")) {
+ emitReplyError(socket, reply, QNetworkReply::InsecureRedirectError);
+ return QUrl();
+ }
+ } else {
+ emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
+ return QUrl();
+ }
+ return rUrl;
+}
+
void QHttpNetworkConnectionPrivate::createAuthorization(QAbstractSocket *socket, QHttpNetworkRequest &request)
{
Q_ASSERT(socket);
@@ -802,6 +849,12 @@ QString QHttpNetworkConnectionPrivate::errorDetail(QNetworkReply::NetworkError e
case QNetworkReply::SslHandshakeFailedError:
errorString = QCoreApplication::translate("QHttp", "SSL handshake failed");
break;
+ case QNetworkReply::TooManyRedirectsError:
+ errorString = QCoreApplication::translate("QHttp", "Too many redirects");
+ break;
+ case QNetworkReply::InsecureRedirectError:
+ errorString = QCoreApplication::translate("QHttp", "Insecure redirect");
+ break;
default:
// all other errors are treated as QNetworkReply::UnknownNetworkError
errorString = extraDetail;
@@ -1394,7 +1447,7 @@ void QHttpNetworkConnectionPrivate::emitProxyAuthenticationRequired(const QHttpN
// but that does not matter because the signal will ultimately be emitted
// by the QNetworkAccessManager.
Q_ASSERT(chan->spdyRequestsToSend.count() > 0);
- reply = chan->spdyRequestsToSend.values().first().second;
+ reply = chan->spdyRequestsToSend.cbegin().value().second;
} else { // HTTP
#endif // QT_NO_SSL
reply = chan->reply;
diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h
index 115eef581e..9af39d416a 100644
--- a/src/network/access/qhttpnetworkconnection_p.h
+++ b/src/network/access/qhttpnetworkconnection_p.h
@@ -250,6 +250,7 @@ public:
void emitReplyError(QAbstractSocket *socket, QHttpNetworkReply *reply, QNetworkReply::NetworkError errorCode);
bool handleAuthenticateChallenge(QAbstractSocket *socket, QHttpNetworkReply *reply, bool isProxy, bool &resend);
+ QUrl parseRedirectResponse(QAbstractSocket *socket, QHttpNetworkReply *reply);
#ifndef QT_NO_NETWORKPROXY
QNetworkProxy networkProxy;
diff --git a/src/network/access/qhttpnetworkconnectionchannel.cpp b/src/network/access/qhttpnetworkconnectionchannel.cpp
index 453a0c71b6..f591abc28b 100644
--- a/src/network/access/qhttpnetworkconnectionchannel.cpp
+++ b/src/network/access/qhttpnetworkconnectionchannel.cpp
@@ -254,6 +254,10 @@ void QHttpNetworkConnectionChannel::handleUnexpectedEOF()
close();
reply->d_func()->errorString = connection->d_func()->errorDetail(QNetworkReply::RemoteHostClosedError, socket);
emit reply->finishedWithError(QNetworkReply::RemoteHostClosedError, reply->d_func()->errorString);
+ reply = 0;
+ if (protocolHandler)
+ protocolHandler->setReply(0);
+ request = QHttpNetworkRequest();
QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
} else {
reconnectAttempts--;
@@ -536,6 +540,20 @@ void QHttpNetworkConnectionChannel::handleStatus()
bool resend = false;
switch (statusCode) {
+ case 301:
+ case 302:
+ case 303:
+ case 305:
+ case 307: {
+ // Parse the response headers and get the "location" url
+ QUrl redirectUrl = connection->d_func()->parseRedirectResponse(socket, reply);
+ if (redirectUrl.isValid())
+ reply->setRedirectUrl(redirectUrl);
+
+ if (qobject_cast<QHttpNetworkConnection *>(connection))
+ QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
+ break;
+ }
case 401: // auth required
case 407: // proxy auth required
if (connection->d_func()->handleAuthenticateChallenge(socket, reply, (statusCode == 407), resend)) {
diff --git a/src/network/access/qhttpnetworkheader.cpp b/src/network/access/qhttpnetworkheader.cpp
index af9f38cdec..cf8259294d 100644
--- a/src/network/access/qhttpnetworkheader.cpp
+++ b/src/network/access/qhttpnetworkheader.cpp
@@ -79,16 +79,8 @@ QByteArray QHttpNetworkHeaderPrivate::headerField(const QByteArray &name, const
QList<QByteArray> allValues = headerFieldValues(name);
if (allValues.isEmpty())
return defaultValue;
-
- QByteArray result;
- bool first = true;
- foreach (const QByteArray &value, allValues) {
- if (!first)
- result += ", ";
- first = false;
- result += value;
- }
- return result;
+ else
+ return allValues.join(", ");
}
QList<QByteArray> QHttpNetworkHeaderPrivate::headerFieldValues(const QByteArray &name) const
diff --git a/src/network/access/qhttpnetworkreply.cpp b/src/network/access/qhttpnetworkreply.cpp
index b744a99f0f..a0f05523e3 100644
--- a/src/network/access/qhttpnetworkreply.cpp
+++ b/src/network/access/qhttpnetworkreply.cpp
@@ -78,6 +78,23 @@ void QHttpNetworkReply::setUrl(const QUrl &url)
d->url = url;
}
+QUrl QHttpNetworkReply::redirectUrl() const
+{
+ return d_func()->redirectUrl;
+}
+
+void QHttpNetworkReply::setRedirectUrl(const QUrl &url)
+{
+ Q_D(QHttpNetworkReply);
+ d->redirectUrl = url;
+}
+
+bool QHttpNetworkReply::isHttpRedirect(int statusCode)
+{
+ return (statusCode == 301 || statusCode == 302 || statusCode == 303
+ || statusCode == 305 || statusCode == 307);
+}
+
qint64 QHttpNetworkReply::contentLength() const
{
return d_func()->contentLength();
@@ -278,6 +295,11 @@ void QHttpNetworkReply::setSpdyWasUsed(bool spdy)
d_func()->spdyUsed = spdy;
}
+bool QHttpNetworkReply::isRedirecting() const
+{
+ return d_func()->isRedirecting();
+}
+
QHttpNetworkConnection* QHttpNetworkReply::connection()
{
return d_func()->connection;
@@ -921,6 +943,14 @@ qint64 QHttpNetworkReplyPrivate::getChunkSize(QAbstractSocket *socket, qint64 *c
return bytes;
}
+bool QHttpNetworkReplyPrivate::isRedirecting() const
+{
+ // We're in the process of redirecting - if the HTTP status code says so and
+ // followRedirect is switched on
+ return (QHttpNetworkReply::isHttpRedirect(statusCode)
+ && request.isFollowRedirects());
+}
+
bool QHttpNetworkReplyPrivate::shouldEmitSignals()
{
// for 401 & 407 don't emit the data signals. Content along with these
diff --git a/src/network/access/qhttpnetworkreply_p.h b/src/network/access/qhttpnetworkreply_p.h
index 46b6541dfa..e8ed73fdac 100644
--- a/src/network/access/qhttpnetworkreply_p.h
+++ b/src/network/access/qhttpnetworkreply_p.h
@@ -130,8 +130,15 @@ public:
bool isSpdyUsed() const;
void setSpdyWasUsed(bool spdy);
+ bool isRedirecting() const;
+
QHttpNetworkConnection* connection();
+ QUrl redirectUrl() const;
+ void setRedirectUrl(const QUrl &url);
+
+ static bool isHttpRedirect(int statusCode);
+
#ifndef QT_NO_SSL
QSslConfiguration sslConfiguration() const;
void setSslConfiguration(const QSslConfiguration &config);
@@ -156,6 +163,7 @@ Q_SIGNALS:
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator);
#endif
void authenticationRequired(const QHttpNetworkRequest &request, QAuthenticator *authenticator);
+ void redirected(const QUrl &url, int httpStatus, int maxRedirectsRemaining);
private:
Q_DECLARE_PRIVATE(QHttpNetworkReply)
friend class QHttpSocketEngine;
@@ -188,6 +196,7 @@ public:
qint64 readReplyBodyChunked(QAbstractSocket *in, QByteDataBuffer *out);
qint64 getChunkSize(QAbstractSocket *in, qint64 *chunkSize);
+ bool isRedirecting() const;
bool shouldEmitSignals();
bool expectContent();
void eraseData();
@@ -249,6 +258,7 @@ public:
bool downstreamLimited;
char* userProvidedDownloadBuffer;
+ QUrl redirectUrl;
#ifndef QT_NO_COMPRESS
z_stream_s *inflateStrm;
diff --git a/src/network/access/qhttpnetworkrequest.cpp b/src/network/access/qhttpnetworkrequest.cpp
index ea1cd3d591..64172fc4fd 100644
--- a/src/network/access/qhttpnetworkrequest.cpp
+++ b/src/network/access/qhttpnetworkrequest.cpp
@@ -42,7 +42,7 @@ QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(QHttpNetworkRequest::Oper
QHttpNetworkRequest::Priority pri, const QUrl &newUrl)
: QHttpNetworkHeaderPrivate(newUrl), operation(op), priority(pri), uploadByteDevice(0),
autoDecompress(false), pipeliningAllowed(false), spdyAllowed(false),
- withCredentials(true), preConnect(false)
+ withCredentials(true), preConnect(false), followRedirect(false), redirectCount(0)
{
}
@@ -59,6 +59,8 @@ QHttpNetworkRequestPrivate::QHttpNetworkRequestPrivate(const QHttpNetworkRequest
withCredentials = other.withCredentials;
ssl = other.ssl;
preConnect = other.preConnect;
+ followRedirect = other.followRedirect;
+ redirectCount = other.redirectCount;
}
QHttpNetworkRequestPrivate::~QHttpNetworkRequestPrivate()
@@ -217,6 +219,26 @@ void QHttpNetworkRequest::setPreConnect(bool preConnect)
d->preConnect = preConnect;
}
+bool QHttpNetworkRequest::isFollowRedirects() const
+{
+ return d->followRedirect;
+}
+
+void QHttpNetworkRequest::setFollowRedirects(bool followRedirect)
+{
+ d->followRedirect = followRedirect;
+}
+
+int QHttpNetworkRequest::redirectCount() const
+{
+ return d->redirectCount;
+}
+
+void QHttpNetworkRequest::setRedirectCount(int count)
+{
+ d->redirectCount = count;
+}
+
qint64 QHttpNetworkRequest::contentLength() const
{
return d->contentLength();
diff --git a/src/network/access/qhttpnetworkrequest_p.h b/src/network/access/qhttpnetworkrequest_p.h
index d136f22b7d..1add3c6150 100644
--- a/src/network/access/qhttpnetworkrequest_p.h
+++ b/src/network/access/qhttpnetworkrequest_p.h
@@ -118,6 +118,12 @@ public:
bool isPreConnect() const;
void setPreConnect(bool preConnect);
+ bool isFollowRedirects() const;
+ void setFollowRedirects(bool followRedirect);
+
+ int redirectCount() const;
+ void setRedirectCount(int count);
+
void setUploadByteDevice(QNonContiguousByteDevice *bd);
QNonContiguousByteDevice* uploadByteDevice() const;
@@ -154,6 +160,8 @@ public:
bool withCredentials;
bool ssl;
bool preConnect;
+ bool followRedirect;
+ int redirectCount;
};
diff --git a/src/network/access/qhttpthreaddelegate.cpp b/src/network/access/qhttpthreaddelegate.cpp
index e4931db304..b0e366d2f8 100644
--- a/src/network/access/qhttpthreaddelegate.cpp
+++ b/src/network/access/qhttpthreaddelegate.cpp
@@ -492,11 +492,14 @@ void QHttpThreadDelegate::finishedSlot()
if (httpReply->statusCode() >= 400) {
// it's an error reply
QString msg = QLatin1String(QT_TRANSLATE_NOOP("QNetworkReply",
- "Error downloading %1 - server replied: %2"));
+ "Error transferring %1 - server replied: %2"));
msg = msg.arg(httpRequest.url().toString(), httpReply->reasonPhrase());
emit error(statusCodeFromHttp(httpReply->statusCode(), httpRequest.url()), msg);
}
+ if (httpRequest.isFollowRedirects() && httpReply->isRedirecting())
+ emit redirected(httpReply->redirectUrl(), httpReply->statusCode(), httpReply->request().redirectCount() - 1);
+
emit downloadFinished();
QMetaObject::invokeMethod(httpReply, "deleteLater", Qt::QueuedConnection);
@@ -515,7 +518,7 @@ void QHttpThreadDelegate::synchronousFinishedSlot()
if (httpReply->statusCode() >= 400) {
// it's an error reply
QString msg = QLatin1String(QT_TRANSLATE_NOOP("QNetworkReply",
- "Error downloading %1 - server replied: %2"));
+ "Error transferring %1 - server replied: %2"));
incomingErrorDetail = msg.arg(httpRequest.url().toString(), httpReply->reasonPhrase());
incomingErrorCode = statusCodeFromHttp(httpReply->statusCode(), httpRequest.url());
}
diff --git a/src/network/access/qhttpthreaddelegate_p.h b/src/network/access/qhttpthreaddelegate_p.h
index 9573d500ea..784e9c14b8 100644
--- a/src/network/access/qhttpthreaddelegate_p.h
+++ b/src/network/access/qhttpthreaddelegate_p.h
@@ -139,6 +139,8 @@ signals:
void downloadData(QByteArray);
void error(QNetworkReply::NetworkError, const QString);
void downloadFinished();
+ void redirected(const QUrl &url, int httpStatus, int maxRedirectsRemainig);
+
public slots:
// This are called via QueuedConnection from user thread
void startRequest();
diff --git a/src/network/access/qnetworkaccessauthenticationmanager_p.h b/src/network/access/qnetworkaccessauthenticationmanager_p.h
index 8f06ecb6b7..462827d7fc 100644
--- a/src/network/access/qnetworkaccessauthenticationmanager_p.h
+++ b/src/network/access/qnetworkaccessauthenticationmanager_p.h
@@ -64,7 +64,7 @@ public:
QString domain;
QString user;
QString password;
- bool isNull() {
+ bool isNull() const {
return domain.isNull() && user.isNull() && password.isNull();
}
};
diff --git a/src/network/access/qnetworkaccessbackend.cpp b/src/network/access/qnetworkaccessbackend.cpp
index 692af1b2fc..321352e045 100644
--- a/src/network/access/qnetworkaccessbackend.cpp
+++ b/src/network/access/qnetworkaccessbackend.cpp
@@ -37,7 +37,6 @@
#include "qnetworkrequest.h"
#include "qnetworkreply.h"
#include "qnetworkreply_p.h"
-#include "QtCore/qhash.h"
#include "QtCore/qmutex.h"
#include "QtCore/qstringlist.h"
#include "QtNetwork/private/qnetworksession_p.h"
diff --git a/src/network/access/qnetworkaccesscache.cpp b/src/network/access/qnetworkaccesscache.cpp
index 19316bda75..3d029f118b 100644
--- a/src/network/access/qnetworkaccesscache.cpp
+++ b/src/network/access/qnetworkaccesscache.cpp
@@ -151,7 +151,7 @@ void QNetworkAccessCache::linkEntry(const QByteArray &key)
oldest = node;
}
- node->timestamp = QDateTime::currentDateTime().addSecs(ExpiryTime);
+ node->timestamp = QDateTime::currentDateTimeUtc().addSecs(ExpiryTime);
newest = node;
}
@@ -190,7 +190,7 @@ void QNetworkAccessCache::updateTimer()
if (!oldest)
return;
- int interval = QDateTime::currentDateTime().secsTo(oldest->timestamp);
+ int interval = QDateTime::currentDateTimeUtc().secsTo(oldest->timestamp);
if (interval <= 0) {
interval = 0;
} else {
@@ -216,7 +216,7 @@ bool QNetworkAccessCache::emitEntryReady(Node *node, QObject *target, const char
void QNetworkAccessCache::timerEvent(QTimerEvent *)
{
// expire old items
- QDateTime now = QDateTime::currentDateTime();
+ const QDateTime now = QDateTime::currentDateTimeUtc();
while (oldest && oldest->timestamp < now) {
Node *next = oldest->newer;
diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp
index f9e9513c55..0e5870a235 100644
--- a/src/network/access/qnetworkaccessmanager.cpp
+++ b/src/network/access/qnetworkaccessmanager.cpp
@@ -448,7 +448,6 @@ static void ensureInitialized()
QNetworkAccessManager::QNetworkAccessManager(QObject *parent)
: QObject(*new QNetworkAccessManagerPrivate, parent)
{
- Q_D(QNetworkAccessManager);
ensureInitialized();
qRegisterMetaType<QNetworkReply::NetworkError>();
@@ -468,6 +467,7 @@ QNetworkAccessManager::QNetworkAccessManager(QObject *parent)
qRegisterMetaType<QSharedPointer<char> >();
#ifndef QT_NO_BEARERMANAGEMENT
+ Q_D(QNetworkAccessManager);
// if a session is required, we track online state through
// the QNetworkSession's signals if a request is already made.
// we need to track current accessibility state by default
@@ -976,7 +976,6 @@ QNetworkAccessManager::NetworkAccessibility QNetworkAccessManager::networkAccess
else
return NotAccessible;
} else {
- // Network accessibility is either disabled or unknown.
if (d->defaultAccessControl) {
if (d->online)
return d->networkAccessible;
@@ -1161,7 +1160,7 @@ QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Opera
#ifndef QT_NO_BEARERMANAGEMENT
// Return a disabled network reply if network access is disabled.
// Except if the scheme is empty or file://.
- if (!d->networkAccessible && !isLocalFile) {
+ if (d->networkAccessible == NotAccessible && !isLocalFile) {
return new QDisabledNetworkReply(this, req, op);
}
@@ -1704,7 +1703,7 @@ QNetworkRequest QNetworkAccessManagerPrivate::prepareMultipart(const QNetworkReq
break;
}
// putting the boundary into quotes, recommended in RFC 2046 section 5.1.1
- contentType += "; boundary=\"" + multiPart->d_func()->boundary + "\"";
+ contentType += "; boundary=\"" + multiPart->d_func()->boundary + '"';
newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));
}
diff --git a/src/network/access/qnetworkaccessmanager.h b/src/network/access/qnetworkaccessmanager.h
index 988eafa18b..c8df213ead 100644
--- a/src/network/access/qnetworkaccessmanager.h
+++ b/src/network/access/qnetworkaccessmanager.h
@@ -90,7 +90,7 @@ public:
};
#endif
- explicit QNetworkAccessManager(QObject *parent = 0);
+ explicit QNetworkAccessManager(QObject *parent = Q_NULLPTR);
~QNetworkAccessManager();
// ### Qt 6: turn into virtual
@@ -120,7 +120,7 @@ public:
QNetworkReply *put(const QNetworkRequest &request, const QByteArray &data);
QNetworkReply *put(const QNetworkRequest &request, QHttpMultiPart *multiPart);
QNetworkReply *deleteResource(const QNetworkRequest &request);
- QNetworkReply *sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = 0);
+ QNetworkReply *sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = Q_NULLPTR);
#ifndef QT_NO_BEARERMANAGEMENT
void setConfiguration(const QNetworkConfiguration &config);
@@ -157,7 +157,7 @@ Q_SIGNALS:
protected:
virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
- QIODevice *outgoingData = 0);
+ QIODevice *outgoingData = Q_NULLPTR);
protected Q_SLOTS:
QStringList supportedSchemesImplementation() const;
diff --git a/src/network/access/qnetworkaccessmanager_p.h b/src/network/access/qnetworkaccessmanager_p.h
index 54ae114581..3fc33b5c15 100644
--- a/src/network/access/qnetworkaccessmanager_p.h
+++ b/src/network/access/qnetworkaccessmanager_p.h
@@ -93,6 +93,8 @@ public:
online = (networkConfiguration.state().testFlag(QNetworkConfiguration::Active));
if (online)
networkAccessible = QNetworkAccessManager::Accessible;
+ else if (networkConfiguration.state().testFlag(QNetworkConfiguration::Undefined))
+ networkAccessible = QNetworkAccessManager::UnknownAccessibility;
else
networkAccessible = QNetworkAccessManager::NotAccessible;
#endif
diff --git a/src/network/access/qnetworkcookie.cpp b/src/network/access/qnetworkcookie.cpp
index 8a24fc55fd..2d8f192d03 100644
--- a/src/network/access/qnetworkcookie.cpp
+++ b/src/network/access/qnetworkcookie.cpp
@@ -901,7 +901,7 @@ QList<QNetworkCookie> QNetworkCookiePrivate::parseSetCookieHeaderLine(const QByt
// We do not support RFC 2965 Set-Cookie2-style cookies
QList<QNetworkCookie> result;
- QDateTime now = QDateTime::currentDateTime().toUTC();
+ const QDateTime now = QDateTime::currentDateTimeUtc();
int position = 0;
const int length = cookieString.length();
diff --git a/src/network/access/qnetworkcookie.h b/src/network/access/qnetworkcookie.h
index 2da86d3f81..27925c8201 100644
--- a/src/network/access/qnetworkcookie.h
+++ b/src/network/access/qnetworkcookie.h
@@ -59,9 +59,12 @@ public:
explicit QNetworkCookie(const QByteArray &name = QByteArray(), const QByteArray &value = QByteArray());
QNetworkCookie(const QNetworkCookie &other);
~QNetworkCookie();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkCookie &operator=(QNetworkCookie &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkCookie &operator=(const QNetworkCookie &other);
- void swap(QNetworkCookie &other) { qSwap(d, other.d); }
+ void swap(QNetworkCookie &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkCookie &other) const;
inline bool operator!=(const QNetworkCookie &other) const
diff --git a/src/network/access/qnetworkcookiejar.cpp b/src/network/access/qnetworkcookiejar.cpp
index 3cefb28f68..39f94a451f 100644
--- a/src/network/access/qnetworkcookiejar.cpp
+++ b/src/network/access/qnetworkcookiejar.cpp
@@ -216,7 +216,7 @@ QList<QNetworkCookie> QNetworkCookieJar::cookiesForUrl(const QUrl &url) const
// It does not implement a very good cross-domain verification yet.
Q_D(const QNetworkCookieJar);
- QDateTime now = QDateTime::currentDateTime();
+ const QDateTime now = QDateTime::currentDateTimeUtc();
QList<QNetworkCookie> result;
bool isEncrypted = url.scheme().toLower() == QLatin1String("https");
@@ -265,7 +265,7 @@ QList<QNetworkCookie> QNetworkCookieJar::cookiesForUrl(const QUrl &url) const
bool QNetworkCookieJar::insertCookie(const QNetworkCookie &cookie)
{
Q_D(QNetworkCookieJar);
- QDateTime now = QDateTime::currentDateTime();
+ const QDateTime now = QDateTime::currentDateTimeUtc();
bool isDeletion = !cookie.isSessionCookie() &&
cookie.expirationDate() < now;
diff --git a/src/network/access/qnetworkcookiejar.h b/src/network/access/qnetworkcookiejar.h
index 59ba7f8738..3ac78ea1c3 100644
--- a/src/network/access/qnetworkcookiejar.h
+++ b/src/network/access/qnetworkcookiejar.h
@@ -47,7 +47,7 @@ class Q_NETWORK_EXPORT QNetworkCookieJar: public QObject
{
Q_OBJECT
public:
- explicit QNetworkCookieJar(QObject *parent = 0);
+ explicit QNetworkCookieJar(QObject *parent = Q_NULLPTR);
virtual ~QNetworkCookieJar();
virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const;
diff --git a/src/network/access/qnetworkdiskcache.h b/src/network/access/qnetworkdiskcache.h
index 568d34dc0f..533eabce9b 100644
--- a/src/network/access/qnetworkdiskcache.h
+++ b/src/network/access/qnetworkdiskcache.h
@@ -47,7 +47,7 @@ class Q_NETWORK_EXPORT QNetworkDiskCache : public QAbstractNetworkCache
Q_OBJECT
public:
- explicit QNetworkDiskCache(QObject *parent = 0);
+ explicit QNetworkDiskCache(QObject *parent = Q_NULLPTR);
~QNetworkDiskCache();
QString cacheDirectory() const;
diff --git a/src/network/access/qnetworkreply.cpp b/src/network/access/qnetworkreply.cpp
index 3e77e1b874..26f7034c09 100644
--- a/src/network/access/qnetworkreply.cpp
+++ b/src/network/access/qnetworkreply.cpp
@@ -132,6 +132,14 @@ QNetworkReplyPrivate::QNetworkReplyPrivate()
\value BackgroundRequestNotAllowedError the background request
is not currently allowed due to platform policy.
+ \value TooManyRedirectsError while following redirects, the maximum
+ limit was reached. The limit is by default set to 50 or as set by
+ QNetworkRequest::setMaxRedirectsAllowed().
+
+ \value InsecureRedirectError while following redirects, the network
+ access API detected a redirect from a encrypted protocol (https) to an
+ unencrypted one (http).
+
\value ProxyConnectionRefusedError the connection to the proxy
server was refused (the proxy server is not accepting requests)
@@ -276,6 +284,19 @@ QNetworkReplyPrivate::QNetworkReplyPrivate()
*/
/*!
+ \fn void QNetworkReply::redirected(const QUrl &url)
+ \since 5.6
+
+ This signal is emitted if the QNetworkRequest::FollowRedirectsAttribute was
+ set in the request and the server responded with a 3xx status (specifically
+ 301, 302, 303, 305 or 307 status code) with a valid url in the location
+ header, indicating a HTTP redirect. The \a url parameter contains the new
+ redirect url as returned by the server in the location header.
+
+ \sa QNetworkRequest::FollowRedirectsAttribute
+*/
+
+/*!
\fn void QNetworkReply::metaDataChanged()
\omit FIXME: Update name? \endomit
@@ -498,7 +519,7 @@ QNetworkAccessManager *QNetworkReply::manager() const
*/
QNetworkRequest QNetworkReply::request() const
{
- return d_func()->request;
+ return d_func()->originalRequest;
}
/*!
@@ -549,9 +570,12 @@ bool QNetworkReply::isRunning() const
/*!
Returns the URL of the content downloaded or uploaded. Note that
- the URL may be different from that of the original request.
+ the URL may be different from that of the original request. If the
+ QNetworkRequest::FollowRedirectsAttribute was set in the request, then this
+ function returns the current url that the network API is accessing, i.e the
+ url emitted in the QNetworkReply::redirected signal.
- \sa request(), setUrl(), QNetworkRequest::url()
+ \sa request(), setUrl(), QNetworkRequest::url(), redirected()
*/
QUrl QNetworkReply::url() const
{
@@ -794,7 +818,7 @@ void QNetworkReply::setOperation(QNetworkAccessManager::Operation operation)
void QNetworkReply::setRequest(const QNetworkRequest &request)
{
Q_D(QNetworkReply);
- d->request = request;
+ d->originalRequest = request;
}
/*!
diff --git a/src/network/access/qnetworkreply.h b/src/network/access/qnetworkreply.h
index 91c9e77d8d..254dd3ff12 100644
--- a/src/network/access/qnetworkreply.h
+++ b/src/network/access/qnetworkreply.h
@@ -69,6 +69,8 @@ public:
TemporaryNetworkFailureError,
NetworkSessionFailedError,
BackgroundRequestNotAllowedError,
+ TooManyRedirectsError,
+ InsecureRedirectError,
UnknownNetworkError = 99,
// proxy errors (101-199):
@@ -153,12 +155,13 @@ Q_SIGNALS:
void sslErrors(const QList<QSslError> &errors);
void preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator);
#endif
+ void redirected(const QUrl &url);
void uploadProgress(qint64 bytesSent, qint64 bytesTotal);
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
protected:
- explicit QNetworkReply(QObject *parent = 0);
+ explicit QNetworkReply(QObject *parent = Q_NULLPTR);
QNetworkReply(QNetworkReplyPrivate &dd, QObject *parent);
virtual qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE;
diff --git a/src/network/access/qnetworkreply_p.h b/src/network/access/qnetworkreply_p.h
index f5fe7bd844..2a3a2e4297 100644
--- a/src/network/access/qnetworkreply_p.h
+++ b/src/network/access/qnetworkreply_p.h
@@ -69,6 +69,7 @@ public:
QNetworkReplyPrivate();
QNetworkRequest request;
+ QNetworkRequest originalRequest;
QUrl url;
QPointer<QNetworkAccessManager> manager;
qint64 readBufferMaxSize;
diff --git a/src/network/access/qnetworkreplyfileimpl.cpp b/src/network/access/qnetworkreplyfileimpl.cpp
index 8f51b2ca3b..1e5608bc90 100644
--- a/src/network/access/qnetworkreplyfileimpl.cpp
+++ b/src/network/access/qnetworkreplyfileimpl.cpp
@@ -36,7 +36,6 @@
#include "QtCore/qdatetime.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
-#include <QDebug>
QT_BEGIN_NAMESPACE
@@ -136,6 +135,7 @@ QNetworkReplyFileImpl::QNetworkReplyFileImpl(QObject *parent, const QNetworkRequ
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
}
+
void QNetworkReplyFileImpl::close()
{
Q_D(QNetworkReplyFileImpl);
@@ -182,8 +182,11 @@ qint64 QNetworkReplyFileImpl::readData(char *data, qint64 maxlen)
d->realFile.close();
if (ret == 0 && bytesAvailable() == 0)
return -1;
- else
+ else {
+ setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200);
+ setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, QLatin1String("OK"));
return ret;
+ }
}
diff --git a/src/network/access/qnetworkreplyhttpimpl.cpp b/src/network/access/qnetworkreplyhttpimpl.cpp
index 76c2f57380..04d391a14c 100644
--- a/src/network/access/qnetworkreplyhttpimpl.cpp
+++ b/src/network/access/qnetworkreplyhttpimpl.cpp
@@ -49,6 +49,8 @@
#include "qthread.h"
#include "QtCore/qcoreapplication.h"
+#include <QtCore/private/qthread_p.h>
+
#include "qnetworkcookiejar.h"
#ifndef QT_NO_HTTP
@@ -166,6 +168,7 @@ QNetworkReplyHttpImpl::QNetworkReplyHttpImpl(QNetworkAccessManager* const manage
d->manager = manager;
d->managerPrivate = manager->d_func();
d->request = request;
+ d->originalRequest = request;
d->operation = operation;
d->outgoingData = outgoingData;
d->url = request.url();
@@ -483,7 +486,7 @@ bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &h
if (!nc)
return false; // no local cache
- QNetworkCacheMetaData metaData = nc->metaData(request.url());
+ QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
if (!metaData.isValid())
return false; // not in cache
@@ -509,7 +512,7 @@ bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &h
return false;
}
- QDateTime currentDateTime = QDateTime::currentDateTime();
+ QDateTime currentDateTime = QDateTime::currentDateTimeUtc();
QDateTime expirationDate = metaData.expirationDate();
bool response_is_fresh;
@@ -542,7 +545,7 @@ bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &h
date_value = dateHeader.toTime_t();
}
- int now = currentDateTime.toUTC().toTime_t();
+ int now = currentDateTime.toTime_t();
int request_time = now;
int response_time = now;
@@ -597,7 +600,7 @@ QHttpNetworkRequest::Priority QNetworkReplyHttpImplPrivate::convert(const QNetwo
}
}
-void QNetworkReplyHttpImplPrivate::postRequest()
+void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpRequest)
{
Q_Q(QNetworkReplyHttpImpl);
@@ -621,8 +624,9 @@ void QNetworkReplyHttpImplPrivate::postRequest()
thread = managerPrivate->httpThread;
}
- QUrl url = request.url();
+ QUrl url = newHttpRequest.url();
httpRequest.setUrl(url);
+ httpRequest.setRedirectCount(newHttpRequest.maximumRedirectsAllowed());
QString scheme = url.scheme().toLower();
bool ssl = (scheme == QLatin1String("https")
@@ -638,7 +642,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
QNetworkProxy transparentProxy, cacheProxy;
// FIXME the proxy stuff should be done in the HTTP thread
- foreach (const QNetworkProxy &p, managerPrivate->queryProxy(QNetworkProxyQuery(request.url()))) {
+ foreach (const QNetworkProxy &p, managerPrivate->queryProxy(QNetworkProxyQuery(newHttpRequest.url()))) {
// use the first proxy that works
// for non-encrypted connections, any transparent or HTTP proxy
// for encrypted, only transparent proxies
@@ -669,9 +673,11 @@ void QNetworkReplyHttpImplPrivate::postRequest()
}
#endif
+ if (newHttpRequest.attribute(QNetworkRequest::FollowRedirectsAttribute).toBool())
+ httpRequest.setFollowRedirects(true);
bool loadedFromCache = false;
- httpRequest.setPriority(convert(request.priority()));
+ httpRequest.setPriority(convert(newHttpRequest.priority()));
switch (operation) {
case QNetworkAccessManager::GetOperation:
@@ -705,7 +711,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
invalidateCache(); // for safety reasons, we don't know what the operation does
httpRequest.setOperation(QHttpNetworkRequest::Custom);
createUploadByteDevice();
- httpRequest.setCustomVerb(request.attribute(
+ httpRequest.setCustomVerb(newHttpRequest.attribute(
QNetworkRequest::CustomVerbAttribute).toByteArray());
break;
@@ -717,7 +723,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
return; // no need to send the request! :)
}
- QList<QByteArray> headers = request.rawHeaderList();
+ QList<QByteArray> headers = newHttpRequest.rawHeaderList();
if (resumeOffset != 0) {
if (headers.contains("Range")) {
// Need to adjust resume offset for user specified range
@@ -725,7 +731,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
headers.removeOne("Range");
// We've already verified that requestRange starts with "bytes=", see canResume.
- QByteArray requestRange = request.rawHeader("Range").mid(6);
+ QByteArray requestRange = newHttpRequest.rawHeader("Range").mid(6);
int index = requestRange.indexOf('-');
@@ -742,16 +748,16 @@ void QNetworkReplyHttpImplPrivate::postRequest()
}
foreach (const QByteArray &header, headers)
- httpRequest.setHeaderField(header, request.rawHeader(header));
+ httpRequest.setHeaderField(header, newHttpRequest.rawHeader(header));
- if (request.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool() == true)
+ if (newHttpRequest.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool() == true)
httpRequest.setPipeliningAllowed(true);
if (request.attribute(QNetworkRequest::SpdyAllowedAttribute).toBool() == true)
httpRequest.setSPDYAllowed(true);
if (static_cast<QNetworkRequest::LoadControl>
- (request.attribute(QNetworkRequest::AuthenticationReuseAttribute,
+ (newHttpRequest.attribute(QNetworkRequest::AuthenticationReuseAttribute,
QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Manual)
httpRequest.setWithCredentials(false);
@@ -778,7 +784,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
delegate->ssl = ssl;
#ifndef QT_NO_SSL
if (ssl)
- delegate->incomingSslConfiguration = request.sslConfiguration();
+ delegate->incomingSslConfiguration = newHttpRequest.sslConfiguration();
#endif
// Do we use synchronous HTTP?
@@ -790,7 +796,7 @@ void QNetworkReplyHttpImplPrivate::postRequest()
if (!synchronous) {
// Tell our zerocopy policy to the delegate
- QVariant downloadBufferMaximumSizeAttribute = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
+ QVariant downloadBufferMaximumSizeAttribute = newHttpRequest.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
if (downloadBufferMaximumSizeAttribute.isValid()) {
delegate->downloadBufferMaximumSize = downloadBufferMaximumSizeAttribute.toLongLong();
} else {
@@ -825,6 +831,9 @@ void QNetworkReplyHttpImplPrivate::postRequest()
QObject::connect(delegate, SIGNAL(error(QNetworkReply::NetworkError,QString)),
q, SLOT(httpError(QNetworkReply::NetworkError,QString)),
Qt::QueuedConnection);
+ QObject::connect(delegate, SIGNAL(redirected(QUrl,int,int)),
+ q, SLOT(onRedirected(QUrl,int,int)),
+ Qt::QueuedConnection);
#ifndef QT_NO_SSL
QObject::connect(delegate, SIGNAL(sslConfigurationChanged(QSslConfiguration)),
q, SLOT(replySslConfigurationChanged(QSslConfiguration)),
@@ -951,7 +960,7 @@ void QNetworkReplyHttpImplPrivate::invalidateCache()
{
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc)
- nc->remove(request.url());
+ nc->remove(httpRequest.url());
}
void QNetworkReplyHttpImplPrivate::initCacheSaveDevice()
@@ -1031,21 +1040,30 @@ void QNetworkReplyHttpImplPrivate::replyDownloadData(QByteArray d)
for (int i = 0; i < pendingDownloadDataCopy.bufferCount(); i++) {
QByteArray const &item = pendingDownloadDataCopy[i];
+ // This is going to look a little strange. When downloading data while a
+ // HTTP redirect is happening (and enabled), we write the redirect
+ // response to the cache. However, we do not append it to our internal
+ // buffer as that will contain the response data only for the final
+ // response
if (cacheSaveDevice)
cacheSaveDevice->write(item.constData(), item.size());
- downloadMultiBuffer.append(item);
+
+ if (!isHttpRedirectResponse())
+ downloadMultiBuffer.append(item);
bytesWritten += item.size();
}
pendingDownloadDataCopy.clear();
- bytesDownloaded += bytesWritten;
-
-
QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
if (preMigrationDownloaded != Q_INT64_C(-1))
totalSize = totalSize.toLongLong() + preMigrationDownloaded;
+ if (isHttpRedirectResponse())
+ return;
+
+ bytesDownloaded += bytesWritten;
+
emit q->readyRead();
// emit readyRead before downloadProgress incase this will cause events to be
// processed and we get into a recursive call (as in QProgressDialog).
@@ -1067,6 +1085,64 @@ void QNetworkReplyHttpImplPrivate::replyFinished()
finished();
}
+QNetworkAccessManager::Operation QNetworkReplyHttpImplPrivate::getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus)
+{
+ // HTTP status code can be used to decide if we can redirect with a GET
+ // operation or not. See http://www.ietf.org/rfc/rfc2616.txt [Sec 10.3] for
+ // more details
+ Q_UNUSED(httpStatus);
+
+ switch (currentOp) {
+ case QNetworkAccessManager::HeadOperation:
+ return QNetworkAccessManager::HeadOperation;
+ default:
+ break;
+ }
+ // For now, we're always returning GET for anything other than HEAD
+ return QNetworkAccessManager::GetOperation;
+}
+
+bool QNetworkReplyHttpImplPrivate::isHttpRedirectResponse() const
+{
+ return httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(statusCode);
+}
+
+QNetworkRequest QNetworkReplyHttpImplPrivate::createRedirectRequest(const QNetworkRequest &originalRequest,
+ const QUrl &url,
+ int maxRedirectsRemaining)
+{
+ QNetworkRequest newRequest(originalRequest);
+ newRequest.setUrl(url);
+ newRequest.setMaximumRedirectsAllowed(maxRedirectsRemaining);
+
+ return newRequest;
+}
+
+void QNetworkReplyHttpImplPrivate::onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemaining)
+{
+ Q_Q(QNetworkReplyHttpImpl);
+
+ if (isFinished)
+ return;
+
+ if (httpRequest.isFollowRedirects()) // update the reply's url as it could've changed
+ url = redirectUrl;
+
+ QNetworkRequest redirectRequest = createRedirectRequest(originalRequest, redirectUrl, maxRedirectsRemaining);
+ operation = getRedirectOperation(operation, httpStatus);
+
+ cookedHeaders.clear();
+
+ if (managerPrivate->httpThread)
+ managerPrivate->httpThread->disconnect();
+
+ // Recurse
+ QMetaObject::invokeMethod(q, "start", Qt::QueuedConnection,
+ Q_ARG(QNetworkRequest, redirectRequest));
+
+ emit q->redirected(redirectUrl);
+}
+
void QNetworkReplyHttpImplPrivate::checkForRedirect(const int statusCode)
{
Q_Q(QNetworkReplyHttpImpl);
@@ -1115,7 +1191,16 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
end = headerMap.constEnd();
for (; it != end; ++it) {
QByteArray value = q->rawHeader(it->first);
+
+ // Reset any previous "location" header set in the reply. In case of
+ // redirects, we don't want to 'append' multiple location header values,
+ // rather we keep only the latest one
+ if (it->first.toLower() == "location")
+ value.clear();
+
if (!value.isEmpty()) {
+ // Why are we appending values for headers which are already
+ // present?
if (qstricmp(it->first.constData(), "set-cookie") == 0)
value += '\n';
else
@@ -1129,12 +1214,13 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, reasonPhrase);
// is it a redirection?
- checkForRedirect(statusCode);
+ if (!isHttpRedirectResponse())
+ checkForRedirect(statusCode);
if (statusCode >= 500 && statusCode < 600) {
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc) {
- QNetworkCacheMetaData metaData = nc->metaData(request.url());
+ QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
QNetworkHeadersPrivate cacheHeaders;
cacheHeaders.setAllRawHeaders(metaData.rawHeaders());
QNetworkHeadersPrivate::RawHeadersList::ConstIterator it;
@@ -1156,7 +1242,7 @@ void QNetworkReplyHttpImplPrivate::replyDownloadMetaData
#endif
QAbstractNetworkCache *nc = managerPrivate->networkCache;
if (nc) {
- QNetworkCacheMetaData oldMetaData = nc->metaData(request.url());
+ QNetworkCacheMetaData oldMetaData = nc->metaData(httpRequest.url());
QNetworkCacheMetaData metaData = fetchCacheMetaData(oldMetaData);
if (oldMetaData != metaData)
nc->updateMetaData(metaData);
@@ -1203,6 +1289,9 @@ void QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(qint64 bytesReceive
// FIXME where is it closed?
}
+ if (isHttpRedirectResponse())
+ return;
+
bytesDownloaded = bytesReceived;
downloadBufferCurrentSize = bytesReceived;
@@ -1361,6 +1450,8 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
if (status < 100)
status = 200; // fake it
+ statusCode = status;
+
q->setAttribute(QNetworkRequest::HttpStatusCodeAttribute, status);
q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));
q->setAttribute(QNetworkRequest::SourceIsFromCacheAttribute, true);
@@ -1368,10 +1459,16 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
QNetworkCacheMetaData::RawHeaderList rawHeaders = metaData.rawHeaders();
QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
end = rawHeaders.constEnd();
- for ( ; it != end; ++it)
+ QUrl redirectUrl;
+ for ( ; it != end; ++it) {
+ if (httpRequest.isFollowRedirects() &&
+ !qstricmp(it->first.toLower().constData(), "location"))
+ redirectUrl = QUrl::fromEncoded(it->second);
setRawHeader(it->first, it->second);
+ }
- checkForRedirect(status);
+ if (!isHttpRedirectResponse())
+ checkForRedirect(status);
cacheLoadDevice = contents;
q->connect(cacheLoadDevice, SIGNAL(readyRead()), SLOT(_q_cacheLoadReadyRead()));
@@ -1388,6 +1485,14 @@ bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData
qDebug() << "Successfully sent cache:" << url << contents->size() << "bytes";
#endif
+ // Do redirect processing
+ if (httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(status)) {
+ QMetaObject::invokeMethod(q, "onRedirected", Qt::QueuedConnection,
+ Q_ARG(QUrl, redirectUrl),
+ Q_ARG(int, status),
+ Q_ARG(int, httpRequest.redirectCount() - 1));
+ }
+
// Set the following flag so we can ignore some signals from HTTP thread
// that would still come
loadingFromCache = true;
@@ -1480,7 +1585,7 @@ QNetworkCacheMetaData QNetworkReplyHttpImplPrivate::fetchCacheMetaData(const QNe
QByteArray maxAge = cacheControl.value("max-age");
if (!maxAge.isEmpty()) {
checkExpired = false;
- QDateTime dt = QDateTime::currentDateTime();
+ QDateTime dt = QDateTime::currentDateTimeUtc();
dt = dt.addSecs(maxAge.toInt());
metaData.setExpirationDate(dt);
}
@@ -1583,13 +1688,13 @@ void QNetworkReplyHttpImplPrivate::setResumeOffset(quint64 offset)
could not be started due to an unopened or roaming session. The caller should recall this
function once the session has been opened or the roaming process has finished.
*/
-bool QNetworkReplyHttpImplPrivate::start()
+bool QNetworkReplyHttpImplPrivate::start(const QNetworkRequest &newHttpRequest)
{
#ifndef QT_NO_BEARERMANAGEMENT
QSharedPointer<QNetworkSession> networkSession(managerPrivate->getNetworkSession());
if (!networkSession) {
#endif
- postRequest();
+ postRequest(newHttpRequest);
return true;
#ifndef QT_NO_BEARERMANAGEMENT
}
@@ -1599,7 +1704,7 @@ bool QNetworkReplyHttpImplPrivate::start()
if (host == QLatin1String("localhost") ||
QHostAddress(host).isLoopback()) {
// Don't need an open session for localhost access.
- postRequest();
+ postRequest(newHttpRequest);
return true;
}
@@ -1608,13 +1713,13 @@ bool QNetworkReplyHttpImplPrivate::start()
Q_Q(QNetworkReplyHttpImpl);
QObject::connect(networkSession.data(), SIGNAL(usagePoliciesChanged(QNetworkSession::UsagePolicies)),
q, SLOT(_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies)));
- postRequest();
+ postRequest(newHttpRequest);
return true;
} else if (synchronous) {
// Command line applications using the synchronous path such as xmlpatterns may need an extra push.
networkSession->open();
if (networkSession->waitForOpened()) {
- postRequest();
+ postRequest(newHttpRequest);
return true;
}
}
@@ -1646,7 +1751,7 @@ void QNetworkReplyHttpImplPrivate::_q_startOperation()
}
#endif
- if (!start()) {
+ if (!start(request)) {
#ifndef QT_NO_BEARERMANAGEMENT
// backend failed to start because the session state is not Connected.
// QNetworkAccessManager will call reply->backend->start() again for us when the session
@@ -1714,18 +1819,20 @@ void QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead()
// emit readyRead before downloadProgress incase this will cause events to be
// processed and we get into a recursive call (as in QProgressDialog).
- // This readyRead() goes to the user. The user then may or may not read() anything.
- emit q->readyRead();
- if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
- downloadProgressSignalChoke.restart();
- emit q->downloadProgress(bytesDownloaded,
- totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
- }
+ if (!(isHttpRedirectResponse())) {
+ // This readyRead() goes to the user. The user then may or may not read() anything.
+ emit q->readyRead();
+ if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
+ downloadProgressSignalChoke.restart();
+ emit q->downloadProgress(bytesDownloaded,
+ totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
+ }
+ }
// If there are still bytes available in the cacheLoadDevice then the user did not read
// in response to the readyRead() signal. This means we have to load from the cacheLoadDevice
// and buffer that stuff. This is needed to be able to properly emit finished() later.
- while (cacheLoadDevice->bytesAvailable()) {
+ while (cacheLoadDevice->bytesAvailable() && !isHttpRedirectResponse()) {
downloadMultiBuffer.append(cacheLoadDevice->readAll());
}
@@ -1748,7 +1855,6 @@ void QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead()
cacheLoadDevice = 0;
QMetaObject::invokeMethod(q, "_q_finished", Qt::QueuedConnection);
}
-
}
@@ -1978,6 +2084,15 @@ void QNetworkReplyHttpImplPrivate::finished()
#endif
}
+ // if we don't know the total size of or we received everything save the cache
+ if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
+ completeCacheSave();
+
+ // We check for errorCode too as in case of SSL handshake failure, we still
+ // get the HTTP redirect status code (301, 303 etc)
+ if (isHttpRedirectResponse() && errorCode == QNetworkReply::NoError)
+ return;
+
state = Finished;
q->setFinished(true);
@@ -1990,10 +2105,6 @@ void QNetworkReplyHttpImplPrivate::finished()
if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
emit q->uploadProgress(0, 0);
- // if we don't know the total size of or we received everything save the cache
- if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
- completeCacheSave();
-
emit q->readChannelFinished();
emit q->finished();
}
diff --git a/src/network/access/qnetworkreplyhttpimpl_p.h b/src/network/access/qnetworkreplyhttpimpl_p.h
index cfc05edbd8..44d51d82a4 100644
--- a/src/network/access/qnetworkreplyhttpimpl_p.h
+++ b/src/network/access/qnetworkreplyhttpimpl_p.h
@@ -89,6 +89,7 @@ public:
Q_DECLARE_PRIVATE(QNetworkReplyHttpImpl)
Q_PRIVATE_SLOT(d_func(), void _q_startOperation())
+ Q_PRIVATE_SLOT(d_func(), bool start(const QNetworkRequest &))
Q_PRIVATE_SLOT(d_func(), void _q_cacheLoadReadyRead())
Q_PRIVATE_SLOT(d_func(), void _q_bufferOutgoingData())
Q_PRIVATE_SLOT(d_func(), void _q_bufferOutgoingDataFinished())
@@ -127,7 +128,7 @@ public:
Q_PRIVATE_SLOT(d_func(), void emitReplyUploadProgress(qint64, qint64))
Q_PRIVATE_SLOT(d_func(), void _q_cacheSaveDeviceAboutToClose())
Q_PRIVATE_SLOT(d_func(), void _q_metaDataChanged())
-
+ Q_PRIVATE_SLOT(d_func(), void onRedirected(const QUrl &, int, int))
#ifndef QT_NO_SSL
protected:
@@ -158,7 +159,7 @@ public:
QNetworkReplyHttpImplPrivate();
~QNetworkReplyHttpImplPrivate();
- bool start();
+ bool start(const QNetworkRequest &newHttpRequest);
void _q_startOperation();
void _q_cacheLoadReadyRead();
@@ -203,6 +204,7 @@ public:
QIODevice *outgoingData;
QSharedPointer<QRingBuffer> outgoingDataBuffer;
void emitReplyUploadProgress(qint64 bytesSent, qint64 bytesTotal); // dup?
+ void onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemainig);
qint64 bytesUploaded;
@@ -262,9 +264,10 @@ public:
QNetworkCacheMetaData fetchCacheMetaData(const QNetworkCacheMetaData &metaData) const;
- void postRequest();
-
-
+ void postRequest(const QNetworkRequest& newHttpRequest);
+ QNetworkAccessManager::Operation getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus);
+ QNetworkRequest createRedirectRequest(const QNetworkRequest &originalRequests, const QUrl &url, int maxRedirectsRemainig);
+ bool isHttpRedirectResponse() const;
public:
// From HTTP thread:
diff --git a/src/network/access/qnetworkreplyimpl.cpp b/src/network/access/qnetworkreplyimpl.cpp
index 18f322f45d..7961a1dbae 100644
--- a/src/network/access/qnetworkreplyimpl.cpp
+++ b/src/network/access/qnetworkreplyimpl.cpp
@@ -65,8 +65,6 @@ inline QNetworkReplyImplPrivate::QNetworkReplyImplPrivate()
void QNetworkReplyImplPrivate::_q_startOperation()
{
- Q_Q(QNetworkReplyImpl);
-
// ensure this function is only being called once
if (state == Working || state == Finished) {
qDebug("QNetworkReplyImpl::_q_startOperation was called more than once");
@@ -85,6 +83,7 @@ void QNetworkReplyImplPrivate::_q_startOperation()
}
#ifndef QT_NO_BEARERMANAGEMENT
+ Q_Q(QNetworkReplyImpl);
// Do not start background requests if they are not allowed by session policy
QSharedPointer<QNetworkSession> session(manager->d_func()->getNetworkSession());
QVariant isBackground = backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(false));
@@ -128,8 +127,10 @@ void QNetworkReplyImplPrivate::_q_startOperation()
return;
} else {
#ifndef QT_NO_BEARERMANAGEMENT
- QObject::connect(session.data(), SIGNAL(stateChanged(QNetworkSession::State)),
- q, SLOT(_q_networkSessionStateChanged(QNetworkSession::State)), Qt::QueuedConnection);
+ if (session) {
+ QObject::connect(session.data(), SIGNAL(stateChanged(QNetworkSession::State)),
+ q, SLOT(_q_networkSessionStateChanged(QNetworkSession::State)), Qt::QueuedConnection);
+ }
#endif
}
@@ -930,13 +931,11 @@ void QNetworkReplyImpl::abort()
QNetworkReply::close();
- if (d->state != QNetworkReplyPrivate::Finished) {
- // call finished which will emit signals
- d->error(OperationCanceledError, tr("Operation canceled"));
- if (d->state == QNetworkReplyPrivate::WaitingForSession)
- d->state = QNetworkReplyPrivate::Working;
- d->finished();
- }
+ // call finished which will emit signals
+ d->error(OperationCanceledError, tr("Operation canceled"));
+ if (d->state == QNetworkReplyPrivate::WaitingForSession)
+ d->state = QNetworkReplyPrivate::Working;
+ d->finished();
d->state = QNetworkReplyPrivate::Aborted;
// finished may access the backend
diff --git a/src/network/access/qnetworkreplyimpl_p.h b/src/network/access/qnetworkreplyimpl_p.h
index 5883c9d1c3..209bf40b72 100644
--- a/src/network/access/qnetworkreplyimpl_p.h
+++ b/src/network/access/qnetworkreplyimpl_p.h
@@ -116,8 +116,6 @@ public:
QNetworkReplyImplPrivate();
void _q_startOperation();
- void _q_sourceReadyRead();
- void _q_sourceReadChannelFinished();
void _q_copyReadyRead();
void _q_copyReadChannelFinished();
void _q_bufferOutgoingData();
@@ -205,6 +203,7 @@ public:
Q_DECLARE_PUBLIC(QNetworkReplyImpl)
};
+Q_DECLARE_TYPEINFO(QNetworkReplyImplPrivate::InternalNotifications, Q_PRIMITIVE_TYPE);
#ifndef QT_NO_BEARERMANAGEMENT
class QDisabledNetworkReply : public QNetworkReply
diff --git a/src/network/access/qnetworkrequest.cpp b/src/network/access/qnetworkrequest.cpp
index c7cb16c71c..558e015ae4 100644
--- a/src/network/access/qnetworkrequest.cpp
+++ b/src/network/access/qnetworkrequest.cpp
@@ -140,7 +140,9 @@ QT_BEGIN_NAMESPACE
request to a different URL. The Network Access API does not by
default follow redirections: it's up to the application to
determine if the requested redirection should be allowed,
- according to its security policies.
+ according to its security policies. However, if
+ QNetworkRequest::FollowRedirectsAttribute is set, then this attribute
+ will not be present in the reply.
The returned URL might be relative. Use QUrl::resolved()
to create an absolute URL out of it.
@@ -256,6 +258,12 @@ QT_BEGIN_NAMESPACE
in 100 millisecond intervals.
(This value was introduced in 5.5.)
+ \value FollowRedirectsAttribute
+ Requests only, type: QMetaType::Bool (default: false)
+ Indicates whether the Network Access API should automatically follow a
+ HTTP redirect response or not. Currently redirects that are insecure,
+ that is redirecting from "https" to "http" protocol, are not allowed.
+
\value User
Special type. Additional information can be passed in
QVariants with types ranging from User to UserMax. The default
@@ -306,11 +314,13 @@ QT_BEGIN_NAMESPACE
class QNetworkRequestPrivate: public QSharedData, public QNetworkHeadersPrivate
{
public:
+ static const int maxRedirectCount = 50;
inline QNetworkRequestPrivate()
: priority(QNetworkRequest::NormalPriority)
#ifndef QT_NO_SSL
, sslConfiguration(0)
#endif
+ , maxRedirectsAllowed(maxRedirectCount)
{ qRegisterMetaType<QNetworkRequest>(); }
~QNetworkRequestPrivate()
{
@@ -325,7 +335,7 @@ public:
{
url = other.url;
priority = other.priority;
-
+ maxRedirectsAllowed = other.maxRedirectsAllowed;
#ifndef QT_NO_SSL
sslConfiguration = 0;
if (other.sslConfiguration)
@@ -338,7 +348,8 @@ public:
return url == other.url &&
priority == other.priority &&
rawHeaders == other.rawHeaders &&
- attributes == other.attributes;
+ attributes == other.attributes &&
+ maxRedirectsAllowed == other.maxRedirectsAllowed;
// don't compare cookedHeaders
}
@@ -347,6 +358,7 @@ public:
#ifndef QT_NO_SSL
mutable QSslConfiguration *sslConfiguration;
#endif
+ int maxRedirectsAllowed;
};
/*!
@@ -657,6 +669,32 @@ void QNetworkRequest::setPriority(Priority priority)
d->priority = priority;
}
+/*!
+ \since 5.6
+
+ Returns the maximum number of redirects allowed to be followed for this
+ request.
+
+ \sa setMaximumRedirectsAllowed()
+*/
+int QNetworkRequest::maximumRedirectsAllowed() const
+{
+ return d->maxRedirectsAllowed;
+}
+
+/*!
+ \since 5.6
+
+ Sets the maximum number of redirects allowed to be followed for this
+ request to \a maxRedirectsAllowed.
+
+ \sa maximumRedirectsAllowed()
+*/
+void QNetworkRequest::setMaximumRedirectsAllowed(int maxRedirectsAllowed)
+{
+ d->maxRedirectsAllowed = maxRedirectsAllowed;
+}
+
static QByteArray headerName(QNetworkRequest::KnownHeaders header)
{
switch (header) {
@@ -881,6 +919,7 @@ QNetworkHeadersPrivate::RawHeadersList QNetworkHeadersPrivate::allRawHeaders() c
QList<QByteArray> QNetworkHeadersPrivate::rawHeadersKeys() const
{
QList<QByteArray> result;
+ result.reserve(rawHeaders.size());
RawHeadersList::ConstIterator it = rawHeaders.constBegin(),
end = rawHeaders.constEnd();
for ( ; it != end; ++it)
diff --git a/src/network/access/qnetworkrequest.h b/src/network/access/qnetworkrequest.h
index d6d907bdc4..eb343c97df 100644
--- a/src/network/access/qnetworkrequest.h
+++ b/src/network/access/qnetworkrequest.h
@@ -81,6 +81,7 @@ public:
SpdyAllowedAttribute,
SpdyWasUsedAttribute,
EmitAllUploadProgressSignalsAttribute,
+ FollowRedirectsAttribute,
User = 1000,
UserMax = 32767
@@ -105,9 +106,12 @@ public:
explicit QNetworkRequest(const QUrl &url = QUrl());
QNetworkRequest(const QNetworkRequest &other);
~QNetworkRequest();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkRequest &operator=(QNetworkRequest &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkRequest &operator=(const QNetworkRequest &other);
- inline void swap(QNetworkRequest &other) { qSwap(d, other.d); }
+ void swap(QNetworkRequest &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkRequest &other) const;
inline bool operator!=(const QNetworkRequest &other) const
@@ -141,6 +145,10 @@ public:
Priority priority() const;
void setPriority(Priority priority);
+ // HTTP redirect related
+ int maximumRedirectsAllowed() const;
+ void setMaximumRedirectsAllowed(int maximumRedirectsAllowed);
+
private:
QSharedDataPointer<QNetworkRequestPrivate> d;
friend class QNetworkRequestPrivate;
diff --git a/src/network/access/qspdyprotocolhandler.cpp b/src/network/access/qspdyprotocolhandler.cpp
index 7430ca029d..5f9697ab92 100644
--- a/src/network/access/qspdyprotocolhandler.cpp
+++ b/src/network/access/qspdyprotocolhandler.cpp
@@ -288,16 +288,14 @@ bool QSpdyProtocolHandler::sendRequest()
m_channel->state = QHttpNetworkConnectionChannel::WritingState;
- // requests will be ordered by priority (see QMultiMap doc)
- QList<HttpMessagePair> requests = m_channel->spdyRequestsToSend.values();
- QList<int> priorities = m_channel->spdyRequestsToSend.keys();
-
- int requestsToSend = qMin(requests.count(), maxPossibleRequests);
+ int requestsToSend = qMin(m_channel->spdyRequestsToSend.size(), maxPossibleRequests);
+ QMultiMap<int, HttpMessagePair>::iterator it = m_channel->spdyRequestsToSend.begin();
+ // requests will be ordered by priority (see QMultiMap doc)
for (int a = 0; a < requestsToSend; ++a) {
- HttpMessagePair currentPair = requests.at(a);
- QHttpNetworkRequest currentRequest = requests.at(a).first;
- QHttpNetworkReply *currentReply = requests.at(a).second;
+ HttpMessagePair currentPair = *it;
+ QHttpNetworkRequest currentRequest = currentPair.first;
+ QHttpNetworkReply *currentReply = currentPair.second;
currentReply->setSpdyWasUsed(true);
qint32 streamID = generateNextStreamID();
@@ -310,10 +308,7 @@ bool QSpdyProtocolHandler::sendRequest()
connect(currentReply, SIGNAL(destroyed(QObject*)), this, SLOT(_q_replyDestroyed(QObject*)));
sendSYN_STREAM(currentPair, streamID, /* associatedToStreamID = */ 0);
- int requestsRemoved = m_channel->spdyRequestsToSend.remove(
- priorities.at(a), currentPair);
- Q_ASSERT(requestsRemoved == 1);
- Q_UNUSED(requestsRemoved); // silence -Wunused-variable
+ m_channel->spdyRequestsToSend.erase(it++);
}
m_channel->state = QHttpNetworkConnectionChannel::IdleState;
return true;
@@ -457,7 +452,7 @@ bool QSpdyProtocolHandler::uncompressHeader(const QByteArray &input, QByteArray
break;
}
default: {
- qWarning() << Q_FUNC_INFO << "got unexpected zlib return value:" << zlibRet;
+ qWarning() << "got unexpected zlib return value:" << zlibRet;
return false;
}
}
@@ -693,7 +688,7 @@ bool QSpdyProtocolHandler::uploadData(qint32 streamID)
Q_ASSERT(replyPrivate);
if (reply->d_func()->state == QHttpNetworkReplyPrivate::SPDYHalfClosed || reply->d_func()->state == QHttpNetworkReplyPrivate::SPDYClosed) {
- qWarning() << Q_FUNC_INFO << "Trying to upload to closed stream";
+ qWarning("Trying to upload to closed stream");
return false;
}
@@ -848,7 +843,7 @@ void QSpdyProtocolHandler::handleControlFrame(const QByteArray &frameHeaders) //
break;
}
default:
- qWarning() << Q_FUNC_INFO << "cannot handle frame of type" << type;
+ qWarning() << "cannot handle frame of type" << type;
}
}
@@ -892,13 +887,13 @@ void QSpdyProtocolHandler::parseHttpHeaders(char flags, const QByteArray &frameD
QByteArray uncompressedHeader;
if (!uncompressHeader(headerValuePairs, &uncompressedHeader)) {
- qWarning() << Q_FUNC_INFO << "error reading header from SYN_REPLY message";
+ qWarning("error reading header from SYN_REPLY message");
return;
}
qint32 headerCount = fourBytesToInt(uncompressedHeader.constData());
if (headerCount * 8 > uncompressedHeader.size()) {
- qWarning() << Q_FUNC_INFO << "error parsing header from SYN_REPLY message";
+ qWarning("error parsing header from SYN_REPLY message");
sendRST_STREAM(streamID, RST_STREAM_PROTOCOL_ERROR);
return;
}
@@ -909,7 +904,7 @@ void QSpdyProtocolHandler::parseHttpHeaders(char flags, const QByteArray &frameD
QByteArray name = uncompressedHeader.mid(readPointer, count);
readPointer += count;
if (readPointer > uncompressedHeader.size()) {
- qWarning() << Q_FUNC_INFO << "error parsing header from SYN_REPLY message";
+ qWarning("error parsing header from SYN_REPLY message");
sendRST_STREAM(streamID, RST_STREAM_PROTOCOL_ERROR);
return;
}
@@ -918,7 +913,7 @@ void QSpdyProtocolHandler::parseHttpHeaders(char flags, const QByteArray &frameD
QByteArray value = uncompressedHeader.mid(readPointer, count);
readPointer += count;
if (readPointer > uncompressedHeader.size()) {
- qWarning() << Q_FUNC_INFO << "error parsing header from SYN_REPLY message";
+ qWarning("error parsing header from SYN_REPLY message");
sendRST_STREAM(streamID, RST_STREAM_PROTOCOL_ERROR);
return;
}
@@ -1019,7 +1014,7 @@ void QSpdyProtocolHandler::handleRST_STREAM(char /*flags*/, quint32 length,
errorMessage = "server cannot process the frame because it is too large";
break;
default:
- qWarning() << Q_FUNC_INFO << "could not understand servers RST_STREAM status code";
+ qWarning("could not understand servers RST_STREAM status code");
errorCode = QNetworkReply::ProtocolFailure;
errorMessage = "got SPDY RST_STREAM message with unknown error code";
}
@@ -1083,7 +1078,7 @@ void QSpdyProtocolHandler::handleSETTINGS(char flags, quint32 /*length*/, const
break;
}
default:
- qWarning() << Q_FUNC_INFO << "found unknown settings value" << value;
+ qWarning() << "found unknown settings value" << value;
}
}
}
@@ -1122,7 +1117,7 @@ void QSpdyProtocolHandler::handleGOAWAY(char /*flags*/, quint32 /*length*/,
break;
}
default:
- qWarning() << Q_FUNC_INFO << "unexpected status code" << statusCode;
+ qWarning() << "unexpected status code" << statusCode;
errorCode = QNetworkReply::ProtocolUnknownError;
}
@@ -1257,7 +1252,7 @@ void QSpdyProtocolHandler::handleDataFrame(const QByteArray &frameHeaders)
}
if (flag_compress) {
- qWarning() << Q_FUNC_INFO << "SPDY level compression is not supported";
+ qWarning("SPDY level compression is not supported");
}
if (flag_fin) {
diff --git a/src/network/bearer/qnetworkconfigmanager.h b/src/network/bearer/qnetworkconfigmanager.h
index b62a44c422..84080ba83e 100644
--- a/src/network/bearer/qnetworkconfigmanager.h
+++ b/src/network/bearer/qnetworkconfigmanager.h
@@ -59,13 +59,13 @@ public:
Q_DECLARE_FLAGS(Capabilities, Capability)
- explicit QNetworkConfigurationManager(QObject *parent = 0);
+ explicit QNetworkConfigurationManager(QObject *parent = Q_NULLPTR);
virtual ~QNetworkConfigurationManager();
QNetworkConfigurationManager::Capabilities capabilities() const;
QNetworkConfiguration defaultConfiguration() const;
- QList<QNetworkConfiguration> allConfigurations(QNetworkConfiguration::StateFlags flags = 0) const;
+ QList<QNetworkConfiguration> allConfigurations(QNetworkConfiguration::StateFlags flags = QNetworkConfiguration::StateFlags()) const;
QNetworkConfiguration configurationFromIdentifier(const QString &identifier) const;
bool isOnline() const;
diff --git a/src/network/bearer/qnetworkconfigmanager_p.cpp b/src/network/bearer/qnetworkconfigmanager_p.cpp
index 8ff6ee828d..71e435b771 100644
--- a/src/network/bearer/qnetworkconfigmanager_p.cpp
+++ b/src/network/bearer/qnetworkconfigmanager_p.cpp
@@ -41,6 +41,11 @@
#include <QtCore/qstringlist.h>
#include <QtCore/qthread.h>
#include <QtCore/private/qcoreapplication_p.h>
+#include <QtCore/private/qthread_p.h>
+
+#include <QtCore/qbytearray.h>
+#include <QtCore/qglobal.h>
+
#ifndef QT_NO_BEARERMANAGEMENT
@@ -61,7 +66,7 @@ QNetworkConfigurationManagerPrivate::QNetworkConfigurationManagerPrivate()
void QNetworkConfigurationManagerPrivate::initialize()
{
//Two stage construction, because we only want to do this heavyweight work for the winner of the Q_GLOBAL_STATIC race.
- bearerThread = new QThread();
+ bearerThread = new QDaemonThread();
bearerThread->setObjectName(QStringLiteral("Qt bearer thread"));
bearerThread->moveToThread(QCoreApplicationPrivate::mainThread()); // because cleanup() is called in main thread context.
@@ -374,6 +379,8 @@ void QNetworkConfigurationManagerPrivate::updateConfigurations()
updating = false;
#ifndef QT_NO_LIBRARY
+ bool envOK = false;
+ const int skipGeneric = qgetenv("QT_EXCLUDE_GENERIC_BEARER").toInt(&envOK);
QBearerEngine *generic = 0;
QFactoryLoader *l = loader();
const PluginKeyMap keyMap = l->keyMap();
@@ -408,8 +415,10 @@ void QNetworkConfigurationManagerPrivate::updateConfigurations()
}
}
- if (generic)
- sessionEngines.append(generic);
+ if (generic) {
+ if (!envOK || skipGeneric <= 0)
+ sessionEngines.append(generic);
+ }
#endif // QT_NO_LIBRARY
}
diff --git a/src/network/bearer/qnetworkconfiguration.cpp b/src/network/bearer/qnetworkconfiguration.cpp
index 6b56d3ec88..378245ce3e 100644
--- a/src/network/bearer/qnetworkconfiguration.cpp
+++ b/src/network/bearer/qnetworkconfiguration.cpp
@@ -211,30 +211,30 @@ static QNetworkConfiguration::BearerType cellularStatus()
int cellularStatusFD;
if ((cellularStatusFD = qt_safe_open(cellularStatusFile, O_RDONLY)) == -1) {
- qWarning() << Q_FUNC_INFO << "failed to open" << cellularStatusFile;
+ qWarning() << "failed to open" << cellularStatusFile;
return ret;
}
char buf[2048];
if (qt_safe_read(cellularStatusFD, &buf, sizeof(buf)) == -1) {
- qWarning() << Q_FUNC_INFO << "read from PPS file failed:" << strerror(errno);
+ qWarning() << "read from PPS file failed:" << strerror(errno);
qt_safe_close(cellularStatusFD);
return ret;
}
pps_decoder_t ppsDecoder;
if (pps_decoder_initialize(&ppsDecoder, buf) != PPS_DECODER_OK) {
- qWarning() << Q_FUNC_INFO << "failed to initialize PPS decoder";
+ qWarning("failed to initialize PPS decoder");
qt_safe_close(cellularStatusFD);
return ret;
}
pps_decoder_error_t err;
if ((err = pps_decoder_push(&ppsDecoder, 0)) != PPS_DECODER_OK) {
- qWarning() << Q_FUNC_INFO << "pps_decoder_push failed" << err;
+ qWarning() << "pps_decoder_push failed" << err;
pps_decoder_cleanup(&ppsDecoder);
qt_safe_close(cellularStatusFD);
return ret;
}
if (!pps_decoder_is_integer(&ppsDecoder, "network_technology")) {
- qWarning() << Q_FUNC_INFO << "field has not the expected data type";
+ qWarning("field has not the expected data type");
pps_decoder_cleanup(&ppsDecoder);
qt_safe_close(cellularStatusFD);
return ret;
@@ -242,7 +242,7 @@ static QNetworkConfiguration::BearerType cellularStatus()
int type;
if (!pps_decoder_get_int(&ppsDecoder, "network_technology", &type)
== PPS_DECODER_OK) {
- qWarning() << Q_FUNC_INFO << "could not read bearer type from PPS";
+ qWarning("could not read bearer type from PPS");
pps_decoder_cleanup(&ppsDecoder);
qt_safe_close(cellularStatusFD);
return ret;
@@ -264,7 +264,7 @@ static QNetworkConfiguration::BearerType cellularStatus()
ret = QNetworkConfiguration::BearerLTE;
break;
default:
- qWarning() << Q_FUNC_INFO << "unhandled bearer type" << type;
+ qWarning() << "unhandled bearer type" << type;
break;
}
pps_decoder_cleanup(&ppsDecoder);
diff --git a/src/network/bearer/qnetworkconfiguration.h b/src/network/bearer/qnetworkconfiguration.h
index dbef344e69..317c232bea 100644
--- a/src/network/bearer/qnetworkconfiguration.h
+++ b/src/network/bearer/qnetworkconfiguration.h
@@ -49,10 +49,13 @@ class Q_NETWORK_EXPORT QNetworkConfiguration
public:
QNetworkConfiguration();
QNetworkConfiguration(const QNetworkConfiguration& other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkConfiguration &operator=(QNetworkConfiguration &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkConfiguration &operator=(const QNetworkConfiguration &other);
~QNetworkConfiguration();
- void swap(QNetworkConfiguration &other) { qSwap(d, other.d); }
+ void swap(QNetworkConfiguration &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkConfiguration &other) const;
inline bool operator!=(const QNetworkConfiguration &other) const
diff --git a/src/network/bearer/qnetworksession.h b/src/network/bearer/qnetworksession.h
index 34d721f484..bee4be7eb6 100644
--- a/src/network/bearer/qnetworksession.h
+++ b/src/network/bearer/qnetworksession.h
@@ -80,7 +80,7 @@ public:
Q_DECLARE_FLAGS(UsagePolicies, UsagePolicy)
- explicit QNetworkSession(const QNetworkConfiguration &connConfig, QObject *parent = 0);
+ explicit QNetworkSession(const QNetworkConfiguration &connConfig, QObject *parent = Q_NULLPTR);
virtual ~QNetworkSession();
bool isOpen() const;
diff --git a/src/network/doc/qtnetwork.qdocconf b/src/network/doc/qtnetwork.qdocconf
index 2a8e577dda..87e322d6c0 100644
--- a/src/network/doc/qtnetwork.qdocconf
+++ b/src/network/doc/qtnetwork.qdocconf
@@ -4,7 +4,7 @@ project = QtNetwork
description = Qt Network Reference Documentation
version = $QT_VERSION
-examplesinstallpath = network
+examplesinstallpath = qtbase/network
qhp.projects = QtNetwork
diff --git a/src/network/doc/snippets/code/src_network_bearer_qnetworkconfigmanager.cpp b/src/network/doc/snippets/code/src_network_bearer_qnetworkconfigmanager.cpp
index cd05ad63fb..00bcf35c07 100644
--- a/src/network/doc/snippets/code/src_network_bearer_qnetworkconfigmanager.cpp
+++ b/src/network/doc/snippets/code/src_network_bearer_qnetworkconfigmanager.cpp
@@ -40,9 +40,9 @@
//! [0]
QNetworkConfigurationManager mgr;
-QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations(QNetworkConfiguration::Active)
+QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations(QNetworkConfiguration::Active);
if (activeConfigs.count() > 0)
- Q_ASSERT(mgr.isOnline())
+ Q_ASSERT(mgr.isOnline());
else
- Q_ASSERT(!mgr.isOnline())
+ Q_ASSERT(!mgr.isOnline());
//! [0]
diff --git a/src/network/doc/snippets/code/src_network_ssl_qsslsocket.cpp b/src/network/doc/snippets/code/src_network_ssl_qsslsocket.cpp
index a7ab8c0977..3bd57f1d44 100644
--- a/src/network/doc/snippets/code/src_network_ssl_qsslsocket.cpp
+++ b/src/network/doc/snippets/code/src_network_ssl_qsslsocket.cpp
@@ -51,7 +51,8 @@ void SslServer::incomingConnection(qintptr socketDescriptor)
{
QSslSocket *serverSocket = new QSslSocket;
if (serverSocket->setSocketDescriptor(socketDescriptor)) {
- connect(serverSocket, SIGNAL(encrypted()), this, SLOT(ready()));
+ addPendingConnection(serverSocket);
+ connect(serverSocket, &QSslSocket::encrypted, this, &SslServer::ready);
serverSocket->startServerEncryption();
} else {
delete serverSocket;
diff --git a/src/network/kernel/kernel.pri b/src/network/kernel/kernel.pri
index e539388b81..ddb30b7b6f 100644
--- a/src/network/kernel/kernel.pri
+++ b/src/network/kernel/kernel.pri
@@ -33,15 +33,16 @@ android {
}
win32: {
+ SOURCES += kernel/qhostinfo_win.cpp
+
!winrt {
- HEADERS += kernel/qnetworkinterface_win_p.h
SOURCES += kernel/qdnslookup_win.cpp \
- kernel/qhostinfo_win.cpp \
kernel/qnetworkinterface_win.cpp
- LIBS_PRIVATE += -ldnsapi
+ LIBS_PRIVATE += -ldnsapi -liphlpapi
+ DEFINES += WINVER=0x0600 _WIN32_WINNT=0x0600
+
} else {
SOURCES += kernel/qdnslookup_winrt.cpp \
- kernel/qhostinfo_winrt.cpp \
kernel/qnetworkinterface_winrt.cpp
}
}
diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp
index d626d0bcfc..95994653e6 100644
--- a/src/network/kernel/qauthenticator.cpp
+++ b/src/network/kernel/qauthenticator.cpp
@@ -693,13 +693,13 @@ QByteArray QAuthenticatorPrivate::digestMd5Response(const QByteArray &challenge,
credentials += "uri=\"" + path + "\", ";
if (!opaque.isEmpty())
credentials += "opaque=\"" + opaque + "\", ";
- credentials += "response=\"" + response + '\"';
+ 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 + '\"';
+ credentials += "cnonce=\"" + cnonce + '"';
}
return credentials;
diff --git a/src/network/kernel/qdnslookup.cpp b/src/network/kernel/qdnslookup.cpp
index 150beb4d39..4a275f0700 100644
--- a/src/network/kernel/qdnslookup.cpp
+++ b/src/network/kernel/qdnslookup.cpp
@@ -148,6 +148,9 @@ static void qt_qdnsservicerecord_sort(QList<QDnsServiceRecord> &records)
}
}
+const char *QDnsLookupPrivate::msgNoIpV6NameServerAdresses =
+ QT_TRANSLATE_NOOP("QDnsLookupRunnable", "IPv6 addresses for nameservers are currently not supported");
+
/*!
\class QDnsLookup
\brief The QDnsLookup class represents a DNS lookup.
diff --git a/src/network/kernel/qdnslookup.h b/src/network/kernel/qdnslookup.h
index 01ebbb6535..ae015a22b8 100644
--- a/src/network/kernel/qdnslookup.h
+++ b/src/network/kernel/qdnslookup.h
@@ -55,16 +55,18 @@ class Q_NETWORK_EXPORT QDnsDomainNameRecord
public:
QDnsDomainNameRecord();
QDnsDomainNameRecord(const QDnsDomainNameRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsDomainNameRecord &operator=(QDnsDomainNameRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsDomainNameRecord &operator=(const QDnsDomainNameRecord &other);
~QDnsDomainNameRecord();
- void swap(QDnsDomainNameRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsDomainNameRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QString value() const;
- QDnsDomainNameRecord &operator=(const QDnsDomainNameRecord &other);
-
private:
QSharedDataPointer<QDnsDomainNameRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -77,16 +79,18 @@ class Q_NETWORK_EXPORT QDnsHostAddressRecord
public:
QDnsHostAddressRecord();
QDnsHostAddressRecord(const QDnsHostAddressRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsHostAddressRecord &operator=(QDnsHostAddressRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsHostAddressRecord &operator=(const QDnsHostAddressRecord &other);
~QDnsHostAddressRecord();
- void swap(QDnsHostAddressRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsHostAddressRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QHostAddress value() const;
- QDnsHostAddressRecord &operator=(const QDnsHostAddressRecord &other);
-
private:
QSharedDataPointer<QDnsHostAddressRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -99,17 +103,19 @@ class Q_NETWORK_EXPORT QDnsMailExchangeRecord
public:
QDnsMailExchangeRecord();
QDnsMailExchangeRecord(const QDnsMailExchangeRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsMailExchangeRecord &operator=(QDnsMailExchangeRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsMailExchangeRecord &operator=(const QDnsMailExchangeRecord &other);
~QDnsMailExchangeRecord();
- void swap(QDnsMailExchangeRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsMailExchangeRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString exchange() const;
QString name() const;
quint16 preference() const;
quint32 timeToLive() const;
- QDnsMailExchangeRecord &operator=(const QDnsMailExchangeRecord &other);
-
private:
QSharedDataPointer<QDnsMailExchangeRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -122,9 +128,13 @@ class Q_NETWORK_EXPORT QDnsServiceRecord
public:
QDnsServiceRecord();
QDnsServiceRecord(const QDnsServiceRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsServiceRecord &operator=(QDnsServiceRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsServiceRecord &operator=(const QDnsServiceRecord &other);
~QDnsServiceRecord();
- void swap(QDnsServiceRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsServiceRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint16 port() const;
@@ -133,8 +143,6 @@ public:
quint32 timeToLive() const;
quint16 weight() const;
- QDnsServiceRecord &operator=(const QDnsServiceRecord &other);
-
private:
QSharedDataPointer<QDnsServiceRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -147,16 +155,18 @@ class Q_NETWORK_EXPORT QDnsTextRecord
public:
QDnsTextRecord();
QDnsTextRecord(const QDnsTextRecord &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QDnsTextRecord &operator=(QDnsTextRecord &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
+ QDnsTextRecord &operator=(const QDnsTextRecord &other);
~QDnsTextRecord();
- void swap(QDnsTextRecord &other) { qSwap(d, other.d); }
+ void swap(QDnsTextRecord &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString name() const;
quint32 timeToLive() const;
QList<QByteArray> values() const;
- QDnsTextRecord &operator=(const QDnsTextRecord &other);
-
private:
QSharedDataPointer<QDnsTextRecordPrivate> d;
friend class QDnsLookupRunnable;
@@ -201,9 +211,9 @@ public:
};
Q_ENUM(Type)
- explicit QDnsLookup(QObject *parent = 0);
- QDnsLookup(Type type, const QString &name, QObject *parent = 0);
- QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent = 0);
+ explicit QDnsLookup(QObject *parent = Q_NULLPTR);
+ QDnsLookup(Type type, const QString &name, QObject *parent = Q_NULLPTR);
+ QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent = Q_NULLPTR);
~QDnsLookup();
Error error() const;
diff --git a/src/network/kernel/qdnslookup_android.cpp b/src/network/kernel/qdnslookup_android.cpp
index b03c63c320..978da57609 100644
--- a/src/network/kernel/qdnslookup_android.cpp
+++ b/src/network/kernel/qdnslookup_android.cpp
@@ -41,7 +41,7 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
Q_UNUSED(requestName);
Q_UNUSED(nameserver);
Q_UNUSED(reply);
- qWarning() << Q_FUNC_INFO << "Not yet supported on Android";
+ qWarning("Not yet supported on Android");
reply->error = QDnsLookup::ResolverError;
reply->errorString = tr("Not yet supported on Android");
return;
diff --git a/src/network/kernel/qdnslookup_p.h b/src/network/kernel/qdnslookup_p.h
index 0ac37f6636..3c8c4d5824 100644
--- a/src/network/kernel/qdnslookup_p.h
+++ b/src/network/kernel/qdnslookup_p.h
@@ -89,6 +89,8 @@ public:
void _q_lookupFinished(const QDnsLookupReply &reply);
+ static const char *msgNoIpV6NameServerAdresses;
+
bool isFinished;
QString name;
QDnsLookup::Type type;
diff --git a/src/network/kernel/qdnslookup_unix.cpp b/src/network/kernel/qdnslookup_unix.cpp
index fa782dadf7..dc8ec5a300 100644
--- a/src/network/kernel/qdnslookup_unix.cpp
+++ b/src/network/kernel/qdnslookup_unix.cpp
@@ -166,9 +166,9 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
ns->sin6_addr.s6_addr[i] = ipv6Address[i];
}
#else
- qWarning() << Q_FUNC_INFO << "IPv6 addresses for nameservers is currently not supported";
+ qWarning("%s", QDnsLookupPrivate::msgNoIpV6NameServerAdresses);
reply->error = QDnsLookup::ResolverError;
- reply->errorString = tr("IPv6 addresses for nameservers is currently not supported");
+ reply->errorString = tr(QDnsLookupPrivate::msgNoIpV6NameServerAdresses);
return;
#endif
}
diff --git a/src/network/kernel/qdnslookup_win.cpp b/src/network/kernel/qdnslookup_win.cpp
index 056a9c7a62..df0203bebb 100644
--- a/src/network/kernel/qdnslookup_win.cpp
+++ b/src/network/kernel/qdnslookup_win.cpp
@@ -60,9 +60,9 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
// For supoprting IPv6 nameserver addresses, we'll need to switch
// from DnsQuey() to DnsQueryEx() as it supports passing an IPv6
// address in the nameserver list
- qWarning() << Q_FUNC_INFO << "IPv6 addresses for nameservers is currently not supported";
+ qWarning("%s", QDnsLookupPrivate::msgNoIpV6NameServerAdresses);
reply->error = QDnsLookup::ResolverError;
- reply->errorString = tr("IPv6 addresses for nameservers is currently not supported");
+ reply->errorString = tr(QDnsLookupPrivate::msgNoIpV6NameServerAdresses);
return;
}
}
diff --git a/src/network/kernel/qdnslookup_winrt.cpp b/src/network/kernel/qdnslookup_winrt.cpp
index 8c6f9bfda5..8be63f1846 100644
--- a/src/network/kernel/qdnslookup_winrt.cpp
+++ b/src/network/kernel/qdnslookup_winrt.cpp
@@ -33,6 +33,7 @@
#include "qdnslookup_p.h"
+#include <qfunctions_winrt.h>
#include <qurl.h>
#include <qdebug.h>
@@ -50,6 +51,8 @@ using namespace ABI::Windows::Networking;
using namespace ABI::Windows::Networking::Connectivity;
using namespace ABI::Windows::Networking::Sockets;
+#define E_NO_SUCH_HOST 0x80072af9
+
QT_BEGIN_NAMESPACE
void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, const QHostAddress &nameserver, QDnsLookupReply *reply)
@@ -83,40 +86,47 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
}
ComPtr<IHostName> host;
HStringReference hostNameRef((const wchar_t*)aceHostname.utf16());
- hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
+ hr = hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IDatagramSocketStatics> datagramSocketStatics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
- datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
+ hr = datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
HString::MakeReference(L"0").Get(),
&op);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IVectorView<EndpointPair *>> endpointPairs;
- hr = op->GetResults(&endpointPairs);
- int waitCount = 0;
- while (hr == E_ILLEGAL_METHOD_CALL) {
- WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
- hr = op->GetResults(&endpointPairs);
- if (++waitCount > 1200) // Wait for 1 minute max
- return;
+ hr = QWinRTFunctions::await(op, endpointPairs.GetAddressOf(), QWinRTFunctions::YieldThread, 60 * 1000);
+ if (hr == E_NO_SUCH_HOST || !endpointPairs) {
+ reply->error = QDnsLookup::NotFoundError;
+ reply->errorString = tr("Host %1 could not be found.").arg(aceHostname);
+ return;
}
-
- if (!endpointPairs)
+ if (FAILED(hr)) {
+ reply->error = QDnsLookup::ServerFailureError;
+ reply->errorString = tr("Unknown error");
return;
+ }
unsigned int size;
- endpointPairs->get_Size(&size);
+ hr = endpointPairs->get_Size(&size);
+ Q_ASSERT_SUCCEEDED(hr);
// endpoint pairs might contain duplicates so we temporarily store addresses in a QSet
QSet<QHostAddress> addresses;
for (unsigned int i = 0; i < size; ++i) {
ComPtr<IEndpointPair> endpointpair;
- endpointPairs->GetAt(i, &endpointpair);
+ hr = endpointPairs->GetAt(i, &endpointpair);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IHostName> remoteHost;
- endpointpair->get_RemoteHostName(&remoteHost);
+ hr = endpointpair->get_RemoteHostName(&remoteHost);
+ Q_ASSERT_SUCCEEDED(hr);
HostNameType type;
- remoteHost->get_Type(&type);
+ hr = remoteHost->get_Type(&type);
+ Q_ASSERT_SUCCEEDED(hr);
if (type == HostNameType_Bluetooth || type == HostNameType_DomainName
|| (requestType != QDnsLookup::ANY
&& ((type == HostNameType_Ipv4 && requestType == QDnsLookup::AAAA)
@@ -124,7 +134,8 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
continue;
HString name;
- remoteHost->get_CanonicalName(name.GetAddressOf());
+ hr = remoteHost->get_CanonicalName(name.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
addresses.insert(QHostAddress(QString::fromWCharArray(rawString, length)));
diff --git a/src/network/kernel/qhostaddress.cpp b/src/network/kernel/qhostaddress.cpp
index 58c0de1f3b..d775007f46 100644
--- a/src/network/kernel/qhostaddress.cpp
+++ b/src/network/kernel/qhostaddress.cpp
@@ -46,6 +46,9 @@
#ifndef QT_NO_DATASTREAM
#include <qdatastream.h>
#endif
+#ifdef __SSE2__
+# include <private/qsimd_p.h>
+#endif
#ifdef QT_LINUXBASE
# include <arpa/inet.h>
@@ -106,7 +109,11 @@ public:
QString scopeId;
quint32 a; // IPv4 address
- Q_IPV6ADDR a6; // IPv6 address
+ union {
+ Q_IPV6ADDR a6; // IPv6 address
+ struct { quint64 c[2]; } a6_64;
+ struct { quint32 c[4]; } a6_32;
+ };
QAbstractSocket::NetworkLayerProtocol protocol;
bool isParsed;
@@ -123,24 +130,17 @@ QHostAddressPrivate::QHostAddressPrivate()
void QHostAddressPrivate::setAddress(quint32 a_)
{
a = a_;
+ protocol = QAbstractSocket::IPv4Protocol;
+ isParsed = true;
+
//create mapped address, except for a_ == 0 (any)
- memset(&a6, 0, sizeof(a6));
+ a6_64.c[0] = 0;
if (a) {
- a6[11] = 0xFF;
- a6[10] = 0xFF;
+ a6_32.c[2] = qToBigEndian(0xffff);
+ a6_32.c[3] = qToBigEndian(a);
} else {
- a6[11] = 0;
- a6[10] = 0;
+ a6_64.c[1] = 0;
}
-
- int i;
- for (i=15; a_ != 0; i--) {
- a6[i] = a_ & 0xFF;
- a_ >>=8;
- }
- Q_ASSERT(i >= 11);
- protocol = QAbstractSocket::IPv4Protocol;
- isParsed = true;
}
/// parses v4-mapped addresses or the AnyIPv6 address and stores in \a a;
@@ -163,21 +163,16 @@ static bool convertToIpv4(quint32& a, const Q_IPV6ADDR &a6)
void QHostAddressPrivate::setAddress(const quint8 *a_)
{
- for (int i = 0; i < 16; i++)
- a6[i] = a_[i];
- a = 0;
- convertToIpv4(a, a6);
protocol = QAbstractSocket::IPv6Protocol;
isParsed = true;
+ memcpy(a6.c, a_, sizeof(a6));
+ a = 0;
+ convertToIpv4(a, a6);
}
void QHostAddressPrivate::setAddress(const Q_IPV6ADDR &a_)
{
- a6 = a_;
- a = 0;
- convertToIpv4(a, a6);
- protocol = QAbstractSocket::IPv6Protocol;
- isParsed = true;
+ setAddress(a_.c);
}
static bool parseIp6(const QString &address, QIPAddressUtils::IPv6Address &addr, QString *scopeId)
@@ -193,7 +188,7 @@ static bool parseIp6(const QString &address, QIPAddressUtils::IPv6Address &addr,
return QIPAddressUtils::parseIp6(addr, tmp.constBegin(), tmp.constEnd()) == 0;
}
-bool QHostAddressPrivate::parse()
+Q_NEVER_INLINE bool QHostAddressPrivate::parse()
{
isParsed = true;
protocol = QAbstractSocket::UnknownNetworkLayerProtocol;
@@ -384,7 +379,7 @@ void QNetmaskAddress::setPrefixLength(QAbstractSocket::NetworkLayerProtocol prot
\value Any The dual stack any-address. A socket bound with this address will listen on both IPv4 and IPv6 interfaces.
*/
-/*! Constructs a host address object with the IP address 0.0.0.0.
+/*! Constructs a null host address object, i.e. an address which is not valid for any host or interface.
\sa clear()
*/
@@ -486,31 +481,35 @@ QHostAddress::QHostAddress(SpecialAddress address)
{
Q_IPV6ADDR ip6;
memset(&ip6, 0, sizeof ip6);
+ quint32 ip4 = INADDR_ANY;
switch (address) {
case Null:
- break;
+ return;
+
case Broadcast:
- d->setAddress(quint32(-1));
+ ip4 = INADDR_BROADCAST;
break;
case LocalHost:
- d->setAddress(0x7f000001);
- break;
- case LocalHostIPv6:
- ip6[15] = 1;
- d->setAddress(ip6);
+ ip4 = INADDR_LOOPBACK;
break;
case AnyIPv4:
- setAddress(0u);
break;
+
+ case LocalHostIPv6:
+ ip6[15] = 1;
+ // fall through
case AnyIPv6:
d->setAddress(ip6);
- break;
+ return;
+
case Any:
- d->clear();
d->protocol = QAbstractSocket::AnyIPProtocol;
- break;
+ return;
}
+
+ // common IPv4 part
+ d->setAddress(ip4);
}
/*!
@@ -775,11 +774,6 @@ QString QHostAddress::toString() const
on your host. Link-local addresses ("fe80...") are generated from the MAC
address of the local network adaptor, and are not guaranteed to be unique.
- \li Site-local: Addresses that are local to the site / private network
- (e.g., the company intranet). Site-local addresses ("fec0...") are
- usually distributed by the site router, and are not guaranteed to be
- unique outside of the local site.
-
\li Global: For globally routable addresses, such as public servers on the
Internet.
@@ -790,7 +784,7 @@ QString QHostAddress::toString() const
usually the same as the interface name (e.g., "eth0", "en1") or number
(e.g., "1", "2").
- \sa setScopeId()
+ \sa setScopeId(), QNetworkInterface, QNetworkInterface::interfaceFromName
*/
QString QHostAddress::scopeId() const
{
@@ -801,8 +795,14 @@ QString QHostAddress::scopeId() const
/*!
\since 4.1
- Sets the IPv6 scope ID of the address to \a id. If the address
- protocol is not IPv6, this function does nothing.
+ Sets the IPv6 scope ID of the address to \a id. If the address protocol is
+ not IPv6, this function does nothing. The scope ID may be set as an
+ interface name (such as "eth0" or "en1") or as an integer representing the
+ interface index. If \a id is an interface name, QtNetwork will convert to
+ an interface index using QNetworkInterface::interfaceIndexFromName() before
+ calling the operating system networking functions.
+
+ \sa scopeId(), QNetworkInterface, QNetworkInterface::interfaceFromName
*/
void QHostAddress::setScopeId(const QString &id)
{
@@ -836,34 +836,36 @@ bool QHostAddress::operator==(const QHostAddress &other) const
bool QHostAddress::operator ==(SpecialAddress other) const
{
QT_ENSURE_PARSED(this);
+ quint32 ip4 = INADDR_ANY;
switch (other) {
case Null:
return d->protocol == QAbstractSocket::UnknownNetworkLayerProtocol;
case Broadcast:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_BROADCAST;
+ ip4 = INADDR_BROADCAST;
+ break;
case LocalHost:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_LOOPBACK;
+ ip4 = INADDR_LOOPBACK;
+ break;
case Any:
return d->protocol == QAbstractSocket::AnyIPProtocol;
case AnyIPv4:
- return d->protocol == QAbstractSocket::IPv4Protocol && d->a == INADDR_ANY;
+ break;
case LocalHostIPv6:
case AnyIPv6:
if (d->protocol == QAbstractSocket::IPv6Protocol) {
- Q_IPV6ADDR ip6 = { { 0 } };
- ip6[15] = quint8(other == LocalHostIPv6); // 1 for localhost, 0 for any
- return memcmp(&d->a6, &ip6, sizeof ip6) == 0;
+ quint64 second = quint8(other == LocalHostIPv6); // 1 for localhost, 0 for any
+ return d->a6_64.c[0] == 0 && d->a6_64.c[1] == qToBigEndian(second);
}
return false;
}
- Q_UNREACHABLE();
- return false;
+ // common IPv4 part
+ return d->protocol == QAbstractSocket::IPv4Protocol && d->a == ip4;
}
/*!
@@ -1085,16 +1087,36 @@ bool QHostAddress::isLoopback() const
if ((d->a & 0xFF000000) == 0x7F000000)
return true; // v4 range (including IPv6 wrapped IPv4 addresses)
if (d->protocol == QAbstractSocket::IPv6Protocol) {
- if (d->a6.c[15] != 1)
+#ifdef __SSE2__
+ const __m128i loopback = _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
+ __m128i ipv6 = _mm_loadu_si128((const __m128i *)d->a6.c);
+ __m128i cmp = _mm_cmpeq_epi8(ipv6, loopback);
+ return _mm_movemask_epi8(cmp) == 0xffff;
+#else
+ if (d->a6_64.c[0] != 0 || qFromBigEndian(d->a6_64.c[1]) != 1)
return false;
- for (int i = 0; i < 15; i++)
- if (d->a6[i] != 0)
- return false;
+#endif
return true;
}
return false;
}
+/*!
+ \since 5.6
+
+ Returns \c true if the address is an IPv4 or IPv6 multicast address, \c
+ false otherwise.
+*/
+bool QHostAddress::isMulticast() const
+{
+ QT_ENSURE_PARSED(this);
+ if ((d->a & 0xF0000000) == 0xE0000000)
+ return true; // 224.0.0.0-239.255.255.255 (including v4-mapped IPv6 addresses)
+ if (d->protocol == QAbstractSocket::IPv6Protocol)
+ return d->a6.c[0] == 0xff;
+ return false;
+}
+
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const QHostAddress &address)
{
@@ -1112,7 +1134,7 @@ uint qHash(const QHostAddress &key, uint seed)
{
// both lines might throw
QT_ENSURE_PARSED(&key);
- return qHash(QByteArray::fromRawData(reinterpret_cast<const char *>(key.d->a6.c), 16), seed);
+ return qHashBits(key.d->a6.c, 16, seed);
}
#ifndef QT_NO_DATASTREAM
diff --git a/src/network/kernel/qhostaddress.h b/src/network/kernel/qhostaddress.h
index 0c2229c334..9e3ee43d04 100644
--- a/src/network/kernel/qhostaddress.h
+++ b/src/network/kernel/qhostaddress.h
@@ -84,9 +84,16 @@ public:
QHostAddress(SpecialAddress address);
~QHostAddress();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QHostAddress &operator=(QHostAddress &&other) Q_DECL_NOTHROW
+ { swap(other); return *this; }
+#endif
+
QHostAddress &operator=(const QHostAddress &other);
QHostAddress &operator=(const QString &address);
+ void swap(QHostAddress &other) Q_DECL_NOTHROW { d.swap(other.d); }
+
void setAddress(quint32 ip4Addr);
void setAddress(quint8 *ip6Addr); // ### Qt 6: remove me
void setAddress(const quint8 *ip6Addr);
@@ -117,6 +124,7 @@ public:
bool isInSubnet(const QPair<QHostAddress, int> &subnet) const;
bool isLoopback() const;
+ bool isMulticast() const;
static QPair<QHostAddress, int> parseSubnet(const QString &subnet);
@@ -124,6 +132,7 @@ public:
protected:
QScopedPointer<QHostAddressPrivate> d;
};
+Q_DECLARE_SHARED_NOT_MOVABLE_UNTIL_QT6(QHostAddress)
inline bool operator ==(QHostAddress::SpecialAddress address1, const QHostAddress &address2)
{ return address2 == address1; }
diff --git a/src/network/kernel/qhostinfo.cpp b/src/network/kernel/qhostinfo.cpp
index a2ac9065fd..c6c09542e7 100644
--- a/src/network/kernel/qhostinfo.cpp
+++ b/src/network/kernel/qhostinfo.cpp
@@ -415,10 +415,22 @@ void QHostInfo::setErrorString(const QString &str)
/*!
\fn QString QHostInfo::localHostName()
- Returns the host name of this machine.
+ Returns this machine's host name, if one is configured. Note that hostnames
+ are not guaranteed to be globally unique, especially if they were
+ configured automatically.
- \sa hostName()
+ This function does not guarantee the returned host name is a Fully
+ Qualified Domain Name (FQDN). For that, use fromName() to resolve the
+ returned name to an FQDN.
+
+ This function returns the same as QSysInfo::machineHostName().
+
+ \sa hostName(), localDomainName()
*/
+QString QHostInfo::localHostName()
+{
+ return QSysInfo::machineHostName();
+}
/*!
\fn QString QHostInfo::localDomainName()
diff --git a/src/network/kernel/qhostinfo_unix.cpp b/src/network/kernel/qhostinfo_unix.cpp
index 90a6f763f7..266a67771c 100644
--- a/src/network/kernel/qhostinfo_unix.cpp
+++ b/src/network/kernel/qhostinfo_unix.cpp
@@ -315,15 +315,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
-QString QHostInfo::localHostName()
-{
- char hostName[512];
- if (gethostname(hostName, sizeof(hostName)) == -1)
- return QString();
- hostName[sizeof(hostName) - 1] = '\0';
- return QString::fromLocal8Bit(hostName);
-}
-
QString QHostInfo::localDomainName()
{
#if !defined(Q_OS_VXWORKS) && !defined(Q_OS_ANDROID)
diff --git a/src/network/kernel/qhostinfo_win.cpp b/src/network/kernel/qhostinfo_win.cpp
index e044728198..7e45e9f949 100644
--- a/src/network/kernel/qhostinfo_win.cpp
+++ b/src/network/kernel/qhostinfo_win.cpp
@@ -34,7 +34,6 @@
#include <winsock2.h>
#include "qhostinfo_p.h"
-#include "private/qnativesocketengine_p.h"
#include <ws2tcpip.h>
#include <private/qsystemlibrary_p.h>
#include <qmutex.h>
@@ -77,14 +76,18 @@ static void resolveLibrary()
{
// Attempt to resolve getaddrinfo(); without it we'll have to fall
// back to gethostbyname(), which has no IPv6 support.
-#if !defined(Q_OS_WINCE)
- local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getaddrinfo");
- local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "freeaddrinfo");
- local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getnameinfo");
-#else
+#if defined(Q_OS_WINCE)
local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "getaddrinfo");
local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "freeaddrinfo");
local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "getnameinfo");
+#elif defined (Q_OS_WINRT)
+ local_getaddrinfo = (getaddrinfoProto) &getaddrinfo;
+ local_freeaddrinfo = (freeaddrinfoProto) &freeaddrinfo;
+ local_getnameinfo = (getnameinfoProto) getnameinfo;
+#else
+ local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getaddrinfo");
+ local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "freeaddrinfo");
+ local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getnameinfo");
#endif
}
@@ -111,7 +114,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
QMutexLocker locker(&qPrivCEMutex);
#endif
- QWindowsSockInit winSock;
+ QSysInfo::machineHostName(); // this initializes ws2_32.dll
// Load res_init on demand.
static QBasicAtomicInt triedResolve = Q_BASIC_ATOMIC_INITIALIZER(false);
@@ -136,7 +139,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
// Reverse lookup
if (local_getnameinfo) {
sockaddr_in sa4;
- qt_sockaddr_in6 sa6;
+ sockaddr_in6 sa6;
sockaddr *sa;
QT_SOCKLEN_T saSize;
if (address.protocol() == QAbstractSocket::IPv4Protocol) {
@@ -150,7 +153,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
saSize = sizeof(sa6);
memset(&sa6, 0, sizeof(sa6));
sa6.sin6_family = AF_INET6;
- memcpy(sa6.sin6_addr.qt_s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.qt_s6_addr));
+ memcpy(&sa6.sin6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr));
}
char hbuf[NI_MAXHOST];
@@ -197,7 +200,7 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
break;
case AF_INET6: {
QHostAddress addr;
- addr.setAddress(((qt_sockaddr_in6 *) p->ai_addr)->sin6_addr.qt_s6_addr);
+ addr.setAddress(((sockaddr_in6 *) p->ai_addr)->sin6_addr.s6_addr);
if (!addresses.contains(addr))
addresses.append(addr);
}
@@ -256,17 +259,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
-QString QHostInfo::localHostName()
-{
- QWindowsSockInit winSock;
-
- char hostName[512];
- if (gethostname(hostName, sizeof(hostName)) == -1)
- return QString();
- hostName[sizeof(hostName) - 1] = '\0';
- return QString::fromLocal8Bit(hostName);
-}
-
// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
QT_END_NAMESPACE
diff --git a/src/network/kernel/qhostinfo_winrt.cpp b/src/network/kernel/qhostinfo_winrt.cpp
deleted file mode 100644
index 1a97fe0e40..0000000000
--- a/src/network/kernel/qhostinfo_winrt.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qhostinfo_p.h"
-
-#include <qurl.h>
-
-#include <wrl.h>
-#include <windows.networking.h>
-#include <windows.networking.sockets.h>
-#include <windows.networking.connectivity.h>
-using namespace Microsoft::WRL;
-using namespace Microsoft::WRL::Wrappers;
-using namespace ABI::Windows::Foundation;
-using namespace ABI::Windows::Foundation::Collections;
-using namespace ABI::Windows::Networking;
-using namespace ABI::Windows::Networking::Connectivity;
-using namespace ABI::Windows::Networking::Sockets;
-
-QT_BEGIN_NAMESPACE
-
-//#define QHOSTINFO_DEBUG
-
-QHostInfo QHostInfoAgent::fromName(const QString &hostName)
-{
- QHostInfo results;
-
- QHostAddress address;
- if (address.setAddress(hostName)) {
- // Reverse lookup
- // TODO: is there a replacement for getnameinfo for winrt?
- Q_UNIMPLEMENTED();
- return results;
- }
-
- QByteArray aceHostname = QUrl::toAce(hostName);
- results.setHostName(hostName);
- if (aceHostname.isEmpty()) {
- results.setError(QHostInfo::HostNotFound);
- results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname"));
- return results;
- }
-
- ComPtr<IHostNameFactory> hostnameFactory;
- HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
- IID_PPV_ARGS(&hostnameFactory));
- Q_ASSERT_X(SUCCEEDED(hr), Q_FUNC_INFO, qPrintable(qt_error_string(hr)));
-
- ComPtr<IHostName> host;
- HStringReference hostNameRef((const wchar_t*)hostName.utf16());
- hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
-
- ComPtr<IDatagramSocketStatics> datagramSocketStatics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
-
- ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
- datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
- HString::MakeReference(L"0").Get(),
- &op);
-
- ComPtr<IVectorView<EndpointPair *>> endpointPairs;
- hr = op->GetResults(&endpointPairs);
- int waitCount = 0;
- while (hr == E_ILLEGAL_METHOD_CALL) {
- WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
- hr = op->GetResults(&endpointPairs);
- if (++waitCount > 1200) // Wait for 1 minute max
- return results;
- }
-
- if (!endpointPairs)
- return results;
-
- unsigned int size;
- endpointPairs->get_Size(&size);
- QList<QHostAddress> addresses;
- for (unsigned int i = 0; i < size; ++i) {
- ComPtr<IEndpointPair> endpointpair;
- endpointPairs->GetAt(i, &endpointpair);
- ComPtr<IHostName> remoteHost;
- endpointpair->get_RemoteHostName(&remoteHost);
- if (!remoteHost)
- continue;
- HostNameType type;
- remoteHost->get_Type(&type);
- if (type == HostNameType_DomainName)
- continue;
-
- HString name;
- remoteHost->get_CanonicalName(name.GetAddressOf());
- UINT32 length;
- PCWSTR rawString = name.GetRawBuffer(&length);
- QHostAddress addr;
- addr.setAddress(QString::fromWCharArray(rawString, length));
- if (!addresses.contains(addr))
- addresses.append(addr);
- }
- results.setAddresses(addresses);
-
- return results;
-}
-
-QString QHostInfo::localHostName()
-{
- ComPtr<INetworkInformationStatics> statics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);
-
- ComPtr<IVectorView<HostName *>> hostNames;
- statics->GetHostNames(&hostNames);
- if (!hostNames)
- return QString();
-
- unsigned int size;
- hostNames->get_Size(&size);
- if (size == 0)
- return QString();
-
- for (unsigned int i = 0; i < size; ++i) {
- ComPtr<IHostName> hostName;
- hostNames->GetAt(i, &hostName);
- HostNameType type;
- hostName->get_Type(&type);
- if (type != HostNameType_DomainName)
- continue;
-
- HString name;
- hostName->get_CanonicalName(name.GetAddressOf());
- UINT32 length;
- PCWSTR rawString = name.GetRawBuffer(&length);
- return QString::fromWCharArray(rawString, length);
- }
- ComPtr<IHostName> firstHost;
- hostNames->GetAt(0, &firstHost);
-
- HString name;
- firstHost->get_CanonicalName(name.GetAddressOf());
- UINT32 length;
- PCWSTR rawString = name.GetRawBuffer(&length);
- return QString::fromWCharArray(rawString, length);
-}
-
-// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
-
-QT_END_NAMESPACE
diff --git a/src/network/kernel/qnetworkinterface.cpp b/src/network/kernel/qnetworkinterface.cpp
index 8d891733ac..4a527052d1 100644
--- a/src/network/kernel/qnetworkinterface.cpp
+++ b/src/network/kernel/qnetworkinterface.cpp
@@ -86,9 +86,16 @@ QSharedDataPointer<QNetworkInterfacePrivate> QNetworkInterfaceManager::interface
{
QList<QSharedDataPointer<QNetworkInterfacePrivate> > interfaceList = allInterfaces();
QList<QSharedDataPointer<QNetworkInterfacePrivate> >::ConstIterator it = interfaceList.constBegin();
- for ( ; it != interfaceList.constEnd(); ++it)
- if ((*it)->name == name)
+
+ bool ok;
+ uint index = name.toUInt(&ok);
+
+ for ( ; it != interfaceList.constEnd(); ++it) {
+ if (ok && (*it)->index == int(index))
return *it;
+ else if ((*it)->name == name)
+ return *it;
+ }
return empty;
}
@@ -108,6 +115,7 @@ QList<QSharedDataPointer<QNetworkInterfacePrivate> > QNetworkInterfaceManager::a
{
QList<QNetworkInterfacePrivate *> list = postProcess(scan());
QList<QSharedDataPointer<QNetworkInterfacePrivate> > result;
+ result.reserve(list.size());
foreach (QNetworkInterfacePrivate *ptr, list)
result << QSharedDataPointer<QNetworkInterfacePrivate>(ptr);
@@ -515,6 +523,9 @@ QList<QNetworkAddressEntry> QNetworkInterface::addressEntries() const
name. If no such interface exists, this function returns an
invalid QNetworkInterface object.
+ The string \a name may be either an actual interface name (such as "eth0"
+ or "en1") or an interface index in string form ("1", "2", etc.).
+
\sa name(), isValid()
*/
QNetworkInterface QNetworkInterface::interfaceFromName(const QString &name)
@@ -549,6 +560,7 @@ QList<QNetworkInterface> QNetworkInterface::allInterfaces()
{
QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
QList<QNetworkInterface> result;
+ result.reserve(privs.size());
foreach (const QSharedDataPointer<QNetworkInterfacePrivate> &p, privs) {
QNetworkInterface item;
item.d = p;
diff --git a/src/network/kernel/qnetworkinterface.h b/src/network/kernel/qnetworkinterface.h
index a4d93156fb..b3daa3d4a0 100644
--- a/src/network/kernel/qnetworkinterface.h
+++ b/src/network/kernel/qnetworkinterface.h
@@ -51,10 +51,13 @@ class Q_NETWORK_EXPORT QNetworkAddressEntry
public:
QNetworkAddressEntry();
QNetworkAddressEntry(const QNetworkAddressEntry &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkAddressEntry &operator=(QNetworkAddressEntry &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkAddressEntry &operator=(const QNetworkAddressEntry &other);
~QNetworkAddressEntry();
- void swap(QNetworkAddressEntry &other) { qSwap(d, other.d); }
+ void swap(QNetworkAddressEntry &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkAddressEntry &other) const;
inline bool operator!=(const QNetworkAddressEntry &other) const
@@ -93,10 +96,13 @@ public:
QNetworkInterface();
QNetworkInterface(const QNetworkInterface &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkInterface &operator=(QNetworkInterface &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkInterface &operator=(const QNetworkInterface &other);
~QNetworkInterface();
- void swap(QNetworkInterface &other) { qSwap(d, other.d); }
+ void swap(QNetworkInterface &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isValid() const;
@@ -127,6 +133,9 @@ Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, const QNetworkInterface &networ
QT_END_NAMESPACE
+Q_DECLARE_METATYPE(QNetworkAddressEntry)
+Q_DECLARE_METATYPE(QNetworkInterface)
+
#endif // QT_NO_NETWORKINTERFACE
#endif
diff --git a/src/network/kernel/qnetworkinterface_unix.cpp b/src/network/kernel/qnetworkinterface_unix.cpp
index 9c5ba4e799..5e6d24dd44 100644
--- a/src/network/kernel/qnetworkinterface_unix.cpp
+++ b/src/network/kernel/qnetworkinterface_unix.cpp
@@ -127,14 +127,13 @@ static QNetworkInterface::InterfaceFlags convertFlags(uint rawFlags)
#ifdef QT_NO_GETIFADDRS
// getifaddrs not available
-static const int STORAGEBUFFER_GROWTH = 256;
-
static QSet<QByteArray> interfaceNames(int socket)
{
QSet<QByteArray> result;
#ifdef QT_NO_IPV6IFNAME
QByteArray storageBuffer;
struct ifconf interfaceList;
+ static const int STORAGEBUFFER_GROWTH = 256;
forever {
// grow the storage buffer
@@ -186,9 +185,14 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
QNetworkInterfacePrivate *iface = 0;
int ifindex = 0;
-#ifndef QT_NO_IPV6IFNAME
+#if !defined(QT_NO_IPV6IFNAME) || defined(SIOCGIFINDEX)
// Get the interface index
+# ifdef SIOCGIFINDEX
+ if (qt_safe_ioctl(socket, SIOCGIFINDEX, &req) >= 0)
+ ifindex = req.ifr_ifindex;
+# else
ifindex = if_nametoindex(req.ifr_name);
+# endif
// find the interface data
QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
@@ -214,6 +218,27 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
iface = new QNetworkInterfacePrivate;
iface->index = ifindex;
interfaces << iface;
+ }
+
+ return iface;
+}
+
+static QList<QNetworkInterfacePrivate *> interfaceListing()
+{
+ QList<QNetworkInterfacePrivate *> interfaces;
+
+ int socket;
+ if ((socket = qt_safe_socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == -1)
+ return interfaces; // error
+
+ QSet<QByteArray> names = interfaceNames(socket);
+ QSet<QByteArray>::ConstIterator it = names.constBegin();
+ for ( ; it != names.constEnd(); ++it) {
+ ifreq req;
+ memset(&req, 0, sizeof(ifreq));
+ memcpy(req.ifr_name, *it, qMin<int>(it->length() + 1, sizeof(req.ifr_name) - 1));
+
+ QNetworkInterfacePrivate *iface = findInterface(socket, interfaces, req);
#ifdef SIOCGIFNAME
// Get the canonical name
@@ -242,27 +267,6 @@ static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfa
iface->hardwareAddress = iface->makeHwAddress(6, addr);
}
#endif
- }
-
- return iface;
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListing()
-{
- QList<QNetworkInterfacePrivate *> interfaces;
-
- int socket;
- if ((socket = qt_safe_socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == -1)
- return interfaces; // error
-
- QSet<QByteArray> names = interfaceNames(socket);
- QSet<QByteArray>::ConstIterator it = names.constBegin();
- for ( ; it != names.constEnd(); ++it) {
- ifreq req;
- memset(&req, 0, sizeof(ifreq));
- memcpy(req.ifr_name, *it, qMin<int>(it->length() + 1, sizeof(req.ifr_name) - 1));
-
- QNetworkInterfacePrivate *iface = findInterface(socket, interfaces, req);
// Get the interface broadcast address
QNetworkAddressEntry entry;
@@ -310,10 +314,15 @@ static QList<QNetworkInterfacePrivate *> createInterfaces(ifaddrs *rawList)
{
QList<QNetworkInterfacePrivate *> interfaces;
QSet<QString> seenInterfaces;
-
- // on Linux, AF_PACKET addresses carry the hardware address and interface index;
- // scan for them first (they're usually first, but we have no guarantee this
- // will be the case forever)
+ QVarLengthArray<int, 16> seenIndexes; // faster than QSet<int>
+
+ // On Linux, glibc, uClibc and MUSL obtain the address listing via two
+ // netlink calls: first an RTM_GETLINK to obtain the interface listing,
+ // then one RTM_GETADDR to get all the addresses (uClibc implementation is
+ // copied from glibc; Bionic currently doesn't support getifaddrs). They
+ // synthesize AF_PACKET addresses from the RTM_GETLINK responses, which
+ // means by construction they currently show up first in the interface
+ // listing.
for (ifaddrs *ptr = rawList; ptr; ptr = ptr->ifa_next) {
if (ptr->ifa_addr && ptr->ifa_addr->sa_family == AF_PACKET) {
sockaddr_ll *sll = (sockaddr_ll *)ptr->ifa_addr;
@@ -324,23 +333,30 @@ static QList<QNetworkInterfacePrivate *> createInterfaces(ifaddrs *rawList)
iface->flags = convertFlags(ptr->ifa_flags);
iface->hardwareAddress = iface->makeHwAddress(sll->sll_halen, (uchar*)sll->sll_addr);
+ Q_ASSERT(!seenIndexes.contains(iface->index));
+ seenIndexes.append(iface->index);
seenInterfaces.insert(iface->name);
}
}
// see if we missed anything:
- // virtual interfaces with no HW address have no AF_PACKET
+ // - virtual interfaces with no HW address have no AF_PACKET
+ // - interface labels have no AF_PACKET, but shouldn't be shown as a new interface
for (ifaddrs *ptr = rawList; ptr; ptr = ptr->ifa_next) {
if (ptr->ifa_addr && ptr->ifa_addr->sa_family != AF_PACKET) {
QString name = QString::fromLatin1(ptr->ifa_name);
if (seenInterfaces.contains(name))
continue;
+ int ifindex = if_nametoindex(ptr->ifa_name);
+ if (seenIndexes.contains(ifindex))
+ continue;
+
QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
interfaces << iface;
iface->name = name;
iface->flags = convertFlags(ptr->ifa_flags);
- iface->index = if_nametoindex(ptr->ifa_name);
+ iface->index = ifindex;
}
}
@@ -419,7 +435,7 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
interfaces = createInterfaces(interfaceListing);
for (ifaddrs *ptr = interfaceListing; ptr; ptr = ptr->ifa_next) {
- // Get the interface index
+ // Find the interface
QString name = QString::fromLatin1(ptr->ifa_name);
QNetworkInterfacePrivate *iface = 0;
QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
@@ -429,6 +445,18 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
iface = *if_it;
break;
}
+
+ if (!iface) {
+ // it may be an interface label, search by interface index
+ int ifindex = if_nametoindex(ptr->ifa_name);
+ for (if_it = interfaces.begin(); if_it != interfaces.end(); ++if_it)
+ if ((*if_it)->index == ifindex) {
+ // found this interface already
+ iface = *if_it;
+ break;
+ }
+ }
+
if (!iface) {
// skip all non-IP interfaces
continue;
diff --git a/src/network/kernel/qnetworkinterface_win.cpp b/src/network/kernel/qnetworkinterface_win.cpp
index ddeb6c111f..907638f73e 100644
--- a/src/network/kernel/qnetworkinterface_win.cpp
+++ b/src/network/kernel/qnetworkinterface_win.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -31,7 +32,7 @@
**
****************************************************************************/
-#include "qnetworkinterface_win_p.h"
+#define WIN32_LEAN_AND_MEAN 1
#include "qnetworkinterface.h"
#include "qnetworkinterface_p.h"
@@ -41,16 +42,23 @@
#include <qhostinfo.h>
#include <qhash.h>
#include <qurl.h>
-#include <private/qsystemlibrary_p.h>
+
+// Since we need to include winsock2.h, we need to define WIN32_LEAN_AND_MEAN
+// (above) so windows.h won't include winsock.h.
+// In addition, we need to include winsock2.h before iphlpapi.h and we need
+// to include ws2ipdef.h to work around an MinGW-w64 bug
+// (http://sourceforge.net/p/mingw-w64/mailman/message/32935366/)
+#include <winsock2.h>
+#include <ws2ipdef.h>
+#include <iphlpapi.h>
+#include <ws2tcpip.h>
+
+#include <qt_windows.h>
QT_BEGIN_NAMESPACE
-typedef DWORD (WINAPI *PtrGetAdaptersInfo)(PIP_ADAPTER_INFO, PULONG);
-static PtrGetAdaptersInfo ptrGetAdaptersInfo = 0;
-typedef ULONG (WINAPI *PtrGetAdaptersAddresses)(ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
-static PtrGetAdaptersAddresses ptrGetAdaptersAddresses = 0;
-typedef DWORD (WINAPI *PtrGetNetworkParams)(PFIXED_INFO, PULONG);
-static PtrGetNetworkParams ptrGetNetworkParams = 0;
+typedef NETIO_STATUS (WINAPI *PtrConvertInterfaceLuidToName)(const NET_LUID *, PWSTR, SIZE_T);
+static PtrConvertInterfaceLuidToName ptrConvertInterfaceLuidToName = 0;
static void resolveLibs()
{
@@ -58,21 +66,17 @@ static void resolveLibs()
static bool done = false;
if (!done) {
- done = true;
-
- HINSTANCE iphlpapiHnd = QSystemLibrary::load(L"iphlpapi");
- if (iphlpapiHnd == NULL)
- return;
+ HINSTANCE iphlpapiHnd = GetModuleHandle(L"iphlpapi");
+ Q_ASSERT(iphlpapiHnd);
#if defined(Q_OS_WINCE)
- ptrGetAdaptersInfo = (PtrGetAdaptersInfo)GetProcAddress(iphlpapiHnd, L"GetAdaptersInfo");
- ptrGetAdaptersAddresses = (PtrGetAdaptersAddresses)GetProcAddress(iphlpapiHnd, L"GetAdaptersAddresses");
- ptrGetNetworkParams = (PtrGetNetworkParams)GetProcAddress(iphlpapiHnd, L"GetNetworkParams");
+ // since Windows Embedded Compact 7
+ ptrConvertInterfaceLuidToName = (PtrConvertInterfaceLuidToName)GetProcAddress(iphlpapiHnd, L"ConvertInterfaceLuidToNameW");
#else
- ptrGetAdaptersInfo = (PtrGetAdaptersInfo)GetProcAddress(iphlpapiHnd, "GetAdaptersInfo");
- ptrGetAdaptersAddresses = (PtrGetAdaptersAddresses)GetProcAddress(iphlpapiHnd, "GetAdaptersAddresses");
- ptrGetNetworkParams = (PtrGetNetworkParams)GetProcAddress(iphlpapiHnd, "GetNetworkParams");
+ // since Windows Vista
+ ptrConvertInterfaceLuidToName = (PtrConvertInterfaceLuidToName)GetProcAddress(iphlpapiHnd, "ConvertInterfaceLuidToNameW");
#endif
+ done = true;
}
}
@@ -85,8 +89,8 @@ static QHostAddress addressFromSockaddr(sockaddr *sa)
if (sa->sa_family == AF_INET)
address.setAddress(htonl(((sockaddr_in *)sa)->sin_addr.s_addr));
else if (sa->sa_family == AF_INET6) {
- address.setAddress(((qt_sockaddr_in6 *)sa)->sin6_addr.qt_s6_addr);
- int scope = ((qt_sockaddr_in6 *)sa)->sin6_scope_id;
+ address.setAddress(((sockaddr_in6 *)sa)->sin6_addr.s6_addr);
+ int scope = ((sockaddr_in6 *)sa)->sin6_scope_id;
if (scope)
address.setScopeId(QString::number(scope));
} else
@@ -103,14 +107,14 @@ static QHash<QHostAddress, QHostAddress> ipv4Netmasks()
ULONG bufSize = sizeof staticBuf;
QHash<QHostAddress, QHostAddress> ipv4netmasks;
- DWORD retval = ptrGetAdaptersInfo(pAdapter, &bufSize);
+ DWORD retval = GetAdaptersInfo(pAdapter, &bufSize);
if (retval == ERROR_BUFFER_OVERFLOW) {
// need more memory
pAdapter = (IP_ADAPTER_INFO *)malloc(bufSize);
if (!pAdapter)
return ipv4netmasks;
// try again
- if (ptrGetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
+ if (GetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
free(pAdapter);
return ipv4netmasks;
}
@@ -145,14 +149,14 @@ static QList<QNetworkInterfacePrivate *> interfaceListingWinXP()
ULONG flags = GAA_FLAG_INCLUDE_PREFIX |
GAA_FLAG_SKIP_DNS_SERVER |
GAA_FLAG_SKIP_MULTICAST;
- ULONG retval = ptrGetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize);
+ ULONG retval = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize);
if (retval == ERROR_BUFFER_OVERFLOW) {
// need more memory
pAdapter = (IP_ADAPTER_ADDRESSES *)malloc(bufSize);
if (!pAdapter)
return interfaces;
// try again
- if (ptrGetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize) != ERROR_SUCCESS) {
+ if (GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize) != ERROR_SUCCESS) {
free(pAdapter);
return interfaces;
}
@@ -180,7 +184,16 @@ static QList<QNetworkInterfacePrivate *> interfaceListingWinXP()
if (ptr->IfType == IF_TYPE_PPP)
iface->flags |= QNetworkInterface::IsPointToPoint;
- iface->name = QString::fromLocal8Bit(ptr->AdapterName);
+ if (ptrConvertInterfaceLuidToName && ptr->Length >= offsetof(IP_ADAPTER_ADDRESSES, Luid)) {
+ // use ConvertInterfaceLuidToName because that returns a friendlier name, though not
+ // as friendly as FriendlyName below
+ WCHAR buf[IF_MAX_STRING_SIZE + 1];
+ if (ptrConvertInterfaceLuidToName(&ptr->Luid, buf, sizeof(buf)/sizeof(buf[0])) == NO_ERROR)
+ iface->name = QString::fromWCharArray(buf);
+ }
+ if (iface->name.isEmpty())
+ iface->name = QString::fromLocal8Bit(ptr->AdapterName);
+
iface->friendlyName = QString::fromWCharArray(ptr->FriendlyName);
if (ptr->PhysicalAddressLength)
iface->hardwareAddress = iface->makeHwAddress(ptr->PhysicalAddressLength,
@@ -221,92 +234,25 @@ static QList<QNetworkInterfacePrivate *> interfaceListingWinXP()
return interfaces;
}
-static QList<QNetworkInterfacePrivate *> interfaceListingWin2k()
-{
- QList<QNetworkInterfacePrivate *> interfaces;
- IP_ADAPTER_INFO staticBuf[2]; // 2 is arbitrary
- PIP_ADAPTER_INFO pAdapter = staticBuf;
- ULONG bufSize = sizeof staticBuf;
-
- DWORD retval = ptrGetAdaptersInfo(pAdapter, &bufSize);
- if (retval == ERROR_BUFFER_OVERFLOW) {
- // need more memory
- pAdapter = (IP_ADAPTER_INFO *)malloc(bufSize);
- if (!pAdapter)
- return interfaces;
- // try again
- if (ptrGetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
- free(pAdapter);
- return interfaces;
- }
- } else if (retval != ERROR_SUCCESS) {
- // error
- return interfaces;
- }
-
- // iterate over the list and add the entries to our listing
- for (PIP_ADAPTER_INFO ptr = pAdapter; ptr; ptr = ptr->Next) {
- QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
- interfaces << iface;
-
- iface->index = ptr->Index;
- iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
- if (ptr->Type == MIB_IF_TYPE_PPP)
- iface->flags |= QNetworkInterface::IsPointToPoint;
- else
- iface->flags |= QNetworkInterface::CanBroadcast;
- iface->name = QString::fromLocal8Bit(ptr->AdapterName);
- iface->hardwareAddress = QNetworkInterfacePrivate::makeHwAddress(ptr->AddressLength,
- ptr->Address);
-
- for (PIP_ADDR_STRING addr = &ptr->IpAddressList; addr; addr = addr->Next) {
- QNetworkAddressEntry entry;
- entry.setIp(QHostAddress(QLatin1String(addr->IpAddress.String)));
- entry.setNetmask(QHostAddress(QLatin1String(addr->IpMask.String)));
- // broadcast address is set on postProcess()
-
- iface->addressEntries << entry;
- }
- }
-
- if (pAdapter != staticBuf)
- free(pAdapter);
-
- return interfaces;
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListing()
-{
- resolveLibs();
- if (ptrGetAdaptersAddresses != NULL)
- return interfaceListingWinXP();
- else if (ptrGetAdaptersInfo != NULL)
- return interfaceListingWin2k();
-
- // failed
- return QList<QNetworkInterfacePrivate *>();
-}
-
QList<QNetworkInterfacePrivate *> QNetworkInterfaceManager::scan()
{
- return interfaceListing();
+ resolveLibs();
+ return interfaceListingWinXP();
}
QString QHostInfo::localDomainName()
{
resolveLibs();
- if (ptrGetNetworkParams == NULL)
- return QString(); // couldn't resolve
FIXED_INFO info, *pinfo;
ULONG bufSize = sizeof info;
pinfo = &info;
- if (ptrGetNetworkParams(pinfo, &bufSize) == ERROR_BUFFER_OVERFLOW) {
+ if (GetNetworkParams(pinfo, &bufSize) == ERROR_BUFFER_OVERFLOW) {
pinfo = (FIXED_INFO *)malloc(bufSize);
if (!pinfo)
return QString();
// try again
- if (ptrGetNetworkParams(pinfo, &bufSize) != ERROR_SUCCESS) {
+ if (GetNetworkParams(pinfo, &bufSize) != ERROR_SUCCESS) {
free(pinfo);
return QString(); // error
}
diff --git a/src/network/kernel/qnetworkinterface_win_p.h b/src/network/kernel/qnetworkinterface_win_p.h
deleted file mode 100644
index 88c1945fe6..0000000000
--- a/src/network/kernel/qnetworkinterface_win_p.h
+++ /dev/null
@@ -1,262 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QNETWORKINTERFACE_WIN_P_H
-#define QNETWORKINTERFACE_WIN_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QLibrary class. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qglobal.h>
-#include <winsock2.h>
-#include <qt_windows.h>
-#include <time.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef GAA_FLAG_INCLUDE_ALL_INTERFACES
-# define GAA_FLAG_INCLUDE_ALL_INTERFACES 0x0100
-#endif
-#ifndef MAX_ADAPTER_ADDRESS_LENGTH
-// definitions from iptypes.h
-# define MAX_ADAPTER_DESCRIPTION_LENGTH 128 // arb.
-# define MAX_ADAPTER_NAME_LENGTH 256 // arb.
-# define MAX_ADAPTER_ADDRESS_LENGTH 8 // arb.
-# define DEFAULT_MINIMUM_ENTITIES 32 // arb.
-# define MAX_HOSTNAME_LEN 128 // arb.
-# define MAX_DOMAIN_NAME_LEN 128 // arb.
-# define MAX_SCOPE_ID_LEN 256 // arb.
-
-# define GAA_FLAG_SKIP_UNICAST 0x0001
-# define GAA_FLAG_SKIP_ANYCAST 0x0002
-# define GAA_FLAG_SKIP_MULTICAST 0x0004
-# define GAA_FLAG_SKIP_DNS_SERVER 0x0008
-# define GAA_FLAG_INCLUDE_PREFIX 0x0010
-# define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020
-
-# define IP_ADAPTER_DDNS_ENABLED 0x01
-# define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX 0x02
-# define IP_ADAPTER_DHCP_ENABLED 0x04
-# define IP_ADAPTER_RECEIVE_ONLY 0x08
-# define IP_ADAPTER_NO_MULTICAST 0x10
-# define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x20
-
-# define MIB_IF_TYPE_OTHER 1
-# define MIB_IF_TYPE_ETHERNET 6
-# define MIB_IF_TYPE_TOKENRING 9
-# define MIB_IF_TYPE_FDDI 15
-# define MIB_IF_TYPE_PPP 23
-# define MIB_IF_TYPE_LOOPBACK 24
-# define MIB_IF_TYPE_SLIP 28
-
-// definitions from Ipifcons.h
-#define IF_TYPE_PPP 23
-
-#endif
-// copied from qnativesocketengine_win.cpp
-struct qt_in6_addr {
- u_char qt_s6_addr[16];
-};
-typedef struct {
- short sin6_family; /* AF_INET6 */
- u_short sin6_port; /* Transport level port number */
- u_long sin6_flowinfo; /* IPv6 flow information */
- struct qt_in6_addr sin6_addr; /* IPv6 address */
- u_long sin6_scope_id; /* set of interfaces for a scope */
-} qt_sockaddr_in6;
-
-// copied from MSDN online help
-typedef enum {
- IpPrefixOriginOther = 0,
- IpPrefixOriginManual,
- IpPrefixOriginWellKnown,
- IpPrefixOriginDhcp,
- IpPrefixOriginRouterAdvertisement
-} IP_PREFIX_ORIGIN;
-
-typedef enum {
- IpSuffixOriginOther = 0,
- IpSuffixOriginManual,
- IpSuffixOriginWellKnown,
- IpSuffixOriginDhcp,
- IpSuffixOriginLinkLayerAddress,
- IpSuffixOriginRandom
-} IP_SUFFIX_ORIGIN;
-
-typedef enum {
- IpDadStateInvalid = 0,
- IpDadStateTentative,
- IpDadStateDuplicate,
- IpDadStateDeprecated,
- IpDadStatePreferred,
-} IP_DAD_STATE;
-
-typedef enum {
- IfOperStatusUp = 1,
- IfOperStatusDown,
- IfOperStatusTesting,
- IfOperStatusUnknown,
- IfOperStatusDormant,
- IfOperStatusNotPresent,
- IfOperStatusLowerLayerDown
-} IF_OPER_STATUS;
-
-typedef struct _IP_ADAPTER_UNICAST_ADDRESS {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_UNICAST_ADDRESS* Next;
- SOCKET_ADDRESS Address;
- IP_PREFIX_ORIGIN PrefixOrigin;
- IP_SUFFIX_ORIGIN SuffixOrigin;
- IP_DAD_STATE DadState;
- ULONG ValidLifetime;
- ULONG PreferredLifetime;
- ULONG LeaseLifetime;
-} IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_ANYCAST_ADDRESS
- IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_MULTICAST_ADDRESS
- IP_ADAPTER_MULTICAST_ADDRESS,
- *PIP_ADAPTER_MULTICAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS
- IP_ADAPTER_DNS_SERVER_ADDRESS,
- *PIP_ADAPTER_DNS_SERVER_ADDRESS;
-
-typedef struct _IP_ADAPTER_PREFIX {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_PREFIX* Next;
- SOCKET_ADDRESS Address;
- ULONG PrefixLength;
-} IP_ADAPTER_PREFIX,
- *PIP_ADAPTER_PREFIX;
-
-typedef struct _IP_ADAPTER_ADDRESSES {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD IfIndex;
- };
- };
- struct _IP_ADAPTER_ADDRESSES* Next;
- PCHAR AdapterName;
- PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
- PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
- PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
- PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
- PWCHAR DnsSuffix;
- PWCHAR Description;
- PWCHAR FriendlyName;
- BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
- DWORD PhysicalAddressLength;
- DWORD Flags;
- DWORD Mtu;
- DWORD IfType;
- IF_OPER_STATUS OperStatus;
- DWORD Ipv6IfIndex;
- DWORD ZoneIndices[16];
- PIP_ADAPTER_PREFIX FirstPrefix;
-} IP_ADAPTER_ADDRESSES,
- *PIP_ADAPTER_ADDRESSES;
-
-typedef struct {
- char String[4 * 4];
-} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;
-
-typedef struct _IP_ADDR_STRING {
- struct _IP_ADDR_STRING* Next;
- IP_ADDRESS_STRING IpAddress;
- IP_MASK_STRING IpMask;
- DWORD Context;
-} IP_ADDR_STRING,
- *PIP_ADDR_STRING;
-
-typedef struct _IP_ADAPTER_INFO {
- struct _IP_ADAPTER_INFO* Next;
- DWORD ComboIndex;
- char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
- char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
- UINT AddressLength;
- BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
- DWORD Index;
- UINT Type;
- UINT DhcpEnabled;
- PIP_ADDR_STRING CurrentIpAddress;
- IP_ADDR_STRING IpAddressList;
- IP_ADDR_STRING GatewayList;
- IP_ADDR_STRING DhcpServer;
- BOOL HaveWins;
- IP_ADDR_STRING PrimaryWinsServer;
- IP_ADDR_STRING SecondaryWinsServer;
- time_t LeaseObtained;
- time_t LeaseExpires;
-} IP_ADAPTER_INFO,
- *PIP_ADAPTER_INFO;
-
-typedef struct {
- char HostName[MAX_HOSTNAME_LEN + 4];
- char DomainName[MAX_DOMAIN_NAME_LEN + 4];
- PIP_ADDR_STRING CurrentDnsServer;
- IP_ADDR_STRING DnsServerList;
- UINT NodeType;
- char ScopeId[MAX_SCOPE_ID_LEN + 4];
- UINT EnableRouting;
- UINT EnableProxy;
- UINT EnableDns;
-} FIXED_INFO, *PFIXED_INFO;
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/network/kernel/qnetworkinterface_winrt.cpp b/src/network/kernel/qnetworkinterface_winrt.cpp
index 0234154427..1945b2427f 100644
--- a/src/network/kernel/qnetworkinterface_winrt.cpp
+++ b/src/network/kernel/qnetworkinterface_winrt.cpp
@@ -36,6 +36,8 @@
#ifndef QT_NO_NETWORKINTERFACE
+#include <qfunctions_winrt.h>
+
#include <wrl.h>
#include <windows.foundation.h>
#include <windows.foundation.collections.h>
@@ -59,6 +61,57 @@ struct HostNameInfo {
QString address;
};
+static QNetworkInterfacePrivate *interfaceFromProfile(IConnectionProfile *profile, QList<HostNameInfo> *hostList)
+{
+ if (!profile)
+ return 0;
+
+ QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
+
+ NetworkConnectivityLevel connectivityLevel;
+ HRESULT hr = profile->GetNetworkConnectivityLevel(&connectivityLevel);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (connectivityLevel != NetworkConnectivityLevel_None)
+ iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
+
+ ComPtr<INetworkAdapter> adapter;
+ hr = profile->get_NetworkAdapter(&adapter);
+ // Indicates that no internet connection is available/the device is in airplane mode
+ if (hr == E_INVALIDARG)
+ return 0;
+ Q_ASSERT_SUCCEEDED(hr);
+ UINT32 type;
+ hr = adapter->get_IanaInterfaceType(&type);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (type == 23)
+ iface->flags |= QNetworkInterface::IsPointToPoint;
+ GUID id;
+ hr = adapter->get_NetworkAdapterId(&id);
+ Q_ASSERT_SUCCEEDED(hr);
+ OLECHAR adapterName[39]={0};
+ StringFromGUID2(id, adapterName, 39);
+ iface->name = QString::fromWCharArray(adapterName);
+
+ // According to http://stackoverflow.com/questions/12936193/how-unique-is-the-ethernet-network-adapter-id-in-winrt-it-is-derived-from-the-m
+ // obtaining the MAC address using WinRT API is impossible
+ // iface->hardwareAddress = ?
+
+ for (int i = 0; i < hostList->length(); ++i) {
+ const HostNameInfo hostInfo = hostList->at(i);
+ if (id != hostInfo.adapterId)
+ continue;
+
+ QNetworkAddressEntry entry;
+ entry.setIp(QHostAddress(hostInfo.address));
+ entry.setPrefixLength(hostInfo.prefixLength);
+ iface->addressEntries << entry;
+
+ hostList->takeAt(i);
+ --i;
+ }
+ return iface;
+}
+
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
QList<QNetworkInterfacePrivate *> interfaces;
@@ -66,36 +119,46 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
QList<HostNameInfo> hostList;
ComPtr<INetworkInformationStatics> hostNameStatics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &hostNameStatics);
+ HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &hostNameStatics);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IVectorView<HostName *>> hostNames;
- hostNameStatics->GetHostNames(&hostNames);
+ hr = hostNameStatics->GetHostNames(&hostNames);
+ Q_ASSERT_SUCCEEDED(hr);
if (!hostNames)
return interfaces;
unsigned int hostNameCount;
- hostNames->get_Size(&hostNameCount);
+ hr = hostNames->get_Size(&hostNameCount);
+ Q_ASSERT_SUCCEEDED(hr);
for (unsigned i = 0; i < hostNameCount; ++i) {
HostNameInfo hostInfo;
ComPtr<IHostName> hostName;
- hostNames->GetAt(i, &hostName);
+ hr = hostNames->GetAt(i, &hostName);
+ Q_ASSERT_SUCCEEDED(hr);
HostNameType type;
- hostName->get_Type(&type);
+ hr = hostName->get_Type(&type);
+ Q_ASSERT_SUCCEEDED(hr);
if (type == HostNameType_DomainName)
continue;
ComPtr<IIPInformation> ipInformation;
- hostName->get_IPInformation(&ipInformation);
+ hr = hostName->get_IPInformation(&ipInformation);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<INetworkAdapter> currentAdapter;
- ipInformation->get_NetworkAdapter(&currentAdapter);
+ hr = ipInformation->get_NetworkAdapter(&currentAdapter);
+ Q_ASSERT_SUCCEEDED(hr);
- currentAdapter->get_NetworkAdapterId(&hostInfo.adapterId);
+ hr = currentAdapter->get_NetworkAdapterId(&hostInfo.adapterId);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IReference<unsigned char>> prefixLengthReference;
- ipInformation->get_PrefixLength(&prefixLengthReference);
+ hr = ipInformation->get_PrefixLength(&prefixLengthReference);
+ Q_ASSERT_SUCCEEDED(hr);
- prefixLengthReference->get_Value(&hostInfo.prefixLength);
+ hr = prefixLengthReference->get_Value(&hostInfo.prefixLength);
+ Q_ASSERT_SUCCEEDED(hr);
// invalid prefixes
if ((type == HostNameType_Ipv4 && hostInfo.prefixLength > 32)
@@ -103,7 +166,8 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
continue;
HString name;
- hostName->get_CanonicalName(name.GetAddressOf());
+ hr = hostName->get_CanonicalName(name.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
hostInfo.address = QString::fromWCharArray(rawString, length);
@@ -112,54 +176,35 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
}
INetworkInformationStatics *networkInfoStatics;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &networkInfoStatics);
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &networkInfoStatics);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IConnectionProfile> connectionProfile;
+ hr = networkInfoStatics->GetInternetConnectionProfile(&connectionProfile);
+ Q_ASSERT_SUCCEEDED(hr);
+ QNetworkInterfacePrivate *iface = interfaceFromProfile(connectionProfile.Get(), &hostList);
+ if (iface) {
+ iface->index = 0;
+ interfaces << iface;
+ }
+
ComPtr<IVectorView<ConnectionProfile *>> connectionProfiles;
- networkInfoStatics->GetConnectionProfiles(&connectionProfiles);
+ hr = networkInfoStatics->GetConnectionProfiles(&connectionProfiles);
+ Q_ASSERT_SUCCEEDED(hr);
if (!connectionProfiles)
return interfaces;
unsigned int size;
- connectionProfiles->get_Size(&size);
+ hr = connectionProfiles->get_Size(&size);
+ Q_ASSERT_SUCCEEDED(hr);
for (unsigned int i = 0; i < size; ++i) {
- QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
- interfaces << iface;
-
ComPtr<IConnectionProfile> profile;
- connectionProfiles->GetAt(i, &profile);
-
- NetworkConnectivityLevel connectivityLevel;
- profile->GetNetworkConnectivityLevel(&connectivityLevel);
- if (connectivityLevel != NetworkConnectivityLevel_None)
- iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
-
- ComPtr<INetworkAdapter> adapter;
- profile->get_NetworkAdapter(&adapter);
- UINT32 type;
- adapter->get_IanaInterfaceType(&type);
- if (type == 23)
- iface->flags |= QNetworkInterface::IsPointToPoint;
- GUID id;
- adapter->get_NetworkAdapterId(&id);
- OLECHAR adapterName[39]={0};
- StringFromGUID2(id, adapterName, 39);
- iface->name = QString::fromWCharArray(adapterName);
-
- // According to http://stackoverflow.com/questions/12936193/how-unique-is-the-ethernet-network-adapter-id-in-winrt-it-is-derived-from-the-m
- // obtaining the MAC address using WinRT API is impossible
- // iface->hardwareAddress = ?
-
- for (int i = 0; i < hostList.length(); ++i) {
- const HostNameInfo hostInfo = hostList.at(i);
- if (id != hostInfo.adapterId)
- continue;
-
- QNetworkAddressEntry entry;
- entry.setIp(QHostAddress(hostInfo.address));
- entry.setPrefixLength(hostInfo.prefixLength);
- iface->addressEntries << entry;
-
- hostList.takeAt(i);
- --i;
+ hr = connectionProfiles->GetAt(i, &profile);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ iface = interfaceFromProfile(profile.Get(), &hostList);
+ if (iface) {
+ iface->index = i + 1;
+ interfaces << iface;
}
}
return interfaces;
diff --git a/src/network/kernel/qnetworkproxy.cpp b/src/network/kernel/qnetworkproxy.cpp
index 53c4410fab..4c7c0c5442 100644
--- a/src/network/kernel/qnetworkproxy.cpp
+++ b/src/network/kernel/qnetworkproxy.cpp
@@ -218,7 +218,6 @@
#include "private/qhttpsocketengine_p.h"
#include "qauthenticator.h"
#include "qdebug.h"
-#include "qhash.h"
#include "qmutex.h"
#include "qstringlist.h"
#include "qurl.h"
@@ -1606,7 +1605,7 @@ QDebug operator<<(QDebug debug, const QNetworkProxy &proxy)
debug << "Unknown proxy " << int(type);
break;
}
- debug << "\"" << proxy.hostName() << ":" << proxy.port() << "\" ";
+ debug << '"' << proxy.hostName() << ':' << proxy.port() << "\" ";
QNetworkProxy::Capabilities caps = proxy.capabilities();
QStringList scaps;
if (caps & QNetworkProxy::TunnelingCapability)
@@ -1619,7 +1618,7 @@ QDebug operator<<(QDebug debug, const QNetworkProxy &proxy)
scaps << QStringLiteral("Caching");
if (caps & QNetworkProxy::HostNameLookupCapability)
scaps << QStringLiteral("NameLookup");
- debug << "[" << scaps.join(QLatin1Char(' ')) << "]";
+ debug << '[' << scaps.join(QLatin1Char(' ')) << ']';
return debug;
}
#endif
diff --git a/src/network/kernel/qnetworkproxy.h b/src/network/kernel/qnetworkproxy.h
index 6b0f4a3937..717c141d60 100644
--- a/src/network/kernel/qnetworkproxy.h
+++ b/src/network/kernel/qnetworkproxy.h
@@ -63,7 +63,6 @@ public:
QueryType queryType = TcpSocket);
explicit QNetworkProxyQuery(quint16 bindPort, const QString &protocolTag = QString(),
QueryType queryType = TcpServer);
- QNetworkProxyQuery(const QNetworkProxyQuery &other);
#ifndef QT_NO_BEARERMANAGEMENT
QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
const QUrl &requestUrl, QueryType queryType = UrlRequest);
@@ -74,10 +73,14 @@ public:
quint16 bindPort, const QString &protocolTag = QString(),
QueryType queryType = TcpServer);
#endif
- ~QNetworkProxyQuery();
+ QNetworkProxyQuery(const QNetworkProxyQuery &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkProxyQuery &operator=(QNetworkProxyQuery &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkProxyQuery &operator=(const QNetworkProxyQuery &other);
+ ~QNetworkProxyQuery();
- void swap(QNetworkProxyQuery &other) { qSwap(d, other.d); }
+ void swap(QNetworkProxyQuery &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkProxyQuery &other) const;
inline bool operator!=(const QNetworkProxyQuery &other) const
@@ -139,10 +142,13 @@ public:
QNetworkProxy(ProxyType type, const QString &hostName = QString(), quint16 port = 0,
const QString &user = QString(), const QString &password = QString());
QNetworkProxy(const QNetworkProxy &other);
+#ifdef Q_COMPILER_RVALUE_REFS
+ QNetworkProxy &operator=(QNetworkProxy &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QNetworkProxy &operator=(const QNetworkProxy &other);
~QNetworkProxy();
- void swap(QNetworkProxy &other) { qSwap(d, other.d); }
+ void swap(QNetworkProxy &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QNetworkProxy &other) const;
inline bool operator!=(const QNetworkProxy &other) const
diff --git a/src/network/kernel/qnetworkproxy_generic.cpp b/src/network/kernel/qnetworkproxy_generic.cpp
index d3295376da..145ba18e3f 100644
--- a/src/network/kernel/qnetworkproxy_generic.cpp
+++ b/src/network/kernel/qnetworkproxy_generic.cpp
@@ -58,7 +58,7 @@ static bool ignoreProxyFor(const QNetworkProxyQuery &query)
QString peerHostName = query.peerHostName();
// Since we use suffix matching, "*" is our 'default' behaviour
- if (token.startsWith("*"))
+ if (token.startsWith('*'))
token = token.mid(1);
// Harmonize trailing dot notation
diff --git a/src/network/kernel/qnetworkproxy_mac.cpp b/src/network/kernel/qnetworkproxy_mac.cpp
index 51400f55bb..05d4c6955a 100644
--- a/src/network/kernel/qnetworkproxy_mac.cpp
+++ b/src/network/kernel/qnetworkproxy_mac.cpp
@@ -35,6 +35,7 @@
#ifndef QT_NO_NETWORKPROXY
+#include <CFNetwork/CFNetwork.h>
#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>
diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp
index e22c5ccca4..385146bb95 100644
--- a/src/network/socket/qabstractsocket.cpp
+++ b/src/network/socket/qabstractsocket.cpp
@@ -426,8 +426,8 @@
\value ReuseAddressHint Provides a hint to QAbstractSocket that it should try
to rebind the service even if the address and port are already bound by
- another socket. On Windows, this is equivalent to the SO_REUSEADDR
- socket option. On Unix, this option is ignored.
+ another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR
+ socket option.
\value DefaultForPlatform The default option for the current platform.
On Unix and OS X, this is equivalent to (DontShareAddress
@@ -559,7 +559,6 @@ QAbstractSocketPrivate::QAbstractSocketPrivate()
readBufferMaxSize(0),
writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
isBuffered(false),
- blockingTimeout(30000),
connectTimer(0),
disconnectTimer(0),
connectTimeElapsed(0),
@@ -631,8 +630,8 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
resetSocketLayer();
socketEngine = QAbstractSocketEngine::createSocketEngine(q->socketType(), proxyInUse, q);
if (!socketEngine) {
- socketError = QAbstractSocket::UnsupportedSocketOperationError;
- q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError,
+ QAbstractSocket::tr("Operation on socket is not supported"));
return false;
}
#ifndef QT_NO_BEARERMANAGEMENT
@@ -645,11 +644,12 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
socketEngine->errorString().toLatin1().constData());
#endif
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
+ setError(socketEngine->error(), socketEngine->errorString());
return false;
}
+ configureCreatedSocket();
+
if (threadData->hasEventDispatcher())
socketEngine->setReceiver(this);
@@ -661,6 +661,12 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
}
/*! \internal
+*/
+void QAbstractSocketPrivate::configureCreatedSocket()
+{
+}
+
+/*! \internal
Slot connected to the read socket notifier. This slot is called
when new data is available for reading, or when the socket has
@@ -811,7 +817,7 @@ bool QAbstractSocketPrivate::canWriteNotification()
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
#endif
- int tmp = writeBuffer.size();
+ qint64 tmp = writeBuffer.size();
flush();
if (socketEngine) {
@@ -871,18 +877,16 @@ bool QAbstractSocketPrivate::flush()
return false;
}
- int nextSize = writeBuffer.nextDataBlockSize();
+ qint64 nextSize = writeBuffer.nextDataBlockSize();
const char *ptr = writeBuffer.readPointer();
// Attempt to write it all in one chunk.
qint64 written = socketEngine->write(ptr, nextSize);
if (written < 0) {
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
#endif
- emit q->error(socketError);
+ setErrorAndEmit(socketEngine->error(), socketEngine->errorString());
// an unexpected error so close the socket.
q->abort();
return false;
@@ -984,8 +988,7 @@ void QAbstractSocketPrivate::startConnectingByName(const QString &host)
}
// failed to connect
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
+ setError(socketEngine->error(), socketEngine->errorString());
}
state = QAbstractSocket::UnconnectedState;
@@ -1044,8 +1047,7 @@ void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
#endif
state = QAbstractSocket::UnconnectedState;
- socketError = QAbstractSocket::HostNotFoundError;
- q->setErrorString(QAbstractSocket::tr("Host not found"));
+ setError(QAbstractSocket::HostNotFoundError, QAbstractSocket::tr("Host not found"));
emit q->stateChanged(state);
emit q->error(QAbstractSocket::HostNotFoundError);
return;
@@ -1094,11 +1096,10 @@ void QAbstractSocketPrivate::_q_connectToNextAddress()
|| socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
#endif
) && socketEngine->state() == QAbstractSocket::ConnectingState) {
- socketError = QAbstractSocket::ConnectionRefusedError;
- q->setErrorString(QAbstractSocket::tr("Connection refused"));
+ setError(QAbstractSocket::ConnectionRefusedError,
+ QAbstractSocket::tr("Connection refused"));
} else {
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
+ setError(socketEngine->error(), socketEngine->errorString());
}
} else {
// socketError = QAbstractSocket::ConnectionRefusedError;
@@ -1222,8 +1223,8 @@ void QAbstractSocketPrivate::_q_abortConnectionAttempt()
if (addresses.isEmpty()) {
state = QAbstractSocket::UnconnectedState;
- socketError = QAbstractSocket::SocketTimeoutError;
- q->setErrorString(QAbstractSocket::tr("Connection timed out"));
+ setError(QAbstractSocket::SocketTimeoutError,
+ QAbstractSocket::tr("Connection timed out"));
emit q->stateChanged(state);
emit q->error(socketError);
} else {
@@ -1247,7 +1248,10 @@ void QAbstractSocketPrivate::_q_forceDisconnect()
*/
bool QAbstractSocketPrivate::readFromSocket()
{
+#ifdef QABSTRACTSOCKET_DEBUG
Q_Q(QAbstractSocket);
+#endif
+
// Find how many bytes we can read from the socket layer.
qint64 bytesToRead = socketEngine->bytesAvailable();
if (bytesToRead == 0) {
@@ -1283,9 +1287,7 @@ bool QAbstractSocketPrivate::readFromSocket()
#endif
if (!socketEngine->isValid()) {
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
- emit q->error(socketError);
+ setErrorAndEmit(socketEngine->error(), socketEngine->errorString());
#if defined(QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
q->errorString().toLatin1().constData());
@@ -1355,6 +1357,31 @@ QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *
return socket->d_func()->socketEngine;
}
+/*!
+ \internal
+
+ Sets the socket error state to \c errorCode and \a errorString.
+*/
+void QAbstractSocketPrivate::setError(QAbstractSocket::SocketError errorCode,
+ const QString &errStr)
+{
+ socketError = errorCode;
+ errorString = errStr;
+}
+
+/*!
+ \internal
+
+ Sets the socket error state to \c errorCode and \a errorString,
+ and emits the QAbstractSocket::error() signal.
+*/
+void QAbstractSocketPrivate::setErrorAndEmit(QAbstractSocket::SocketError errorCode,
+ const QString &errorString)
+{
+ Q_Q(QAbstractSocket);
+ setError(errorCode, errorString);
+ emit q->error(errorCode);
+}
/*! \internal
@@ -1519,9 +1546,7 @@ bool QAbstractSocketPrivate::bind(const QHostAddress &address, quint16 port, QAb
cachedSocketDescriptor = socketEngine->socketDescriptor();
if (!result) {
- socketError = socketEngine->error();
- q->setErrorString(socketEngine->errorString());
- emit q->error(socketError);
+ setErrorAndEmit(socketEngine->error(), socketEngine->errorString());
return false;
}
@@ -1599,9 +1624,7 @@ void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
if (d->state == ConnectedState || d->state == ConnectingState
|| d->state == ClosingState || d->state == HostLookupState) {
qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
- d->socketError = QAbstractSocket::OperationError;
- setErrorString(QAbstractSocket::tr("Trying to connect while connection is in progress"));
- emit error(d->socketError);
+ d->setErrorAndEmit(OperationError, tr("Trying to connect while connection is in progress"));
return;
}
@@ -1630,9 +1653,8 @@ void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
d->resolveProxy(hostName, port);
if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
// failed to setup the proxy
- d->socketError = QAbstractSocket::UnsupportedSocketOperationError;
- setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
- emit error(d->socketError);
+ d->setErrorAndEmit(UnsupportedSocketOperationError,
+ tr("Operation on socket is not supported"));
return;
}
#endif
@@ -1707,9 +1729,9 @@ qint64 QAbstractSocket::bytesToWrite() const
{
Q_D(const QAbstractSocket);
#if defined(QABSTRACTSOCKET_DEBUG)
- qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
+ qDebug("QAbstractSocket::bytesToWrite() == %lld", d->writeBuffer.size());
#endif
- return (qint64)d->writeBuffer.size();
+ return d->writeBuffer.size();
}
/*!
@@ -1803,12 +1825,12 @@ QString QAbstractSocket::peerName() const
*/
bool QAbstractSocket::canReadLine() const
{
- bool hasLine = d_func()->buffer.canReadLine();
+ bool hasLine = QIODevice::canReadLine();
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %lld, size = %lld",
hasLine ? "true" : "false", d_func()->buffer.size(), d_func()->buffer.size());
#endif
- return hasLine || QIODevice::canReadLine();
+ return hasLine;
}
/*!
@@ -1852,8 +1874,7 @@ bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState
d->buffer.clear();
d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
if (!d->socketEngine) {
- d->socketError = UnsupportedSocketOperationError;
- setErrorString(tr("Operation on socket is not supported"));
+ d->setError(UnsupportedSocketOperationError, tr("Operation on socket is not supported"));
return false;
}
#ifndef QT_NO_BEARERMANAGEMENT
@@ -1862,8 +1883,7 @@ bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState
#endif
bool result = d->socketEngine->initialize(socketDescriptor, socketState);
if (!result) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
+ d->setError(d->socketEngine->error(), d->socketEngine->errorString());
return false;
}
@@ -2073,11 +2093,10 @@ bool QAbstractSocket::waitForConnected(int msecs)
}
if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
- d->socketError = SocketTimeoutError;
+ d->setError(SocketTimeoutError, tr("Socket operation timed out"));
d->state = UnconnectedState;
emit stateChanged(d->state);
d->resetSocketLayer();
- setErrorString(tr("Socket operation timed out"));
}
#if defined (QABSTRACTSOCKET_DEBUG)
@@ -2136,13 +2155,11 @@ bool QAbstractSocket::waitForReadyRead(int msecs)
bool readyToWrite = false;
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
- msecs, d->socketError, errorString().toLatin1().constData());
+ msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
#endif
- emit error(d->socketError);
+ d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
if (d->socketError != SocketTimeoutError)
close();
return false;
@@ -2208,13 +2225,11 @@ bool QAbstractSocket::waitForBytesWritten(int msecs)
bool readyToWrite = false;
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
- msecs, d->socketError, errorString().toLatin1().constData());
+ msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
#endif
- emit error(d->socketError);
+ d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
if (d->socketError != SocketTimeoutError)
close();
return false;
@@ -2290,13 +2305,11 @@ bool QAbstractSocket::waitForDisconnected(int msecs)
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
!d->writeBuffer.isEmpty(),
qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
- msecs, d->socketError, errorString().toLatin1().constData());
+ msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
#endif
- emit error(d->socketError);
+ d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
if (d->socketError != SocketTimeoutError)
close();
return false;
@@ -2427,8 +2440,7 @@ qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
// -2 from the engine means no bytes available (EAGAIN) so read more later
return 0;
} else if (readBytes < 0) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
+ d->setError(d->socketEngine->error(), d->socketEngine->errorString());
d->resetSocketLayer();
d->state = QAbstractSocket::UnconnectedState;
} else if (!d->socketEngine->isReadNotificationEnabled()) {
@@ -2459,8 +2471,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
Q_D(QAbstractSocket);
if (d->state == QAbstractSocket::UnconnectedState
|| (!d->socketEngine && d->socketType != TcpSocket && !d->isBuffered)) {
- d->socketError = QAbstractSocket::UnknownSocketError;
- setErrorString(tr("Socket is not connected"));
+ d->setError(UnknownSocketError, tr("Socket is not connected"));
return -1;
}
@@ -2469,8 +2480,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
// This code is for the new Unbuffered QTcpSocket use case
qint64 written = d->socketEngine->write(data, size);
if (written < 0) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
+ d->setError(d->socketEngine->error(), d->socketEngine->errorString());
return written;
} else if (written < size) {
// Buffer what was not written yet
@@ -2483,8 +2493,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
// This is for a QUdpSocket that was connect()ed
qint64 written = d->socketEngine->write(data, size);
if (written < 0) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
+ d->setError(d->socketEngine->error(), d->socketEngine->errorString());
} else if (!d->writeBuffer.isEmpty()) {
d->socketEngine->setWriteNotificationEnabled(true);
}
diff --git a/src/network/socket/qabstractsocket.h b/src/network/socket/qabstractsocket.h
index f3d7f13f48..23f0d26cbd 100644
--- a/src/network/socket/qabstractsocket.h
+++ b/src/network/socket/qabstractsocket.h
@@ -149,7 +149,7 @@ public:
qint64 bytesAvailable() const Q_DECL_OVERRIDE;
qint64 bytesToWrite() const Q_DECL_OVERRIDE;
- bool canReadLine() const Q_DECL_OVERRIDE;
+ bool canReadLine() const Q_DECL_OVERRIDE; // ### Qt6: remove me
quint16 localPort() const;
QHostAddress localAddress() const;
@@ -213,7 +213,7 @@ protected:
void setPeerAddress(const QHostAddress &address);
void setPeerName(const QString &name);
- QAbstractSocket(SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent = 0);
+ QAbstractSocket(SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent = Q_NULLPTR);
private:
Q_DECLARE_PRIVATE(QAbstractSocket)
diff --git a/src/network/socket/qabstractsocket_p.h b/src/network/socket/qabstractsocket_p.h
index 63440b6416..a905625b19 100644
--- a/src/network/socket/qabstractsocket_p.h
+++ b/src/network/socket/qabstractsocket_p.h
@@ -130,16 +130,19 @@ public:
bool flush();
bool initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol);
+ virtual void configureCreatedSocket();
void startConnectingByName(const QString &host);
void fetchConnectionParameters();
void setupSocketNotifiers();
bool readFromSocket();
+ void setError(QAbstractSocket::SocketError errorCode, const QString &errorString);
+ void setErrorAndEmit(QAbstractSocket::SocketError errorCode, const QString &errorString);
+
qint64 readBufferMaxSize;
QRingBuffer writeBuffer;
bool isBuffered;
- int blockingTimeout;
QTimer *connectTimer;
QTimer *disconnectTimer;
diff --git a/src/network/socket/qabstractsocketengine_p.h b/src/network/socket/qabstractsocketengine_p.h
index f2a3149678..3771cdb135 100644
--- a/src/network/socket/qabstractsocketengine_p.h
+++ b/src/network/socket/qabstractsocketengine_p.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -58,6 +59,30 @@ class QNetworkInterface;
#endif
class QNetworkProxy;
+class QIpPacketHeader
+{
+public:
+ QIpPacketHeader(const QHostAddress &dstAddr = QHostAddress(), quint16 port = 0)
+ : destinationAddress(dstAddr), ifindex(0), hopLimit(-1), destinationPort(port)
+ {}
+
+ void clear()
+ {
+ senderAddress.clear();
+ destinationAddress.clear();
+ ifindex = 0;
+ hopLimit = -1;
+ }
+
+ QHostAddress senderAddress;
+ QHostAddress destinationAddress;
+
+ uint ifindex;
+ int hopLimit;
+ quint16 senderPort;
+ quint16 destinationPort;
+};
+
class QAbstractSocketEngineReceiver {
public:
virtual ~QAbstractSocketEngineReceiver(){}
@@ -93,9 +118,21 @@ public:
KeepAliveOption,
MulticastTtlOption,
MulticastLoopbackOption,
- TypeOfServiceOption
+ TypeOfServiceOption,
+ ReceivePacketInformation,
+ ReceiveHopLimit
};
+ enum PacketHeaderOption {
+ WantNone = 0,
+ WantDatagramSender = 0x01,
+ WantDatagramDestination = 0x02,
+ WantDatagramHopLimit = 0x04,
+
+ WantAll = 0xff
+ };
+ Q_DECLARE_FLAGS(PacketHeaderOptions, PacketHeaderOption)
+
virtual bool initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol = QAbstractSocket::IPv4Protocol) = 0;
virtual bool initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState = QAbstractSocket::ConnectedState) = 0;
@@ -126,10 +163,9 @@ public:
virtual bool setMulticastInterface(const QNetworkInterface &iface) = 0;
#endif // QT_NO_NETWORKINTERFACE
- virtual qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) = 0;
- virtual qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) = 0;
+ virtual qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header = 0,
+ PacketHeaderOptions = WantNone) = 0;
+ virtual qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header) = 0;
virtual bool hasPendingDatagrams() const = 0;
virtual qint64 pendingDatagramSize() const = 0;
#endif // QT_NO_UDPSOCKET
@@ -225,6 +261,8 @@ private:
friend class QAbstractSocketEngine;
};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QAbstractSocketEngine::PacketHeaderOptions)
+
QT_END_NAMESPACE
#endif // QABSTRACTSOCKETENGINE_P_H
diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp
index 23347ce08b..a744688f29 100644
--- a/src/network/socket/qhttpsocketengine.cpp
+++ b/src/network/socket/qhttpsocketengine.cpp
@@ -271,14 +271,12 @@ bool QHttpSocketEngine::setMulticastInterface(const QNetworkInterface &)
}
#endif // QT_NO_NETWORKINTERFACE
-qint64 QHttpSocketEngine::readDatagram(char *, qint64, QHostAddress *,
- quint16 *)
+qint64 QHttpSocketEngine::readDatagram(char *, qint64, QIpPacketHeader *, PacketHeaderOptions)
{
return 0;
}
-qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QHostAddress &,
- quint16)
+qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QIpPacketHeader &)
{
return 0;
}
@@ -441,8 +439,11 @@ void QHttpSocketEngine::setReadNotificationEnabled(bool enable)
d->readNotificationEnabled = enable;
if (enable) {
// Enabling read notification can trigger a notification.
- if (bytesAvailable())
+ if (bytesAvailable()) {
slotSocketReadNotification();
+ } else if (d->socket && d->socket->state() == QAbstractSocket::UnconnectedState) {
+ emitReadNotification();
+ }
}
}
@@ -483,7 +484,7 @@ void QHttpSocketEngine::slotSocketConnected()
QUrl::toAce(d->peerName);
QByteArray path = peerAddress + ':' + QByteArray::number(d->peerPort);
QByteArray data = method;
- data += " ";
+ data += ' ';
data += path;
data += " HTTP/1.1\r\n";
data += "Proxy-Connection: keep-alive\r\n";
diff --git a/src/network/socket/qhttpsocketengine_p.h b/src/network/socket/qhttpsocketengine_p.h
index 4d90487679..41c63fe11e 100644
--- a/src/network/socket/qhttpsocketengine_p.h
+++ b/src/network/socket/qhttpsocketengine_p.h
@@ -105,10 +105,9 @@ public:
bool setMulticastInterface(const QNetworkInterface &iface) Q_DECL_OVERRIDE;
#endif // QT_NO_NETWORKINTERFACE
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader *,
+ PacketHeaderOptions) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qlocalserver.h b/src/network/socket/qlocalserver.h
index a03cdb726d..24908db4aa 100644
--- a/src/network/socket/qlocalserver.h
+++ b/src/network/socket/qlocalserver.h
@@ -64,7 +64,7 @@ public:
};
Q_DECLARE_FLAGS(SocketOptions, SocketOption)
- explicit QLocalServer(QObject *parent = 0);
+ explicit QLocalServer(QObject *parent = Q_NULLPTR);
~QLocalServer();
void close();
@@ -80,7 +80,7 @@ public:
static bool removeServer(const QString &name);
QAbstractSocket::SocketError serverError() const;
void setMaxPendingConnections(int numConnections);
- bool waitForNewConnection(int msec = 0, bool *timedOut = 0);
+ bool waitForNewConnection(int msec = 0, bool *timedOut = Q_NULLPTR);
void setSocketOptions(SocketOptions options);
SocketOptions socketOptions() const;
diff --git a/src/network/socket/qlocalserver_unix.cpp b/src/network/socket/qlocalserver_unix.cpp
index 634074d91f..a356e21214 100644
--- a/src/network/socket/qlocalserver_unix.cpp
+++ b/src/network/socket/qlocalserver_unix.cpp
@@ -209,7 +209,7 @@ bool QLocalServerPrivate::listen(qintptr socketDescriptor)
QString name = QString::fromLatin1(addr.sun_path);
if (!name.isEmpty()) {
fullServerName = name;
- serverName = fullServerName.mid(fullServerName.lastIndexOf(QLatin1String("/"))+1);
+ serverName = fullServerName.mid(fullServerName.lastIndexOf(QLatin1Char('/')) + 1);
if (serverName.isEmpty()) {
serverName = fullServerName;
}
diff --git a/src/network/socket/qlocalsocket.h b/src/network/socket/qlocalsocket.h
index a4d8405912..4b39a7c562 100644
--- a/src/network/socket/qlocalsocket.h
+++ b/src/network/socket/qlocalsocket.h
@@ -73,7 +73,7 @@ public:
ClosingState = QAbstractSocket::ClosingState
};
- QLocalSocket(QObject *parent = 0);
+ QLocalSocket(QObject *parent = Q_NULLPTR);
~QLocalSocket();
void connectToServer(OpenMode openMode = ReadWrite);
diff --git a/src/network/socket/qnativesocketengine.cpp b/src/network/socket/qnativesocketengine.cpp
index dfece60036..805acde860 100644
--- a/src/network/socket/qnativesocketengine.cpp
+++ b/src/network/socket/qnativesocketengine.cpp
@@ -88,6 +88,25 @@
errorString() can be called to determine the cause of the error.
*/
+/*!
+ \enum QAbstractSocketEngine::PacketHeaderOption
+
+ Specifies which fields in the IP packet header are desired in the call to
+ readDatagram().
+
+ \value WantNone caller isn't interested in the packet metadata
+ \value WantDatagramSender caller wants the sender address and port number
+ \value WantDatagramDestination caller wants the packet's destination address and port number
+ (this option is useful to distinguish multicast packets from unicast)
+ \value WantDatagramHopLimit caller wants the packet's remaining hop limit or time to live
+ (this option is useful in IPv4 multicasting, where the TTL is used
+ to indicate the realm)
+ \value WantAll this is a catch-all value to indicate the caller is
+ interested in all the available information
+
+ \sa readDatagram(), QUdpDatagram
+*/
+
#include "qnativesocketengine_p.h"
#include <qabstracteventdispatcher.h>
@@ -152,10 +171,6 @@ QT_BEGIN_NAMESPACE
/*! \internal
Constructs the private class and initializes all data members.
-
- On Windows, WSAStartup is called "recursively" for every
- concurrent QNativeSocketEngine. This is safe, because WSAStartup and
- WSACleanup are reference counted.
*/
QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
socketDescriptor(-1),
@@ -163,6 +178,9 @@ QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
writeNotifier(0),
exceptNotifier(0)
{
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+ QSysInfo::machineHostName(); // this initializes ws2_32.dll
+#endif
}
/*! \internal
@@ -401,13 +419,18 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
return false;
}
- // Set the broadcasting flag if it's a UDP socket.
- if (socketType == QAbstractSocket::UdpSocket
- && !setOption(BroadcastSocketOption, 1)) {
- d->setError(QAbstractSocket::UnsupportedSocketOperationError,
- QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
- close();
- return false;
+ if (socketType == QAbstractSocket::UdpSocket) {
+ // Set the broadcasting flag if it's a UDP socket.
+ if (!setOption(BroadcastSocketOption, 1)) {
+ d->setError(QAbstractSocket::UnsupportedSocketOperationError,
+ QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
+ close();
+ return false;
+ }
+
+ // Set some extra flags that are interesting to us, but accept failure
+ setOption(ReceivePacketInformation, 1);
+ setOption(ReceiveHopLimit, 1);
}
@@ -431,8 +454,6 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
// setReceiveBufferSize(49152);
// setSendBufferSize(49152);
- d->socketType = socketType;
- d->socketProtocol = protocol;
return true;
}
@@ -769,9 +790,8 @@ qint64 QNativeSocketEngine::pendingDatagramSize() const
/*!
Reads up to \a maxSize bytes of a datagram from the socket,
stores it in \a data and returns the number of bytes read. The
- address and port of the sender are stored in \a address and \a
- port. If either of these pointers is 0, the corresponding value is
- discarded.
+ address, port, and other IP header fields are stored in \a header
+ according to the request in \a options.
To avoid unnecessarily loss of data, call pendingDatagramSize() to
determine the size of the pending message before reading it. If \a
@@ -781,20 +801,23 @@ qint64 QNativeSocketEngine::pendingDatagramSize() const
\sa hasPendingDatagrams()
*/
-qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
- quint16 *port)
+qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QIpPacketHeader *header,
+ PacketHeaderOptions options)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::readDatagram(), -1);
Q_CHECK_TYPE(QNativeSocketEngine::readDatagram(), QAbstractSocket::UdpSocket, -1);
- return d->nativeReceiveDatagram(data, maxSize, address, port);
+ return d->nativeReceiveDatagram(data, maxSize, header, options);
}
/*!
Writes a UDP datagram of size \a size bytes to the socket from
- \a data to the address \a host on port \a port, and returns the
- number of bytes written, or -1 if an error occurred.
+ \a data to the destination contained in \a header, and returns the
+ number of bytes written, or -1 if an error occurred. If \a header
+ contains other settings like hop limit or source address, this function
+ will try to pass them to the operating system too, but will not
+ indicate an error if it could not pass them.
Only one datagram is sent, and if there is too much data to fit
into a single datagram, the operation will fail and error()
@@ -804,18 +827,19 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddres
disadvised, as even if they are sent successfully, they are likely
to be fragmented before arriving at their destination.
- Experience has shown that it is in general safe to send datagrams
- no larger than 512 bytes.
+ Experience has shown that it is in general safe to send IPv4 datagrams
+ no larger than 512 bytes or IPv6 datagrams no larger than 1280 (the
+ minimum MTU).
\sa readDatagram()
*/
-qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size,
- const QHostAddress &host, quint16 port)
+qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size, const QIpPacketHeader &header)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::writeDatagram(), -1);
Q_CHECK_TYPE(QNativeSocketEngine::writeDatagram(), QAbstractSocket::UdpSocket, -1);
- return d->nativeSendDatagram(data, size, d->adjustAddressProtocol(host), port);
+
+ return d->nativeSendDatagram(data, size, header);
}
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h
index e540b47069..10e34c485a 100644
--- a/src/network/socket/qnativesocketengine_p.h
+++ b/src/network/socket/qnativesocketengine_p.h
@@ -51,46 +51,51 @@
# include <netinet/in.h>
#else
# include <winsock2.h>
+# include <ws2tcpip.h>
+# include <mswsock.h>
#endif
QT_BEGIN_NAMESPACE
-// Use our own defines and structs which we know are correct
-# define QT_SS_MAXSIZE 128
-# define QT_SS_ALIGNSIZE (sizeof(qint64))
-# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short))
-# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE))
-struct qt_sockaddr_storage {
- short ss_family;
- char __ss_pad1[QT_SS_PAD1SIZE];
- qint64 __ss_align;
- char __ss_pad2[QT_SS_PAD2SIZE];
-};
-
#ifdef Q_OS_WIN
#define QT_SOCKLEN_T int
#define QT_SOCKOPTLEN_T int
-#endif
-// sockaddr_in6 size changed between old and new SDK
-// Only the new version is the correct one, so always
-// use this structure.
-struct qt_in6_addr {
- quint8 qt_s6_addr[16];
-};
-struct qt_sockaddr_in6 {
- short sin6_family; /* AF_INET6 */
- quint16 sin6_port; /* Transport level port number */
- quint32 sin6_flowinfo; /* IPv6 flow information */
- struct qt_in6_addr sin6_addr; /* IPv6 address */
- quint32 sin6_scope_id; /* set of interfaces for a scope */
-};
+// The following definitions are copied from the MinGW header mswsock.h which
+// was placed in the public domain. The WSASendMsg and WSARecvMsg functions
+// were introduced with Windows Vista, so some Win32 headers are lacking them.
+// There are no known versions of Windows CE or Embedded that contain them.
+#ifndef Q_OS_WINCE
+# ifndef WSAID_WSARECVMSG
+typedef INT (WINAPI *LPFN_WSARECVMSG)(SOCKET s, LPWSAMSG lpMsg,
+ LPDWORD lpdwNumberOfBytesRecvd,
+ LPWSAOVERLAPPED lpOverlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
+# define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
+# endif
+# ifndef WSAID_WSASENDMSG
+typedef struct {
+ LPWSAMSG lpMsg;
+ DWORD dwFlags;
+ LPDWORD lpNumberOfBytesSent;
+ LPWSAOVERLAPPED lpOverlapped;
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine;
+} WSASENDMSG, *LPWSASENDMSG;
+
+typedef INT (WSAAPI *LPFN_WSASENDMSG)(SOCKET s, LPWSAMSG lpMsg, DWORD dwFlags,
+ LPDWORD lpNumberOfBytesSent,
+ LPWSAOVERLAPPED lpOverlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
+
+# define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
+# endif
+#endif
+#endif
union qt_sockaddr {
sockaddr a;
sockaddr_in a4;
- qt_sockaddr_in6 a6;
- qt_sockaddr_storage storage;
+ sockaddr_in6 a6;
};
class QNativeSocketEnginePrivate;
@@ -134,10 +139,9 @@ public:
bool setMulticastInterface(const QNetworkInterface &iface) Q_DECL_OVERRIDE;
#endif
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader * = 0,
+ PacketHeaderOptions = WantNone) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
#endif // QT_NO_UDPSOCKET
@@ -175,16 +179,6 @@ private:
Q_DISABLE_COPY(QNativeSocketEngine)
};
-#ifdef Q_OS_WIN
-class QWindowsSockInit
-{
-public:
- QWindowsSockInit();
- ~QWindowsSockInit();
- int version;
-};
-#endif
-
class QSocketNotifier;
class QNativeSocketEnginePrivate : public QAbstractSocketEnginePrivate
@@ -198,10 +192,10 @@ public:
QSocketNotifier *readNotifier, *writeNotifier, *exceptNotifier;
-#ifdef Q_OS_WIN
- QWindowsSockInit winSock;
-#endif
-
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+ LPFN_WSASENDMSG sendmsg;
+ LPFN_WSARECVMSG recvmsg;
+# endif
enum ErrorString {
NonBlockingInitFailedErrorString,
BroadcastingInitFailedErrorString,
@@ -260,24 +254,48 @@ public:
bool nativeHasPendingDatagrams() const;
qint64 nativePendingDatagramSize() const;
- qint64 nativeReceiveDatagram(char *data, qint64 maxLength,
- QHostAddress *address, quint16 *port);
- qint64 nativeSendDatagram(const char *data, qint64 length,
- const QHostAddress &host, quint16 port);
+ qint64 nativeReceiveDatagram(char *data, qint64 maxLength, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options);
+ qint64 nativeSendDatagram(const char *data, qint64 length, const QIpPacketHeader &header);
qint64 nativeRead(char *data, qint64 maxLength);
qint64 nativeWrite(const char *data, qint64 length);
int nativeSelect(int timeout, bool selectForRead) const;
int nativeSelect(int timeout, bool checkRead, bool checkWrite,
bool *selectForRead, bool *selectForWrite) const;
-#ifdef Q_OS_WIN
- void setPortAndAddress(sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
- quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize);
-#endif
void nativeClose();
bool checkProxy(const QHostAddress &address);
bool fetchConnectionParameters();
+
+ static uint scopeIdFromString(const QString &scopeid);
+
+ /*! \internal
+ Sets \a address and \a port in the \a aa sockaddr structure and the size in \a sockAddrSize.
+ The address \a is converted to IPv6 if the current socket protocol is also IPv6.
+ */
+ void setPortAndAddress(quint16 port, const QHostAddress &address, qt_sockaddr *aa, QT_SOCKLEN_T *sockAddrSize)
+ {
+ if (address.protocol() == QAbstractSocket::IPv6Protocol
+ || address.protocol() == QAbstractSocket::AnyIPProtocol
+ || socketProtocol == QAbstractSocket::IPv6Protocol
+ || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ memset(&aa->a6, 0, sizeof(sockaddr_in6));
+ aa->a6.sin6_family = AF_INET6;
+ aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());
+ aa->a6.sin6_port = htons(port);
+ Q_IPV6ADDR tmp = address.toIPv6Address();
+ memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));
+ *sockAddrSize = sizeof(sockaddr_in6);
+ } else {
+ memset(&aa->a, 0, sizeof(sockaddr_in));
+ aa->a4.sin_family = AF_INET;
+ aa->a4.sin_port = htons(port);
+ aa->a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ *sockAddrSize = sizeof(sockaddr_in);
+ }
+ }
+
};
QT_END_NAMESPACE
diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp
index 8869d75c8b..6a740f4c30 100644
--- a/src/network/socket/qnativesocketengine_unix.cpp
+++ b/src/network/socket/qnativesocketengine_unix.cpp
@@ -49,6 +49,9 @@
#ifdef QT_LINUXBASE
#include <arpa/inet.h>
#endif
+#ifdef Q_OS_BSD4
+#include <net/if_dl.h>
+#endif
#if defined QNATIVESOCKETENGINE_DEBUG
#include <qstring.h>
@@ -128,9 +131,9 @@ static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *po
}
}
-static inline uint makeScopeId(const QHostAddress &addr)
+// inline on purpose
+inline uint QNativeSocketEnginePrivate::scopeIdFromString(const QString &scopeid)
{
- QString scopeid = addr.scopeId();
if (scopeid.isEmpty())
return 0;
@@ -202,6 +205,32 @@ static void convertToLevelAndOption(QNativeSocketEngine::SocketOption opt,
n = IP_TOS;
}
break;
+ case QNativeSocketEngine::ReceivePacketInformation:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_RECVPKTINFO;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+#ifdef IP_PKTINFO
+ n = IP_PKTINFO;
+#elif defined(IP_RECVDSTADDR)
+ // variant found in QNX and FreeBSD; it will get us only the
+ // destination address, not the interface; we need IP_RECVIF for that.
+ n = IP_RECVDSTADDR;
+#endif
+ }
+ break;
+ case QNativeSocketEngine::ReceiveHopLimit:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_RECVHOPLIMIT;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+#ifdef IP_RECVTTL // IP_RECVTTL is a non-standard extension supported on some OS
+ level = IPPROTO_IP;
+ n = IP_RECVTTL;
+#endif
+ }
+ break;
}
}
@@ -259,6 +288,10 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
#endif
socketDescriptor = socket;
+ if (socket != -1) {
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
+ }
return true;
}
@@ -281,7 +314,7 @@ int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) co
QT_SOCKOPTLEN_T len = sizeof(v);
convertToLevelAndOption(opt, socketProtocol, level, n);
- if (::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
+ if (n != -1 && ::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
return v;
return -1;
@@ -356,37 +389,11 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
qDebug() << "QNativeSocketEnginePrivate::nativeConnect() " << socketDescriptor;
#endif
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- struct sockaddr_in6 sockAddrIPv6;
-
- if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(addr);
-
- Q_IPV6ADDR ip6 = addr.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6));
-
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
- } else
- if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(addr.toIPv4Address());
-
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- } else {
- // unreachable
- }
+ qt_sockaddr aa;
+ QT_SOCKLEN_T sockAddrSize;
+ setPortAndAddress(port, addr, &aa, &sockAddrSize);
- int connectResult = qt_safe_connect(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int connectResult = qt_safe_connect(socketDescriptor, &aa.a, sockAddrSize);
#if defined (QNATIVESOCKETENGINE_DEBUG)
int ecopy = errno;
#endif
@@ -458,51 +465,28 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16 port)
{
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
-
- struct sockaddr_in6 sockAddrIPv6;
+ qt_sockaddr aa;
+ QT_SOCKLEN_T sockAddrSize;
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
- if (address.protocol() == QAbstractSocket::IPv6Protocol || address.protocol() == QAbstractSocket::AnyIPProtocol) {
#ifdef IPV6_V6ONLY
+ if (aa.a.sa_family == AF_INET6) {
int ipv6only = 0;
if (address.protocol() == QAbstractSocket::IPv6Protocol)
ipv6only = 1;
//default value of this socket option varies depending on unix variant (or system configuration on BSD), so always set it explicitly
::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
+ }
#endif
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(address);
-
- Q_IPV6ADDR tmp = address.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
- } else
- if (address.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- } else {
- // unreachable
- }
- int bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);
if (bindResult < 0 && errno == EAFNOSUPPORT && address.protocol() == QAbstractSocket::AnyIPProtocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
- bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
+ // retry with v4
+ aa.a4.sin_family = AF_INET;
+ aa.a4.sin_port = htons(port);
+ aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ sockAddrSize = sizeof(aa.a4);
+ bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);
}
if (bindResult < 0) {
@@ -840,68 +824,189 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
return qint64(recvResult);
}
-qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize,
- QHostAddress *address, quint16 *port)
+qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options)
{
+ // we use quintptr to force the alignment
+ quintptr cbuf[(CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(int))
+#if !defined(IP_PKTINFO) && defined(IP_RECVIF) && defined(Q_OS_BSD4)
+ + CMSG_SPACE(sizeof(sockaddr_dl))
+#endif
+ + sizeof(quintptr) - 1) / sizeof(quintptr)];
+
+ struct msghdr msg;
+ struct iovec vec;
qt_sockaddr aa;
+ char c;
+ memset(&msg, 0, sizeof(msg));
memset(&aa, 0, sizeof(aa));
- QT_SOCKLEN_T sz;
- sz = sizeof(aa);
- ssize_t recvFromResult = 0;
+ // we need to receive at least one byte, even if our user isn't interested in it
+ vec.iov_base = maxSize ? data : &c;
+ vec.iov_len = maxSize ? maxSize : 1;
+ msg.msg_iov = &vec;
+ msg.msg_iovlen = 1;
+ if (options & QAbstractSocketEngine::WantDatagramSender) {
+ msg.msg_name = &aa;
+ msg.msg_namelen = sizeof(aa);
+ }
+ if (options & (QAbstractSocketEngine::WantDatagramHopLimit | QAbstractSocketEngine::WantDatagramDestination)) {
+ msg.msg_control = cbuf;
+ msg.msg_controllen = sizeof(cbuf);
+ }
+
+ ssize_t recvResult = 0;
do {
- char c;
- recvFromResult = ::recvfrom(socketDescriptor, maxSize ? data : &c, maxSize ? maxSize : 1,
- 0, &aa.a, &sz);
- } while (recvFromResult == -1 && errno == EINTR);
+ recvResult = ::recvmsg(socketDescriptor, &msg, 0);
+ } while (recvResult == -1 && errno == EINTR);
- if (recvFromResult == -1) {
+ if (recvResult == -1) {
setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
- } else if (port || address) {
- qt_socket_getPortAndAddress(&aa, port, address);
+ if (header)
+ header->clear();
+ } else if (options != QAbstractSocketEngine::WantNone) {
+ Q_ASSERT(header);
+ qt_socket_getPortAndAddress(&aa, &header->senderPort, &header->senderAddress);
+ header->destinationPort = localPort;
+
+ // parse the ancillary data
+ struct cmsghdr *cmsgptr;
+ for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
+ cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) {
+ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in6_pktinfo))) {
+ in6_pktinfo *info = reinterpret_cast<in6_pktinfo *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(reinterpret_cast<quint8 *>(&info->ipi6_addr));
+ header->ifindex = info->ipi6_ifindex;
+ if (header->ifindex)
+ header->destinationAddress.setScopeId(QString::number(info->ipi6_ifindex));
+ }
+
+#ifdef IP_PKTINFO
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_PKTINFO
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in_pktinfo))) {
+ in_pktinfo *info = reinterpret_cast<in_pktinfo *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(ntohl(info->ipi_addr.s_addr));
+ header->ifindex = info->ipi_ifindex;
+ }
+#else
+# ifdef IP_RECVDSTADDR
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_RECVDSTADDR
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(in_addr))) {
+ in_addr *addr = reinterpret_cast<in_addr *>(CMSG_DATA(cmsgptr));
+
+ header->destinationAddress.setAddress(ntohl(addr->s_addr));
+ }
+# endif
+# if defined(IP_RECVIF) && defined(Q_OS_BSD4)
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_RECVIF
+ && cmsgptr->cmsg_len >= CMSG_LEN(sizeof(sockaddr_dl))) {
+ sockaddr_dl *sdl = reinterpret_cast<sockaddr_dl *>(CMSG_DATA(cmsgptr));
+
+ header->ifindex = LLINDEX(sdl);
+ }
+# endif
+#endif
+
+ if (cmsgptr->cmsg_len == CMSG_LEN(sizeof(int))
+ && ((cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT)
+ || (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_TTL))) {
+ header->hopLimit = *reinterpret_cast<int *>(CMSG_DATA(cmsgptr));
+ }
+ }
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
- data, qt_prettyDebug(data, qMin(recvFromResult, ssize_t(16)), recvFromResult).data(), maxSize,
- address ? address->toString().toLatin1().constData() : "(nil)",
- port ? *port : 0, (qint64) recvFromResult);
+ data, qt_prettyDebug(data, qMin(recvResult, ssize_t(16)), recvResult).data(), maxSize,
+ (recvResult != -1 && options != QAbstractSocketEngine::WantNone)
+ ? header->senderAddress.toString().toLatin1().constData() : "(unknown)",
+ (recvResult != -1 && options != QAbstractSocketEngine::WantNone)
+ ? header->senderPort : 0, (qint64) recvResult);
#endif
- return qint64(maxSize ? recvFromResult : recvFromResult == -1 ? -1 : 0);
+ return qint64(maxSize ? recvResult : recvResult == -1 ? -1 : 0);
}
-qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
- const QHostAddress &host, quint16 port)
+qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
- struct sockaddr_in sockAddrIPv4;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- struct sockaddr_in6 sockAddrIPv6;
- if (host.protocol() == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::AnyIPProtocol) {
- memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
- sockAddrIPv6.sin6_family = AF_INET6;
- sockAddrIPv6.sin6_port = htons(port);
- sockAddrIPv6.sin6_scope_id = makeScopeId(host);
-
- Q_IPV6ADDR tmp = host.toIPv6Address();
- memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
- sockAddrSize = sizeof(sockAddrIPv6);
- sockAddrPtr = (struct sockaddr *)&sockAddrIPv6;
- } else if (host.protocol() == QAbstractSocket::IPv4Protocol) {
- memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
- sockAddrIPv4.sin_family = AF_INET;
- sockAddrIPv4.sin_port = htons(port);
- sockAddrIPv4.sin_addr.s_addr = htonl(host.toIPv4Address());
- sockAddrSize = sizeof(sockAddrIPv4);
- sockAddrPtr = (struct sockaddr *)&sockAddrIPv4;
+ // we use quintptr to force the alignment
+ quintptr cbuf[(CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(int)) + sizeof(quintptr) - 1) / sizeof(quintptr)];
+
+ struct cmsghdr *cmsgptr = reinterpret_cast<struct cmsghdr *>(cbuf);
+ struct msghdr msg;
+ struct iovec vec;
+ qt_sockaddr aa;
+
+ memset(&msg, 0, sizeof(msg));
+ memset(&aa, 0, sizeof(aa));
+ vec.iov_base = const_cast<char *>(data);
+ vec.iov_len = len;
+ msg.msg_iov = &vec;
+ msg.msg_iovlen = 1;
+ msg.msg_name = &aa.a;
+ msg.msg_control = &cbuf;
+
+ setPortAndAddress(header.destinationPort, header.destinationAddress, &aa, &msg.msg_namelen);
+
+ if (msg.msg_namelen == sizeof(aa.a6)) {
+ if (header.hopLimit != -1) {
+ msg.msg_controllen += CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_HOPLIMIT;
+ memcpy(CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in6_pktinfo *data = reinterpret_cast<in6_pktinfo *>(CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.msg_controllen += CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_PKTINFO;
+ data->ipi6_ifindex = header.ifindex;
+
+ QIPv6Address tmp = header.senderAddress.toIPv6Address();
+ memcpy(&data->ipi6_addr, &tmp, sizeof(tmp));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(*data)));
+ }
+ } else {
+ if (header.hopLimit != -1) {
+ msg.msg_controllen += CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_TTL;
+ memcpy(CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(int)));
+ }
+
+#if defined(IP_PKTINFO) || defined(IP_SENDSRCADDR)
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+# ifdef IP_PKTINFO
+ struct in_pktinfo *data = reinterpret_cast<in_pktinfo *>(CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ cmsgptr->cmsg_type = IP_PKTINFO;
+ data->ipi_ifindex = header.ifindex;
+ data->ipi_addr.s_addr = htonl(header.senderAddress.toIPv4Address());
+# elif defined(IP_SENDSRCADDR)
+ struct in_addr *data = reinterpret_cast<in_addr *>(CMSG_DATA(cmsgptr));
+ cmsgptr->cmsg_type = IP_SENDSRCADDR;
+ data->s_addr = htonl(header.senderAddress.toIPv4Address());
+# endif
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ msg.msg_controllen += CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = CMSG_LEN(sizeof(*data));
+ cmsgptr = reinterpret_cast<cmsghdr *>(reinterpret_cast<char *>(cmsgptr) + CMSG_SPACE(sizeof(*data)));
+ }
+#endif
}
- ssize_t sentBytes = qt_safe_sendto(socketDescriptor, data, len,
- 0, sockAddrPtr, sockAddrSize);
+ if (msg.msg_controllen == 0)
+ msg.msg_control = 0;
+ ssize_t sentBytes = qt_safe_sendmsg(socketDescriptor, &msg, 0);
if (sentBytes < 0) {
switch (errno) {
@@ -915,8 +1020,9 @@ qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 l
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEngine::sendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli", data,
- qt_prettyDebug(data, qMin<int>(len, 16), len).data(), len, host.toString().toLatin1().constData(),
- port, (qint64) sentBytes);
+ qt_prettyDebug(data, qMin<int>(len, 16), len).data(), len,
+ header.destinationAddress.toString().toLatin1().constData(),
+ header.destinationPort, (qint64) sentBytes);
#endif
return qint64(sentBytes);
diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp
index d673d3a15e..ca0a8b95d5 100644
--- a/src/network/socket/qnativesocketengine_win.cpp
+++ b/src/network/socket/qnativesocketengine_win.cpp
@@ -59,6 +59,9 @@ QT_BEGIN_NAMESPACE
#ifndef IPV6_V6ONLY
#define IPV6_V6ONLY 27
#endif
+#ifndef IP_HOPLIMIT
+#define IP_HOPLIMIT 21 // Receive packet hop limit.
+#endif
#if defined(QNATIVESOCKETENGINE_DEBUG)
@@ -168,10 +171,10 @@ static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
static inline void qt_socket_getPortAndAddress(SOCKET socketDescriptor, const qt_sockaddr *sa, quint16 *port, QHostAddress *address)
{
if (sa->a.sa_family == AF_INET6) {
- const qt_sockaddr_in6 *sa6 = &sa->a6;
+ const sockaddr_in6 *sa6 = &sa->a6;
Q_IPV6ADDR tmp;
for (int i = 0; i < 16; ++i)
- tmp.c[i] = sa6->sin6_addr.qt_s6_addr[i];
+ tmp.c[i] = sa6->sin6_addr.s6_addr[i];
if (address) {
QHostAddress a;
a.setAddress(tmp);
@@ -252,40 +255,24 @@ static void convertToLevelAndOption(QNativeSocketEngine::SocketOption opt,
n = IP_MULTICAST_LOOP;
}
break;
- }
-}
-
-/*! \internal
-
- Sets the port and address to a sockaddr. Requires that sa point to the IPv6 struct if the address is IPv6.
-*/
-void QNativeSocketEnginePrivate::setPortAndAddress(sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
- quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize)
-{
- if (address.protocol() == QAbstractSocket::IPv6Protocol
- || address.protocol() == QAbstractSocket::AnyIPProtocol
- || socketProtocol == QAbstractSocket::IPv6Protocol
- || socketProtocol == QAbstractSocket::AnyIPProtocol) {
- memset(sockAddrIPv6, 0, sizeof(qt_sockaddr_in6));
- sockAddrIPv6->sin6_family = AF_INET6;
- sockAddrIPv6->sin6_scope_id = address.scopeId().toUInt();
- WSAHtons(socketDescriptor, port, &(sockAddrIPv6->sin6_port));
- Q_IPV6ADDR tmp = address.toIPv6Address();
- memcpy(&(sockAddrIPv6->sin6_addr.qt_s6_addr), &tmp, sizeof(tmp));
- *sockAddrSize = sizeof(qt_sockaddr_in6);
- *sockAddrPtr = (struct sockaddr *) sockAddrIPv6;
- } else
-
- if (address.protocol() == QAbstractSocket::IPv4Protocol
- || address.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
- memset(sockAddrIPv4, 0, sizeof(sockaddr_in));
- sockAddrIPv4->sin_family = AF_INET;
- WSAHtons(socketDescriptor, port, &(sockAddrIPv4->sin_port));
- WSAHtonl(socketDescriptor, address.toIPv4Address(), &(sockAddrIPv4->sin_addr.s_addr));
- *sockAddrSize = sizeof(sockaddr_in);
- *sockAddrPtr = (struct sockaddr *) sockAddrIPv4;
- } else {
- // unreachable
+ case QNativeSocketEngine::ReceivePacketInformation:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_PKTINFO;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+ n = IP_PKTINFO;
+ }
+ break;
+ case QNativeSocketEngine::ReceiveHopLimit:
+ if (socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) {
+ level = IPPROTO_IPV6;
+ n = IPV6_HOPLIMIT;
+ } else if (socketProtocol == QAbstractSocket::IPv4Protocol) {
+ level = IPPROTO_IP;
+ n = IP_HOPLIMIT;
+ }
+ break;
}
}
@@ -320,25 +307,6 @@ static inline int qt_socket_getMaxMsgSize(qintptr socketDescriptor)
return value;
}
-QWindowsSockInit::QWindowsSockInit()
-: version(0)
-{
- //### should we try for 2.2 on all platforms ??
- WSAData wsadata;
-
- // IPv6 requires Winsock v2.0 or better.
- if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
- qWarning("QTcpSocketAPI: WinSock v2.0 initialization failed.");
- } else {
- version = 0x20;
- }
-}
-
-QWindowsSockInit::~QWindowsSockInit()
-{
- WSACleanup();
-}
-
// MS Transport Provider IOCTL to control
// reporting PORT_UNREACHABLE messages
// on UDP sockets via recv/WSARecv/etc.
@@ -354,6 +322,12 @@ QWindowsSockInit::~QWindowsSockInit()
# define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
#endif
+// inline on purpose
+inline uint QNativeSocketEnginePrivate::scopeIdFromString(const QString &scopeid)
+{
+ return scopeid.toUInt();
+}
+
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
@@ -439,9 +413,27 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
WS_ERROR_DEBUG(err);
}
}
+
+ // get the pointer to sendmsg and recvmsg
+ DWORD bytesReturned;
+ GUID recvmsgguid = WSAID_WSARECVMSG;
+ if (WSAIoctl(socketDescriptor, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &recvmsgguid, sizeof(recvmsgguid),
+ &recvmsg, sizeof(recvmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
+ recvmsg = 0;
+
+ GUID sendmsgguid = WSAID_WSASENDMSG;
+ if (WSAIoctl(socketDescriptor, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &sendmsgguid, sizeof(sendmsgguid),
+ &sendmsg, sizeof(sendmsg), &bytesReturned, NULL, NULL) == SOCKET_ERROR)
+ sendmsg = 0;
#endif
socketDescriptor = socket;
+ if (socket != INVALID_SOCKET) {
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
+ }
// Make the socket nonblocking.
if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
@@ -626,12 +618,10 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
#endif
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
+ qt_sockaddr aa;
QT_SOCKLEN_T sockAddrSize = 0;
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
if ((socketProtocol == QAbstractSocket::IPv6Protocol || socketProtocol == QAbstractSocket::AnyIPProtocol) && address.toIPv4Address()) {
//IPV6_V6ONLY option must be cleared to connect to a V4 mapped address
@@ -642,7 +632,7 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
}
forever {
- int connectResult = ::WSAConnect(socketDescriptor, sockAddrPtr, sockAddrSize, 0,0,0,0);
+ int connectResult = ::WSAConnect(socketDescriptor, &aa.a, sockAddrSize, 0,0,0,0);
if (connectResult == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
@@ -765,46 +755,36 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &a, quint16 port)
{
QHostAddress address = a;
- DWORD ipv6only = 0;
- switch (address.protocol()) {
- case QAbstractSocket::IPv6Protocol:
- if (address.toIPv6Address()[0] == 0xff) {
- // binding to a multicast address
- address = QHostAddress(QHostAddress::AnyIPv6);
- }
- //This is default in current windows versions, it may change in future so set it explicitly
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_6_0) {
- ipv6only = 1;
- ipv6only = ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
- }
- break;
- case QAbstractSocket::IPv4Protocol:
+ if (address.protocol() == QAbstractSocket::IPv4Protocol) {
if ((address.toIPv4Address() & 0xffff0000) == 0xefff0000) {
// binding to a multicast address
address = QHostAddress(QHostAddress::AnyIPv4);
}
- break;
- case QAbstractSocket::AnyIPProtocol:
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_6_0) {
- ipv6only = ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
- } else {
- address = QHostAddress(QHostAddress::AnyIPv4); //xp/WS2003 and earlier don't support dual stack, so bind to IPv4
- socketProtocol = QAbstractSocket::IPv4Protocol;
- }
- break;
- default:
- break;
}
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
+ qt_sockaddr aa;
QT_SOCKLEN_T sockAddrSize = 0;
+ setPortAndAddress(port, address, &aa, &sockAddrSize);
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
+ if (aa.a.sa_family == AF_INET6) {
+ // The default may change in future, so set it explicitly
+ int ipv6only = 0;
+ if (address.protocol() == QAbstractSocket::IPv6Protocol)
+ ipv6only = 1;
+ ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
+ }
- int bindResult = ::bind(socketDescriptor, sockAddrPtr, sockAddrSize);
+ int bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
+ if (bindResult == SOCKET_ERROR && WSAGetLastError() == WSAEAFNOSUPPORT
+ && address.protocol() == QAbstractSocket::AnyIPProtocol) {
+ // retry with v4
+ aa.a4.sin_family = AF_INET;
+ aa.a4.sin_port = htons(port);
+ aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());
+ sockAddrSize = sizeof(aa.a4);
+ bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);
+ }
if (bindResult == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
@@ -1216,33 +1196,47 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
return ret;
}
+#ifdef Q_OS_WINCE
+// Windows CE has no support for sendmsg or recvmsg. We set it to null here to simplify the code below.
+static int (*const recvmsg)(...) = 0;
+static int (*const sendmsg)(...) = 0;
+#endif
-qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength,
- QHostAddress *address, quint16 *port)
+qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength, QIpPacketHeader *header,
+ QAbstractSocketEngine::PacketHeaderOptions options)
{
- qint64 ret = 0;
-
+ union {
+ char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
+ WSACMSGHDR align; // only to ensure alignment
+ };
+ WSAMSG msg;
+ WSABUF buf;
qt_sockaddr aa;
+ char c;
+ memset(&msg, 0, sizeof(msg));
memset(&aa, 0, sizeof(aa));
- QT_SOCKLEN_T sz;
- sz = sizeof(aa);
- WSABUF buf;
- buf.buf = data;
- buf.len = maxLength;
-#if !defined(Q_OS_WINCE)
- buf.buf = data;
- buf.len = maxLength;
-#else
- char tmpChar;
- buf.buf = data ? data : &tmpChar;
- buf.len = maxLength;
-#endif
+ // we need to receive at least one byte, even if our user isn't interested in it
+ buf.buf = maxLength ? data : &c;
+ buf.len = maxLength ? maxLength : 1;
+ msg.lpBuffers = &buf;
+ msg.dwBufferCount = 1;
+ msg.name = reinterpret_cast<LPSOCKADDR>(&aa);
+ msg.namelen = sizeof(aa);
+ if (options & (QAbstractSocketEngine::WantDatagramHopLimit | QAbstractSocketEngine::WantDatagramDestination)) {
+ msg.Control.buf = cbuf;
+ msg.Control.len = sizeof(cbuf);
+ }
DWORD flags = 0;
DWORD bytesRead = 0;
- int wsaRet = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, &aa.a, &sz,0,0);
- if (wsaRet == SOCKET_ERROR) {
+ qint64 ret;
+
+ if (recvmsg)
+ ret = recvmsg(socketDescriptor, &msg, &bytesRead, 0,0);
+ else
+ ret = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, msg.name, &msg.namelen,0,0);
+ if (ret == SOCKET_ERROR) {
int err = WSAGetLastError();
if (err == WSAEMSGSIZE) {
// it is ok the buffer was to small if bytesRead is larger than
@@ -1262,12 +1256,44 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
break;
}
ret = -1;
+ if (header)
+ header->clear();
}
} else {
ret = qint64(bytesRead);
+ if (options & QNativeSocketEngine::WantDatagramSender)
+ qt_socket_getPortAndAddress(socketDescriptor, &aa, &header->senderPort, &header->senderAddress);
}
- qt_socket_getPortAndAddress(socketDescriptor, &aa, port, address);
+ if (ret != -1 && recvmsg) {
+ // get the ancillary data
+ WSACMSGHDR *cmsgptr;
+ for (cmsgptr = WSA_CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
+ cmsgptr = WSA_CMSG_NXTHDR(&msg, cmsgptr)) {
+ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO
+ && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in6_pktinfo))) {
+ in6_pktinfo *info = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ QHostAddress target(reinterpret_cast<quint8 *>(&info->ipi6_addr));
+ if (info->ipi6_ifindex)
+ target.setScopeId(QString::number(info->ipi6_ifindex));
+ }
+ if (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_PKTINFO
+ && cmsgptr->cmsg_len >= WSA_CMSG_LEN(sizeof(in_pktinfo))) {
+ in_pktinfo *info = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ u_long addr;
+ WSANtohl(socketDescriptor, info->ipi_addr.s_addr, &addr);
+ QHostAddress target(addr);
+ if (info->ipi_ifindex)
+ target.setScopeId(QString::number(info->ipi_ifindex));
+ }
+
+ if (cmsgptr->cmsg_len == WSA_CMSG_LEN(sizeof(int))
+ && ((cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT)
+ || (cmsgptr->cmsg_level == IPPROTO_IP && cmsgptr->cmsg_type == IP_TTL))) {
+ header->hopLimit = *reinterpret_cast<int *>(WSA_CMSG_DATA(cmsgptr));
+ }
+ }
+ }
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %li, %s, %i) == %li",
@@ -1281,27 +1307,94 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
- const QHostAddress &address, quint16 port)
+ const QIpPacketHeader &header)
{
- qint64 ret = -1;
- struct sockaddr_in sockAddrIPv4;
- qt_sockaddr_in6 sockAddrIPv6;
- struct sockaddr *sockAddrPtr = 0;
- QT_SOCKLEN_T sockAddrSize = 0;
-
- setPortAndAddress(&sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
-
+ union {
+ char cbuf[WSA_CMSG_SPACE(sizeof(struct in6_pktinfo)) + WSA_CMSG_SPACE(sizeof(int))];
+ WSACMSGHDR align; // ensures alignment
+ };
+ WSACMSGHDR *cmsgptr = &align;
+ WSAMSG msg;
WSABUF buf;
+ qt_sockaddr aa;
+
+ memset(&msg, 0, sizeof(msg));
+ memset(&aa, 0, sizeof(aa));
#if !defined(Q_OS_WINCE)
buf.buf = len ? (char*)data : 0;
#else
char tmp;
buf.buf = len ? (char*)data : &tmp;
#endif
+ msg.lpBuffers = &buf;
+ msg.dwBufferCount = 1;
+ msg.name = &aa.a;
buf.len = len;
+
+ setPortAndAddress(header.destinationPort, header.destinationAddress, &aa, &msg.namelen);
+
+ if (msg.namelen == sizeof(aa.a6)) {
+ // sending IPv6
+ if (header.hopLimit != -1) {
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_HOPLIMIT;
+ memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in6_pktinfo *data = reinterpret_cast<in6_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IPV6;
+ cmsgptr->cmsg_type = IPV6_PKTINFO;
+ data->ipi6_ifindex = header.ifindex;
+
+ Q_IPV6ADDR tmp = header.senderAddress.toIPv6Address();
+ memcpy(&data->ipi6_addr, &tmp, sizeof(tmp));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(*data)));
+ }
+ } else {
+ // sending IPv4
+ if (header.hopLimit != -1) {
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(int));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(int));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_TTL;
+ memcpy(WSA_CMSG_DATA(cmsgptr), &header.hopLimit, sizeof(int));
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(int)));
+ }
+ if (header.ifindex != 0 || !header.senderAddress.isNull()) {
+ struct in_pktinfo *data = reinterpret_cast<in_pktinfo *>(WSA_CMSG_DATA(cmsgptr));
+ memset(data, 0, sizeof(*data));
+ msg.Control.len += WSA_CMSG_SPACE(sizeof(*data));
+ cmsgptr->cmsg_len = WSA_CMSG_LEN(sizeof(*data));
+ cmsgptr->cmsg_level = IPPROTO_IP;
+ cmsgptr->cmsg_type = IP_PKTINFO;
+ data->ipi_ifindex = header.ifindex;
+ WSAHtonl(socketDescriptor, header.senderAddress.toIPv4Address(), &data->ipi_addr.s_addr);
+ cmsgptr = reinterpret_cast<WSACMSGHDR *>(reinterpret_cast<char *>(cmsgptr)
+ + WSA_CMSG_SPACE(sizeof(*data)));
+ }
+ }
+
+ if (msg.Control.len != 0)
+ msg.Control.buf = cbuf;
+
DWORD flags = 0;
DWORD bytesSent = 0;
- if (::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, sockAddrPtr, sockAddrSize, 0,0) == SOCKET_ERROR) {
+ qint64 ret = -1;
+ if (sendmsg) {
+ ret = sendmsg(socketDescriptor, &msg, flags, &bytesSent, 0,0);
+ } else {
+ ret = ::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, msg.name, msg.namelen, 0,0);
+ }
+ if (ret == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
switch (err) {
diff --git a/src/network/socket/qnativesocketengine_winrt.cpp b/src/network/socket/qnativesocketengine_winrt.cpp
index 378a539411..1c68b28784 100644
--- a/src/network/socket/qnativesocketengine_winrt.cpp
+++ b/src/network/socket/qnativesocketengine_winrt.cpp
@@ -47,11 +47,13 @@
#include <private/qthread_p.h>
#include <private/qabstractsocket_p.h>
+#include <private/qeventdispatcher_winrt_p.h>
#ifndef QT_NO_SSL
#include <QSslSocket>
#endif
+#include <functional>
#include <wrl.h>
#include <windows.foundation.collections.h>
#include <windows.storage.streams.h>
@@ -76,6 +78,21 @@ typedef IAsyncOperationWithProgress<IBuffer *, UINT32> IAsyncBufferOperation;
QT_BEGIN_NAMESPACE
+static QByteArray socketDescription(const QAbstractSocketEngine *s)
+{
+ QByteArray result;
+ if (const QObject *o = s->parent()) {
+ const QString name = o->objectName();
+ if (!name.isEmpty()) {
+ result += '"';
+ result += name.toLocal8Bit();
+ result += "\"/";
+ }
+ result += o->metaObject()->className();
+ }
+ return result;
+}
+
// Common constructs
#define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \
if (!isValid()) { \
@@ -150,16 +167,10 @@ static AsyncStatus opStatus(const ComPtr<T> &op)
{
ComPtr<IAsyncInfo> info;
HRESULT hr = op.As(&info);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to cast op to IAsyncInfo.");
- return Error;
- }
+ Q_ASSERT_SUCCEEDED(hr);
AsyncStatus status;
hr = info->get_Status(&status);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to get AsyncStatus.");
- return Error;
- }
+ Q_ASSERT_SUCCEEDED(hr);
return status;
}
@@ -265,25 +276,27 @@ bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
Q_D(QNativeSocketEngine);
HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(name.utf16()));
ComPtr<IHostNameFactory> hostNameFactory;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
- &hostNameFactory);
+ HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
+ &hostNameFactory);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IHostName> remoteHost;
- if (FAILED(hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost))) {
- qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not create hostname");
- return false;
- }
+ hr = hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost);
+ RETURN_FALSE_IF_FAILED("QNativeSocketEngine::connectToHostByName: Could not create hostname.");
const QString portString = QString::number(port);
HStringReference portReference(reinterpret_cast<LPCWSTR>(portString.utf16()));
- HRESULT hr = E_FAIL;
if (d->socketType == QAbstractSocket::TcpSocket)
hr = d->tcpSocket()->ConnectAsync(remoteHost.Get(), portReference.Get(), &d->connectOp);
else if (d->socketType == QAbstractSocket::UdpSocket)
hr = d->udpSocket()->ConnectAsync(remoteHost.Get(), portReference.Get(), &d->connectOp);
- if (FAILED(hr)) {
- qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not obtain connect action");
+ if (hr == E_ACCESSDENIED) {
+ qErrnoWarning(hr, "QNativeSocketEngine::connectToHostByName: Unable to connect to host (%s:%hu/%s). "
+ "Please check your manifest capabilities.",
+ qPrintable(name), port, socketDescription(this).constData());
return false;
}
+ Q_ASSERT_SUCCEEDED(hr);
+
d->socketState = QAbstractSocket::ConnectingState;
hr = d->connectOp->put_Completed(Callback<IAsyncActionCompletedHandler>(
d, &QNativeSocketEnginePrivate::handleConnectToHost).Get());
@@ -295,68 +308,55 @@ bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
{
Q_D(QNativeSocketEngine);
+ HRESULT hr;
ComPtr<IHostName> hostAddress;
+
if (address != QHostAddress::Any && address != QHostAddress::AnyIPv4 && address != QHostAddress::AnyIPv6) {
ComPtr<IHostNameFactory> hostNameFactory;
- GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory);
+ Q_ASSERT_SUCCEEDED(hr);
const QString addressString = address.toString();
HStringReference addressRef(reinterpret_cast<LPCWSTR>(addressString.utf16()));
- hostNameFactory->CreateHostName(addressRef.Get(), &hostAddress);
+ hr = hostNameFactory->CreateHostName(addressRef.Get(), &hostAddress);
+ RETURN_FALSE_IF_FAILED("QNativeSocketEngine::bind: Could not create hostname.");
}
- HRESULT hr;
QString portQString = port ? QString::number(port) : QString();
HStringReference portString(reinterpret_cast<LPCWSTR>(portQString.utf16()));
ComPtr<IAsyncAction> op;
if (d->socketType == QAbstractSocket::TcpSocket) {
- if (!d->tcpListener
- && FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocketListener).Get(),
- &d->tcpListener))) {
- qWarning("Failed to create listener");
- return false;
+ if (!d->tcpListener) {
+ hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocketListener).Get(),
+ &d->tcpListener);
+ Q_ASSERT_SUCCEEDED(hr);
}
- d->tcpListener->add_ConnectionReceived(Callback<ClientConnectedHandler>(d, &QNativeSocketEnginePrivate::handleClientConnection).Get(), &d->connectionToken);
+ hr = QEventDispatcherWinRT::runOnXamlThread([d]() {
+ return d->tcpListener->add_ConnectionReceived(
+ Callback<ClientConnectedHandler>(d, &QNativeSocketEnginePrivate::handleClientConnection).Get(),
+ &d->connectionToken);
+ });
+ Q_ASSERT_SUCCEEDED(hr);
hr = d->tcpListener->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message
- return false;
- }
} else if (d->socketType == QAbstractSocket::UdpSocket) {
hr = d->udpSocket()->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message
- return false;
- }
- hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(d, &QNativeSocketEnginePrivate::handleBindCompleted).Get());
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Unable to set bind callback.");
- return false;
- }
}
-
- if (op) {
- while (opStatus(op) == Started)
- d->eventLoop.processEvents();
-
- AsyncStatus status = opStatus(op);
- if (status == Error || status == Canceled)
- return false;
-
- hr = op->GetResults();
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to bind socket");
- return false;
- }
-
- d->socketState = QAbstractSocket::BoundState;
- d->fetchConnectionParameters();
- return true;
+ if (hr == E_ACCESSDENIED) {
+ qErrnoWarning(hr, "Unable to bind socket (%s:%hu/%s). Please check your manifest capabilities.",
+ qPrintable(address.toString()), port, socketDescription(this).constData());
+ return false;
}
+ Q_ASSERT_SUCCEEDED(hr);
- return false;
+ hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(d, &QNativeSocketEnginePrivate::handleBindCompleted).Get());
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = QWinRTFunctions::await(op);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ d->socketState = QAbstractSocket::BoundState;
+ return d->fetchConnectionParameters();
}
bool QNativeSocketEngine::listen()
@@ -380,8 +380,10 @@ int QNativeSocketEngine::accept()
Q_CHECK_STATE(QNativeSocketEngine::accept(), QAbstractSocket::ListeningState, -1);
Q_CHECK_TYPE(QNativeSocketEngine::accept(), QAbstractSocket::TcpSocket, -1);
- if (d->socketDescriptor == -1 || d->pendingConnections.isEmpty())
+ if (d->socketDescriptor == -1 || d->pendingConnections.isEmpty()) {
+ d->setError(QAbstractSocket::TemporaryError, QNativeSocketEnginePrivate::TemporaryErrorString);
return -1;
+ }
// Start processing incoming data
if (d->socketType == QAbstractSocket::TcpSocket) {
@@ -398,12 +400,14 @@ int QNativeSocketEngine::accept()
ComPtr<IAsyncBufferOperation> op;
hr = stream->ReadAsync(buffer.Get(), READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
- qErrnoWarning(hr, "Faild to read from the socket buffer.");
+ qErrnoWarning(hr, "accept(): Failed to read from the socket buffer (%s).",
+ socketDescription(this).constData());
return -1;
}
hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get());
if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to set socket read callback.");
+ qErrnoWarning(hr, "accept(): Failed to set socket read callback (%s).",
+ socketDescription(this).constData());
return -1;
}
d->currentConnections.append(socket);
@@ -420,28 +424,46 @@ void QNativeSocketEngine::close()
{
Q_D(QNativeSocketEngine);
+ if (d->closingDown)
+ return;
+
+ d->closingDown = true;
+
+
+ d->notifyOnRead = false;
+ d->notifyOnWrite = false;
+ d->notifyOnException = false;
+
+ HRESULT hr;
if (d->connectOp) {
ComPtr<IAsyncInfo> info;
- d->connectOp.As(&info);
+ hr = d->connectOp.As(&info);
+ Q_ASSERT_SUCCEEDED(hr);
if (info) {
- info->Cancel();
- info->Close();
+ hr = info->Cancel();
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = info->Close();
+ Q_ASSERT_SUCCEEDED(hr);
}
}
if (d->socketDescriptor != -1) {
ComPtr<IClosable> socket;
if (d->socketType == QAbstractSocket::TcpSocket) {
- d->tcpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
- d->tcpSocket()->Release();
+ hr = d->tcpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = d->tcpSocket()->Release();
+ Q_ASSERT_SUCCEEDED(hr);
} else if (d->socketType == QAbstractSocket::UdpSocket) {
- d->udpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
- d->udpSocket()->Release();
+ hr = d->udpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = d->udpSocket()->Release();
+ Q_ASSERT_SUCCEEDED(hr);
}
if (socket) {
- d->closingDown = true;
- socket->Close();
+ hr = socket->Close();
+ Q_ASSERT_SUCCEEDED(hr);
d->socketDescriptor = -1;
}
d->socketDescriptor = -1;
@@ -498,6 +520,14 @@ qint64 QNativeSocketEngine::read(char *data, qint64 maxlen)
if (d->socketType != QAbstractSocket::TcpSocket)
return -1;
+ // There will be a read notification when the socket was closed by the remote host. If that
+ // happens and there isn't anything left in the buffer, we have to return -1 in order to signal
+ // the closing of the socket.
+ if (d->readBytes.pos() == d->readBytes.size() && d->socketState != QAbstractSocket::ConnectedState) {
+ close();
+ return -1;
+ }
+
QMutexLocker mutexLocker(&d->readMutex);
return d->readBytes.read(data, maxlen);
}
@@ -514,7 +544,7 @@ qint64 QNativeSocketEngine::write(const char *data, qint64 len)
hr = d->tcpSocket()->get_OutputStream(&stream);
else if (d->socketType == QAbstractSocket::UdpSocket)
hr = d->udpSocket()->get_OutputStream(&stream);
- RETURN_IF_FAILED("Failed to get output stream to socket", return -1);
+ Q_ASSERT_SUCCEEDED(hr);
qint64 bytesWritten = writeIOStream(stream, data, len);
if (bytesWritten < 0)
@@ -525,18 +555,19 @@ qint64 QNativeSocketEngine::write(const char *data, qint64 len)
return bytesWritten;
}
-qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr, quint16 *port)
+qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header,
+ PacketHeaderOptions)
{
Q_D(QNativeSocketEngine);
- if (d->socketType != QAbstractSocket::UdpSocket || d->pendingDatagrams.isEmpty())
+ if (d->socketType != QAbstractSocket::UdpSocket || d->pendingDatagrams.isEmpty()) {
+ if (header)
+ header->clear();
return -1;
+ }
WinRtDatagram datagram = d->pendingDatagrams.takeFirst();
- if (addr)
- *addr = datagram.address;
-
- if (port)
- *port = datagram.port;
+ if (header)
+ *header = datagram.header;
QByteArray readOrigin;
// Do not read the whole datagram. Put the rest of it back into the "queue"
@@ -551,7 +582,7 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress
return readOrigin.length();
}
-qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &addr, quint16 port)
+qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
Q_D(QNativeSocketEngine);
if (d->socketType != QAbstractSocket::UdpSocket)
@@ -562,20 +593,21 @@ qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QH
HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory);
- RETURN_IF_FAILED("Could not obtain hostname factory", return -1);
- const QString addressString = addr.toString();
+ Q_ASSERT_SUCCEEDED(hr);
+ const QString addressString = header.destinationAddress.toString();
HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(addressString.utf16()));
- hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost);
+ hr = hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost);
+ RETURN_IF_FAILED("QNativeSocketEngine::writeDatagram: Could not create hostname.", return -1);
ComPtr<IAsyncOperation<IOutputStream *>> streamOperation;
ComPtr<IOutputStream> stream;
- const QString portString = QString::number(port);
+ const QString portString = QString::number(header.destinationPort);
HStringReference portRef(reinterpret_cast<LPCWSTR>(portString.utf16()));
hr = d->udpSocket()->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation);
- RETURN_IF_FAILED("Failed to get output stream to socket", return -1);
+ Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(streamOperation, stream.GetAddressOf());
- RETURN_IF_FAILED("Failed to get output stream to socket", return -1);
+ Q_ASSERT_SUCCEEDED(hr);
return writeIOStream(stream, data, len);
}
@@ -760,26 +792,23 @@ void QNativeSocketEngine::establishRead()
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
Q_UNUSED(socketProtocol);
+ HRESULT hr;
+
switch (socketType) {
case QAbstractSocket::TcpSocket: {
ComPtr<IStreamSocket> socket;
- HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(), &socket);
- if (FAILED(hr)) {
- qWarning("Failed to create StreamSocket instance");
- return false;
- }
+ hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(), &socket);
+ Q_ASSERT_SUCCEEDED(hr);
socketDescriptor = qintptr(socket.Detach());
break;
}
case QAbstractSocket::UdpSocket: {
ComPtr<IDatagramSocket> socket;
- HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &socket);
- if (FAILED(hr)) {
- qWarning("Failed to create stream socket");
- return false;
- }
+ hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &socket);
+ Q_ASSERT_SUCCEEDED(hr);
socketDescriptor = qintptr(socket.Detach());
- udpSocket()->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &connectionToken);
+ hr = udpSocket()->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &connectionToken);
+ Q_ASSERT_SUCCEEDED(hr);
break;
}
default:
@@ -787,6 +816,8 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
return false;
}
+ this->socketType = socketType;
+
// Make the socket nonblocking.
if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
setError(QAbstractSocket::UnsupportedSocketOperationError, NonBlockingInitFailedErrorString);
@@ -814,10 +845,12 @@ QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate()
if (socketDescriptor == -1 || connectionToken.value == -1)
return;
+ HRESULT hr;
if (socketType == QAbstractSocket::UdpSocket)
- udpSocket()->remove_MessageReceived(connectionToken);
+ hr = udpSocket()->remove_MessageReceived(connectionToken);
else if (socketType == QAbstractSocket::TcpSocket)
- tcpListener->remove_ConnectionReceived(connectionToken);
+ hr = tcpListener->remove_ConnectionReceived(connectionToken);
+ Q_ASSERT_SUCCEEDED(hr);
}
void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const
@@ -1044,56 +1077,66 @@ bool QNativeSocketEnginePrivate::fetchConnectionParameters()
peerPort = 0;
peerAddress.clear();
+ HRESULT hr;
if (socketType == QAbstractSocket::TcpSocket) {
ComPtr<IHostName> hostName;
HString tmpHString;
ComPtr<IStreamSocketInformation> info;
- if (FAILED(tcpSocket()->get_Information(&info))) {
- qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket info");
- return false;
- }
- info->get_LocalAddress(&hostName);
+ hr = tcpSocket()->get_Information(&info);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = info->get_LocalAddress(&hostName);
+ Q_ASSERT_SUCCEEDED(hr);
if (hostName) {
- hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ hr = hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
localAddress.setAddress(qt_QStringFromHString(tmpHString));
- info->get_LocalPort(tmpHString.GetAddressOf());
+ hr = info->get_LocalPort(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
localPort = qt_QStringFromHString(tmpHString).toInt();
}
if (!localPort && tcpListener) {
ComPtr<IStreamSocketListenerInformation> listenerInfo = 0;
- tcpListener->get_Information(&listenerInfo);
- listenerInfo->get_LocalPort(tmpHString.GetAddressOf());
+ hr = tcpListener->get_Information(&listenerInfo);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = listenerInfo->get_LocalPort(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
localPort = qt_QStringFromHString(tmpHString).toInt();
- localAddress == QHostAddress::Any;
+ localAddress = QHostAddress::Any;
}
info->get_RemoteAddress(&hostName);
if (hostName) {
- hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ hr = hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
peerAddress.setAddress(qt_QStringFromHString(tmpHString));
- info->get_RemotePort(tmpHString.GetAddressOf());
+ hr = info->get_RemotePort(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
peerPort = qt_QStringFromHString(tmpHString).toInt();
}
} else if (socketType == QAbstractSocket::UdpSocket) {
ComPtr<IHostName> hostName;
HString tmpHString;
ComPtr<IDatagramSocketInformation> info;
- if (FAILED(udpSocket()->get_Information(&info))) {
- qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket information");
- return false;
- }
- info->get_LocalAddress(&hostName);
+ hr = udpSocket()->get_Information(&info);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = info->get_LocalAddress(&hostName);
+ Q_ASSERT_SUCCEEDED(hr);
if (hostName) {
- hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ hr = hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
localAddress.setAddress(qt_QStringFromHString(tmpHString));
- info->get_LocalPort(tmpHString.GetAddressOf());
+ hr = info->get_LocalPort(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
localPort = qt_QStringFromHString(tmpHString).toInt();
}
- info->get_RemoteAddress(&hostName);
+ hr = info->get_RemoteAddress(&hostName);
+ Q_ASSERT_SUCCEEDED(hr);
if (hostName) {
- hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ hr = hostName->get_CanonicalName(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
peerAddress.setAddress(qt_QStringFromHString(tmpHString));
- info->get_RemotePort(tmpHString.GetAddressOf());
+ hr = info->get_RemotePort(tmpHString.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
peerPort = qt_QStringFromHString(tmpHString).toInt();
}
}
@@ -1154,12 +1197,16 @@ void QNativeSocketEnginePrivate::handleConnectionEstablished(IAsyncAction *actio
// The callback might be triggered several times if we do not cancel/reset it here
if (connectOp) {
ComPtr<IAsyncInfo> info;
- connectOp.As(&info);
+ hr = connectOp.As(&info);
+ Q_ASSERT_SUCCEEDED(hr);
if (info) {
- info->Cancel();
- info->Close();
+ hr = info->Cancel();
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = info->Close();
+ Q_ASSERT_SUCCEEDED(hr);
}
- connectOp.Reset();
+ hr = connectOp.Reset();
+ Q_ASSERT_SUCCEEDED(hr);
}
socketState = QAbstractSocket::ConnectedState;
@@ -1181,8 +1228,16 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
if (wasDeleted || isDeletingChildren)
return S_OK;
- if (status == Error || status == Canceled)
+ // A read in UnconnectedState will close the socket and return -1 and thus tell the caller,
+ // that the connection was closed. The socket cannot be closed here, as the subsequent read
+ // might fail then.
+ if (status == Error || status == Canceled) {
+ setError(QAbstractSocket::NetworkError, RemoteHostClosedErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
+ if (notifyOnRead)
+ emit q->readReady();
return S_OK;
+ }
ComPtr<IBuffer> buffer;
HRESULT hr = asyncInfo->GetResults(&buffer);
@@ -1191,7 +1246,13 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
UINT32 bufferLength;
hr = buffer->get_Length(&bufferLength);
Q_ASSERT_SUCCEEDED(hr);
+ // A zero sized buffer length signals, that the remote host closed the connection. The socket
+ // cannot be closed though, as the following read might have socket descriptor -1 and thus and
+ // the closing of the socket won't be communicated to the caller. So only the error is set. The
+ // actual socket close happens inside of read.
if (!bufferLength) {
+ setError(QAbstractSocket::NetworkError, RemoteHostClosedErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
if (notifyOnRead)
emit q->readReady();
return S_OK;
@@ -1232,12 +1293,14 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
ComPtr<IAsyncBufferOperation> op;
hr = stream->ReadAsync(buffer.Get(), bufferLength, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
- qErrnoWarning(hr, "Could not read into socket stream buffer.");
+ qErrnoWarning(hr, "handleReadyRead(): Could not read into socket stream buffer (%s).",
+ socketDescription(q).constData());
return S_OK;
}
hr = op->put_Completed(Callback<SocketReadCompletedHandler>(this, &QNativeSocketEnginePrivate::handleReadyRead).Get());
if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to set socket read callback.");
+ qErrnoWarning(hr, "handleReadyRead(): Failed to set socket read callback (%s).",
+ socketDescription(q).constData());
return S_OK;
}
return S_OK;
@@ -1257,11 +1320,11 @@ HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, I
remoteHost->get_CanonicalName(remoteHostString.GetAddressOf());
RETURN_OK_IF_FAILED("Could not obtain remote host's canonical name");
returnAddress.setAddress(qt_QStringFromHString(remoteHostString));
- datagram.address = returnAddress;
+ datagram.header.senderAddress = returnAddress;
HString remotePort;
hr = args->get_RemotePort(remotePort.GetAddressOf());
RETURN_OK_IF_FAILED("Could not obtain remote port");
- datagram.port = qt_QStringFromHString(remotePort).toInt();
+ datagram.header.senderPort = qt_QStringFromHString(remotePort).toInt();
ComPtr<IDataReader> reader;
hr = args->GetDataReader(&reader);
diff --git a/src/network/socket/qnativesocketengine_winrt_p.h b/src/network/socket/qnativesocketengine_winrt_p.h
index 79e1a3391e..c48b0e85d9 100644
--- a/src/network/socket/qnativesocketengine_winrt_p.h
+++ b/src/network/socket/qnativesocketengine_winrt_p.h
@@ -58,8 +58,7 @@ class QNativeSocketEnginePrivate;
struct WinRtDatagram {
QByteArray data;
- int port;
- QHostAddress address;
+ QIpPacketHeader header;
};
class Q_AUTOTEST_EXPORT QNativeSocketEngine : public QAbstractSocketEngine
@@ -97,10 +96,8 @@ public:
qint64 read(char *data, qint64 maxlen);
qint64 write(const char *data, qint64 len);
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0);
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port);
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader * = 0, PacketHeaderOptions = WantNone);
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header);
bool hasPendingDatagrams() const;
qint64 pendingDatagramSize() const;
diff --git a/src/network/socket/qnet_unix_p.h b/src/network/socket/qnet_unix_p.h
index 979afb82ba..9626c53711 100644
--- a/src/network/socket/qnet_unix_p.h
+++ b/src/network/socket/qnet_unix_p.h
@@ -77,15 +77,13 @@ static inline int qt_safe_socket(int domain, int type, int protocol, int flags =
Q_ASSERT((flags & ~O_NONBLOCK) == 0);
int fd;
-#if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+#ifdef QT_THREADSAFE_CLOEXEC
int newtype = type | SOCK_CLOEXEC;
if (flags & O_NONBLOCK)
newtype |= SOCK_NONBLOCK;
fd = ::socket(domain, newtype, protocol);
- if (fd != -1 || errno != EINVAL)
- return fd;
-#endif
-
+ return fd;
+#else
fd = ::socket(domain, type, protocol);
if (fd == -1)
return -1;
@@ -97,6 +95,7 @@ static inline int qt_safe_socket(int domain, int type, int protocol, int flags =
::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);
return fd;
+#endif
}
// Tru64 redefines accept -> _accept with _XOPEN_SOURCE_EXTENDED
@@ -105,16 +104,14 @@ static inline int qt_safe_accept(int s, struct sockaddr *addr, QT_SOCKLEN_T *add
Q_ASSERT((flags & ~O_NONBLOCK) == 0);
int fd;
-#if QT_UNIX_SUPPORTS_THREADSAFE_CLOEXEC && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+#ifdef QT_THREADSAFE_CLOEXEC
// use accept4
int sockflags = SOCK_CLOEXEC;
if (flags & O_NONBLOCK)
sockflags |= SOCK_NONBLOCK;
fd = ::accept4(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen), sockflags);
- if (fd != -1 || !(errno == ENOSYS || errno == EINVAL))
- return fd;
-#endif
-
+ return fd;
+#else
fd = ::accept(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen));
if (fd == -1)
return -1;
@@ -126,6 +123,7 @@ static inline int qt_safe_accept(int s, struct sockaddr *addr, QT_SOCKLEN_T *add
::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);
return fd;
+#endif
}
// UnixWare 7 redefines listen -> _listen
@@ -175,8 +173,7 @@ static inline in_addr_t qt_safe_inet_addr(const char *cp)
#endif
}
-// VxWorks' headers do not specify any const modifiers
-static inline int qt_safe_sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *to, QT_SOCKLEN_T tolen)
+static inline int qt_safe_sendmsg(int sockfd, const struct msghdr *msg, int flags)
{
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
@@ -185,11 +182,15 @@ static inline int qt_safe_sendto(int sockfd, const void *buf, size_t len, int fl
#endif
int ret;
-#ifdef Q_OS_VXWORKS
- EINTR_LOOP(ret, ::sendto(sockfd, (char *) buf, len, flags, (struct sockaddr *) to, tolen));
-#else
- EINTR_LOOP(ret, ::sendto(sockfd, buf, len, flags, to, tolen));
-#endif
+ EINTR_LOOP(ret, ::sendmsg(sockfd, msg, flags));
+ return ret;
+}
+
+static inline int qt_safe_recvmsg(int sockfd, struct msghdr *msg, int flags)
+{
+ int ret;
+
+ EINTR_LOOP(ret, ::recvmsg(sockfd, msg, flags));
return ret;
}
diff --git a/src/network/socket/qsocks5socketengine.cpp b/src/network/socket/qsocks5socketengine.cpp
index a6eafd2601..6868e8c73a 100644
--- a/src/network/socket/qsocks5socketengine.cpp
+++ b/src/network/socket/qsocks5socketengine.cpp
@@ -1111,14 +1111,16 @@ bool QSocks5SocketEngine::connectInternal()
}
}
- if (d->socks5State == QSocks5SocketEnginePrivate::Uninitialized
- && d->socketState != QAbstractSocket::ConnectingState) {
- setState(QAbstractSocket::ConnectingState);
- //limit buffer in internal socket, data is buffered in the external socket under application control
- d->data->controlSocket->setReadBufferSize(65536);
+ if (d->socketState != QAbstractSocket::ConnectingState) {
+ if (d->socks5State == QSocks5SocketEnginePrivate::Uninitialized) {
+ setState(QAbstractSocket::ConnectingState);
+ //limit buffer in internal socket, data is buffered in the external socket under application control
+ d->data->controlSocket->setReadBufferSize(65536);
+ }
+
d->data->controlSocket->connectToHost(d->proxyInfo.hostName(), d->proxyInfo.port());
- return false;
}
+
return false;
}
@@ -1383,7 +1385,7 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
#endif
dummy.setProxy(QNetworkProxy::NoProxy);
if (!dummy.bind()
- || writeDatagram(0,0, d->data->controlSocket->localAddress(), dummy.localPort()) != 0
+ || writeDatagram(0,0, QIpPacketHeader(d->data->controlSocket->localAddress(), dummy.localPort())) != 0
|| !dummy.waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))
|| dummy.readDatagram(0,0, &d->localAddress, &d->localPort) != 0) {
QSOCKS5_DEBUG << "udp actual address and port lookup failed";
@@ -1555,7 +1557,7 @@ qint64 QSocks5SocketEngine::write(const char *data, qint64 len)
#ifndef QT_NO_UDPSOCKET
} else if (d->mode == QSocks5SocketEnginePrivate::UdpAssociateMode) {
// send to connected address
- return writeDatagram(data, len, d->peerAddress, d->peerPort);
+ return writeDatagram(data, len, QIpPacketHeader(d->peerAddress, d->peerPort));
#endif
}
//### set an error ???
@@ -1594,8 +1596,7 @@ bool QSocks5SocketEngine::setMulticastInterface(const QNetworkInterface &)
}
#endif // QT_NO_NETWORKINTERFACE
-qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr,
- quint16 *port)
+qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QIpPacketHeader *header, PacketHeaderOptions)
{
Q_D(QSocks5SocketEngine);
@@ -1607,15 +1608,12 @@ qint64 QSocks5SocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress
QSocks5RevivedDatagram datagram = d->udpData->pendingDatagrams.dequeue();
int copyLen = qMin<int>(maxlen, datagram.data.size());
memcpy(data, datagram.data.constData(), copyLen);
- if (addr)
- *addr = datagram.address;
- if (port)
- *port = datagram.port;
+ header->senderAddress = datagram.address;
+ header->senderPort = datagram.port;
return copyLen;
}
-qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &address,
- quint16 port)
+qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QIpPacketHeader &header)
{
Q_D(QSocks5SocketEngine);
@@ -1634,7 +1632,7 @@ qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QH
outBuf[0] = 0x00;
outBuf[1] = 0x00;
outBuf[2] = 0x00;
- if (!qt_socks5_set_host_address_and_port(address, port, &outBuf)) {
+ if (!qt_socks5_set_host_address_and_port(header.destinationAddress, header.destinationPort, &outBuf)) {
}
outBuf += QByteArray(data, len);
QSOCKS5_DEBUG << "sending" << dump(outBuf);
diff --git a/src/network/socket/qsocks5socketengine_p.h b/src/network/socket/qsocks5socketengine_p.h
index c97b0e89ce..de20e0ef0e 100644
--- a/src/network/socket/qsocks5socketengine_p.h
+++ b/src/network/socket/qsocks5socketengine_p.h
@@ -93,10 +93,9 @@ public:
bool setMulticastInterface(const QNetworkInterface &iface) Q_DECL_OVERRIDE;
#endif // QT_NO_NETWORKINTERFACE
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *addr = 0,
- quint16 *port = 0) Q_DECL_OVERRIDE;
- qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &addr,
- quint16 port) Q_DECL_OVERRIDE;
+ qint64 readDatagram(char *data, qint64 maxlen, QIpPacketHeader * = 0,
+ PacketHeaderOptions = WantNone) Q_DECL_OVERRIDE;
+ qint64 writeDatagram(const char *data, qint64 len, const QIpPacketHeader &) Q_DECL_OVERRIDE;
bool hasPendingDatagrams() const Q_DECL_OVERRIDE;
qint64 pendingDatagramSize() const Q_DECL_OVERRIDE;
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qtcpserver.cpp b/src/network/socket/qtcpserver.cpp
index b41d207947..bf75666548 100644
--- a/src/network/socket/qtcpserver.cpp
+++ b/src/network/socket/qtcpserver.cpp
@@ -160,6 +160,23 @@ QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint
/*! \internal
*/
+void QTcpServerPrivate::configureCreatedSocket()
+{
+#if defined(Q_OS_UNIX)
+ // Under Unix, we want to be able to bind to the port, even if a socket on
+ // the same address-port is in TIME_WAIT. Under Windows this is possible
+ // anyway -- furthermore, the meaning of reusable on Windows is different:
+ // it means that you can use the same address-port for multiple listening
+ // sockets.
+ // Don't abort though if we can't set that option. For example the socks
+ // engine doesn't support that option, but that shouldn't prevent us from
+ // trying to bind/listen.
+ socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
+#endif
+}
+
+/*! \internal
+*/
void QTcpServerPrivate::readNotification()
{
Q_Q(QTcpServer);
@@ -205,6 +222,9 @@ void QTcpServerPrivate::readNotification()
QTcpServer::QTcpServer(QObject *parent)
: QObject(*new QTcpServerPrivate, parent)
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::QTcpServer(%p)", parent);
+#endif
}
/*!
@@ -218,6 +238,9 @@ QTcpServer::QTcpServer(QObject *parent)
*/
QTcpServer::~QTcpServer()
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::~QTcpServer()");
+#endif
close();
}
@@ -226,6 +249,9 @@ QTcpServer::~QTcpServer()
QTcpServer::QTcpServer(QTcpServerPrivate &dd, QObject *parent)
: QObject(dd, parent)
{
+#if defined(QTCPSERVER_DEBUG)
+ qDebug("QTcpServer::QTcpServer(QTcpServerPrivate == %p, parent == %p)", &dd, parent);
+#endif
}
/*!
@@ -275,17 +301,7 @@ bool QTcpServer::listen(const QHostAddress &address, quint16 port)
if (addr.protocol() == QAbstractSocket::AnyIPProtocol && proto == QAbstractSocket::IPv4Protocol)
addr = QHostAddress::AnyIPv4;
-#if defined(Q_OS_UNIX)
- // Under Unix, we want to be able to bind to the port, even if a socket on
- // the same address-port is in TIME_WAIT. Under Windows this is possible
- // anyway -- furthermore, the meaning of reusable on Windows is different:
- // it means that you can use the same address-port for multiple listening
- // sockets.
- // Don't abort though if we can't set that option. For example the socks
- // engine doesn't support that option, but that shouldn't prevent us from
- // trying to bind/listen.
- d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
-#endif
+ d->configureCreatedSocket();
if (!d->socketEngine->bind(addr, port)) {
d->serverSocketError = d->socketEngine->error();
@@ -543,6 +559,10 @@ QTcpSocket *QTcpServer::nextPendingConnection()
may not be usable with native socket functions, and should only be
used with QTcpSocket::setSocketDescriptor().
+ \note If another socket is created in the reimplementation
+ of this method, it needs to be added to the Pending Connections mechanism
+ by calling addPendingConnection().
+
\note If you want to handle an incoming connection as a new QTcpSocket
object in another thread you have to pass the socketDescriptor
to the other thread and create the QTcpSocket object there and
diff --git a/src/network/socket/qtcpserver.h b/src/network/socket/qtcpserver.h
index 8c7537a9b1..dd7b12c96a 100644
--- a/src/network/socket/qtcpserver.h
+++ b/src/network/socket/qtcpserver.h
@@ -51,7 +51,7 @@ class Q_NETWORK_EXPORT QTcpServer : public QObject
{
Q_OBJECT
public:
- explicit QTcpServer(QObject *parent = 0);
+ explicit QTcpServer(QObject *parent = Q_NULLPTR);
virtual ~QTcpServer();
bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
@@ -68,7 +68,7 @@ public:
qintptr socketDescriptor() const;
bool setSocketDescriptor(qintptr socketDescriptor);
- bool waitForNewConnection(int msec = 0, bool *timedOut = 0);
+ bool waitForNewConnection(int msec = 0, bool *timedOut = Q_NULLPTR);
virtual bool hasPendingConnections() const;
virtual QTcpSocket *nextPendingConnection();
@@ -87,7 +87,7 @@ protected:
virtual void incomingConnection(qintptr handle);
void addPendingConnection(QTcpSocket* socket);
- QTcpServer(QTcpServerPrivate &dd, QObject *parent = 0);
+ QTcpServer(QTcpServerPrivate &dd, QObject *parent = Q_NULLPTR);
Q_SIGNALS:
void newConnection();
diff --git a/src/network/socket/qtcpserver_p.h b/src/network/socket/qtcpserver_p.h
index 415a0e190a..47505e7e91 100644
--- a/src/network/socket/qtcpserver_p.h
+++ b/src/network/socket/qtcpserver_p.h
@@ -80,6 +80,8 @@ public:
QNetworkProxy resolveProxy(const QHostAddress &address, quint16 port);
#endif
+ virtual void configureCreatedSocket();
+
// from QAbstractSocketEngineReceiver
void readNotification() Q_DECL_OVERRIDE;
void closeNotification() Q_DECL_OVERRIDE { readNotification(); }
diff --git a/src/network/socket/qtcpsocket.cpp b/src/network/socket/qtcpsocket.cpp
index b6072b2909..13865fbc9c 100644
--- a/src/network/socket/qtcpsocket.cpp
+++ b/src/network/socket/qtcpsocket.cpp
@@ -103,4 +103,13 @@ QTcpSocket::QTcpSocket(QTcpSocketPrivate &dd, QObject *parent)
d_func()->isBuffered = true;
}
+/*!
+ \internal
+*/
+QTcpSocket::QTcpSocket(QAbstractSocket::SocketType socketType,
+ QTcpSocketPrivate &dd, QObject *parent)
+ : QAbstractSocket(socketType, dd, parent)
+{
+}
+
QT_END_NAMESPACE
diff --git a/src/network/socket/qtcpsocket.h b/src/network/socket/qtcpsocket.h
index 3449beeceb..8e3cb5946f 100644
--- a/src/network/socket/qtcpsocket.h
+++ b/src/network/socket/qtcpsocket.h
@@ -46,11 +46,13 @@ class Q_NETWORK_EXPORT QTcpSocket : public QAbstractSocket
{
Q_OBJECT
public:
- explicit QTcpSocket(QObject *parent = 0);
+ explicit QTcpSocket(QObject *parent = Q_NULLPTR);
virtual ~QTcpSocket();
protected:
- QTcpSocket(QTcpSocketPrivate &dd, QObject *parent = 0);
+ QTcpSocket(QTcpSocketPrivate &dd, QObject *parent = Q_NULLPTR);
+ QTcpSocket(QAbstractSocket::SocketType socketType, QTcpSocketPrivate &dd,
+ QObject *parent = Q_NULLPTR);
private:
Q_DISABLE_COPY(QTcpSocket)
diff --git a/src/network/socket/qudpsocket.cpp b/src/network/socket/qudpsocket.cpp
index 87686f94e1..a46e6ade04 100644
--- a/src/network/socket/qudpsocket.cpp
+++ b/src/network/socket/qudpsocket.cpp
@@ -333,15 +333,13 @@ qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddre
if (state() == UnconnectedState)
bind();
- qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
+ qint64 sent = d->socketEngine->writeDatagram(data, size, QIpPacketHeader(address, port));
d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
if (sent >= 0) {
emit bytesWritten(sent);
} else {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
- emit error(d->socketError);
+ d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
}
return sent;
}
@@ -379,13 +377,23 @@ qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *addres
qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
#endif
QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
- qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
- d_func()->socketEngine->setReadNotificationEnabled(true);
- if (readBytes < 0) {
- d->socketError = d->socketEngine->error();
- setErrorString(d->socketEngine->errorString());
- emit error(d->socketError);
+
+ qint64 readBytes;
+ if (address || port) {
+ QIpPacketHeader header;
+ readBytes = d->socketEngine->readDatagram(data, maxSize, &header,
+ QAbstractSocketEngine::WantDatagramSender);
+ if (address)
+ *address = header.senderAddress;
+ if (port)
+ *port = header.senderPort;
+ } else {
+ readBytes = d->socketEngine->readDatagram(data, maxSize);
}
+
+ d_func()->socketEngine->setReadNotificationEnabled(true);
+ if (readBytes < 0)
+ d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
return readBytes;
}
#endif // QT_NO_UDPSOCKET
diff --git a/src/network/socket/qudpsocket.h b/src/network/socket/qudpsocket.h
index fcf16fb345..e902984b4f 100644
--- a/src/network/socket/qudpsocket.h
+++ b/src/network/socket/qudpsocket.h
@@ -49,7 +49,7 @@ class Q_NETWORK_EXPORT QUdpSocket : public QAbstractSocket
{
Q_OBJECT
public:
- explicit QUdpSocket(QObject *parent = 0);
+ explicit QUdpSocket(QObject *parent = Q_NULLPTR);
virtual ~QUdpSocket();
#ifndef QT_NO_NETWORKINTERFACE
@@ -66,7 +66,7 @@ public:
bool hasPendingDatagrams() const;
qint64 pendingDatagramSize() const;
- qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host = 0, quint16 *port = 0);
+ qint64 readDatagram(char *data, qint64 maxlen, QHostAddress *host = Q_NULLPTR, quint16 *port = Q_NULLPTR);
qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port);
inline qint64 writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{ return writeDatagram(datagram.constData(), datagram.size(), host, port); }
diff --git a/src/network/ssl/qssl.cpp b/src/network/ssl/qssl.cpp
index 26381fcb8e..84aa9d7dca 100644
--- a/src/network/ssl/qssl.cpp
+++ b/src/network/ssl/qssl.cpp
@@ -166,6 +166,10 @@ Q_LOGGING_CATEGORY(lcSsl, "qt.network.ssl");
in ASN.1 format as returned by QSslConfiguration::sessionTicket(). Enabling
this feature adds memory overhead of approximately 1K per used session
ticket.
+ \value SslOptionDisableServerCipherPreference Disables selecting the cipher
+ chosen based on the servers preferences rather than the order ciphers were
+ sent by the client. This option is only relevant to server sockets, and is
+ only honored by the OpenSSL backend.
By default, SslOptionDisableEmptyFragments is turned on since this causes
problems with a large number of servers. SslOptionDisableLegacyRenegotiation
diff --git a/src/network/ssl/qssl.h b/src/network/ssl/qssl.h
index f56c36b219..03497ecf76 100644
--- a/src/network/ssl/qssl.h
+++ b/src/network/ssl/qssl.h
@@ -95,7 +95,8 @@ namespace QSsl {
SslOptionDisableServerNameIndication = 0x08,
SslOptionDisableLegacyRenegotiation = 0x10,
SslOptionDisableSessionSharing = 0x20,
- SslOptionDisableSessionPersistence = 0x40
+ SslOptionDisableSessionPersistence = 0x40,
+ SslOptionDisableServerCipherPreference = 0x80
};
Q_DECLARE_FLAGS(SslOptions, SslOption)
}
diff --git a/src/network/ssl/qsslcertificate.h b/src/network/ssl/qsslcertificate.h
index ef0767ae8f..d58cfcf5d1 100644
--- a/src/network/ssl/qsslcertificate.h
+++ b/src/network/ssl/qsslcertificate.h
@@ -83,9 +83,12 @@ public:
explicit QSslCertificate(const QByteArray &data = QByteArray(), QSsl::EncodingFormat format = QSsl::Pem);
QSslCertificate(const QSslCertificate &other);
~QSslCertificate();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCertificate &operator=(QSslCertificate &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCertificate &operator=(const QSslCertificate &other);
- inline void swap(QSslCertificate &other)
+ void swap(QSslCertificate &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslCertificate &other) const;
@@ -94,7 +97,7 @@ public:
bool isNull() const;
#if QT_DEPRECATED_SINCE(5,0)
QT_DEPRECATED inline bool isValid() const {
- const QDateTime currentTime = QDateTime::currentDateTime();
+ const QDateTime currentTime = QDateTime::currentDateTimeUtc();
return currentTime >= effectiveDate() &&
currentTime <= expiryDate() &&
!isBlacklisted();
@@ -144,7 +147,7 @@ public:
static bool importPkcs12(QIODevice *device,
QSslKey *key, QSslCertificate *cert,
- QList<QSslCertificate> *caCertificates=0,
+ QList<QSslCertificate> *caCertificates = Q_NULLPTR,
const QByteArray &passPhrase=QByteArray());
Qt::HANDLE handle() const;
diff --git a/src/network/ssl/qsslcertificate_openssl.cpp b/src/network/ssl/qsslcertificate_openssl.cpp
index ad88ea5d56..3324587821 100644
--- a/src/network/ssl/qsslcertificate_openssl.cpp
+++ b/src/network/ssl/qsslcertificate_openssl.cpp
@@ -464,8 +464,9 @@ QList<QSslCertificateExtension> QSslCertificate::extensions() const
return result;
int count = q_X509_get_ext_count(d->x509);
+ result.reserve(count);
- for (int i=0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
X509_EXTENSION *ext = q_X509_get_ext(d->x509, i);
result << QSslCertificatePrivate::convertExtension(ext);
}
diff --git a/src/network/ssl/qsslcertificateextension.h b/src/network/ssl/qsslcertificateextension.h
index 7c958eff30..8dd0e8eb4b 100644
--- a/src/network/ssl/qsslcertificateextension.h
+++ b/src/network/ssl/qsslcertificateextension.h
@@ -51,11 +51,13 @@ class Q_NETWORK_EXPORT QSslCertificateExtension
public:
QSslCertificateExtension();
QSslCertificateExtension(const QSslCertificateExtension &other);
- ~QSslCertificateExtension();
-
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCertificateExtension &operator=(QSslCertificateExtension &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCertificateExtension &operator=(const QSslCertificateExtension &other);
+ ~QSslCertificateExtension();
- void swap(QSslCertificateExtension &other) { qSwap(d, other.d); }
+ void swap(QSslCertificateExtension &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
QString oid() const;
QString name() const;
diff --git a/src/network/ssl/qsslcipher.h b/src/network/ssl/qsslcipher.h
index dc65e32111..64122cdd53 100644
--- a/src/network/ssl/qsslcipher.h
+++ b/src/network/ssl/qsslcipher.h
@@ -52,10 +52,13 @@ public:
explicit QSslCipher(const QString &name);
QSslCipher(const QString &name, QSsl::SslProtocol protocol);
QSslCipher(const QSslCipher &other);
- ~QSslCipher();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslCipher &operator=(QSslCipher &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslCipher &operator=(const QSslCipher &other);
+ ~QSslCipher();
- inline void swap(QSslCipher &other)
+ void swap(QSslCipher &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslCipher &other) const;
diff --git a/src/network/ssl/qsslconfiguration.h b/src/network/ssl/qsslconfiguration.h
index 960aec60ce..2cbc31b032 100644
--- a/src/network/ssl/qsslconfiguration.h
+++ b/src/network/ssl/qsslconfiguration.h
@@ -71,9 +71,12 @@ public:
QSslConfiguration();
QSslConfiguration(const QSslConfiguration &other);
~QSslConfiguration();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslConfiguration &operator=(QSslConfiguration &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslConfiguration &operator=(const QSslConfiguration &other);
- inline void swap(QSslConfiguration &other)
+ void swap(QSslConfiguration &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
bool operator==(const QSslConfiguration &other) const;
diff --git a/src/network/ssl/qsslcontext_openssl.cpp b/src/network/ssl/qsslcontext_openssl.cpp
index b88ab54038..68caaeb6dc 100644
--- a/src/network/ssl/qsslcontext_openssl.cpp
+++ b/src/network/ssl/qsslcontext_openssl.cpp
@@ -215,6 +215,8 @@ init_context:
return sslContext;
}
+ const QDateTime now = QDateTime::currentDateTimeUtc();
+
// Add all our CAs to this store.
foreach (const QSslCertificate &caCertificate, sslContext->sslConfiguration.caCertificates()) {
// From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html:
@@ -228,7 +230,7 @@ init_context:
// certificates mixed with valid ones.
//
// See also: QSslSocketBackendPrivate::verify()
- if (caCertificate.expiryDate() >= QDateTime::currentDateTime()) {
+ if (caCertificate.expiryDate() >= now) {
q_X509_STORE_add_cert(q_SSL_CTX_get_cert_store(sslContext->ctx), (X509 *)caCertificate.handle());
}
}
diff --git a/src/network/ssl/qsslellipticcurve.cpp b/src/network/ssl/qsslellipticcurve.cpp
index b4396d567b..0824a61e8d 100644
--- a/src/network/ssl/qsslellipticcurve.cpp
+++ b/src/network/ssl/qsslellipticcurve.cpp
@@ -170,7 +170,7 @@ QDebug operator<<(QDebug debug, QSslEllipticCurve curve)
{
QDebugStateSaver saver(debug);
debug.resetFormat().nospace();
- debug << "QSslEllipticCurve(" << curve.shortName() << ")";
+ debug << "QSslEllipticCurve(" << curve.shortName() << ')';
return debug;
}
#endif
diff --git a/src/network/ssl/qsslellipticcurve.h b/src/network/ssl/qsslellipticcurve.h
index a991881b93..5716e3447d 100644
--- a/src/network/ssl/qsslellipticcurve.h
+++ b/src/network/ssl/qsslellipticcurve.h
@@ -37,7 +37,10 @@
#include <QtCore/QtGlobal>
#include <QtCore/QString>
#include <QtCore/QMetaType>
+#if QT_DEPRECATED_SINCE(5, 5)
#include <QtCore/QHash>
+#endif
+#include <QtCore/qhashfunctions.h>
QT_BEGIN_NAMESPACE
diff --git a/src/network/ssl/qsslerror.h b/src/network/ssl/qsslerror.h
index b149f86d9e..bc2a2d5220 100644
--- a/src/network/ssl/qsslerror.h
+++ b/src/network/ssl/qsslerror.h
@@ -84,10 +84,13 @@ public:
QSslError(const QSslError &other);
- inline void swap(QSslError &other)
+ void swap(QSslError &other) Q_DECL_NOTHROW
{ qSwap(d, other.d); }
~QSslError();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslError &operator=(QSslError &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslError &operator=(const QSslError &other);
bool operator==(const QSslError &other) const;
inline bool operator!=(const QSslError &other) const
diff --git a/src/network/ssl/qsslkey.h b/src/network/ssl/qsslkey.h
index b89069e4cb..d02c031015 100644
--- a/src/network/ssl/qsslkey.h
+++ b/src/network/ssl/qsslkey.h
@@ -64,10 +64,13 @@ public:
const QByteArray &passPhrase = QByteArray());
explicit QSslKey(Qt::HANDLE handle, QSsl::KeyType type = QSsl::PrivateKey);
QSslKey(const QSslKey &other);
- ~QSslKey();
+#ifdef Q_COMPILER_RVALUE_REFS
+ QSslKey &operator=(QSslKey &&other) Q_DECL_NOTHROW { swap(other); return *this; }
+#endif
QSslKey &operator=(const QSslKey &other);
+ ~QSslKey();
- inline void swap(QSslKey &other) { qSwap(d, other.d); }
+ void swap(QSslKey &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool isNull() const;
void clear();
diff --git a/src/network/ssl/qsslkey_openssl.cpp b/src/network/ssl/qsslkey_openssl.cpp
index 33cb81ce71..a90c9411b7 100644
--- a/src/network/ssl/qsslkey_openssl.cpp
+++ b/src/network/ssl/qsslkey_openssl.cpp
@@ -265,4 +265,53 @@ Qt::HANDLE QSslKeyPrivate::handle() const
}
}
+static QByteArray doCrypt(QSslKeyPrivate::Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv, int enc)
+{
+ EVP_CIPHER_CTX ctx;
+ const EVP_CIPHER* type = 0;
+ int i = 0, len = 0;
+
+ switch (cipher) {
+ case QSslKeyPrivate::DesCbc:
+ type = q_EVP_des_cbc();
+ break;
+ case QSslKeyPrivate::DesEde3Cbc:
+ type = q_EVP_des_ede3_cbc();
+ break;
+ case QSslKeyPrivate::Rc2Cbc:
+ type = q_EVP_rc2_cbc();
+ break;
+ }
+
+ QByteArray output;
+ output.resize(data.size() + EVP_MAX_BLOCK_LENGTH);
+ q_EVP_CIPHER_CTX_init(&ctx);
+ q_EVP_CipherInit(&ctx, type, NULL, NULL, enc);
+ q_EVP_CIPHER_CTX_set_key_length(&ctx, key.size());
+ if (cipher == QSslKeyPrivate::Rc2Cbc)
+ q_EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_SET_RC2_KEY_BITS, 8 * key.size(), NULL);
+ q_EVP_CipherInit(&ctx, NULL,
+ reinterpret_cast<const unsigned char *>(key.constData()),
+ reinterpret_cast<const unsigned char *>(iv.constData()), enc);
+ q_EVP_CipherUpdate(&ctx,
+ reinterpret_cast<unsigned char *>(output.data()), &len,
+ reinterpret_cast<const unsigned char *>(data.constData()), data.size());
+ q_EVP_CipherFinal(&ctx,
+ reinterpret_cast<unsigned char *>(output.data()) + len, &i);
+ len += i;
+ q_EVP_CIPHER_CTX_cleanup(&ctx);
+
+ return output.left(len);
+}
+
+QByteArray QSslKeyPrivate::decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, 0);
+}
+
+QByteArray QSslKeyPrivate::encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, 1);
+}
+
QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslkey_p.h b/src/network/ssl/qsslkey_p.h
index be981bb484..fea0e30bbc 100644
--- a/src/network/ssl/qsslkey_p.h
+++ b/src/network/ssl/qsslkey_p.h
@@ -90,6 +90,16 @@ public:
bool isNull;
QSsl::KeyType type;
QSsl::KeyAlgorithm algorithm;
+
+ enum Cipher {
+ DesCbc,
+ DesEde3Cbc,
+ Rc2Cbc
+ };
+
+ Q_AUTOTEST_EXPORT static QByteArray decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+ Q_AUTOTEST_EXPORT static QByteArray encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+
#ifndef QT_NO_OPENSSL
union {
EVP_PKEY *opaque;
@@ -100,15 +110,6 @@ public:
#endif
};
#else
- enum Cipher {
- DesCbc,
- DesEde3Cbc,
- Rc2Cbc
- };
-
- Q_AUTOTEST_EXPORT static QByteArray decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
- Q_AUTOTEST_EXPORT static QByteArray encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
-
Qt::HANDLE opaque;
QByteArray derData;
int keyLength;
diff --git a/src/network/ssl/qsslpresharedkeyauthenticator.h b/src/network/ssl/qsslpresharedkeyauthenticator.h
index 159b16d563..34e5d6fd50 100644
--- a/src/network/ssl/qsslpresharedkeyauthenticator.h
+++ b/src/network/ssl/qsslpresharedkeyauthenticator.h
@@ -52,14 +52,10 @@ public:
Q_NETWORK_EXPORT QSslPreSharedKeyAuthenticator &operator=(const QSslPreSharedKeyAuthenticator &authenticator);
#ifdef Q_COMPILER_RVALUE_REFS
- inline QSslPreSharedKeyAuthenticator &operator=(QSslPreSharedKeyAuthenticator &&authenticator)
- { d.swap(authenticator.d); return *this; }
+ QSslPreSharedKeyAuthenticator &operator=(QSslPreSharedKeyAuthenticator &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
- void swap(QSslPreSharedKeyAuthenticator &authenticator)
- {
- d.swap(authenticator.d);
- }
+ void swap(QSslPreSharedKeyAuthenticator &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
Q_NETWORK_EXPORT QByteArray identityHint() const;
diff --git a/src/network/ssl/qsslpresharedkeyauthenticator_p.h b/src/network/ssl/qsslpresharedkeyauthenticator_p.h
index ba7a740907..c57b6b10ca 100644
--- a/src/network/ssl/qsslpresharedkeyauthenticator_p.h
+++ b/src/network/ssl/qsslpresharedkeyauthenticator_p.h
@@ -34,6 +34,17 @@
#ifndef QSSLPRESHAREDKEYAUTHENTICATOR_P_H
#define QSSLPRESHAREDKEYAUTHENTICATOR_P_H
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
#include <QSharedData>
QT_BEGIN_NAMESPACE
diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp
index 9b5d90225f..805adc734f 100644
--- a/src/network/ssl/qsslsocket.cpp
+++ b/src/network/ssl/qsslsocket.cpp
@@ -131,19 +131,18 @@
before the handshake phase with setLocalCertificate() and
setPrivateKey().
\li The CA certificate database can be extended and customized with
- addCaCertificate(), addCaCertificates(), setCaCertificates(),
- addDefaultCaCertificate(), addDefaultCaCertificates(), and
- setDefaultCaCertificates().
+ addCaCertificate(), addCaCertificates(), addDefaultCaCertificate(),
+ addDefaultCaCertificates(), and QSslConfiguration::defaultConfiguration().setCaCertificates().
\endlist
\note If available, root certificates on Unix (excluding OS X) will be
- loaded on demand from the standard certificate directories. If
- you do not want to load root certificates on demand, you need to call either
- the static function setDefaultCaCertificates() before the first SSL handshake
- is made in your application, (e.g. via
- "QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates());"),
- or call setCaCertificates() on your QSslSocket instance prior to the SSL
- handshake.
+ loaded on demand from the standard certificate directories. If you do not
+ want to load root certificates on demand, you need to call either
+ QSslConfiguration::defaultConfiguration().setCaCertificates() before the first
+ SSL handshake is made in your application (for example, via passing
+ QSslSocket::systemCaCertificates() to it), or call
+ QSslConfiguration::defaultConfiguration()::setCaCertificates() on your QSslSocket instance
+ prior to the SSL handshake.
For more information about ciphers and certificates, refer to QSslCipher and
QSslCertificate.
@@ -499,8 +498,7 @@ bool QSslSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state
d->createPlainSocket(openMode);
bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode);
d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
- setSocketError(d->plainSocket->error());
- setErrorString(d->plainSocket->errorString());
+ d->setError(d->plainSocket->error(), d->plainSocket->errorString());
setSocketState(state);
setOpenMode(openMode);
setLocalPort(d->plainSocket->localPort());
@@ -1243,7 +1241,7 @@ void QSslSocket::setCiphers(const QString &ciphers)
{
Q_D(QSslSocket);
d->configuration.ciphers.clear();
- foreach (const QString &cipherName, ciphers.split(QLatin1String(":"),QString::SkipEmptyParts)) {
+ foreach (const QString &cipherName, ciphers.split(QLatin1Char(':'), QString::SkipEmptyParts)) {
QSslCipher cipher(cipherName);
if (!cipher.isNull())
d->configuration.ciphers << cipher;
@@ -1532,8 +1530,7 @@ bool QSslSocket::waitForConnected(int msecs)
bool retVal = d->plainSocket->waitForConnected(msecs);
if (!retVal) {
setSocketState(d->plainSocket->state());
- setSocketError(d->plainSocket->error());
- setErrorString(d->plainSocket->errorString());
+ d->setError(d->plainSocket->error(), d->plainSocket->errorString());
}
return retVal;
}
@@ -1688,8 +1685,7 @@ bool QSslSocket::waitForDisconnected(int msecs)
bool retVal = d->plainSocket->waitForDisconnected(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
if (!retVal) {
setSocketState(d->plainSocket->state());
- setSocketError(d->plainSocket->error());
- setErrorString(d->plainSocket->errorString());
+ d->setError(d->plainSocket->error(), d->plainSocket->errorString());
}
return retVal;
}
@@ -2402,8 +2398,9 @@ void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state)
*/
void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error)
{
- Q_Q(QSslSocket);
+ Q_UNUSED(error)
#ifdef QSSLSOCKET_DEBUG
+ Q_Q(QSslSocket);
qCDebug(lcSsl) << "QSslSocket::_q_errorSlot(" << error << ')';
qCDebug(lcSsl) << "\tstate =" << q->state();
qCDebug(lcSsl) << "\terrorString =" << q->errorString();
@@ -2416,9 +2413,7 @@ void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error)
readBufferMaxSize = tmpReadBufferMaxSize;
}
- q->setSocketError(plainSocket->error());
- q->setErrorString(plainSocket->errorString());
- emit q->error(error);
+ setErrorAndEmit(plainSocket->error(), plainSocket->errorString());
}
/*!
@@ -2483,7 +2478,6 @@ void QSslSocketPrivate::_q_flushReadBuffer()
*/
void QSslSocketPrivate::_q_resumeImplementation()
{
- Q_Q(QSslSocket);
if (plainSocket)
plainSocket->resume();
paused = false;
@@ -2491,9 +2485,7 @@ void QSslSocketPrivate::_q_resumeImplementation()
if (verifyErrorsHaveBeenIgnored()) {
continueHandshake();
} else {
- q->setErrorString(sslErrors.first().errorString());
- q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
- emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, sslErrors.first().errorString());
plainSocket->disconnectFromHost();
return;
}
diff --git a/src/network/ssl/qsslsocket.h b/src/network/ssl/qsslsocket.h
index 4124f5b7e5..22856c6ea9 100644
--- a/src/network/ssl/qsslsocket.h
+++ b/src/network/ssl/qsslsocket.h
@@ -72,7 +72,7 @@ public:
AutoVerifyPeer
};
- explicit QSslSocket(QObject *parent = 0);
+ explicit QSslSocket(QObject *parent = Q_NULLPTR);
~QSslSocket();
void resume() Q_DECL_OVERRIDE; // to continue after proxy authentication required, SSL errors etc.
diff --git a/src/network/ssl/qsslsocket_mac.cpp b/src/network/ssl/qsslsocket_mac.cpp
index aabae81eed..4e090f96cb 100644
--- a/src/network/ssl/qsslsocket_mac.cpp
+++ b/src/network/ssl/qsslsocket_mac.cpp
@@ -600,7 +600,7 @@ void QSslSocketBackendPrivate::startClientEncryption()
// Error description/code were set, 'error' emitted
// by initSslContext, but OpenSSL socket also sets error
// emits a signal twice, so ...
- setError("Unable to init SSL Context", QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError, "Unable to init SSL Context");
return;
}
@@ -613,7 +613,7 @@ void QSslSocketBackendPrivate::startServerEncryption()
// Error description/code were set, 'error' emitted
// by initSslContext, but OpenSSL socket also sets error
// emits a signal twice, so ...
- setError("Unable to init SSL Context", QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError, "Unable to init SSL Context");
return;
}
@@ -642,8 +642,8 @@ void QSslSocketBackendPrivate::transmit()
qCDebug(lcSsl) << plainSocket << "SSLWrite returned" << err;
#endif
if (err != noErr && err != errSSLWouldBlock) {
- setError(QStringLiteral("SSLWrite failed: %1").arg(err),
- QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QStringLiteral("SSLWrite failed: %1").arg(err));
break;
}
@@ -677,12 +677,12 @@ void QSslSocketBackendPrivate::transmit()
#endif
if (err == errSSLClosedGraceful) {
shutdown = true; // the other side shut down, make sure we do not send shutdown ourselves
- setError(QSslSocket::tr("The TLS/SSL connection has been closed"),
- QAbstractSocket::RemoteHostClosedError);
+ setErrorAndEmit(QAbstractSocket::RemoteHostClosedError,
+ QSslSocket::tr("The TLS/SSL connection has been closed"));
break;
} else if (err != noErr && err != errSSLWouldBlock) {
- setError(QStringLiteral("SSLRead failed: %1").arg(err),
- QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QStringLiteral("SSLRead failed: %1").arg(err));
break;
}
@@ -936,7 +936,7 @@ bool QSslSocketBackendPrivate::initSslContext()
context.reset(qt_createSecureTransportContext(mode));
if (!context) {
- setError("SSLCreateContext failed", QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError, "SSLCreateContext failed");
return false;
}
@@ -944,8 +944,8 @@ bool QSslSocketBackendPrivate::initSslContext()
reinterpret_cast<SSLWriteFunc>(&_q_SSLWrite));
if (err != noErr) {
destroySslContext();
- setError(QStringLiteral("SSLSetIOFuncs failed: %1").arg(err),
- QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QStringLiteral("SSLSetIOFuncs failed: %1").arg(err));
return false;
}
@@ -957,14 +957,14 @@ bool QSslSocketBackendPrivate::initSslContext()
QAbstractSocket::SocketError errorCode = QAbstractSocket::UnknownSocketError;
if (!setSessionCertificate(errorDescription, errorCode)) {
destroySslContext();
- setError(errorDescription, errorCode);
+ setErrorAndEmit(errorCode, errorDescription);
return false;
}
}
if (!setSessionProtocol()) {
destroySslContext();
- setError("Failed to set protocol version", QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError, "Failed to set protocol version");
return false;
}
@@ -976,8 +976,8 @@ bool QSslSocketBackendPrivate::initSslContext()
const OSStatus err = SSLSetEnableCertVerify(context, false);
if (err != noErr) {
destroySslContext();
- setError(QStringLiteral("SSLSetEnableCertVerify failed: %1").arg(err),
- QSslSocket::SslInternalError);
+ setErrorAndEmit(QSslSocket::SslInternalError,
+ QStringLiteral("SSLSetEnableCertVerify failed: %1").arg(err));
return false;
}
}
@@ -998,8 +998,8 @@ bool QSslSocketBackendPrivate::initSslContext()
if (err != noErr) {
destroySslContext();
- setError(QStringLiteral("SSLSetSessionOption failed: %1").arg(err),
- QSslSocket::SslInternalError);
+ setErrorAndEmit(QSslSocket::SslInternalError,
+ QStringLiteral("SSLSetSessionOption failed: %1").arg(err));
return false;
}
//
@@ -1015,8 +1015,8 @@ bool QSslSocketBackendPrivate::initSslContext()
if (err != noErr) {
destroySslContext();
- setError(QStringLiteral("failed to set SSL context option in server mode: %1").arg(err),
- QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QStringLiteral("failed to set SSL context option in server mode: %1").arg(err));
return false;
}
}
@@ -1192,8 +1192,8 @@ bool QSslSocketBackendPrivate::verifyPeerTrust()
// !trust - SSLCopyPeerTrust can return noErr but null trust.
if (err != noErr || !trust) {
if (!canIgnoreVerify) {
- setError(QStringLiteral("Failed to obtain peer trust: %1").arg(err),
- QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError,
+ QStringLiteral("Failed to obtain peer trust: %1").arg(err));
plainSocket->disconnectFromHost();
return false;
} else {
@@ -1216,8 +1216,8 @@ bool QSslSocketBackendPrivate::verifyPeerTrust()
if (err != noErr) {
// We can not ignore this, it's not even about trust verification
// probably ...
- setError(QStringLiteral("SecTrustEvaluate failed: %1").arg(err),
- QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError,
+ QStringLiteral("SecTrustEvaluate failed: %1").arg(err));
plainSocket->disconnectFromHost();
return false;
}
@@ -1335,8 +1335,8 @@ bool QSslSocketBackendPrivate::checkSslErrors()
pauseSocketNotifiers(q);
paused = true;
} else {
- setError(sslErrors.first().errorString(),
- QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError,
+ sslErrors.first().errorString());
plainSocket->disconnectFromHost();
}
return false;
@@ -1373,7 +1373,7 @@ bool QSslSocketBackendPrivate::startHandshake()
// setSessionCertificate does not fail if we have no certificate.
// Failure means a real error (invalid certificate, no private key, etc).
if (!setSessionCertificate(errorDescription, errorCode)) {
- setError(errorDescription, errorCode);
+ setErrorAndEmit(errorCode, errorDescription);
return false;
} else {
// We try to resume a handshake, even if have no
@@ -1388,8 +1388,8 @@ bool QSslSocketBackendPrivate::startHandshake()
return startHandshake();
}
- setError(QStringLiteral("SSLHandshake failed: %1").arg(err),
- QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError,
+ QStringLiteral("SSLHandshake failed: %1").arg(err));
plainSocket->disconnectFromHost();
return false;
}
@@ -1403,8 +1403,8 @@ bool QSslSocketBackendPrivate::startHandshake()
// check protocol version ourselves, as Secure Transport does not enforce
// the requested min / max versions.
if (!verifySessionProtocol()) {
- setError("Protocol version mismatch",
- QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError,
+ "Protocol version mismatch");
plainSocket->disconnectFromHost();
return false;
}
@@ -1417,16 +1417,6 @@ bool QSslSocketBackendPrivate::startHandshake()
}
}
-void QSslSocketBackendPrivate::setError(const QString &errorString,
- QAbstractSocket::SocketError errorCode)
-{
- Q_Q(QSslSocket);
-
- q->setErrorString(errorString);
- q->setSocketError(errorCode);
- emit q->error(errorCode);
-}
-
/*
PKCS12 helpers.
*/
diff --git a/src/network/ssl/qsslsocket_mac_p.h b/src/network/ssl/qsslsocket_mac_p.h
index 0479e30d97..7a622db185 100644
--- a/src/network/ssl/qsslsocket_mac_p.h
+++ b/src/network/ssl/qsslsocket_mac_p.h
@@ -113,13 +113,6 @@ private:
bool checkSslErrors();
bool startHandshake();
- // Aux. function, sets:
- //1) socket error code,
- //2) error string (description)
- //3) emits a signal.
- void setError(const QString &errorString,
- QAbstractSocket::SocketError errorCode);
-
QSecureTransportContext context;
Q_DISABLE_COPY(QSslSocketBackendPrivate);
diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp
index a21317d0f2..dd47dfc45f 100644
--- a/src/network/ssl/qsslsocket_openssl.cpp
+++ b/src/network/ssl/qsslsocket_openssl.cpp
@@ -225,7 +225,7 @@ QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *ciph
char buf [256];
QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
- QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
+ QStringList descriptionList = descriptionOneLine.split(QLatin1Char(' '), QString::SkipEmptyParts);
if (descriptionList.size() > 5) {
// ### crude code.
ciph.d->isNull = false;
@@ -290,7 +290,7 @@ int q_X509Callback(int ok, X509_STORE_CTX *ctx)
<< "OU=" << cert.subjectInfo(QSslCertificate::OrganizationalUnitName)
<< "C=" << cert.subjectInfo(QSslCertificate::CountryName)
<< "ST=" << cert.subjectInfo(QSslCertificate::StateOrProvinceName);
- qCDebug(lcSsl) << "Valid:" << cert.effectiveDate() << "-" << cert.expiryDate();
+ qCDebug(lcSsl) << "Valid:" << cert.effectiveDate() << '-' << cert.expiryDate();
}
#endif
}
@@ -344,6 +344,9 @@ long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, Q
options |= SSL_OP_NO_COMPRESSION;
#endif
+ if (!(sslOptions & QSsl::SslOptionDisableServerCipherPreference))
+ options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
+
return options;
}
@@ -361,9 +364,7 @@ bool QSslSocketBackendPrivate::initSslContext()
}
if (sslContextPointer->error() != QSslError::NoError) {
- q->setErrorString(sslContextPointer->errorString());
- q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
- emit q->error(QAbstractSocket::SslInvalidUserDataError);
+ setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
sslContextPointer.clear(); // deletes the QSslContext
return false;
}
@@ -371,9 +372,8 @@ bool QSslSocketBackendPrivate::initSslContext()
// Create and initialize SSL session
if (!(ssl = sslContextPointer->createSsl())) {
// ### Bad error code
- q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
return false;
}
@@ -402,9 +402,8 @@ bool QSslSocketBackendPrivate::initSslContext()
readBio = q_BIO_new(q_BIO_s_mem());
writeBio = q_BIO_new(q_BIO_s_mem());
if (!readBio || !writeBio) {
- q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
return false;
}
@@ -488,30 +487,8 @@ bool QSslSocketPrivate::ensureLibraryLoaded()
// Initialize OpenSSL's random seed.
if (!q_RAND_status()) {
- struct {
- int msec;
- int sec;
- void *stack;
- } randomish;
-
- int attempts = 500;
- do {
- if (attempts < 500) {
-#ifdef Q_OS_UNIX
- struct timespec ts = {0, 33333333};
- nanosleep(&ts, 0);
-#else
- Sleep(3);
-#endif
- randomish.msec = attempts;
- }
- randomish.stack = (void *)&randomish;
- randomish.msec = QTime::currentTime().msec();
- randomish.sec = QTime::currentTime().second();
- q_RAND_seed((const char *)&randomish, sizeof(randomish));
- } while (!q_RAND_status() && --attempts);
- if (!attempts)
- return false;
+ qWarning("Random number generator not seeded, disabling SSL support");
+ return false;
}
}
return true;
@@ -659,8 +636,10 @@ void QSslSocketPrivate::resetDefaultCiphers()
if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
if (!ciph.isNull()) {
- // Unconditionally exclude ADH ciphers since they offer no MITM protection
- if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
+ // Unconditionally exclude ADH and AECDH ciphers since they offer no MITM protection
+ if (!ciph.name().toLower().startsWith(QLatin1String("adh")) &&
+ !ciph.name().toLower().startsWith(QLatin1String("exp-adh")) &&
+ !ciph.name().toLower().startsWith(QLatin1String("aecdh")))
ciphers << ciph;
if (ciph.usedBits() >= 128)
defaultCiphers << ciph;
@@ -685,6 +664,7 @@ void QSslSocketPrivate::resetDefaultEllipticCurves()
QVarLengthArray<EC_builtin_curve> builtinCurves(static_cast<int>(curveCount));
if (q_EC_get_builtin_curves(builtinCurves.data(), curveCount) == curveCount) {
+ curves.reserve(int(curveCount));
for (size_t i = 0; i < curveCount; ++i) {
QSslEllipticCurve curve;
curve.id = builtinCurves[int(i)].nid;
@@ -824,11 +804,9 @@ QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
void QSslSocketBackendPrivate::startClientEncryption()
{
- Q_Q(QSslSocket);
if (!initSslContext()) {
- q->setErrorString(QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
return;
}
@@ -840,11 +818,9 @@ void QSslSocketBackendPrivate::startClientEncryption()
void QSslSocketBackendPrivate::startServerEncryption()
{
- Q_Q(QSslSocket);
if (!initSslContext()) {
- q->setErrorString(QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
return;
}
@@ -890,9 +866,9 @@ void QSslSocketBackendPrivate::transmit()
break;
} else {
// ### Better error handling.
- q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Unable to write data: %1").arg(
+ getErrorsFromOpenSsl()));
return;
}
}
@@ -934,9 +910,7 @@ void QSslSocketBackendPrivate::transmit()
#endif
if (actualWritten < 0) {
//plain socket write fails if it was in the pending close state.
- q->setErrorString(plainSocket->errorString());
- q->setSocketError(plainSocket->error());
- emit q->error(plainSocket->error());
+ setErrorAndEmit(plainSocket->error(), plainSocket->errorString());
return;
}
transmitting = true;
@@ -962,9 +936,9 @@ void QSslSocketBackendPrivate::transmit()
plainSocket->read(data.data(), writtenToBio);
} else {
// ### Better error handling.
- q->setErrorString(QSslSocket::tr("Unable to decrypt data: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Unable to decrypt data: %1").arg(
+ getErrorsFromOpenSsl()));
return;
}
@@ -1038,17 +1012,15 @@ void QSslSocketBackendPrivate::transmit()
qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: remote disconnect";
#endif
shutdown = true; // the other side shut down, make sure we do not send shutdown ourselves
- q->setErrorString(QSslSocket::tr("The TLS/SSL connection has been closed"));
- q->setSocketError(QAbstractSocket::RemoteHostClosedError);
- emit q->error(QAbstractSocket::RemoteHostClosedError);
+ setErrorAndEmit(QAbstractSocket::RemoteHostClosedError,
+ QSslSocket::tr("The TLS/SSL connection has been closed"));
return;
case SSL_ERROR_SYSCALL: // some IO error
case SSL_ERROR_SSL: // error in the SSL library
// we do not know exactly what the error is, nor whether we can recover from it,
// so just return to prevent an endless loop in the outer "while" statement
- q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
return;
default:
// SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
@@ -1056,9 +1028,8 @@ void QSslSocketBackendPrivate::transmit()
// SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
// SSL_CTX_set_client_cert_cb(), which we do not call.
// So this default case should never be triggered.
- q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
break;
}
} while (ssl && readBytes > 0);
@@ -1150,12 +1121,12 @@ bool QSslSocketBackendPrivate::startHandshake()
// The handshake is not yet complete.
break;
default:
- q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
- q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
+ QString errorString
+ = QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl());
#ifdef QSSLSOCKET_DEBUG
- qCDebug(lcSsl) << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
+ qCDebug(lcSsl) << "QSslSocketBackendPrivate::startHandshake: error!" << errorString;
#endif
- emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, errorString);
q->abort();
}
return false;
@@ -1213,7 +1184,9 @@ bool QSslSocketBackendPrivate::startHandshake()
}
// Translate errors from the error list into QSslErrors.
- for (int i = 0; i < errorList.size(); ++i) {
+ const int numErrors = errorList.size();
+ errors.reserve(errors.size() + numErrors);
+ for (int i = 0; i < numErrors; ++i) {
const QPair<int, int> &errorAndDepth = errorList.at(i);
int err = errorAndDepth.first;
int depth = errorAndDepth.second;
@@ -1304,9 +1277,7 @@ bool QSslSocketBackendPrivate::checkSslErrors()
pauseSocketNotifiers(q);
paused = true;
} else {
- q->setErrorString(sslErrors.first().errorString());
- q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
- emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, sslErrors.first().errorString());
plainSocket->disconnectFromHost();
}
return false;
@@ -1689,6 +1660,7 @@ QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &
setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
}
+ const QDateTime now = QDateTime::currentDateTimeUtc();
foreach (const QSslCertificate &caCertificate, QSslConfiguration::defaultConfiguration().caCertificates()) {
// From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html:
//
@@ -1701,7 +1673,7 @@ QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &
// certificates mixed with valid ones.
//
// See also: QSslContext::fromConfiguration()
- if (caCertificate.expiryDate() >= QDateTime::currentDateTime()) {
+ if (caCertificate.expiryDate() >= now) {
q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
}
}
@@ -1782,7 +1754,9 @@ QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &
}
// Translate errors from the error list into QSslErrors.
- for (int i = 0; i < errorList.size(); ++i) {
+ const int numErrors = errorList.size();
+ errors.reserve(errors.size() + numErrors);
+ for (int i = 0; i < numErrors; ++i) {
const QPair<int, int> &errorAndDepth = errorList.at(i);
int err = errorAndDepth.first;
int depth = errorAndDepth.second;
diff --git a/src/network/ssl/qsslsocket_openssl_symbols.cpp b/src/network/ssl/qsslsocket_openssl_symbols.cpp
index e2700df3cc..e7829bac90 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols.cpp
+++ b/src/network/ssl/qsslsocket_openssl_symbols.cpp
@@ -119,10 +119,13 @@ void qsslSocketUnresolvedSymbolWarning(const char *functionName)
qCWarning(lcSsl, "QSslSocket: cannot call unresolved function %s", functionName);
}
+#ifndef QT_NO_LIBRARY
void qsslSocketCannotResolveSymbolWarning(const char *functionName)
{
qCWarning(lcSsl, "QSslSocket: cannot resolve %s", functionName);
}
+#endif
+
}
#endif // QT_LINKED_OPENSSL
@@ -156,7 +159,16 @@ DEFINEFUNC3(X509 *, d2i_X509, X509 **a, a, const unsigned char **b, b, long c, c
DEFINEFUNC2(char *, ERR_error_string, unsigned long a, a, char *b, b, return 0, return)
DEFINEFUNC(unsigned long, ERR_get_error, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(void, ERR_free_strings, void, DUMMYARG, return, DUMMYARG)
+DEFINEFUNC(void, EVP_CIPHER_CTX_cleanup, EVP_CIPHER_CTX *a, a, return, DUMMYARG)
+DEFINEFUNC(void, EVP_CIPHER_CTX_init, EVP_CIPHER_CTX *a, a, return, DUMMYARG)
+DEFINEFUNC4(int, EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX *ctx, ctx, int type, type, int arg, arg, void *ptr, ptr, return 0, return);
+DEFINEFUNC2(int, EVP_CIPHER_CTX_set_key_length, EVP_CIPHER_CTX *ctx, ctx, int keylen, keylen, return 0, return)
+DEFINEFUNC5(int, EVP_CipherInit, EVP_CIPHER_CTX *ctx, ctx, const EVP_CIPHER *type, type, const unsigned char *key, key, const unsigned char *iv, iv, int enc, enc, return 0, return);
+DEFINEFUNC5(int, EVP_CipherUpdate, EVP_CIPHER_CTX *ctx, ctx, unsigned char *out, out, int *outl, outl, const unsigned char *in, in, int inl, inl, return 0, return);
+DEFINEFUNC3(int, EVP_CipherFinal, EVP_CIPHER_CTX *ctx, ctx, unsigned char *out, out, int *outl, outl, return 0, return);
+DEFINEFUNC(const EVP_CIPHER *, EVP_des_cbc, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(const EVP_CIPHER *, EVP_des_ede3_cbc, DUMMYARG, DUMMYARG, return 0, return)
+DEFINEFUNC(const EVP_CIPHER *, EVP_rc2_cbc, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC3(int, EVP_PKEY_assign, EVP_PKEY *a, a, int b, b, char *c, c, return -1, return)
DEFINEFUNC2(int, EVP_PKEY_set1_RSA, EVP_PKEY *a, a, RSA *b, b, return -1, return)
DEFINEFUNC2(int, EVP_PKEY_set1_DSA, EVP_PKEY *a, a, DSA *b, b, return -1, return)
@@ -309,13 +321,17 @@ DEFINEFUNC(const SSL_METHOD *, TLSv1_1_server_method, DUMMYARG, DUMMYARG, return
DEFINEFUNC(const SSL_METHOD *, TLSv1_2_server_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
#else
+#ifndef OPENSSL_NO_SSL2
DEFINEFUNC(SSL_METHOD *, SSLv2_client_method, DUMMYARG, DUMMYARG, return 0, return)
+#endif
#ifndef OPENSSL_NO_SSL3_METHOD
DEFINEFUNC(SSL_METHOD *, SSLv3_client_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
DEFINEFUNC(SSL_METHOD *, SSLv23_client_method, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(SSL_METHOD *, TLSv1_client_method, DUMMYARG, DUMMYARG, return 0, return)
+#ifndef OPENSSL_NO_SSL2
DEFINEFUNC(SSL_METHOD *, SSLv2_server_method, DUMMYARG, DUMMYARG, return 0, return)
+#endif
#ifndef OPENSSL_NO_SSL3_METHOD
DEFINEFUNC(SSL_METHOD *, SSLv3_server_method, DUMMYARG, DUMMYARG, return 0, return)
#endif
@@ -436,39 +452,41 @@ bool q_resolveOpenSslSymbols()
#else
# ifdef Q_OS_UNIX
-static bool libGreaterThan(const QString &lhs, const QString &rhs)
+struct NumericallyLess
{
- QStringList lhsparts = lhs.split(QLatin1Char('.'));
- QStringList rhsparts = rhs.split(QLatin1Char('.'));
- Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);
-
- for (int i = 1; i < rhsparts.count(); ++i) {
- if (lhsparts.count() <= i)
- // left hand side is shorter, so it's less than rhs
- return false;
-
+ typedef bool result_type;
+ result_type operator()(const QStringRef &lhs, const QStringRef &rhs) const
+ {
bool ok = false;
int b = 0;
- int a = lhsparts.at(i).toInt(&ok);
+ int a = lhs.toInt(&ok);
if (ok)
- b = rhsparts.at(i).toInt(&ok);
+ b = rhs.toInt(&ok);
if (ok) {
// both toInt succeeded
- if (a == b)
- continue;
- return a > b;
+ return a < b;
} else {
// compare as strings;
- if (lhsparts.at(i) == rhsparts.at(i))
- continue;
- return lhsparts.at(i) > rhsparts.at(i);
+ return lhs < rhs;
}
}
+};
- // they compared strictly equally so far
- // lhs cannot be less than rhs
- return true;
-}
+struct LibGreaterThan
+{
+ typedef bool result_type;
+ result_type operator()(const QString &lhs, const QString &rhs) const
+ {
+ const QVector<QStringRef> lhsparts = lhs.splitRef(QLatin1Char('.'));
+ const QVector<QStringRef> rhsparts = rhs.splitRef(QLatin1Char('.'));
+ Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);
+
+ // note: checking rhs < lhs, the same as lhs > rhs
+ return std::lexicographical_compare(rhsparts.begin() + 1, rhsparts.end(),
+ lhsparts.begin() + 1, lhsparts.end(),
+ NumericallyLess());
+ }
+};
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
static int dlIterateCallback(struct dl_phdr_info *info, size_t size, void *data)
@@ -522,39 +540,33 @@ static QStringList libraryPathList()
return paths;
}
-
-static QStringList findAllLibSsl()
+Q_NEVER_INLINE
+static QStringList findAllLibs(QLatin1String filter)
{
QStringList paths = libraryPathList();
- QStringList foundSsls;
+ QStringList found;
+ const QStringList filters((QString(filter)));
foreach (const QString &path, paths) {
QDir dir(path);
- QStringList entryList = dir.entryList(QStringList() << QLatin1String("libssl.*"), QDir::Files);
+ QStringList entryList = dir.entryList(filters, QDir::Files);
- std::sort(entryList.begin(), entryList.end(), libGreaterThan);
+ std::sort(entryList.begin(), entryList.end(), LibGreaterThan());
foreach (const QString &entry, entryList)
- foundSsls << path + QLatin1Char('/') + entry;
+ found << path + QLatin1Char('/') + entry;
}
- return foundSsls;
+ return found;
}
-static QStringList findAllLibCrypto()
+static QStringList findAllLibSsl()
{
- QStringList paths = libraryPathList();
-
- QStringList foundCryptos;
- foreach (const QString &path, paths) {
- QDir dir(path);
- QStringList entryList = dir.entryList(QStringList() << QLatin1String("libcrypto.*"), QDir::Files);
-
- std::sort(entryList.begin(), entryList.end(), libGreaterThan);
- foreach (const QString &entry, entryList)
- foundCryptos << path + QLatin1Char('/') + entry;
- }
+ return findAllLibs(QLatin1String("libssl.*"));
+}
- return foundCryptos;
+static QStringList findAllLibCrypto()
+{
+ return findAllLibs(QLatin1String("libcrypto.*"));
}
# endif
@@ -759,7 +771,16 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(ERR_error_string)
RESOLVEFUNC(ERR_get_error)
RESOLVEFUNC(ERR_free_strings)
+ RESOLVEFUNC(EVP_CIPHER_CTX_cleanup)
+ RESOLVEFUNC(EVP_CIPHER_CTX_init)
+ RESOLVEFUNC(EVP_CIPHER_CTX_ctrl)
+ RESOLVEFUNC(EVP_CIPHER_CTX_set_key_length)
+ RESOLVEFUNC(EVP_CipherInit)
+ RESOLVEFUNC(EVP_CipherUpdate)
+ RESOLVEFUNC(EVP_CipherFinal)
+ RESOLVEFUNC(EVP_des_cbc)
RESOLVEFUNC(EVP_des_ede3_cbc)
+ RESOLVEFUNC(EVP_rc2_cbc)
RESOLVEFUNC(EVP_PKEY_assign)
RESOLVEFUNC(EVP_PKEY_set1_RSA)
RESOLVEFUNC(EVP_PKEY_set1_DSA)
diff --git a/src/network/ssl/qsslsocket_openssl_symbols_p.h b/src/network/ssl/qsslsocket_openssl_symbols_p.h
index 626c049629..7f87f11b7c 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols_p.h
+++ b/src/network/ssl/qsslsocket_openssl_symbols_p.h
@@ -235,7 +235,16 @@ X509 *q_d2i_X509(X509 **a, const unsigned char **b, long c);
char *q_ERR_error_string(unsigned long a, char *b);
unsigned long q_ERR_get_error();
void q_ERR_free_strings();
+void q_EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a);
+void q_EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a);
+int q_EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
+int q_EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
+int q_EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, const unsigned char *key, const unsigned char *iv, int enc);
+int q_EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl);
+int q_EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
+const EVP_CIPHER *q_EVP_des_cbc();
const EVP_CIPHER *q_EVP_des_ede3_cbc();
+const EVP_CIPHER *q_EVP_rc2_cbc();
int q_EVP_PKEY_assign(EVP_PKEY *a, int b, char *c);
Q_AUTOTEST_EXPORT int q_EVP_PKEY_set1_RSA(EVP_PKEY *a, RSA *b);
int q_EVP_PKEY_set1_DSA(EVP_PKEY *a, DSA *b);
@@ -363,27 +372,43 @@ typedef unsigned int (*q_psk_client_callback_t)(SSL *ssl, const char *hint, char
void q_SSL_set_psk_client_callback(SSL *ssl, q_psk_client_callback_t callback);
#endif // OPENSSL_NO_PSK
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+#ifndef OPENSSL_NO_SSL2
const SSL_METHOD *q_SSLv2_client_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *q_SSLv3_client_method();
+#endif
const SSL_METHOD *q_SSLv23_client_method();
const SSL_METHOD *q_TLSv1_client_method();
const SSL_METHOD *q_TLSv1_1_client_method();
const SSL_METHOD *q_TLSv1_2_client_method();
+#ifndef OPENSSL_NO_SSL2
const SSL_METHOD *q_SSLv2_server_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *q_SSLv3_server_method();
+#endif
const SSL_METHOD *q_SSLv23_server_method();
const SSL_METHOD *q_TLSv1_server_method();
const SSL_METHOD *q_TLSv1_1_server_method();
const SSL_METHOD *q_TLSv1_2_server_method();
#else
+#ifndef OPENSSL_NO_SSL2
SSL_METHOD *q_SSLv2_client_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
SSL_METHOD *q_SSLv3_client_method();
+#endif
SSL_METHOD *q_SSLv23_client_method();
SSL_METHOD *q_TLSv1_client_method();
SSL_METHOD *q_TLSv1_1_client_method();
SSL_METHOD *q_TLSv1_2_client_method();
+#ifndef OPENSSL_NO_SSL2
SSL_METHOD *q_SSLv2_server_method();
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
SSL_METHOD *q_SSLv3_server_method();
+#endif
SSL_METHOD *q_SSLv23_server_method();
SSL_METHOD *q_TLSv1_server_method();
SSL_METHOD *q_TLSv1_1_server_method();
diff --git a/src/network/ssl/qsslsocket_winrt.cpp b/src/network/ssl/qsslsocket_winrt.cpp
index aba3ea8170..b03f234d49 100644
--- a/src/network/ssl/qsslsocket_winrt.cpp
+++ b/src/network/ssl/qsslsocket_winrt.cpp
@@ -251,9 +251,8 @@ void QSslSocketBackendPrivate::startClientEncryption()
case QSsl::TlsV1_2OrLater:
// TlsV1_0OrLater, TlsV1_1OrLater and TlsV1_2OrLater are disabled on WinRT
// because there is no good way to map them to the native API.
- q->setErrorString(QStringLiteral("unsupported protocol"));
- q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
- emit q->error(QAbstractSocket::SslInvalidUserDataError);
+ setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
+ QStringLiteral("unsupported protocol"));
return;
default:
protectionLevel = SocketProtectionLevel_Tls12; // default to highest
@@ -347,13 +346,10 @@ QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
void QSslSocketBackendPrivate::continueHandshake()
{
- Q_Q(QSslSocket);
-
IStreamSocket *socket = reinterpret_cast<IStreamSocket *>(plainSocket->socketDescriptor());
if (qintptr(socket) == -1) {
- q->setErrorString(QStringLiteral("At attempt was made to continue the handshake on an invalid socket."));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QStringLiteral("At attempt was made to continue the handshake on an invalid socket."));
return;
}
@@ -372,9 +368,7 @@ void QSslSocketBackendPrivate::continueHandshake()
Q_ASSERT_SUCCEEDED(hr);
}
if (FAILED(hr)) {
- q->setErrorString(qt_error_string(hr));
- q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
- emit q->error(QAbstractSocket::SslInvalidUserDataError);
+ setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError, qt_error_string(hr));
return;
}
@@ -440,10 +434,8 @@ void QSslSocketBackendPrivate::continueHandshake()
ComPtr<IAsyncAction> op;
hr = socket->UpgradeToSslAsync(protectionLevel, hostName.Get(), &op);
if (FAILED(hr)) {
- q->setErrorString(QSslSocket::tr("Error creating SSL session: %1")
- .arg(qt_error_string(hr)));
- q->setSocketError(QAbstractSocket::SslInternalError);
- emit q->error(QAbstractSocket::SslInternalError);
+ setErrorAndEmit(QAbstractSocket::SslInternalError,
+ QSslSocket::tr("Error creating SSL session: %1").arg(qt_error_string(hr)));
return;
}
@@ -467,9 +459,7 @@ HRESULT QSslSocketBackendPrivate::onSslUpgrade(IAsyncAction *action, AsyncStatus
QSet<QSslError> errors;
switch (hr) {
case SEC_E_INVALID_TOKEN: // Occurs when the server doesn't support the requested protocol
- q->setErrorString(qt_error_string(hr));
- q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
- emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, qt_error_string(hr));
q->disconnectFromHost();
return S_OK;
default:
@@ -628,9 +618,7 @@ HRESULT QSslSocketBackendPrivate::onSslUpgrade(IAsyncAction *action, AsyncStatus
if (!sslErrors.isEmpty()) {
emit q->sslErrors(sslErrors);
- q->setErrorString(sslErrors.first().errorString());
- q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
- emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, sslErrors.first().errorString());
// Disconnect if there are any non-ignorable errors
foreach (const QSslError &error, sslErrors) {