summaryrefslogtreecommitdiffstats
path: root/src/network/socket
diff options
context:
space:
mode:
Diffstat (limited to 'src/network/socket')
-rw-r--r--src/network/socket/qabstractsocket.cpp265
-rw-r--r--src/network/socket/qabstractsocket.h70
-rw-r--r--src/network/socket/qabstractsocket_p.h86
-rw-r--r--src/network/socket/qabstractsocketengine.cpp42
-rw-r--r--src/network/socket/qabstractsocketengine_p.h60
-rw-r--r--src/network/socket/qhttpsocketengine.cpp166
-rw-r--r--src/network/socket/qhttpsocketengine_p.h61
-rw-r--r--src/network/socket/qlocalserver.cpp120
-rw-r--r--src/network/socket/qlocalserver.h55
-rw-r--r--src/network/socket/qlocalserver_p.h45
-rw-r--r--src/network/socket/qlocalserver_tcp.cpp56
-rw-r--r--src/network/socket/qlocalserver_unix.cpp174
-rw-r--r--src/network/socket/qlocalserver_win.cpp79
-rw-r--r--src/network/socket/qlocalsocket.cpp111
-rw-r--r--src/network/socket/qlocalsocket.h62
-rw-r--r--src/network/socket/qlocalsocket_p.h65
-rw-r--r--src/network/socket/qlocalsocket_tcp.cpp69
-rw-r--r--src/network/socket/qlocalsocket_unix.cpp216
-rw-r--r--src/network/socket/qlocalsocket_win.cpp387
-rw-r--r--src/network/socket/qnativesocketengine.cpp108
-rw-r--r--src/network/socket/qnativesocketengine_p.h266
-rw-r--r--src/network/socket/qnativesocketengine_p_p.h189
-rw-r--r--src/network/socket/qnativesocketengine_unix.cpp179
-rw-r--r--src/network/socket/qnativesocketengine_win.cpp178
-rw-r--r--src/network/socket/qnet_unix_p.h51
-rw-r--r--src/network/socket/qsctpserver.cpp42
-rw-r--r--src/network/socket/qsctpserver.h42
-rw-r--r--src/network/socket/qsctpserver_p.h40
-rw-r--r--src/network/socket/qsctpsocket.cpp49
-rw-r--r--src/network/socket/qsctpsocket.h42
-rw-r--r--src/network/socket/qsctpsocket_p.h40
-rw-r--r--src/network/socket/qsocks5socketengine.cpp207
-rw-r--r--src/network/socket/qsocks5socketengine_p.h65
-rw-r--r--src/network/socket/qtcpserver.cpp125
-rw-r--r--src/network/socket/qtcpserver.h44
-rw-r--r--src/network/socket/qtcpserver_p.h44
-rw-r--r--src/network/socket/qtcpsocket.cpp48
-rw-r--r--src/network/socket/qtcpsocket.h48
-rw-r--r--src/network/socket/qtcpsocket_p.h40
-rw-r--r--src/network/socket/qudpsocket.cpp48
-rw-r--r--src/network/socket/qudpsocket.h47
-rw-r--r--src/network/socket/socket.pri84
42 files changed, 1650 insertions, 2565 deletions
diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp
index f3885a22fe..e456d00713 100644
--- a/src/network/socket/qabstractsocket.cpp
+++ b/src/network/socket/qabstractsocket.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QABSTRACTSOCKET_DEBUG
@@ -209,8 +173,9 @@
parameter describes the type of error that occurred.
When this signal is emitted, the socket may not be ready for a reconnect
- attempt. In that case, attempts to reconnect should be done from the event
- loop. For example, use a QTimer::singleShot() with 0 as the timeout.
+ attempt. In that case, attempts to reconnect should be done from the
+ event loop. For example, use QChronoTimer::singleShot() with 0ns as
+ the timeout.
QAbstractSocket::SocketError is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
@@ -430,7 +395,7 @@
\value DontShareAddress Bind the address and port exclusively, so that
no other services are allowed to rebind. By passing this option to
- QAbstractSocket::bind(), you are guaranteed that on successs, your service
+ QAbstractSocket::bind(), you are guaranteed that on success, your service
is the only one that listens to the address and port. No services are
allowed to rebind, even if they pass ReuseAddressHint. This option
provides more security than ShareAddress, but on certain operating
@@ -475,7 +440,7 @@
#include <qmetaobject.h>
#include <qpointer.h>
#include <qtimer.h>
-#include <qelapsedtimer.h>
+#include <qdeadlinetimer.h>
#include <qscopedvaluerollback.h>
#include <qvarlengtharray.h>
@@ -483,6 +448,7 @@
#ifdef QABSTRACTSOCKET_DEBUG
#include <qdebug.h>
+#include <private/qdebug_p.h>
#endif
#include <time.h>
@@ -499,43 +465,13 @@
QT_BEGIN_NAMESPACE
-static const int DefaultConnectTimeout = 30000;
-
-#if defined QABSTRACTSOCKET_DEBUG
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qstring.h>
-#include <ctype.h>
-QT_END_INCLUDE_NAMESPACE
-
-/*
- Returns a human readable representation of the first \a len
- characters in \a data.
-*/
-static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
-{
- if (!data) return "(null)";
- QByteArray out;
- for (int i = 0; i < qMin(len, maxLength); ++i) {
- char c = data[i];
- if (isprint(int(uchar(c)))) {
- out += c;
- } else switch (c) {
- case '\n': out += "\\n"; break;
- case '\r': out += "\\r"; break;
- case '\t': out += "\\t"; break;
- default:
- QString tmp;
- tmp.sprintf("\\%o", c);
- out += tmp.toLatin1();
- }
- }
+using namespace Qt::StringLiterals;
+using namespace std::chrono_literals;
- if (len < maxLength)
- out += "...";
+QT_IMPL_METATYPE_EXTERN_TAGGED(QAbstractSocket::SocketState, QAbstractSocket__SocketState)
+QT_IMPL_METATYPE_EXTERN_TAGGED(QAbstractSocket::SocketError, QAbstractSocket__SocketError)
- return out;
-}
-#endif
+static constexpr auto DefaultConnectTimeout = 30s;
static bool isProxyError(QAbstractSocket::SocketError error)
{
@@ -557,25 +493,6 @@ static bool isProxyError(QAbstractSocket::SocketError error)
Constructs a QAbstractSocketPrivate. Initializes all members.
*/
QAbstractSocketPrivate::QAbstractSocketPrivate()
- : emittedReadyRead(false),
- emittedBytesWritten(false),
- abortCalled(false),
- pendingClose(false),
- pauseMode(QAbstractSocket::PauseNever),
- port(0),
- localPort(0),
- peerPort(0),
- socketEngine(nullptr),
- cachedSocketDescriptor(-1),
- readBufferMaxSize(0),
- isBuffered(false),
- hasPendingData(false),
- connectTimer(nullptr),
- hostLookupId(-1),
- socketType(QAbstractSocket::UnknownSocketType),
- state(QAbstractSocket::UnconnectedState),
- socketError(QAbstractSocket::UnknownSocketError),
- preferredNetworkLayerProtocol(QAbstractSocket::UnknownNetworkLayerProtocol)
{
writeBufferChunkSize = QABSTRACTSOCKET_BUFFERSIZE;
}
@@ -627,14 +544,14 @@ bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtoc
Q_Q(QAbstractSocket);
#if defined (QABSTRACTSOCKET_DEBUG)
QString typeStr;
- if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
- else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
- else if (q->socketType() == QAbstractSocket::SctpSocket) typeStr = QLatin1String("SctpSocket");
- else typeStr = QLatin1String("UnknownSocketType");
+ if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = "TcpSocket"_L1;
+ else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = "UdpSocket"_L1;
+ else if (q->socketType() == QAbstractSocket::SctpSocket) typeStr = "SctpSocket"_L1;
+ else typeStr = "UnknownSocketType"_L1;
QString protocolStr;
- if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
- else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
- else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
+ if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = "IPv4Protocol"_L1;
+ else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = "IPv6Protocol"_L1;
+ else protocolStr = "UnknownNetworkLayerProtocol"_L1;
#endif
resetSocketLayer();
@@ -721,11 +638,19 @@ bool QAbstractSocketPrivate::canReadNotification()
return !q->isReadable();
}
} else {
- if (hasPendingData) {
+ const bool isUdpSocket = (socketType == QAbstractSocket::UdpSocket);
+ if (hasPendingData && (!isUdpSocket || hasPendingDatagram)) {
socketEngine->setReadNotificationEnabled(false);
return true;
}
- hasPendingData = true;
+ if (!isUdpSocket
+#if QT_CONFIG(udpsocket)
+ || socketEngine->hasPendingDatagrams()
+#endif
+ ) {
+ hasPendingData = true;
+ hasPendingDatagram = isUdpSocket;
+ }
}
emitReadyRead();
@@ -921,7 +846,7 @@ void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
}
// return the first that we can use
- for (const QNetworkProxy &p : qAsConst(proxies)) {
+ for (const QNetworkProxy &p : std::as_const(proxies)) {
if (socketType == QAbstractSocket::UdpSocket &&
(p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
continue;
@@ -1020,12 +945,12 @@ void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
#if defined(QABSTRACTSOCKET_DEBUG)
- QString s = QLatin1String("{");
+ QString s = "{"_L1;
for (int i = 0; i < addresses.count(); ++i) {
- if (i != 0) s += QLatin1String(", ");
+ if (i != 0) s += ", "_L1;
s += addresses.at(i).toString();
}
- s += QLatin1Char('}');
+ s += u'}';
qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
#endif
@@ -1142,8 +1067,7 @@ void QAbstractSocketPrivate::_q_connectToNextAddress()
q, SLOT(_q_abortConnectionAttempt()),
Qt::DirectConnection);
}
- int connectTimeout = DefaultConnectTimeout;
- connectTimer->start(connectTimeout);
+ connectTimer->start(DefaultConnectTimeout);
}
// Wait for a write notification that will eventually call
@@ -1381,12 +1305,29 @@ void QAbstractSocketPrivate::pauseSocketNotifiers(QAbstractSocket *socket)
QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
if (!socketEngine)
return;
- socket->d_func()->prePauseReadSocketNotifierState = socketEngine->isReadNotificationEnabled();
- socket->d_func()->prePauseWriteSocketNotifierState = socketEngine->isWriteNotificationEnabled();
- socket->d_func()->prePauseExceptionSocketNotifierState = socketEngine->isExceptionNotificationEnabled();
- socketEngine->setReadNotificationEnabled(false);
- socketEngine->setWriteNotificationEnabled(false);
- socketEngine->setExceptionNotificationEnabled(false);
+ bool read = socketEngine->isReadNotificationEnabled();
+ bool write = socketEngine->isWriteNotificationEnabled();
+ bool except = socketEngine->isExceptionNotificationEnabled();
+
+#ifdef QABSTRACTSOCKET_DEBUG
+ qDebug() << socketEngine->socketDescriptor()
+ << "pause notifiers, storing 'true' states, currently read:" << read
+ << "write:" << write << "except:" << except;
+#endif
+ // We do this if-check to avoid accidentally overwriting any previously stored state
+ // It will reset to false once the socket is re-enabled.
+ if (read) {
+ socket->d_func()->prePauseReadSocketNotifierState = true;
+ socketEngine->setReadNotificationEnabled(false);
+ }
+ if (write) {
+ socket->d_func()->prePauseWriteSocketNotifierState = true;
+ socketEngine->setWriteNotificationEnabled(false);
+ }
+ if (except) {
+ socket->d_func()->prePauseExceptionSocketNotifierState = true;
+ socketEngine->setExceptionNotificationEnabled(false);
+ }
}
void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
@@ -1394,9 +1335,19 @@ void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
if (!socketEngine)
return;
- socketEngine->setReadNotificationEnabled(socket->d_func()->prePauseReadSocketNotifierState);
- socketEngine->setWriteNotificationEnabled(socket->d_func()->prePauseWriteSocketNotifierState);
- socketEngine->setExceptionNotificationEnabled(socket->d_func()->prePauseExceptionSocketNotifierState);
+ QAbstractSocketPrivate *priv = socket->d_func();
+#ifdef QABSTRACTSOCKET_DEBUG
+ qDebug() << socketEngine->socketDescriptor()
+ << "Maybe resume notifiers, read:" << priv->prePauseReadSocketNotifierState
+ << "write:" << priv->prePauseWriteSocketNotifierState
+ << "exception:" << priv->prePauseExceptionSocketNotifierState;
+#endif
+ if (std::exchange(priv->prePauseReadSocketNotifierState, false))
+ socketEngine->setReadNotificationEnabled(true);
+ if (std::exchange(priv->prePauseWriteSocketNotifierState, false))
+ socketEngine->setWriteNotificationEnabled(true);
+ if (std::exchange(priv->prePauseExceptionSocketNotifierState, false))
+ socketEngine->setExceptionNotificationEnabled(true);
}
QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *socket)
@@ -1604,6 +1555,19 @@ bool QAbstractSocketPrivate::bind(const QHostAddress &address, quint16 port, QAb
}
/*!
+ \fn bool QAbstractSocket::bind(QHostAddress::SpecialAddress addr, quint16 port, BindMode mode)
+ \since 6.2
+ \overload
+
+ Binds to the special address \a addr on port \a port, using the BindMode \a
+ mode.
+
+ By default, the socket is bound using the DefaultForPlatform BindMode.
+ If a port is not specified, a random port is chosen.
+*/
+
+/*!
+ \fn bool QAbstractSocket::bind(quint16 port, BindMode mode)
\since 5.0
\overload
@@ -1612,10 +1576,12 @@ bool QAbstractSocketPrivate::bind(const QHostAddress &address, quint16 port, QAb
By default, the socket is bound using the DefaultForPlatform BindMode.
If a port is not specified, a random port is chosen.
*/
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
bool QAbstractSocket::bind(quint16 port, BindMode mode)
{
return bind(QHostAddress::Any, port, mode);
}
+#endif
/*!
Returns \c true if the socket is valid and ready for use; otherwise
@@ -1958,8 +1924,9 @@ bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState
\since 4.6
Sets the given \a option to the value described by \a value.
- \note On Windows Runtime, QAbstractSocket::KeepAliveOption must be set
- before the socket is connected.
+ \note Since the options are set on an internal socket the options
+ only apply if the socket has been created. This is only guaranteed to
+ have happened after a call to bind(), or when connected() has been emitted.
\sa socketOption()
*/
@@ -2094,8 +2061,7 @@ bool QAbstractSocket::waitForConnected(int msecs)
bool wasPendingClose = d->pendingClose;
d->pendingClose = false;
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QDeadlineTimer deadline{msecs};
if (d->state == HostLookupState) {
#if defined (QABSTRACTSOCKET_DEBUG)
@@ -2115,22 +2081,21 @@ bool QAbstractSocket::waitForConnected(int msecs)
if (state() == UnconnectedState)
return false; // connect not im progress anymore!
- int connectTimeout = DefaultConnectTimeout;
bool timedOut = true;
#if defined (QABSTRACTSOCKET_DEBUG)
int attempt = 1;
#endif
- while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
- int timeout = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
- if (msecs != -1 && timeout > connectTimeout)
- timeout = connectTimeout;
+ while (state() == ConnectingState && !deadline.hasExpired()) {
+ QDeadlineTimer timer = deadline;
+ if (!deadline.isForever() && deadline.remainingTimeAsDuration() > DefaultConnectTimeout)
+ timer = QDeadlineTimer(DefaultConnectTimeout);
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
- msecs, timeout / 1000.0, attempt++);
+ msecs, timer.remainingTime() / 1000.0, attempt++);
#endif
timedOut = false;
- if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
+ if (d->socketEngine && d->socketEngine->waitForWrite(timer, &timedOut) && !timedOut) {
d->_q_testConnection();
} else {
d->_q_connectToNextAddress();
@@ -2185,8 +2150,7 @@ bool QAbstractSocket::waitForReadyRead(int msecs)
return false;
}
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QDeadlineTimer deadline{msecs};
// handle a socket in connecting state
if (state() == HostLookupState || state() == ConnectingState) {
@@ -2197,11 +2161,12 @@ bool QAbstractSocket::waitForReadyRead(int msecs)
do {
if (state() != ConnectedState && state() != BoundState)
return false;
+ Q_ASSERT(d->socketEngine);
bool readyToRead = false;
bool readyToWrite = false;
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
- qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ deadline)) {
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
@@ -2219,7 +2184,7 @@ bool QAbstractSocket::waitForReadyRead(int msecs)
if (readyToWrite)
d->canWriteNotification();
- } while (msecs == -1 || qt_subtract_from_timeout(msecs, stopWatch.elapsed()) > 0);
+ } while (!deadline.hasExpired());
return false;
}
@@ -2255,8 +2220,7 @@ bool QAbstractSocket::waitForBytesWritten(int msecs)
if (d->writeBuffer.isEmpty())
return false;
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QDeadlineTimer deadline{msecs};
// handle a socket in connecting state
if (state() == HostLookupState || state() == ConnectingState) {
@@ -2264,13 +2228,13 @@ bool QAbstractSocket::waitForBytesWritten(int msecs)
return false;
}
- forever {
+ for (;;) {
bool readyToRead = false;
bool readyToWrite = false;
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite,
!d->readBufferMaxSize || d->buffer.size() < d->readBufferMaxSize,
!d->writeBuffer.isEmpty(),
- qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ deadline)) {
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
@@ -2334,8 +2298,7 @@ bool QAbstractSocket::waitForDisconnected(int msecs)
return false;
}
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QDeadlineTimer deadline{msecs};
// handle a socket in connecting state
if (state() == HostLookupState || state() == ConnectingState) {
@@ -2345,12 +2308,12 @@ bool QAbstractSocket::waitForDisconnected(int msecs)
return true;
}
- forever {
+ for (;;) {
bool readyToRead = false;
bool readyToWrite = false;
if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
!d->writeBuffer.isEmpty(),
- qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ deadline)) {
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
@@ -2443,9 +2406,8 @@ qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
}
#if defined (QABSTRACTSOCKET_DEBUG)
- qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
- data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
- readBytes);
+ qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]", data,
+ QtDebugUtils::toPrintable(data, readBytes, 32).constData(), maxSize, readBytes);
#endif
return readBytes;
}
@@ -2483,8 +2445,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
- qt_prettyDebug(data, qMin((int)size, 32), size).data(),
- size, written);
+ QtDebugUtils::toPrintable(data, size, 32).constData(), size, written);
#endif
return written; // written = actually written + what has been buffered
} else if (!d->isBuffered && d->socketType != TcpSocket) {
@@ -2495,8 +2456,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
- qt_prettyDebug(data, qMin((int)size, 32), size).data(),
- size, written);
+ QtDebugUtils::toPrintable(data, size, 32).constData(), size, written);
#endif
if (written >= 0)
d->emitBytesWritten(written);
@@ -2517,8 +2477,7 @@ qint64 QAbstractSocket::writeData(const char *data, qint64 size)
#if defined (QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
- qt_prettyDebug(data, qMin((int)size, 32), size).data(),
- size, written);
+ QtDebugUtils::toPrintable(data, size, 32).constData(), size, written);
#endif
return written;
}
diff --git a/src/network/socket/qabstractsocket.h b/src/network/socket/qabstractsocket.h
index bf1ff7e9a2..1d5d45096a 100644
--- a/src/network/socket/qabstractsocket.h
+++ b/src/network/socket/qabstractsocket.h
@@ -1,46 +1,16 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QABSTRACTSOCKET_H
#define QABSTRACTSOCKET_H
#include <QtNetwork/qtnetworkglobal.h>
+#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
+#include <QtNetwork/qabstractsocket.h>
+#endif
+#ifdef Q_QDOC
+#include <QtNetwork/qhostaddress.h>
+#endif
#include <QtCore/qiodevice.h>
#include <QtCore/qobject.h>
#ifndef QT_NO_DEBUG_STREAM
@@ -70,6 +40,8 @@ public:
UnknownSocketType = -1
};
Q_ENUM(SocketType)
+
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
enum NetworkLayerProtocol {
IPv4Protocol,
IPv6Protocol,
@@ -77,6 +49,15 @@ public:
UnknownNetworkLayerProtocol = -1
};
Q_ENUM(NetworkLayerProtocol)
+#else
+ // compatibility with Qt 4 to 6
+ using NetworkLayerProtocol = QHostAddress::NetworkLayerProtocol;
+ static constexpr auto IPv4Protocol = QHostAddress::IPv4Protocol;
+ static constexpr auto IPv6Protocol = QHostAddress::IPv6Protocol;
+ static constexpr auto AnyIPProtocol = QHostAddress::AnyIPProtocol;
+ static constexpr auto UnknownNetworkLayerProtocol = QHostAddress::UnknownNetworkLayerProtocol;
+#endif
+
enum SocketError {
ConnectionRefusedError,
RemoteHostClosedError,
@@ -148,7 +129,14 @@ public:
virtual bool bind(const QHostAddress &address, quint16 port = 0,
BindMode mode = DefaultForPlatform);
+#if QT_VERSION >= QT_VERSION_CHECK(7,0,0) || defined(Q_QDOC)
+ bool bind(QHostAddress::SpecialAddress addr, quint16 port = 0, BindMode mode = DefaultForPlatform)
+ { return bind(QHostAddress(addr), port, mode); }
+ bool bind(quint16 port = 0, BindMode mode = DefaultForPlatform)
+ { return bind(QHostAddress::Any, port, mode); }
+#else
bool bind(quint16 port = 0, BindMode mode = DefaultForPlatform);
+#endif
virtual void connectToHost(const QString &hostName, quint16 port, OpenMode mode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol);
void connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite);
@@ -246,7 +234,9 @@ Q_NETWORK_EXPORT QDebug operator<<(QDebug, QAbstractSocket::SocketState);
QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QAbstractSocket::SocketState)
-Q_DECLARE_METATYPE(QAbstractSocket::SocketError)
+QT_DECL_METATYPE_EXTERN_TAGGED(QAbstractSocket::SocketState,
+ QAbstractSocket__SocketState, Q_NETWORK_EXPORT)
+QT_DECL_METATYPE_EXTERN_TAGGED(QAbstractSocket::SocketError,
+ QAbstractSocket__SocketError, Q_NETWORK_EXPORT)
#endif // QABSTRACTSOCKET_H
diff --git a/src/network/socket/qabstractsocket_p.h b/src/network/socket/qabstractsocket_p.h
index 83a8afe36d..cc5f53179c 100644
--- a/src/network/socket/qabstractsocket_p.h
+++ b/src/network/socket/qabstractsocket_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QABSTRACTSOCKET_P_H
#define QABSTRACTSOCKET_P_H
@@ -96,27 +60,27 @@ public:
void _q_testConnection();
void _q_abortConnectionAttempt();
- bool emittedReadyRead;
- bool emittedBytesWritten;
+ bool emittedReadyRead = false;
+ bool emittedBytesWritten = false;
- bool abortCalled;
- bool pendingClose;
+ bool abortCalled = false;
+ bool pendingClose = false;
- QAbstractSocket::PauseModes pauseMode;
+ QAbstractSocket::PauseModes pauseMode = QAbstractSocket::PauseNever;
QString hostName;
- quint16 port;
+ quint16 port = 0;
QHostAddress host;
QList<QHostAddress> addresses;
- quint16 localPort;
- quint16 peerPort;
+ quint16 localPort = 0;
+ quint16 peerPort = 0;
QHostAddress localAddress;
QHostAddress peerAddress;
QString peerName;
- QAbstractSocketEngine *socketEngine;
- qintptr cachedSocketDescriptor;
+ QAbstractSocketEngine *socketEngine = nullptr;
+ qintptr cachedSocketDescriptor = -1;
#ifndef QT_NO_NETWORKPROXY
QNetworkProxy proxy;
@@ -143,25 +107,27 @@ public:
void setError(QAbstractSocket::SocketError errorCode, const QString &errorString);
void setErrorAndEmit(QAbstractSocket::SocketError errorCode, const QString &errorString);
- qint64 readBufferMaxSize;
- bool isBuffered;
- bool hasPendingData;
+ qint64 readBufferMaxSize = 0;
+ bool isBuffered = false;
+ bool hasPendingData = false;
+ bool hasPendingDatagram = false;
- QTimer *connectTimer;
+ QTimer *connectTimer = nullptr;
- int hostLookupId;
+ int hostLookupId = -1;
- QAbstractSocket::SocketType socketType;
- QAbstractSocket::SocketState state;
+ QAbstractSocket::SocketType socketType = QAbstractSocket::UnknownSocketType;
+ QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState;
// Must be kept in sync with QIODevicePrivate::errorString.
- QAbstractSocket::SocketError socketError;
+ QAbstractSocket::SocketError socketError = QAbstractSocket::UnknownSocketError;
- QAbstractSocket::NetworkLayerProtocol preferredNetworkLayerProtocol;
+ QAbstractSocket::NetworkLayerProtocol preferredNetworkLayerProtocol =
+ QAbstractSocket::UnknownNetworkLayerProtocol;
- bool prePauseReadSocketNotifierState;
- bool prePauseWriteSocketNotifierState;
- bool prePauseExceptionSocketNotifierState;
+ bool prePauseReadSocketNotifierState = false;
+ bool prePauseWriteSocketNotifierState = false;
+ bool prePauseExceptionSocketNotifierState = false;
static void pauseSocketNotifiers(QAbstractSocket*);
static void resumeSocketNotifiers(QAbstractSocket*);
static QAbstractSocketEngine* getSocketEngine(QAbstractSocket*);
diff --git a/src/network/socket/qabstractsocketengine.cpp b/src/network/socket/qabstractsocketengine.cpp
index 50462fb11f..864ce8d9ea 100644
--- a/src/network/socket/qabstractsocketengine.cpp
+++ b/src/network/socket/qabstractsocketengine.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qabstractsocketengine_p.h"
@@ -73,7 +37,7 @@ QSocketEngineHandler::~QSocketEngineHandler()
QAbstractSocketEnginePrivate::QAbstractSocketEnginePrivate()
: socketError(QAbstractSocket::UnknownSocketError)
, hasSetSocketError(false)
- , socketErrorString(QLatin1String(QT_TRANSLATE_NOOP(QSocketLayer, "Unknown error")))
+ , socketErrorString(QLatin1StringView(QT_TRANSLATE_NOOP(QSocketLayer, "Unknown error")))
, socketState(QAbstractSocket::UnconnectedState)
, socketType(QAbstractSocket::UnknownSocketType)
, socketProtocol(QAbstractSocket::UnknownNetworkLayerProtocol)
diff --git a/src/network/socket/qabstractsocketengine_p.h b/src/network/socket/qabstractsocketengine_p.h
index 3d9ce96cb3..9ee79cebc1 100644
--- a/src/network/socket/qabstractsocketengine_p.h
+++ b/src/network/socket/qabstractsocketengine_p.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QABSTRACTSOCKETENGINE_P_H
#define QABSTRACTSOCKETENGINE_P_H
@@ -55,8 +19,9 @@
#include <QtNetwork/private/qtnetworkglobal_p.h>
#include "QtNetwork/qhostaddress.h"
#include "QtNetwork/qabstractsocket.h"
-#include "private/qobject_p.h"
+#include <QtCore/qdeadlinetimer.h>
#include "private/qnetworkdatagram_p.h"
+#include "private/qobject_p.h"
QT_BEGIN_NAMESPACE
@@ -80,6 +45,8 @@ public:
#endif
};
+static constexpr std::chrono::seconds DefaultTimeout{30};
+
class Q_AUTOTEST_EXPORT QAbstractSocketEngine : public QObject
{
Q_OBJECT
@@ -133,8 +100,8 @@ public:
virtual bool connectToHost(const QHostAddress &address, quint16 port) = 0;
virtual bool connectToHostByName(const QString &name, quint16 port) = 0;
virtual bool bind(const QHostAddress &address, quint16 port) = 0;
- virtual bool listen() = 0;
- virtual int accept() = 0;
+ virtual bool listen(int backlog) = 0;
+ virtual qintptr accept() = 0;
virtual void close() = 0;
virtual qint64 bytesAvailable() const = 0;
@@ -164,11 +131,14 @@ public:
virtual int option(SocketOption option) const = 0;
virtual bool setOption(SocketOption option, int value) = 0;
- virtual bool waitForRead(int msecs = 30000, bool *timedOut = nullptr) = 0;
- virtual bool waitForWrite(int msecs = 30000, bool *timedOut = nullptr) = 0;
+ virtual bool waitForRead(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) = 0;
+ virtual bool waitForWrite(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) = 0;
virtual bool waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs = 30000, bool *timedOut = nullptr) = 0;
+ QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) = 0;
QAbstractSocket::SocketError error() const;
QString errorString() const;
diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp
index 5324038dbd..a700023bd5 100644
--- a/src/network/socket/qhttpsocketengine.cpp
+++ b/src/network/socket/qhttpsocketengine.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qhttpsocketengine_p.h"
#include "qtcpsocket.h"
@@ -43,7 +7,7 @@
#include "qurl.h"
#include "private/qhttpnetworkreply_p.h"
#include "private/qiodevice_p.h"
-#include "qelapsedtimer.h"
+#include "qdeadlinetimer.h"
#include "qnetworkinterface.h"
#if !defined(QT_NO_NETWORKPROXY)
@@ -51,6 +15,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
#define DEBUG
QHttpSocketEngine::QHttpSocketEngine(QObject *parent)
@@ -186,24 +152,22 @@ bool QHttpSocketEngine::connectToHostByName(const QString &hostname, quint16 por
bool QHttpSocketEngine::bind(const QHostAddress &, quint16)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return false;
}
-bool QHttpSocketEngine::listen()
+bool QHttpSocketEngine::listen(int backlog)
{
+ Q_UNUSED(backlog);
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return false;
}
-int QHttpSocketEngine::accept()
+qintptr QHttpSocketEngine::accept()
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return -1;
}
@@ -238,8 +202,7 @@ qint64 QHttpSocketEngine::read(char *data, qint64 maxlen)
// failed, return the socket's error. Otherwise, fall through and
// return as much as we read so far.
close();
- setError(QAbstractSocket::RemoteHostClosedError,
- QLatin1String("Remote host closed"));
+ setError(QAbstractSocket::RemoteHostClosedError, "Remote host closed"_L1);
setState(QAbstractSocket::UnconnectedState);
return -1;
}
@@ -258,8 +221,7 @@ bool QHttpSocketEngine::joinMulticastGroup(const QHostAddress &,
const QNetworkInterface &)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return false;
}
@@ -267,8 +229,7 @@ bool QHttpSocketEngine::leaveMulticastGroup(const QHostAddress &,
const QNetworkInterface &)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return false;
}
@@ -280,8 +241,7 @@ QNetworkInterface QHttpSocketEngine::multicastInterface() const
bool QHttpSocketEngine::setMulticastInterface(const QNetworkInterface &)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return false;
}
#endif // QT_NO_NETWORKINTERFACE
@@ -302,16 +262,14 @@ qint64 QHttpSocketEngine::pendingDatagramSize() const
qint64 QHttpSocketEngine::readDatagram(char *, qint64, QIpPacketHeader *, PacketHeaderOptions)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return -1;
}
qint64 QHttpSocketEngine::writeDatagram(const char *, qint64, const QIpPacketHeader &)
{
qWarning("Operation is not supported");
- setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Unsupported socket operation"));
+ setError(QAbstractSocket::UnsupportedSocketOperationError, "Unsupported socket operation"_L1);
return -1;
}
@@ -352,19 +310,16 @@ bool QHttpSocketEngine::setOption(SocketOption option, int value)
return false;
}
-bool QHttpSocketEngine::waitForRead(int msecs, bool *timedOut)
+bool QHttpSocketEngine::waitForRead(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(const QHttpSocketEngine);
if (!d->socket || d->socket->state() == QAbstractSocket::UnconnectedState)
return false;
- QElapsedTimer stopWatch;
- stopWatch.start();
-
// Wait for more data if nothing is available.
if (!d->socket->bytesAvailable()) {
- if (!d->socket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ if (!d->socket->waitForReadyRead(deadline.remainingTime())) {
if (d->socket->state() == QAbstractSocket::UnconnectedState)
return true;
setError(d->socket->error(), d->socket->errorString());
@@ -374,11 +329,7 @@ bool QHttpSocketEngine::waitForRead(int msecs, bool *timedOut)
}
}
- // If we're not connected yet, wait until we are, or until an error
- // occurs.
- while (d->state != Connected && d->socket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
- // Loop while the protocol handshake is taking place.
- }
+ waitForProtocolHandshake(deadline);
// Report any error that may occur.
if (d->state != Connected) {
@@ -390,14 +341,14 @@ bool QHttpSocketEngine::waitForRead(int msecs, bool *timedOut)
return true;
}
-bool QHttpSocketEngine::waitForWrite(int msecs, bool *timedOut)
+bool QHttpSocketEngine::waitForWrite(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(const QHttpSocketEngine);
// If we're connected, just forward the call.
if (d->state == Connected) {
if (d->socket->bytesToWrite()) {
- if (!d->socket->waitForBytesWritten(msecs)) {
+ if (!d->socket->waitForBytesWritten(deadline.remainingTime())) {
if (d->socket->error() == QAbstractSocket::SocketTimeoutError && timedOut)
*timedOut = true;
return false;
@@ -406,15 +357,7 @@ bool QHttpSocketEngine::waitForWrite(int msecs, bool *timedOut)
return true;
}
- QElapsedTimer stopWatch;
- stopWatch.start();
-
- // If we're not connected yet, wait until we are, and until bytes have
- // been received (i.e., the socket has connected, we have sent the
- // greeting, and then received the response).
- while (d->state != Connected && d->socket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
- // Loop while the protocol handshake is taking place.
- }
+ waitForProtocolHandshake(deadline);
// Report any error that may occur.
if (d->state != Connected) {
@@ -428,25 +371,37 @@ bool QHttpSocketEngine::waitForWrite(int msecs, bool *timedOut)
bool QHttpSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs, bool *timedOut)
+ QDeadlineTimer deadline, bool *timedOut)
{
Q_UNUSED(checkRead);
if (!checkWrite) {
// Not interested in writing? Then we wait for read notifications.
- bool canRead = waitForRead(msecs, timedOut);
+ bool canRead = waitForRead(deadline, timedOut);
if (readyToRead)
*readyToRead = canRead;
return canRead;
}
// Interested in writing? Then we wait for write notifications.
- bool canWrite = waitForWrite(msecs, timedOut);
+ bool canWrite = waitForWrite(deadline, timedOut);
if (readyToWrite)
*readyToWrite = canWrite;
return canWrite;
}
+void QHttpSocketEngine::waitForProtocolHandshake(QDeadlineTimer deadline) const
+{
+ Q_D(const QHttpSocketEngine);
+
+ // If we're not connected yet, wait until we are (and until bytes have
+ // been received, i.e. the socket has connected, we have sent the
+ // greeting, and then received the response), or until an error occurs.
+ while (d->state != Connected && d->socket->waitForReadyRead(deadline.remainingTime())) {
+ // Loop while the protocol handshake is taking place.
+ }
+}
+
bool QHttpSocketEngine::isReadNotificationEnabled() const
{
Q_D(const QHttpSocketEngine);
@@ -578,7 +533,7 @@ void QHttpSocketEngine::slotSocketReadNotification()
d->pendingResponseData -= uint(skipped);
if (d->pendingResponseData > 0)
return;
- if (d->reply->d_func()->statusCode == 407)
+ if (d->reply->statusCode() == 407)
d->state = SendAuthentication;
}
@@ -598,16 +553,8 @@ void QHttpSocketEngine::slotSocketReadNotification()
d->authenticator.detach();
priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
- if (d->credentialsSent && priv->phase != QAuthenticatorPrivate::Phase2) {
- // Remember that (e.g.) NTLM is two-phase, so only reset when the authentication is not currently in progress.
- //407 response again means the provided username/password were invalid.
- d->authenticator = QAuthenticator(); //this is needed otherwise parseHttpResponse won't set the state, and then signal isn't emitted.
- d->authenticator.detach();
- priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
- priv->hasFailed = true;
- }
-
- priv->parseHttpResponse(d->reply->header(), true, d->proxy.hostName());
+ const auto headers = d->reply->header();
+ priv->parseHttpResponse(headers, true, d->proxy.hostName());
if (priv->phase == QAuthenticatorPrivate::Invalid) {
// problem parsing the reply
@@ -618,6 +565,29 @@ void QHttpSocketEngine::slotSocketReadNotification()
return;
}
+ if (priv->phase == QAuthenticatorPrivate::Done
+ || (priv->phase == QAuthenticatorPrivate::Start
+ && (priv->method == QAuthenticatorPrivate::Ntlm
+ || priv->method == QAuthenticatorPrivate::Negotiate))) {
+ if (priv->phase == QAuthenticatorPrivate::Start)
+ priv->phase = QAuthenticatorPrivate::Phase1;
+ bool credentialsWasSent = d->credentialsSent;
+ if (d->credentialsSent) {
+ // Remember that (e.g.) NTLM is two-phase, so only reset when the authentication is
+ // not currently in progress. 407 response again means the provided
+ // username/password were invalid.
+ d->authenticator.detach();
+ priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
+ priv->hasFailed = true;
+ d->credentialsSent = false;
+ priv->phase = QAuthenticatorPrivate::Done;
+ }
+ if ((priv->method != QAuthenticatorPrivate::Ntlm
+ && priv->method != QAuthenticatorPrivate::Negotiate)
+ || credentialsWasSent)
+ proxyAuthenticationRequired(d->proxy, &d->authenticator);
+ }
+
bool willClose;
QByteArray proxyConnectionHeader = d->reply->headerField("Proxy-Connection");
// Although most proxies use the unofficial Proxy-Connection header, the Connection header
@@ -642,13 +612,11 @@ void QHttpSocketEngine::slotSocketReadNotification()
d->socket->readAll();
//We're done with the reply and need to reset it for the next connection
delete d->reply;
- d->reply = new QHttpNetworkReply;
+ d->reply = new QHttpNetworkReply(QUrl(), this);
}
- if (priv->phase == QAuthenticatorPrivate::Done)
- proxyAuthenticationRequired(d->proxy, &d->authenticator);
- // priv->phase will get reset to QAuthenticatorPrivate::Start if the authenticator got modified in the signal above.
if (priv->phase == QAuthenticatorPrivate::Done) {
+ d->authenticator = QAuthenticator();
setError(QAbstractSocket::ProxyAuthenticationRequiredError, tr("Authentication required"));
d->socket->disconnectFromHost();
} else {
@@ -790,7 +758,7 @@ void QHttpSocketEngine::emitReadNotification()
{
Q_D(QHttpSocketEngine);
// if there is a connection notification pending we have to emit the readNotification
- // incase there is connection error. This is only needed for Windows, but it does not
+ // in case there is connection error. This is only needed for Windows, but it does not
// hurt in other cases.
if ((d->readNotificationEnabled && !d->readNotificationPending) || d->connectionNotificationPending) {
d->readNotificationPending = true;
diff --git a/src/network/socket/qhttpsocketengine_p.h b/src/network/socket/qhttpsocketengine_p.h
index 0c2c450c81..7926abf513 100644
--- a/src/network/socket/qhttpsocketengine_p.h
+++ b/src/network/socket/qhttpsocketengine_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QHTTPSOCKETENGINE_P_H
#define QHTTPSOCKETENGINE_P_H
@@ -52,10 +16,12 @@
//
#include <QtNetwork/private/qtnetworkglobal_p.h>
-#include "private/qabstractsocketengine_p.h"
+
+#include <QtNetwork/qnetworkproxy.h>
+
#include "qabstractsocket.h"
-#include "qnetworkproxy.h"
#include "private/qauthenticator_p.h"
+#include "private/qabstractsocketengine_p.h"
QT_REQUIRE_CONFIG(http);
@@ -95,8 +61,8 @@ public:
bool connectToHost(const QHostAddress &address, quint16 port) override;
bool connectToHostByName(const QString &name, quint16 port) override;
bool bind(const QHostAddress &address, quint16 port) override;
- bool listen() override;
- int accept() override;
+ bool listen(int backlog) override;
+ qintptr accept() override;
void close() override;
qint64 bytesAvailable() const override;
@@ -126,11 +92,16 @@ public:
int option(SocketOption option) const override;
bool setOption(SocketOption option, int value) override;
- bool waitForRead(int msecs = 30000, bool *timedOut = nullptr) override;
- bool waitForWrite(int msecs = 30000, bool *timedOut = nullptr) override;
+ bool waitForRead(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
+ bool waitForWrite(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
bool waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs = 30000, bool *timedOut = nullptr) override;
+ QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
+
+ void waitForProtocolHandshake(QDeadlineTimer deadline) const;
bool isReadNotificationEnabled() const override;
void setReadNotificationEnabled(bool enable) override;
diff --git a/src/network/socket/qlocalserver.cpp b/src/network/socket/qlocalserver.cpp
index bce5b9a1a4..5ef2db6b94 100644
--- a/src/network/socket/qlocalserver.cpp
+++ b/src/network/socket/qlocalserver.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalserver.h"
#include "qlocalserver_p.h"
@@ -47,6 +11,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QLocalServer
\since 4.4
@@ -90,6 +56,8 @@ QT_BEGIN_NAMESPACE
socket. This changes the access permissions on platforms (Linux, Windows)
that support access permissions on the socket. Both GroupAccess and OtherAccess
may vary slightly in meanings depending on the platform.
+ On Linux and Android it is possible to use sockets with abstract addresses;
+ socket permissions have no meaning for such sockets.
\value NoOptions No access restrictions have been set.
\value UserAccessOption
@@ -102,6 +70,10 @@ QT_BEGIN_NAMESPACE
Access is available to everyone on Windows.
\value WorldAccessOption
No access restrictions.
+ \value AbstractNamespaceOption
+ The listening socket will be created in the abstract namespace. This flag is specific to Linux.
+ In case of other platforms, for the sake of code portability, this flag is equivalent
+ to WorldAccessOption.
\sa socketOptions
*/
@@ -148,7 +120,7 @@ QLocalServer::~QLocalServer()
In some cases, such as with Unix domain sockets on Linux, the
access to the socket will be determined by file system permissions,
and are created based on the umask. Setting the access flags will
- overide this and will restrict or permit access as specified.
+ override this and will restrict or permit access as specified.
Other Unix-based operating systems, such as \macos, do not
honor file permissions for Unix domain sockets and by default
@@ -161,6 +133,11 @@ QLocalServer::~QLocalServer()
in the Windows documentation). OtherAccessOption refers to
the well known "Everyone" group.
+ On Linux platforms it is possible to create a socket in the abstract
+ namespace, which is independent of the filesystem. Using this kind
+ of socket implies ignoring permission options. On other platforms
+ AbstractNamespaceOption is equivalent to WorldAccessOption.
+
By default none of the flags are set, access permissions
are the platform default.
@@ -185,6 +162,12 @@ QLocalServer::SocketOptions QLocalServer::socketOptions() const
return d->socketOptions;
}
+QBindable<QLocalServer::SocketOptions> QLocalServer::bindableSocketOptions()
+{
+ Q_D(QLocalServer);
+ return &d->socketOptions;
+}
+
/*!
\since 5.10
Returns the native socket descriptor the server uses to listen
@@ -193,8 +176,7 @@ QLocalServer::SocketOptions QLocalServer::socketOptions() const
The type of the descriptor depends on the platform:
\list
\li On Windows, the returned value is a
- \l{https://msdn.microsoft.com/en-us/library/windows/desktop/ms740522(v=vs.85).aspx}
- {Winsock 2 Socket Handle}.
+ \l{Winsock 2 Socket Handle}.
\li On INTEGRITY, the returned value is the
QTcpServer socket descriptor and the type is defined by
@@ -283,9 +265,27 @@ bool QLocalServer::hasPendingConnections() const
*/
void QLocalServer::incomingConnection(quintptr socketDescriptor)
{
- Q_D(QLocalServer);
QLocalSocket *socket = new QLocalSocket(this);
socket->setSocketDescriptor(socketDescriptor);
+ addPendingConnection(socket);
+}
+
+/*!
+ This function is called by QLocalServer::incomingConnection()
+ to add the \a socket to the list of pending incoming connections.
+
+ \note Don't forget to call this member from reimplemented
+ incomingConnection() if you do not want to break the
+ Pending Connections mechanism. This function emits the
+ pendingConnectionAvailable() signal after the socket has been
+ added.
+
+ \sa incomingConnection(), pendingConnectionAvailable()
+ \since 6.8
+*/
+void QLocalServer::addPendingConnection(QLocalSocket *socket)
+{
+ Q_D(QLocalServer);
d->pendingConnections.enqueue(socket);
emit newConnection();
}
@@ -332,7 +332,7 @@ bool QLocalServer::listen(const QString &name)
if (name.isEmpty()) {
d->error = QAbstractSocket::HostNotFoundError;
- QString function = QLatin1String("QLocalServer::listen");
+ QString function = "QLocalServer::listen"_L1;
d->errorString = tr("%1: Name error").arg(function);
return false;
}
@@ -359,7 +359,9 @@ bool QLocalServer::listen(const QString &name)
serverName(), fullServerName() may return a string with
a name if this option is supported by the platform;
- otherwise, they return an empty QString.
+ otherwise, they return an empty QString. In particular, the addresses
+ of sockets in the abstract namespace supported by Linux will
+ not yield useful names if they contain unprintable characters.
\sa isListening(), close()
*/
@@ -535,6 +537,36 @@ bool QLocalServer::waitForNewConnection(int msec, bool *timedOut)
return !d->pendingConnections.isEmpty();
}
+/*!
+ Sets the backlog queue size of to be accepted connections to \a
+ size. The operating system might reduce or ignore this value.
+ By default, the queue size is 50.
+
+ \note This property must be set prior to calling listen().
+
+ \since 6.3
+
+ \sa listenBacklogSize()
+*/
+void QLocalServer::setListenBacklogSize(int size)
+{
+ Q_D(QLocalServer);
+ d->listenBacklog = size;
+}
+
+/*!
+ Returns the backlog queue size of to be accepted connections.
+
+ \since 6.3
+
+ \sa setListenBacklogSize()
+*/
+int QLocalServer::listenBacklogSize() const
+{
+ Q_D(const QLocalServer);
+ return d->listenBacklog;
+}
+
QT_END_NAMESPACE
#include "moc_qlocalserver.cpp"
diff --git a/src/network/socket/qlocalserver.h b/src/network/socket/qlocalserver.h
index 211aa94d85..685253e8be 100644
--- a/src/network/socket/qlocalserver.h
+++ b/src/network/socket/qlocalserver.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QLOCALSERVER_H
#define QLOCALSERVER_H
@@ -43,6 +7,8 @@
#include <QtNetwork/qtnetworkglobal.h>
#include <QtNetwork/qabstractsocket.h>
+#include <QtCore/qproperty.h>
+
QT_REQUIRE_CONFIG(localserver);
QT_BEGIN_NAMESPACE
@@ -54,7 +20,8 @@ class Q_NETWORK_EXPORT QLocalServer : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE(QLocalServer)
- Q_PROPERTY(SocketOptions socketOptions READ socketOptions WRITE setSocketOptions)
+ Q_PROPERTY(SocketOptions socketOptions READ socketOptions WRITE setSocketOptions
+ BINDABLE bindableSocketOptions)
Q_SIGNALS:
void newConnection();
@@ -65,9 +32,10 @@ public:
UserAccessOption = 0x01,
GroupAccessOption = 0x2,
OtherAccessOption = 0x4,
- WorldAccessOption = 0x7
+ WorldAccessOption = 0x7,
+ AbstractNamespaceOption = 0x8
};
- Q_FLAG(SocketOption)
+ Q_ENUM(SocketOption)
Q_DECLARE_FLAGS(SocketOptions, SocketOption)
Q_FLAG(SocketOptions)
@@ -89,13 +57,18 @@ public:
void setMaxPendingConnections(int numConnections);
bool waitForNewConnection(int msec = 0, bool *timedOut = nullptr);
+ void setListenBacklogSize(int size);
+ int listenBacklogSize() const;
+
void setSocketOptions(SocketOptions options);
SocketOptions socketOptions() const;
+ QBindable<SocketOptions> bindableSocketOptions();
qintptr socketDescriptor() const;
protected:
virtual void incomingConnection(quintptr socketDescriptor);
+ void addPendingConnection(QLocalSocket *socket);
private:
Q_DISABLE_COPY(QLocalServer)
diff --git a/src/network/socket/qlocalserver_p.h b/src/network/socket/qlocalserver_p.h
index f331a3f10d..f7afd5cd32 100644
--- a/src/network/socket/qlocalserver_p.h
+++ b/src/network/socket/qlocalserver_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QLOCALSERVER_P_H
#define QLOCALSERVER_P_H
@@ -61,6 +25,7 @@ QT_REQUIRE_CONFIG(localserver);
#if defined(QT_LOCALSOCKET_TCP)
# include <qtcpserver.h>
+# include <QtCore/qmap.h>
#elif defined(Q_OS_WIN)
# include <qt_windows.h>
# include <qwineventnotifier.h>
@@ -126,7 +91,9 @@ public:
QQueue<QLocalSocket*> pendingConnections;
QString errorString;
QAbstractSocket::SocketError error;
- QLocalServer::SocketOptions socketOptions;
+ int listenBacklog = 50;
+
+ Q_OBJECT_BINDABLE_PROPERTY(QLocalServerPrivate, QLocalServer::SocketOptions, socketOptions)
};
QT_END_NAMESPACE
diff --git a/src/network/socket/qlocalserver_tcp.cpp b/src/network/socket/qlocalserver_tcp.cpp
index b3f1188afa..4d52d2c23a 100644
--- a/src/network/socket/qlocalserver_tcp.cpp
+++ b/src/network/socket/qlocalserver_tcp.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalserver.h"
#include "qlocalserver_p.h"
@@ -48,6 +12,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
void QLocalServerPrivate::init()
{
Q_Q(QLocalServer);
@@ -56,16 +22,18 @@ void QLocalServerPrivate::init()
bool QLocalServerPrivate::listen(const QString &requestedServerName)
{
+ tcpServer.setListenBacklogSize(listenBacklog);
+
if (!tcpServer.listen(QHostAddress::LocalHost))
return false;
- const QLatin1String prefix("QLocalServer/");
+ const auto prefix = "QLocalServer/"_L1;
if (requestedServerName.startsWith(prefix))
fullServerName = requestedServerName;
else
fullServerName = prefix + requestedServerName;
- QSettings settings(QLatin1String("QtProject"), QLatin1String("Qt"));
+ QSettings settings("QtProject"_L1, "Qt"_L1);
if (settings.contains(fullServerName)) {
qWarning("QLocalServer::listen: server name is already in use.");
tcpServer.close();
@@ -83,8 +51,8 @@ bool QLocalServerPrivate::listen(qintptr socketDescriptor)
void QLocalServerPrivate::closeServer()
{
- QSettings settings(QLatin1String("QtProject"), QLatin1String("Qt"));
- if (fullServerName == QLatin1String("QLocalServer"))
+ QSettings settings("QtProject"_L1, "Qt"_L1);
+ if (fullServerName == "QLocalServer"_L1)
settings.setValue(fullServerName, QVariant());
else
settings.remove(fullServerName);
@@ -115,14 +83,14 @@ void QLocalServerPrivate::_q_onNewConnection()
bool QLocalServerPrivate::removeServer(const QString &name)
{
- const QLatin1String prefix("QLocalServer/");
+ const auto prefix = "QLocalServer/"_L1;
QString serverName;
if (name.startsWith(prefix))
serverName = name;
else
serverName = prefix + name;
- QSettings settings(QLatin1String("QtProject"), QLatin1String("Qt"));
+ QSettings settings("QtProject"_L1, "Qt"_L1);
if (settings.contains(serverName))
settings.remove(serverName);
diff --git a/src/network/socket/qlocalserver_unix.cpp b/src/network/socket/qlocalserver_unix.cpp
index ea7e8e1e0e..9aa9a5b86f 100644
--- a/src/network/socket/qlocalserver_unix.cpp
+++ b/src/network/socket/qlocalserver_unix.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalserver.h"
#include "qlocalserver_p.h"
@@ -44,6 +8,7 @@
#include "qnet_unix_p.h"
#include "qtemporarydir.h"
+#include <stddef.h>
#include <sys/socket.h>
#include <sys/un.h>
@@ -51,12 +16,33 @@
#include <qdir.h>
#include <qdatetime.h>
+#include <optional>
+
#ifdef Q_OS_VXWORKS
# include <selectLib.h>
#endif
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
+namespace {
+QLocalServer::SocketOptions optionsForPlatform(QLocalServer::SocketOptions srcOptions)
+{
+ // For OS that does not support abstract namespace the AbstractNamespaceOption
+ // means that we go for WorldAccessOption - as it is the closest option in
+ // regards of access rights. In Linux/Android case we clean-up the access rights.
+
+ if (srcOptions.testFlag(QLocalServer::AbstractNamespaceOption)) {
+ if (PlatformSupportsAbstractNamespace)
+ return QLocalServer::AbstractNamespaceOption;
+ else
+ return QLocalServer::WorldAccessOption;
+ }
+ return srcOptions;
+}
+}
+
void QLocalServerPrivate::init()
{
}
@@ -64,11 +50,11 @@ void QLocalServerPrivate::init()
bool QLocalServerPrivate::removeServer(const QString &name)
{
QString fileName;
- if (name.startsWith(QLatin1Char('/'))) {
+ if (name.startsWith(u'/')) {
fileName = name;
} else {
fileName = QDir::cleanPath(QDir::tempPath());
- fileName += QLatin1Char('/') + name;
+ fileName += u'/' + name;
}
if (QFile::exists(fileName))
return QFile::remove(fileName);
@@ -80,50 +66,66 @@ bool QLocalServerPrivate::listen(const QString &requestedServerName)
{
Q_Q(QLocalServer);
+ // socket options adjusted for current platform
+ auto options = optionsForPlatform(socketOptions.value());
+
// determine the full server path
- if (requestedServerName.startsWith(QLatin1Char('/'))) {
+ if (options.testFlag(QLocalServer::AbstractNamespaceOption)
+ || requestedServerName.startsWith(u'/')) {
fullServerName = requestedServerName;
} else {
fullServerName = QDir::cleanPath(QDir::tempPath());
- fullServerName += QLatin1Char('/') + requestedServerName;
+ fullServerName += u'/' + requestedServerName;
}
serverName = requestedServerName;
QByteArray encodedTempPath;
const QByteArray encodedFullServerName = QFile::encodeName(fullServerName);
- QScopedPointer<QTemporaryDir> tempDir;
+ std::optional<QTemporaryDir> tempDir;
- // Check any of the flags
- if (socketOptions & QLocalServer::WorldAccessOption) {
+ if (options & QLocalServer::WorldAccessOption) {
QFileInfo serverNameFileInfo(fullServerName);
- tempDir.reset(new QTemporaryDir(serverNameFileInfo.absolutePath() + QLatin1Char('/')));
+ tempDir.emplace(serverNameFileInfo.absolutePath() + u'/');
if (!tempDir->isValid()) {
- setError(QLatin1String("QLocalServer::listen"));
+ setError("QLocalServer::listen"_L1);
return false;
}
- encodedTempPath = QFile::encodeName(tempDir->path() + QLatin1String("/s"));
+ encodedTempPath = QFile::encodeName(tempDir->path() + "/s"_L1);
}
// create the unix socket
listenSocket = qt_safe_socket(PF_UNIX, SOCK_STREAM, 0);
if (-1 == listenSocket) {
- setError(QLatin1String("QLocalServer::listen"));
+ setError("QLocalServer::listen"_L1);
closeServer();
return false;
}
// Construct the unix address
struct ::sockaddr_un addr;
+
addr.sun_family = PF_UNIX;
- if (sizeof(addr.sun_path) < (uint)encodedFullServerName.size() + 1) {
- setError(QLatin1String("QLocalServer::listen"));
+ ::memset(addr.sun_path, 0, sizeof(addr.sun_path));
+
+ // for abstract namespace add 2 to length, to take into account trailing AND leading null
+ constexpr unsigned int extraCharacters = PlatformSupportsAbstractNamespace ? 2 : 1;
+
+ if (sizeof(addr.sun_path) < static_cast<size_t>(encodedFullServerName.size() + extraCharacters)) {
+ setError("QLocalServer::listen"_L1);
closeServer();
return false;
}
- if (socketOptions & QLocalServer::WorldAccessOption) {
- if (sizeof(addr.sun_path) < (uint)encodedTempPath.size() + 1) {
- setError(QLatin1String("QLocalServer::listen"));
+ QT_SOCKLEN_T addrSize = sizeof(::sockaddr_un);
+ if (options.testFlag(QLocalServer::AbstractNamespaceOption)) {
+ // Abstract socket address is distinguished by the fact
+ // that sun_path[0] is a null byte ('\0')
+ ::memcpy(addr.sun_path + 1, encodedFullServerName.constData(),
+ encodedFullServerName.size() + 1);
+ addrSize = offsetof(::sockaddr_un, sun_path) + encodedFullServerName.size() + 1;
+ } else if (options & QLocalServer::WorldAccessOption) {
+ if (sizeof(addr.sun_path) < static_cast<size_t>(encodedTempPath.size() + 1)) {
+ setError("QLocalServer::listen"_L1);
closeServer();
return false;
}
@@ -135,8 +137,8 @@ bool QLocalServerPrivate::listen(const QString &requestedServerName)
}
// bind
- if (-1 == QT_SOCKET_BIND(listenSocket, (sockaddr *)&addr, sizeof(sockaddr_un))) {
- setError(QLatin1String("QLocalServer::listen"));
+ if (-1 == QT_SOCKET_BIND(listenSocket, (sockaddr *)&addr, addrSize)) {
+ setError("QLocalServer::listen"_L1);
// if address is in use already, just close the socket, but do not delete the file
if (errno == EADDRINUSE)
QT_CLOSE(listenSocket);
@@ -148,35 +150,32 @@ bool QLocalServerPrivate::listen(const QString &requestedServerName)
}
// listen for connections
- if (-1 == qt_safe_listen(listenSocket, 50)) {
- setError(QLatin1String("QLocalServer::listen"));
+ if (-1 == qt_safe_listen(listenSocket, listenBacklog)) {
+ setError("QLocalServer::listen"_L1);
closeServer();
- listenSocket = -1;
- if (error != QAbstractSocket::AddressInUseError)
- QFile::remove(fullServerName);
return false;
}
- if (socketOptions & QLocalServer::WorldAccessOption) {
+ if (options & QLocalServer::WorldAccessOption) {
mode_t mode = 000;
- if (socketOptions & QLocalServer::UserAccessOption)
+ if (options & QLocalServer::UserAccessOption)
mode |= S_IRWXU;
- if (socketOptions & QLocalServer::GroupAccessOption)
+ if (options & QLocalServer::GroupAccessOption)
mode |= S_IRWXG;
- if (socketOptions & QLocalServer::OtherAccessOption)
+ if (options & QLocalServer::OtherAccessOption)
mode |= S_IRWXO;
if (::chmod(encodedTempPath.constData(), mode) == -1) {
- setError(QLatin1String("QLocalServer::listen"));
+ setError("QLocalServer::listen"_L1);
closeServer();
return false;
}
if (::rename(encodedTempPath.constData(), encodedFullServerName.constData()) == -1) {
- setError(QLatin1String("QLocalServer::listen"));
+ setError("QLocalServer::listen"_L1);
closeServer();
return false;
}
@@ -201,28 +200,21 @@ bool QLocalServerPrivate::listen(qintptr socketDescriptor)
::fcntl(listenSocket, F_SETFD, FD_CLOEXEC);
::fcntl(listenSocket, F_SETFL, ::fcntl(listenSocket, F_GETFL) | O_NONBLOCK);
-#ifdef Q_OS_LINUX
+ bool abstractAddress = false;
struct ::sockaddr_un addr;
QT_SOCKLEN_T len = sizeof(addr);
memset(&addr, 0, sizeof(addr));
- if (0 == ::getsockname(listenSocket, (sockaddr *)&addr, &len)) {
- // check for absract sockets
- if (addr.sun_family == PF_UNIX && addr.sun_path[0] == 0) {
- addr.sun_path[0] = '@';
- }
- QString name = QString::fromLatin1(addr.sun_path);
- if (!name.isEmpty()) {
- fullServerName = name;
- serverName = fullServerName.mid(fullServerName.lastIndexOf(QLatin1Char('/')) + 1);
- if (serverName.isEmpty()) {
- serverName = fullServerName;
- }
+ if (::getsockname(socketDescriptor, (sockaddr *)&addr, &len) == 0) {
+#if defined(Q_OS_QNX)
+ if (addr.sun_path[0] == 0 && addr.sun_path[1] == 0)
+ len = SUN_LEN(&addr);
+#endif
+ if (QLocalSocketPrivate::parseSockaddr(addr, len, fullServerName, serverName,
+ abstractAddress)) {
+ QLocalServer::SocketOptions options = socketOptions.value();
+ socketOptions = options.setFlag(QLocalServer::AbstractNamespaceOption, abstractAddress);
}
}
-#else
- serverName.clear();
- fullServerName.clear();
-#endif
Q_ASSERT(!socketNotifier);
socketNotifier = new QSocketNotifier(listenSocket,
@@ -250,8 +242,13 @@ void QLocalServerPrivate::closeServer()
QT_CLOSE(listenSocket);
listenSocket = -1;
- if (!fullServerName.isEmpty())
+ if (!fullServerName.isEmpty()
+ && !optionsForPlatform(socketOptions).testFlag(QLocalServer::AbstractNamespaceOption)) {
QFile::remove(fullServerName);
+ }
+
+ serverName.clear();
+ fullServerName.clear();
}
/*!
@@ -270,7 +267,7 @@ void QLocalServerPrivate::_q_onNewConnection()
QT_SOCKLEN_T length = sizeof(sockaddr_un);
int connectedSocket = qt_safe_accept(listenSocket, (sockaddr *)&addr, &length);
if (-1 == connectedSocket) {
- setError(QLatin1String("QLocalSocket::activated"));
+ setError("QLocalSocket::activated"_L1);
closeServer();
} else {
socketNotifier->setEnabled(pendingConnections.size()
@@ -282,8 +279,7 @@ void QLocalServerPrivate::_q_onNewConnection()
void QLocalServerPrivate::waitForNewConnection(int msec, bool *timedOut)
{
pollfd pfd = qt_make_pollfd(listenSocket, POLLIN);
-
- switch (qt_poll_msecs(&pfd, 1, msec)) {
+ switch (qt_safe_poll(&pfd, 1, QDeadlineTimer(msec))) {
case 0:
if (timedOut)
*timedOut = true;
@@ -299,7 +295,7 @@ void QLocalServerPrivate::waitForNewConnection(int msec, bool *timedOut)
errno = EBADF;
Q_FALLTHROUGH();
case -1:
- setError(QLatin1String("QLocalServer::waitForNewConnection"));
+ setError("QLocalServer::waitForNewConnection"_L1);
closeServer();
break;
}
diff --git a/src/network/socket/qlocalserver_win.cpp b/src/network/socket/qlocalserver_win.cpp
index 6d92ebe93a..bc761b1e8f 100644
--- a/src/network/socket/qlocalserver_win.cpp
+++ b/src/network/socket/qlocalserver_win.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalserver.h"
#include "qlocalserver_p.h"
@@ -53,11 +17,10 @@
// before it is read. Pipewriter is used for write buffering.
#define BUFSIZE 0
-// ###: This should be a property. Should replace the insane 50 on unix as well.
-#define SYSTEM_MAX_PENDING_SOCKETS 8
-
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
bool QLocalServerPrivate::addListener()
{
// The object must not change its address once the
@@ -77,10 +40,10 @@ bool QLocalServerPrivate::addListener()
QByteArray tokenGroupBuffer;
// create security descriptor if access options were specified
- if ((socketOptions & QLocalServer::WorldAccessOption)) {
+ if ((socketOptions.value() & QLocalServer::WorldAccessOption)) {
pSD.reset(new SECURITY_DESCRIPTOR);
if (!InitializeSecurityDescriptor(pSD.data(), SECURITY_DESCRIPTOR_REVISION)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
return false;
}
HANDLE hToken = NULL;
@@ -91,7 +54,7 @@ bool QLocalServerPrivate::addListener()
tokenUserBuffer.fill(0, dwBufferSize);
auto pTokenUser = reinterpret_cast<PTOKEN_USER>(tokenUserBuffer.data());
if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwBufferSize, &dwBufferSize)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
CloseHandle(hToken);
return false;
}
@@ -101,7 +64,7 @@ bool QLocalServerPrivate::addListener()
tokenGroupBuffer.fill(0, dwBufferSize);
auto pTokenGroup = reinterpret_cast<PTOKEN_PRIMARY_GROUP>(tokenGroupBuffer.data());
if (!GetTokenInformation(hToken, TokenPrimaryGroup, pTokenGroup, dwBufferSize, &dwBufferSize)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
CloseHandle(hToken);
return false;
}
@@ -128,7 +91,7 @@ bool QLocalServerPrivate::addListener()
if (!AllocateAndInitializeSid(&WorldAuth, 1, SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&worldSID)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
return false;
}
@@ -143,23 +106,23 @@ bool QLocalServerPrivate::addListener()
auto acl = reinterpret_cast<PACL>(aclBuffer.data());
InitializeAcl(acl, aclSize, ACL_REVISION_DS);
- if (socketOptions & QLocalServer::UserAccessOption) {
+ if (socketOptions.value() & QLocalServer::UserAccessOption) {
if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_ALL_ACCESS, pTokenUser->User.Sid)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
FreeSid(worldSID);
return false;
}
}
- if (socketOptions & QLocalServer::GroupAccessOption) {
+ if (socketOptions.value() & QLocalServer::GroupAccessOption) {
if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_ALL_ACCESS, pTokenGroup->PrimaryGroup)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
FreeSid(worldSID);
return false;
}
}
- if (socketOptions & QLocalServer::OtherAccessOption) {
+ if (socketOptions.value() & QLocalServer::OtherAccessOption) {
if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_ALL_ACCESS, worldSID)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
FreeSid(worldSID);
return false;
}
@@ -167,7 +130,7 @@ bool QLocalServerPrivate::addListener()
SetSecurityDescriptorOwner(pSD.data(), pTokenUser->User.Sid, FALSE);
SetSecurityDescriptorGroup(pSD.data(), pTokenGroup->PrimaryGroup, FALSE);
if (!SetSecurityDescriptorDacl(pSD.data(), TRUE, acl, FALSE)) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
FreeSid(worldSID);
return false;
}
@@ -188,7 +151,7 @@ bool QLocalServerPrivate::addListener()
&sa);
if (listener->handle == INVALID_HANDLE_VALUE) {
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
listeners.pop_back();
return false;
}
@@ -211,7 +174,7 @@ bool QLocalServerPrivate::addListener()
break;
default:
CloseHandle(listener->handle);
- setError(QLatin1String("QLocalServerPrivate::addListener"));
+ setError("QLocalServerPrivate::addListener"_L1);
listeners.pop_back();
return false;
}
@@ -243,7 +206,7 @@ bool QLocalServerPrivate::listen(const QString &name)
{
Q_Q(QLocalServer);
- const QLatin1String pipePath("\\\\.\\pipe\\");
+ const auto pipePath = "\\\\.\\pipe\\"_L1;
if (name.startsWith(pipePath))
fullServerName = name;
else
@@ -256,7 +219,7 @@ bool QLocalServerPrivate::listen(const QString &name)
connectionEventNotifier = new QWinEventNotifier(eventHandle , q);
q->connect(connectionEventNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_onNewConnection()));
- for (int i = 0; i < SYSTEM_MAX_PENDING_SOCKETS; ++i)
+ for (int i = 0; i < listenBacklog; ++i)
if (!addListener())
return false;
@@ -303,7 +266,7 @@ void QLocalServerPrivate::_q_onNewConnection()
} else {
if (GetLastError() != ERROR_IO_INCOMPLETE) {
q->close();
- setError(QLatin1String("QLocalServerPrivate::_q_onNewConnection"));
+ setError("QLocalServerPrivate::_q_onNewConnection"_L1);
return;
}
diff --git a/src/network/socket/qlocalsocket.cpp b/src/network/socket/qlocalsocket.cpp
index 19c0b2389e..dff7e42849 100644
--- a/src/network/socket/qlocalsocket.cpp
+++ b/src/network/socket/qlocalsocket.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include <QtNetwork/private/qtnetworkglobal_p.h>
@@ -66,6 +30,21 @@ QT_BEGIN_NAMESPACE
*/
/*!
+ \enum QLocalSocket::SocketOption
+ \since 6.2
+ This enum describes the possible options that can be used to connect to
+ a server. Currently, on Linux and Android it is used for specifying
+ connection to a server listening to a socket bound to an abstract address.
+
+ \value NoOptions No options have been set.
+ \value AbstractNamespaceOption
+ The socket will try to connect to an abstract address. This flag is specific
+ to Linux and Android. On other platforms is ignored.
+
+ \sa socketOptions
+*/
+
+/*!
\fn void QLocalSocket::connectToServer(OpenMode openMode)
\since 5.1
@@ -90,7 +69,7 @@ QT_BEGIN_NAMESPACE
Note that unlike in most other QIODevice subclasses, open() may not open the device directly.
The function return false if the socket was already connected or if the server to connect
to was not defined and true in any other case. The connected() or errorOccurred() signals will be
- emitted once the device is actualy open (or the connection failed).
+ emitted once the device is actually open (or the connection failed).
See connectToServer() for more details.
*/
@@ -132,8 +111,7 @@ QT_BEGIN_NAMESPACE
\list
\li On Windows, the returned value is a
- \l{https://msdn.microsoft.com/en-us/library/windows/desktop/ms740522(v=vs.85).aspx}
- {Winsock 2 Socket Handle}.
+ \l{Winsock 2 Socket Handle}.
\li On INTEGRITY, the returned value is the
QTcpSocket socket descriptor and the type is defined by
@@ -152,6 +130,11 @@ QT_BEGIN_NAMESPACE
*/
/*!
+ \fn qint64 QLocalSocket::readLineData(char *data, qint64 maxSize)
+ \reimp
+*/
+
+/*!
\fn qint64 QLocalSocket::skipData(qint64 maxSize)
\reimp
*/
@@ -188,7 +171,14 @@ QT_BEGIN_NAMESPACE
/*!
\fn void QLocalSocket::close()
- \reimp
+
+ Closes the I/O device for the socket and calls disconnectFromServer()
+ to close the socket's connection.
+
+ See QIODevice::close() for a description of the actions that occur when an I/O
+ device is closed.
+
+ \sa abort()
*/
/*!
@@ -219,7 +209,7 @@ QT_BEGIN_NAMESPACE
Attempts to close the socket. If there is pending data waiting to be
written, QLocalSocket will enter ClosingState and wait until all data
has been written. Eventually, it will enter UnconnectedState and emit
- the disconnectedFromServer() signal.
+ the disconnected() signal.
\sa connectToServer()
*/
@@ -369,6 +359,8 @@ QLocalSocket::QLocalSocket(QObject * parent)
: QIODevice(*new QLocalSocketPrivate, parent)
{
Q_D(QLocalSocket);
+
+ d->readBufferChunkSize = 0; // force QIODevice unbuffered mode
d->init();
}
@@ -377,7 +369,7 @@ QLocalSocket::QLocalSocket(QObject * parent)
*/
QLocalSocket::~QLocalSocket()
{
- QLocalSocket::close();
+ abort();
#if !defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
Q_D(QLocalSocket);
d->unixSocket.setParent(nullptr);
@@ -439,6 +431,37 @@ QString QLocalSocket::serverName() const
}
/*!
+ \property QLocalSocket::socketOptions
+ \since 6.2
+ \brief the socket options.
+
+ Options must be set while the socket is in \l{UnconnectedState} state.
+
+ \sa connectToServer()
+ */
+QLocalSocket::SocketOptions QLocalSocket::socketOptions() const
+{
+ Q_D(const QLocalSocket);
+ return d->socketOptions;
+}
+
+void QLocalSocket::setSocketOptions(QLocalSocket::SocketOptions option)
+{
+ Q_D(QLocalSocket);
+ if (d->state != UnconnectedState) {
+ qWarning("QLocalSocket::setSocketOptions() called while not in unconnected state");
+ return;
+ }
+ d->socketOptions = option;
+}
+
+QBindable<QLocalSocket::SocketOptions> QLocalSocket::bindableSocketOptions()
+{
+ Q_D(QLocalSocket);
+ return &d->socketOptions;
+}
+
+/*!
Returns the server path that the socket is connected to.
\note The return value of this function is platform specific.
diff --git a/src/network/socket/qlocalsocket.h b/src/network/socket/qlocalsocket.h
index 22763cb339..2bd9689a05 100644
--- a/src/network/socket/qlocalsocket.h
+++ b/src/network/socket/qlocalsocket.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QLOCALSOCKET_H
#define QLOCALSOCKET_H
@@ -44,6 +8,10 @@
#include <QtCore/qiodevice.h>
#include <QtNetwork/qabstractsocket.h>
+#ifndef QT_NO_DEBUG_STREAM
+#include <QtCore/qdebug.h>
+#endif
+
QT_REQUIRE_CONFIG(localserver);
QT_BEGIN_NAMESPACE
@@ -54,6 +22,8 @@ class Q_NETWORK_EXPORT QLocalSocket : public QIODevice
{
Q_OBJECT
Q_DECLARE_PRIVATE(QLocalSocket)
+ Q_PROPERTY(SocketOptions socketOptions READ socketOptions WRITE setSocketOptions
+ BINDABLE bindableSocketOptions)
public:
enum LocalSocketError
@@ -79,6 +49,13 @@ public:
ClosingState = QAbstractSocket::ClosingState
};
+ enum SocketOption {
+ NoOptions = 0x00,
+ AbstractNamespaceOption = 0x01
+ };
+ Q_DECLARE_FLAGS(SocketOptions, SocketOption)
+ Q_FLAG(SocketOptions)
+
QLocalSocket(QObject *parent = nullptr);
~QLocalSocket();
@@ -108,6 +85,10 @@ public:
OpenMode openMode = ReadWrite);
qintptr socketDescriptor() const;
+ void setSocketOptions(SocketOptions option);
+ SocketOptions socketOptions() const;
+ QBindable<SocketOptions> bindableSocketOptions();
+
LocalSocketState state() const;
bool waitForBytesWritten(int msecs = 30000) override;
bool waitForConnected(int msecs = 30000);
@@ -122,6 +103,7 @@ Q_SIGNALS:
protected:
virtual qint64 readData(char*, qint64) override;
+ qint64 readLineData(char *data, qint64 maxSize) override;
qint64 skipData(qint64 maxSize) override;
virtual qint64 writeData(const char*, qint64) override;
@@ -131,7 +113,6 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_stateChanged(QAbstractSocket::SocketState))
Q_PRIVATE_SLOT(d_func(), void _q_errorOccurred(QAbstractSocket::SocketError))
#elif defined(Q_OS_WIN)
- Q_PRIVATE_SLOT(d_func(), void _q_canWrite())
Q_PRIVATE_SLOT(d_func(), void _q_pipeClosed())
Q_PRIVATE_SLOT(d_func(), void _q_winError(ulong, const QString &))
#else
@@ -143,11 +124,12 @@ private:
};
#ifndef QT_NO_DEBUG_STREAM
-#include <QtCore/qdebug.h>
Q_NETWORK_EXPORT QDebug operator<<(QDebug, QLocalSocket::LocalSocketError);
Q_NETWORK_EXPORT QDebug operator<<(QDebug, QLocalSocket::LocalSocketState);
#endif
+Q_DECLARE_OPERATORS_FOR_FLAGS(QLocalSocket::SocketOptions)
+
QT_END_NAMESPACE
#endif // QLOCALSOCKET_H
diff --git a/src/network/socket/qlocalsocket_p.h b/src/network/socket/qlocalsocket_p.h
index 7eff502607..82446161c7 100644
--- a/src/network/socket/qlocalsocket_p.h
+++ b/src/network/socket/qlocalsocket_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QLOCALSOCKET_P_H
#define QLOCALSOCKET_P_H
@@ -73,9 +37,12 @@ QT_REQUIRE_CONFIG(localserver);
# include <errno.h>
#endif
+struct sockaddr_un;
+
QT_BEGIN_NAMESPACE
#if !defined(Q_OS_WIN) || defined(QT_LOCALSOCKET_TCP)
+
class QLocalUnixSocket : public QTcpSocket
{
@@ -113,9 +80,9 @@ public:
class QLocalSocketPrivate : public QIODevicePrivate
{
+public:
Q_DECLARE_PUBLIC(QLocalSocket)
-public:
QLocalSocketPrivate();
void init();
@@ -129,10 +96,12 @@ public:
void _q_errorOccurred(QAbstractSocket::SocketError newError);
#elif defined(Q_OS_WIN)
~QLocalSocketPrivate();
- void destroyPipeHandles();
- void _q_canWrite();
+ qint64 pipeWriterBytesToWrite() const;
+ void _q_canRead();
+ void _q_bytesWritten(qint64 bytes);
void _q_pipeClosed();
void _q_winError(ulong windowsError, const QString &function);
+ void _q_writeFailed();
HANDLE handle;
QWindowsPipeWriter *pipeWriter;
QWindowsPipeReader *pipeReader;
@@ -146,16 +115,24 @@ public:
void _q_connectToSocket();
void _q_abortConnectionAttempt();
void cancelDelayedConnect();
+ void describeSocket(qintptr socketDescriptor);
+ static bool parseSockaddr(const sockaddr_un &addr, uint len,
+ QString &fullServerName, QString &serverName, bool &abstractNamespace);
QSocketNotifier *delayConnect;
QTimer *connectTimer;
- int connectingSocket;
QString connectingName;
+ int connectingSocket;
QIODevice::OpenMode connectingOpenMode;
#endif
-
+ QLocalSocket::LocalSocketState state;
QString serverName;
QString fullServerName;
- QLocalSocket::LocalSocketState state;
+#if defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
+ bool emittedReadyRead;
+ bool emittedBytesWritten;
+#endif
+
+ Q_OBJECT_BINDABLE_PROPERTY(QLocalSocketPrivate, QLocalSocket::SocketOptions, socketOptions)
};
QT_END_NAMESPACE
diff --git a/src/network/socket/qlocalsocket_tcp.cpp b/src/network/socket/qlocalsocket_tcp.cpp
index 2f0179f40a..c7870b3dff 100644
--- a/src/network/socket/qlocalsocket_tcp.cpp
+++ b/src/network/socket/qlocalsocket_tcp.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
@@ -47,6 +11,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
tcpSocket(0),
ownsTcpSocket(true),
@@ -68,7 +34,6 @@ void QLocalSocketPrivate::setSocket(QLocalUnixSocket* socket)
Q_Q(QLocalSocket);
// QIODevice signals
- q->connect(tcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
q->connect(tcpSocket, SIGNAL(bytesWritten(qint64)),
q, SIGNAL(bytesWritten(qint64)));
q->connect(tcpSocket, SIGNAL(readyRead()), q, SIGNAL(readyRead()));
@@ -86,7 +51,7 @@ void QLocalSocketPrivate::setSocket(QLocalUnixSocket* socket)
void QLocalSocketPrivate::_q_errorOccurred(QAbstractSocket::SocketError socketError)
{
Q_Q(QLocalSocket);
- QString function = QLatin1String("QLocalSocket");
+ QString function = "QLocalSocket"_L1;
QLocalSocket::LocalSocketError error = (QLocalSocket::LocalSocketError)socketError;
QString errorString = generateErrorString(error, function);
q->setErrorString(errorString);
@@ -226,23 +191,21 @@ void QLocalSocket::connectToServer(OpenMode openMode)
emit stateChanged(d->state);
if (d->serverName.isEmpty()) {
- d->setErrorAndEmit(ServerNotFoundError,
- QLatin1String("QLocalSocket::connectToServer"));
+ d->setErrorAndEmit(ServerNotFoundError, "QLocalSocket::connectToServer"_L1);
return;
}
- const QLatin1String prefix("QLocalServer/");
+ const auto prefix = "QLocalServer/"_L1;
if (d->serverName.startsWith(prefix))
d->fullServerName = d->serverName;
else
d->fullServerName = prefix + d->serverName;
- QSettings settings(QLatin1String("QtProject"), QLatin1String("Qt"));
+ QSettings settings("QtProject"_L1, "Qt"_L1);
bool ok;
const quint16 port = settings.value(d->fullServerName).toUInt(&ok);
if (!ok) {
- d->setErrorAndEmit(ServerNotFoundError,
- QLatin1String("QLocalSocket::connectToServer"));
+ d->setErrorAndEmit(ServerNotFoundError, "QLocalSocket::connectToServer"_L1);
return;
}
QIODevice::open(openMode);
@@ -301,6 +264,16 @@ qint64 QLocalSocket::readData(char *data, qint64 c)
return d->tcpSocket->read(data, c);
}
+qint64 QLocalSocket::readLineData(char *data, qint64 maxSize)
+{
+ if (!maxSize)
+ return 0;
+
+ // QIODevice::readLine() reserves space for the trailing '\0' byte,
+ // so we must read 'maxSize + 1' bytes.
+ return d_func()->tcpSocket->readLine(data, maxSize + 1);
+}
+
qint64 QLocalSocket::skipData(qint64 maxSize)
{
return d_func()->tcpSocket->skip(maxSize);
@@ -316,6 +289,7 @@ void QLocalSocket::abort()
{
Q_D(QLocalSocket);
d->tcpSocket->abort();
+ close();
}
qint64 QLocalSocket::bytesAvailable() const
@@ -339,10 +313,11 @@ bool QLocalSocket::canReadLine() const
void QLocalSocket::close()
{
Q_D(QLocalSocket);
+
+ QIODevice::close();
d->tcpSocket->close();
d->serverName.clear();
d->fullServerName.clear();
- QIODevice::close();
}
bool QLocalSocket::waitForBytesWritten(int msecs)
diff --git a/src/network/socket/qlocalsocket_unix.cpp b/src/network/socket/qlocalsocket_unix.cpp
index 6fd17a6213..af0dc988af 100644
--- a/src/network/socket/qlocalsocket_unix.cpp
+++ b/src/network/socket/qlocalsocket_unix.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
@@ -49,22 +13,51 @@
#include <errno.h>
#include <qdir.h>
+#include <qdeadlinetimer.h>
#include <qdebug.h>
-#include <qelapsedtimer.h>
+#include <qstringconverter.h>
#ifdef Q_OS_VXWORKS
# include <selectLib.h>
#endif
+using namespace std::chrono_literals;
+
#define QT_CONNECT_TIMEOUT 30000
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
+namespace {
+// determine the full server path
+static QString pathNameForConnection(const QString &connectingName,
+ QLocalSocket::SocketOptions options)
+{
+ if (options.testFlag(QLocalSocket::AbstractNamespaceOption)
+ || connectingName.startsWith(u'/')) {
+ return connectingName;
+ }
+
+ return QDir::tempPath() + u'/' + connectingName;
+}
+
+static QLocalSocket::SocketOptions optionsForPlatform(QLocalSocket::SocketOptions srcOptions)
+{
+ // For OS that does not support abstract namespace the AbstractNamespaceOption
+ // option is cleared.
+ if (!PlatformSupportsAbstractNamespace)
+ return QLocalSocket::NoOptions;
+ return srcOptions;
+}
+}
+
QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
delayConnect(nullptr),
connectTimer(nullptr),
connectingSocket(-1),
- state(QLocalSocket::UnconnectedState)
+ state(QLocalSocket::UnconnectedState),
+ socketOptions(QLocalSocket::NoOptions)
{
}
@@ -72,7 +65,6 @@ void QLocalSocketPrivate::init()
{
Q_Q(QLocalSocket);
// QIODevice signals
- q->connect(&unixSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
q->connect(&unixSocket, SIGNAL(bytesWritten(qint64)),
q, SIGNAL(bytesWritten(qint64)));
q->connect(&unixSocket, SIGNAL(readyRead()), q, SIGNAL(readyRead()));
@@ -90,7 +82,7 @@ void QLocalSocketPrivate::init()
void QLocalSocketPrivate::_q_errorOccurred(QAbstractSocket::SocketError socketError)
{
Q_Q(QLocalSocket);
- QString function = QLatin1String("QLocalSocket");
+ QString function = "QLocalSocket"_L1;
QLocalSocket::LocalSocketError error = (QLocalSocket::LocalSocketError)socketError;
QString errorString = generateErrorString(error, function);
q->setErrorString(errorString);
@@ -220,7 +212,7 @@ void QLocalSocket::connectToServer(OpenMode openMode)
{
Q_D(QLocalSocket);
if (state() == ConnectedState || state() == ConnectingState) {
- QString errorString = d->generateErrorString(QLocalSocket::OperationError, QLatin1String("QLocalSocket::connectToserver"));
+ QString errorString = d->generateErrorString(QLocalSocket::OperationError, "QLocalSocket::connectToserver"_L1);
setErrorString(errorString);
emit errorOccurred(QLocalSocket::OperationError);
return;
@@ -232,15 +224,13 @@ void QLocalSocket::connectToServer(OpenMode openMode)
emit stateChanged(d->state);
if (d->serverName.isEmpty()) {
- d->setErrorAndEmit(ServerNotFoundError,
- QLatin1String("QLocalSocket::connectToServer"));
+ d->setErrorAndEmit(ServerNotFoundError, "QLocalSocket::connectToServer"_L1);
return;
}
// create the socket
if (-1 == (d->connectingSocket = qt_safe_socket(PF_UNIX, SOCK_STREAM, 0, O_NONBLOCK))) {
- d->setErrorAndEmit(UnsupportedSocketOperationError,
- QLatin1String("QLocalSocket::connectToServer"));
+ d->setErrorAndEmit(UnsupportedSocketOperationError, "QLocalSocket::connectToServer"_L1);
return;
}
@@ -261,28 +251,34 @@ void QLocalSocket::connectToServer(OpenMode openMode)
void QLocalSocketPrivate::_q_connectToSocket()
{
Q_Q(QLocalSocket);
- QString connectingPathName;
-
- // determine the full server path
- if (connectingName.startsWith(QLatin1Char('/'))) {
- connectingPathName = connectingName;
- } else {
- connectingPathName = QDir::tempPath();
- connectingPathName += QLatin1Char('/') + connectingName;
- }
+ QLocalSocket::SocketOptions options = optionsForPlatform(socketOptions);
+ const QString connectingPathName = pathNameForConnection(connectingName, options);
const QByteArray encodedConnectingPathName = QFile::encodeName(connectingPathName);
- struct sockaddr_un name;
- name.sun_family = PF_UNIX;
- if (sizeof(name.sun_path) < (uint)encodedConnectingPathName.size() + 1) {
- QString function = QLatin1String("QLocalSocket::connectToServer");
+ struct ::sockaddr_un addr;
+ addr.sun_family = PF_UNIX;
+ memset(addr.sun_path, 0, sizeof(addr.sun_path));
+
+ // for abstract socket add 2 to length, to take into account trailing AND leading null
+ constexpr unsigned int extraCharacters = PlatformSupportsAbstractNamespace ? 2 : 1;
+
+ if (sizeof(addr.sun_path) < static_cast<size_t>(encodedConnectingPathName.size() + extraCharacters)) {
+ QString function = "QLocalSocket::connectToServer"_L1;
setErrorAndEmit(QLocalSocket::ServerNotFoundError, function);
return;
}
- ::memcpy(name.sun_path, encodedConnectingPathName.constData(),
- encodedConnectingPathName.size() + 1);
- if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&name, sizeof(name))) {
- QString function = QLatin1String("QLocalSocket::connectToServer");
+
+ QT_SOCKLEN_T addrSize = sizeof(::sockaddr_un);
+ if (options.testFlag(QLocalSocket::AbstractNamespaceOption)) {
+ ::memcpy(addr.sun_path + 1, encodedConnectingPathName.constData(),
+ encodedConnectingPathName.size() + 1);
+ addrSize = offsetof(::sockaddr_un, sun_path) + encodedConnectingPathName.size() + 1;
+ } else {
+ ::memcpy(addr.sun_path, encodedConnectingPathName.constData(),
+ encodedConnectingPathName.size() + 1);
+ }
+ if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&addr, addrSize)) {
+ QString function = "QLocalSocket::connectToServer"_L1;
switch (errno)
{
case EINVAL:
@@ -327,10 +323,10 @@ void QLocalSocketPrivate::_q_connectToSocket()
fullServerName = connectingPathName;
if (unixSocket.setSocketDescriptor(connectingSocket,
QAbstractSocket::ConnectedState, connectingOpenMode)) {
- q->QIODevice::open(connectingOpenMode | QIODevice::Unbuffered);
+ q->QIODevice::open(connectingOpenMode);
q->emit connected();
} else {
- QString function = QLatin1String("QLocalSocket::connectToServer");
+ QString function = "QLocalSocket::connectToServer"_L1;
setErrorAndEmit(QLocalSocket::UnknownSocketError, function);
}
connectingSocket = -1;
@@ -359,10 +355,69 @@ bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor,
}
QIODevice::open(openMode);
d->state = socketState;
+ d->describeSocket(socketDescriptor);
return d->unixSocket.setSocketDescriptor(socketDescriptor,
newSocketState, openMode);
}
+void QLocalSocketPrivate::describeSocket(qintptr socketDescriptor)
+{
+ bool abstractAddress = false;
+
+ struct ::sockaddr_un addr;
+ QT_SOCKLEN_T len = sizeof(addr);
+ memset(&addr, 0, sizeof(addr));
+ const int getpeernameStatus = ::getpeername(socketDescriptor, (sockaddr *)&addr, &len);
+ if (getpeernameStatus != 0 || len == offsetof(sockaddr_un, sun_path)) {
+ // this is the case when we call it from QLocalServer, then there is no peername
+ len = sizeof(addr);
+ if (::getsockname(socketDescriptor, (sockaddr *)&addr, &len) != 0)
+ return;
+ }
+ if (parseSockaddr(addr, static_cast<uint>(len), fullServerName, serverName, abstractAddress)) {
+ QLocalSocket::SocketOptions options = socketOptions.value();
+ socketOptions = options.setFlag(QLocalSocket::AbstractNamespaceOption, abstractAddress);
+ }
+}
+
+bool QLocalSocketPrivate::parseSockaddr(const struct ::sockaddr_un &addr,
+ uint len,
+ QString &fullServerName,
+ QString &serverName,
+ bool &abstractNamespace)
+{
+ if (len <= offsetof(::sockaddr_un, sun_path))
+ return false;
+ len -= offsetof(::sockaddr_un, sun_path);
+ // check for abstract socket address
+ abstractNamespace = PlatformSupportsAbstractNamespace
+ && (addr.sun_family == PF_UNIX && addr.sun_path[0] == 0);
+ QStringDecoder toUtf16(QStringDecoder::System, QStringDecoder::Flag::Stateless);
+ // An abstract socket address can be arbitrary binary. To properly handle such a case,
+ // we'd have to add new access functions for this very specific case. Instead, we just
+ // attempt to decode it according to OS text encoding. If it fails we ignore the result.
+ QByteArrayView textData(addr.sun_path + (abstractNamespace ? 1 : 0),
+ len - (abstractNamespace ? 1 : 0));
+ QString name = toUtf16(textData);
+ if (!name.isEmpty() && !toUtf16.hasError()) {
+ //conversion encodes the trailing zeros. So, in case of non-abstract namespace we
+ //chop them off as \0 character is not allowed in filenames
+ if (!abstractNamespace && (name.at(name.size() - 1) == QChar::fromLatin1('\0'))) {
+ int truncPos = name.size() - 1;
+ while (truncPos > 0 && name.at(truncPos - 1) == QChar::fromLatin1('\0'))
+ truncPos--;
+ name.truncate(truncPos);
+ }
+ fullServerName = name;
+ serverName = abstractNamespace
+ ? name
+ : fullServerName.mid(fullServerName.lastIndexOf(u'/') + 1);
+ if (serverName.isEmpty())
+ serverName = fullServerName;
+ }
+ return true;
+}
+
void QLocalSocketPrivate::_q_abortConnectionAttempt()
{
Q_Q(QLocalSocket);
@@ -393,6 +448,16 @@ qint64 QLocalSocket::readData(char *data, qint64 c)
return d->unixSocket.read(data, c);
}
+qint64 QLocalSocket::readLineData(char *data, qint64 maxSize)
+{
+ if (!maxSize)
+ return 0;
+
+ // QIODevice::readLine() reserves space for the trailing '\0' byte,
+ // so we must read 'maxSize + 1' bytes.
+ return d_func()->unixSocket.readLine(data, maxSize + 1);
+}
+
qint64 QLocalSocket::skipData(qint64 maxSize)
{
return d_func()->unixSocket.skip(maxSize);
@@ -408,6 +473,7 @@ void QLocalSocket::abort()
{
Q_D(QLocalSocket);
d->unixSocket.abort();
+ close();
}
qint64 QLocalSocket::bytesAvailable() const
@@ -431,6 +497,8 @@ bool QLocalSocket::canReadLine() const
void QLocalSocket::close()
{
Q_D(QLocalSocket);
+
+ QIODevice::close();
d->unixSocket.close();
d->cancelDelayedConnect();
if (d->connectingSocket != -1)
@@ -440,7 +508,6 @@ void QLocalSocket::close()
d->connectingOpenMode = { };
d->serverName.clear();
d->fullServerName.clear();
- QIODevice::close();
}
bool QLocalSocket::waitForBytesWritten(int msecs)
@@ -519,21 +586,20 @@ bool QLocalSocket::waitForConnected(int msec)
if (state() != ConnectingState)
return (state() == ConnectedState);
- QElapsedTimer timer;
- timer.start();
-
pollfd pfd = qt_make_pollfd(d->connectingSocket, POLLIN);
- do {
- const int timeout = (msec > 0) ? qMax(msec - timer.elapsed(), Q_INT64_C(0)) : msec;
- const int result = qt_poll_msecs(&pfd, 1, timeout);
+ QDeadlineTimer deadline{msec};
+ auto remainingTime = deadline.remainingTimeAsDuration();
+ do {
+ const int result = qt_safe_poll(&pfd, 1, deadline);
if (result == -1)
d->setErrorAndEmit(QLocalSocket::UnknownSocketError,
- QLatin1String("QLocalSocket::waitForConnected"));
+ "QLocalSocket::waitForConnected"_L1);
else if (result > 0)
d->_q_connectToSocket();
- } while (state() == ConnectingState && !timer.hasExpired(msec));
+ } while (state() == ConnectingState
+ && (remainingTime = deadline.remainingTimeAsDuration()) > 0ns);
return (state() == ConnectedState);
}
diff --git a/src/network/socket/qlocalsocket_win.cpp b/src/network/socket/qlocalsocket_win.cpp
index 41ec5a94d4..b3f3f9002a 100644
--- a/src/network/socket/qlocalsocket_win.cpp
+++ b/src/network/socket/qlocalsocket_win.cpp
@@ -1,51 +1,86 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlocalsocket_p.h"
+#include <qscopedvaluerollback.h>
+#include <qdeadlinetimer.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
+namespace {
+struct QSocketPoller
+{
+ QSocketPoller(const QLocalSocketPrivate &socket);
+
+ qint64 getRemainingTime(const QDeadlineTimer &deadline) const;
+ bool poll(const QDeadlineTimer &deadline);
+
+ enum { maxHandles = 2 };
+ HANDLE handles[maxHandles];
+ DWORD handleCount = 0;
+ bool waitForClose = false;
+ bool writePending = false;
+};
+
+QSocketPoller::QSocketPoller(const QLocalSocketPrivate &socket)
+{
+ if (socket.pipeWriter && socket.pipeWriter->isWriteOperationActive()) {
+ handles[handleCount++] = socket.pipeWriter->syncEvent();
+ writePending = true;
+ }
+ if (socket.pipeReader->isReadOperationActive())
+ handles[handleCount++] = socket.pipeReader->syncEvent();
+ else
+ waitForClose = true;
+}
+
+qint64 QSocketPoller::getRemainingTime(const QDeadlineTimer &deadline) const
+{
+ const qint64 sleepTime = 10;
+ qint64 remainingTime = deadline.remainingTime();
+ if (waitForClose && (remainingTime > sleepTime || remainingTime == -1))
+ return sleepTime;
+
+ return remainingTime;
+}
+
+/*!
+ \internal
+
+ Waits until new data is available for reading or write operation
+ completes. Returns \c true, if we need to check pipe workers;
+ otherwise it returns \c false (if an error occurred or the operation
+ timed out).
+
+ \note If the read operation is inactive, it succeeds after
+ a short wait, allowing the caller to check the state of the socket.
+*/
+bool QSocketPoller::poll(const QDeadlineTimer &deadline)
+{
+ Q_ASSERT(handleCount != 0);
+ QDeadlineTimer timer(getRemainingTime(deadline));
+ DWORD waitRet;
+
+ do {
+ waitRet = WaitForMultipleObjectsEx(handleCount, handles, FALSE,
+ timer.remainingTime(), TRUE);
+ } while (waitRet == WAIT_IO_COMPLETION);
+
+ if (waitRet == WAIT_TIMEOUT)
+ return waitForClose || !deadline.hasExpired();
+
+ return waitRet - WAIT_OBJECT_0 < handleCount;
+}
+} // anonymous namespace
+
void QLocalSocketPrivate::init()
{
Q_Q(QLocalSocket);
pipeReader = new QWindowsPipeReader(q);
- q->connect(pipeReader, SIGNAL(readyRead()), SIGNAL(readyRead()));
+ QObjectPrivate::connect(pipeReader, &QWindowsPipeReader::readyRead,
+ this, &QLocalSocketPrivate::_q_canRead);
q->connect(pipeReader, SIGNAL(pipeClosed()), SLOT(_q_pipeClosed()), Qt::QueuedConnection);
q->connect(pipeReader, SIGNAL(winError(ulong,QString)), SLOT(_q_winError(ulong,QString)));
}
@@ -99,22 +134,17 @@ QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
pipeWriter(0),
pipeReader(0),
error(QLocalSocket::UnknownSocketError),
- state(QLocalSocket::UnconnectedState)
+ state(QLocalSocket::UnconnectedState),
+ emittedReadyRead(false),
+ emittedBytesWritten(false)
{
- writeBufferChunkSize = QIODEVICE_BUFFERSIZE;
}
QLocalSocketPrivate::~QLocalSocketPrivate()
{
- destroyPipeHandles();
-}
-
-void QLocalSocketPrivate::destroyPipeHandles()
-{
- if (handle != INVALID_HANDLE_VALUE) {
- DisconnectNamedPipe(handle);
- CloseHandle(handle);
- }
+ Q_ASSERT(state == QLocalSocket::UnconnectedState);
+ Q_ASSERT(handle == INVALID_HANDLE_VALUE);
+ Q_ASSERT(pipeWriter == nullptr);
}
void QLocalSocket::connectToServer(OpenMode openMode)
@@ -133,14 +163,14 @@ void QLocalSocket::connectToServer(OpenMode openMode)
emit stateChanged(d->state);
if (d->serverName.isEmpty()) {
d->error = ServerNotFoundError;
- d->errorString = tr("%1: Invalid name").arg(QLatin1String("QLocalSocket::connectToServer"));
+ d->errorString = tr("%1: Invalid name").arg("QLocalSocket::connectToServer"_L1);
d->state = UnconnectedState;
emit errorOccurred(d->error);
emit stateChanged(d->state);
return;
}
- const QLatin1String pipePath("\\\\.\\pipe\\");
+ const auto pipePath = "\\\\.\\pipe\\"_L1;
if (d->serverName.startsWith(pipePath))
d->fullServerName = d->serverName;
else
@@ -173,7 +203,7 @@ void QLocalSocket::connectToServer(OpenMode openMode)
if (localSocket == INVALID_HANDLE_VALUE) {
const DWORD winError = GetLastError();
- d->_q_winError(winError, QLatin1String("QLocalSocket::connectToServer"));
+ d->_q_winError(winError, "QLocalSocket::connectToServer"_L1);
d->fullServerName = QString();
return;
}
@@ -183,6 +213,20 @@ void QLocalSocket::connectToServer(OpenMode openMode)
emit connected();
}
+static qint64 transformPipeReaderResult(qint64 res)
+{
+ // QWindowsPipeReader's reading functions return error codes
+ // that don't match what we need.
+ switch (res) {
+ case 0: // EOF -> transform to error
+ return -1;
+ case -2: // EWOULDBLOCK -> no error, just no bytes
+ return 0;
+ default:
+ return res;
+ }
+}
+
// This is reading from the buffer
qint64 QLocalSocket::readData(char *data, qint64 maxSize)
{
@@ -191,22 +235,29 @@ qint64 QLocalSocket::readData(char *data, qint64 maxSize)
if (!maxSize)
return 0;
- qint64 ret = d->pipeReader->read(data, maxSize);
+ return transformPipeReaderResult(d->pipeReader->read(data, maxSize));
+}
- // QWindowsPipeReader::read() returns error codes that don't match what we need
- switch (ret) {
- case 0: // EOF -> transform to error
- return -1;
- case -2: // EWOULDBLOCK -> no error, just no bytes
+qint64 QLocalSocket::readLineData(char *data, qint64 maxSize)
+{
+ Q_D(QLocalSocket);
+
+ if (!maxSize)
return 0;
- default:
- return ret;
- }
+
+ // QIODevice::readLine() reserves space for the trailing '\0' byte,
+ // so we must read 'maxSize + 1' bytes.
+ return transformPipeReaderResult(d->pipeReader->readLine(data, maxSize + 1));
}
qint64 QLocalSocket::skipData(qint64 maxSize)
{
- return QIODevice::skipData(maxSize);
+ Q_D(QLocalSocket);
+
+ if (!maxSize)
+ return 0;
+
+ return transformPipeReaderResult(d->pipeReader->skip(maxSize));
}
qint64 QLocalSocket::writeData(const char *data, qint64 len)
@@ -220,15 +271,20 @@ qint64 QLocalSocket::writeData(const char *data, qint64 len)
if (len == 0)
return 0;
- d->write(data, len);
+
if (!d->pipeWriter) {
d->pipeWriter = new QWindowsPipeWriter(d->handle, this);
- connect(d->pipeWriter, &QWindowsPipeWriter::bytesWritten,
- this, &QLocalSocket::bytesWritten);
- QObjectPrivate::connect(d->pipeWriter, &QWindowsPipeWriter::canWrite,
- d, &QLocalSocketPrivate::_q_canWrite);
+ QObjectPrivate::connect(d->pipeWriter, &QWindowsPipeWriter::bytesWritten,
+ d, &QLocalSocketPrivate::_q_bytesWritten);
+ QObjectPrivate::connect(d->pipeWriter, &QWindowsPipeWriter::writeFailed,
+ d, &QLocalSocketPrivate::_q_writeFailed);
}
- d->_q_canWrite();
+
+ if (d->isWriteChunkCached(data, len))
+ d->pipeWriter->write(*(d->currentWriteChunk));
+ else
+ d->pipeWriter->write(data, len);
+
return len;
}
@@ -242,31 +298,43 @@ void QLocalSocket::abort()
close();
}
+void QLocalSocketPrivate::_q_canRead()
+{
+ Q_Q(QLocalSocket);
+ if (!emittedReadyRead) {
+ QScopedValueRollback<bool> guard(emittedReadyRead, true);
+ emit q->readyRead();
+ }
+}
+
void QLocalSocketPrivate::_q_pipeClosed()
{
Q_Q(QLocalSocket);
if (state == QLocalSocket::UnconnectedState)
return;
- emit q->readChannelFinished();
if (state != QLocalSocket::ClosingState) {
state = QLocalSocket::ClosingState;
emit q->stateChanged(state);
if (state != QLocalSocket::ClosingState)
return;
}
- state = QLocalSocket::UnconnectedState;
- emit q->stateChanged(state);
- emit q->disconnected();
+ serverName.clear();
+ fullServerName.clear();
pipeReader->stop();
- destroyPipeHandles();
- handle = INVALID_HANDLE_VALUE;
-
- if (pipeWriter) {
- delete pipeWriter;
- pipeWriter = 0;
+ delete pipeWriter;
+ pipeWriter = nullptr;
+ if (handle != INVALID_HANDLE_VALUE) {
+ DisconnectNamedPipe(handle);
+ CloseHandle(handle);
+ handle = INVALID_HANDLE_VALUE;
}
+
+ state = QLocalSocket::UnconnectedState;
+ emit q->stateChanged(state);
+ emit q->readChannelFinished();
+ emit q->disconnected();
}
qint64 QLocalSocket::bytesAvailable() const
@@ -280,7 +348,7 @@ qint64 QLocalSocket::bytesAvailable() const
qint64 QLocalSocket::bytesToWrite() const
{
Q_D(const QLocalSocket);
- return d->writeBuffer.size() + (d->pipeWriter ? d->pipeWriter->bytesToWrite() : 0);
+ return d->pipeWriterBytesToWrite();
}
bool QLocalSocket::canReadLine() const
@@ -292,52 +360,30 @@ bool QLocalSocket::canReadLine() const
void QLocalSocket::close()
{
Q_D(QLocalSocket);
- if (openMode() == NotOpen)
- return;
- d->setWriteChannelCount(0);
QIODevice::close();
+ d->pipeReader->stopAndClear();
d->serverName = QString();
d->fullServerName = QString();
-
- if (state() != UnconnectedState) {
- if (bytesToWrite() > 0) {
- disconnectFromServer();
- return;
- }
-
- d->_q_pipeClosed();
- }
+ disconnectFromServer();
}
bool QLocalSocket::flush()
{
Q_D(QLocalSocket);
- bool written = false;
- while (d->pipeWriter && d->pipeWriter->waitForWrite(0))
- written = true;
- return written;
+
+ return d->pipeWriter && d->pipeWriter->checkForWrite();
}
void QLocalSocket::disconnectFromServer()
{
Q_D(QLocalSocket);
- // Are we still connected?
- if (!isValid()) {
- // If we have unwritten data, the pipeWriter is still present.
- // It must be destroyed before close() to prevent an infinite loop.
- delete d->pipeWriter;
- d->pipeWriter = 0;
- d->writeBuffer.clear();
- }
-
- flush();
- if (bytesToWrite() != 0) {
+ if (bytesToWrite() == 0) {
+ d->_q_pipeClosed();
+ } else if (d->state != QLocalSocket::ClosingState) {
d->state = QLocalSocket::ClosingState;
emit stateChanged(d->state);
- } else {
- close();
}
}
@@ -362,17 +408,30 @@ bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor,
return true;
}
-void QLocalSocketPrivate::_q_canWrite()
+qint64 QLocalSocketPrivate::pipeWriterBytesToWrite() const
+{
+ return pipeWriter ? pipeWriter->bytesToWrite() : qint64(0);
+}
+
+void QLocalSocketPrivate::_q_bytesWritten(qint64 bytes)
{
Q_Q(QLocalSocket);
- if (writeBuffer.isEmpty()) {
- if (state == QLocalSocket::ClosingState)
- q->close();
- } else {
- Q_ASSERT(pipeWriter);
- if (!pipeWriter->isWriteOperationActive())
- pipeWriter->write(writeBuffer.read());
+ if (!emittedBytesWritten) {
+ QScopedValueRollback<bool> guard(emittedBytesWritten, true);
+ emit q->bytesWritten(bytes);
}
+ if (state == QLocalSocket::ClosingState)
+ q->disconnectFromServer();
+}
+
+void QLocalSocketPrivate::_q_writeFailed()
+{
+ Q_Q(QLocalSocket);
+ error = QLocalSocket::PeerClosedError;
+ errorString = QLocalSocket::tr("Remote closed");
+ emit q->errorOccurred(error);
+
+ _q_pipeClosed();
}
qintptr QLocalSocket::socketDescriptor() const
@@ -406,15 +465,38 @@ bool QLocalSocket::waitForDisconnected(int msecs)
qWarning("QLocalSocket::waitForDisconnected() is not allowed in UnconnectedState");
return false;
}
- if (!openMode().testFlag(QIODevice::ReadOnly)) {
- qWarning("QLocalSocket::waitForDisconnected isn't supported for write only pipes.");
- return false;
- }
- if (d->pipeReader->waitForPipeClosed(msecs)) {
- d->_q_pipeClosed();
- return true;
+
+ QDeadlineTimer deadline(msecs);
+ bool wasChecked = false;
+ while (!d->pipeReader->isPipeClosed()) {
+ if (wasChecked && deadline.hasExpired())
+ return false;
+
+ QSocketPoller poller(*d);
+ // The first parameter of the WaitForMultipleObjectsEx() call cannot
+ // be zero. So we have to call SleepEx() here.
+ if (!poller.writePending && poller.waitForClose) {
+ // Prevent waiting on the first pass, if both the pipe reader
+ // and the pipe writer are inactive.
+ if (wasChecked)
+ SleepEx(poller.getRemainingTime(deadline), TRUE);
+ } else if (!poller.poll(deadline)) {
+ return false;
+ }
+
+ if (d->pipeWriter)
+ d->pipeWriter->checkForWrite();
+
+ // When the read buffer is full, the read sequence is not running,
+ // so we need to peek the pipe to detect disconnection.
+ if (poller.waitForClose && isValid())
+ d->pipeReader->checkPipeState();
+
+ d->pipeReader->checkForReadyRead();
+ wasChecked = true;
}
- return false;
+ d->_q_pipeClosed();
+ return true;
}
bool QLocalSocket::isValid() const
@@ -430,32 +512,51 @@ bool QLocalSocket::waitForReadyRead(int msecs)
if (d->state != QLocalSocket::ConnectedState)
return false;
- // We already know that the pipe is gone, but did not enter the event loop yet.
- if (d->pipeReader->isPipeClosed()) {
- d->_q_pipeClosed();
- return false;
- }
+ QDeadlineTimer deadline(msecs);
+ while (!d->pipeReader->isPipeClosed()) {
+ QSocketPoller poller(*d);
+ if (poller.waitForClose || !poller.poll(deadline))
+ return false;
- bool result = d->pipeReader->waitForReadyRead(msecs);
-
- // We just noticed that the pipe is gone.
- if (d->pipeReader->isPipeClosed())
- d->_q_pipeClosed();
+ if (d->pipeWriter)
+ d->pipeWriter->checkForWrite();
- return result;
+ if (d->pipeReader->checkForReadyRead())
+ return true;
+ }
+ d->_q_pipeClosed();
+ return false;
}
bool QLocalSocket::waitForBytesWritten(int msecs)
{
- Q_D(const QLocalSocket);
- if (!d->pipeWriter)
+ Q_D(QLocalSocket);
+
+ if (d->state == QLocalSocket::UnconnectedState)
return false;
- // Wait for the pipe writer to acknowledge that it has
- // written. This will succeed if either the pipe writer has
- // already written the data, or if it manages to write data
- // within the given timeout.
- return d->pipeWriter->waitForWrite(msecs);
+ QDeadlineTimer deadline(msecs);
+ bool wasChecked = false;
+ while (!d->pipeReader->isPipeClosed()) {
+ if (wasChecked && deadline.hasExpired())
+ return false;
+
+ QSocketPoller poller(*d);
+ if (!poller.writePending || !poller.poll(deadline))
+ return false;
+
+ Q_ASSERT(d->pipeWriter);
+ if (d->pipeWriter->checkForWrite())
+ return true;
+
+ if (poller.waitForClose && isValid())
+ d->pipeReader->checkPipeState();
+
+ d->pipeReader->checkForReadyRead();
+ wasChecked = true;
+ }
+ d->_q_pipeClosed();
+ return false;
}
QT_END_NAMESPACE
diff --git a/src/network/socket/qnativesocketengine.cpp b/src/network/socket/qnativesocketengine.cpp
index 302b714cb4..4c8b3ebf3f 100644
--- a/src/network/socket/qnativesocketengine.cpp
+++ b/src/network/socket/qnativesocketengine.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QNATIVESOCKETENGINE_DEBUG
@@ -114,7 +78,7 @@
\sa readDatagram(), QNetworkDatagram
*/
-#include "qnativesocketengine_p.h"
+#include "qnativesocketengine_p_p.h"
#include <qabstracteventdispatcher.h>
#include <qsocketnotifier.h>
@@ -135,6 +99,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
//#define QNATIVESOCKETENGINE_DEBUG
#define Q_VOID
@@ -448,13 +414,13 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
// Create the socket
if (!d->createNewSocket(socketType, protocol)) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
- QString typeStr = QLatin1String("UnknownSocketType");
- if (socketType == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
- else if (socketType == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
- else if (socketType == QAbstractSocket::SctpSocket) typeStr = QLatin1String("SctpSocket");
- QString protocolStr = QLatin1String("UnknownProtocol");
- if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
- else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
+ QString typeStr = "UnknownSocketType"_L1;
+ if (socketType == QAbstractSocket::TcpSocket) typeStr = "TcpSocket"_L1;
+ else if (socketType == QAbstractSocket::UdpSocket) typeStr = "UdpSocket"_L1;
+ else if (socketType == QAbstractSocket::SctpSocket) typeStr = "SctpSocket"_L1;
+ QString protocolStr = "UnknownProtocol"_L1;
+ if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = "IPv4Protocol"_L1;
+ else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = "IPv6Protocol"_L1;
qDebug("QNativeSocketEngine::initialize(type == %s, protocol == %s) failed: %s",
typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(), d->socketErrorString.toLatin1().constData());
#endif
@@ -476,16 +442,18 @@ bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAb
}
+#ifndef Q_OS_WASM
// Make sure we receive out-of-band data
if (socketType == QAbstractSocket::TcpSocket
&& !setOption(ReceiveOutOfBandData, 1)) {
qWarning("QNativeSocketEngine::initialize unable to inline out-of-band data");
}
+#endif
// Before Qt 4.6, we always set the send and receive buffer size to 49152 as
// this was found to be an optimal value. However, modern OS
// all have some kind of auto tuning for this and we therefore don't set
- // this explictly anymore.
+ // this explicitly anymore.
// If it introduces any performance regressions for Qt 4.6.x (x > 0) then
// it will be put back in.
//
@@ -689,7 +657,7 @@ bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
\sa bind(), accept()
*/
-bool QNativeSocketEngine::listen()
+bool QNativeSocketEngine::listen(int backlog)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::listen(), false);
@@ -701,11 +669,7 @@ bool QNativeSocketEngine::listen()
Q_CHECK_TYPE(QNativeSocketEngine::listen(), QAbstractSocket::TcpSocket, false);
#endif
- // We're using a backlog of 50. Most modern kernels support TCP
- // syncookies by default, and if they do, the backlog is ignored.
- // When there is no support for TCP syncookies, this value is
- // fine.
- return d->nativeListen(50);
+ return d->nativeListen(backlog);
}
/*!
@@ -715,7 +679,7 @@ bool QNativeSocketEngine::listen()
\sa bind(), listen()
*/
-int QNativeSocketEngine::accept()
+qintptr QNativeSocketEngine::accept()
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::accept(), -1);
@@ -984,23 +948,23 @@ void QNativeSocketEngine::close()
d->peerAddress.clear();
d->inboundStreamCount = d->outboundStreamCount = 0;
if (d->readNotifier) {
- qDeleteInEventHandler(d->readNotifier);
+ delete d->readNotifier;
d->readNotifier = nullptr;
}
if (d->writeNotifier) {
- qDeleteInEventHandler(d->writeNotifier);
+ delete d->writeNotifier;
d->writeNotifier = nullptr;
}
if (d->exceptNotifier) {
- qDeleteInEventHandler(d->exceptNotifier);
+ delete d->exceptNotifier;
d->exceptNotifier = nullptr;
}
}
/*!
- Waits for \a msecs milliseconds or until the socket is ready for
- reading. If \a timedOut is not \nullptr and \a msecs milliseconds
- have passed, the value of \a timedOut is set to true.
+ Waits until \a deadline has expired or until the socket is ready for
+ reading. If \a timedOut is not \nullptr and \a deadline has expired,
+ the value of \a timedOut is set to true.
Returns \c true if data is available for reading; otherwise returns
false.
@@ -1012,7 +976,7 @@ void QNativeSocketEngine::close()
is to create a QSocketNotifier, passing the socket descriptor
returned by socketDescriptor() to its constructor.
*/
-bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
+bool QNativeSocketEngine::waitForRead(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(const QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false);
@@ -1022,7 +986,7 @@ bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
if (timedOut)
*timedOut = false;
- int ret = d->nativeSelect(msecs, true);
+ int ret = d->nativeSelect(deadline, true);
if (ret == 0) {
if (timedOut)
*timedOut = true;
@@ -1038,9 +1002,9 @@ bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
}
/*!
- Waits for \a msecs milliseconds or until the socket is ready for
- writing. If \a timedOut is not \nullptr and \a msecs milliseconds
- have passed, the value of \a timedOut is set to true.
+ Waits until \a deadline has expired or until the socket is ready for
+ writing. If \a timedOut is not \nullptr and \a deadline has expired,
+ the value of \a timedOut is set to true.
Returns \c true if data is available for writing; otherwise returns
false.
@@ -1052,7 +1016,7 @@ bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
is to create a QSocketNotifier, passing the socket descriptor
returned by socketDescriptor() to its constructor.
*/
-bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
+bool QNativeSocketEngine::waitForWrite(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false);
@@ -1062,7 +1026,7 @@ bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
if (timedOut)
*timedOut = false;
- int ret = d->nativeSelect(msecs, false);
+ int ret = d->nativeSelect(deadline, false);
// On Windows, the socket is in connected state if a call to
// select(writable) is successful. In this case we should not
// issue a second call to WSAConnect()
@@ -1110,14 +1074,14 @@ bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
bool QNativeSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs, bool *timedOut)
+ QDeadlineTimer deadline, bool *timedOut)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForReadOrWrite(), false);
Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForReadOrWrite(),
QAbstractSocket::UnconnectedState, false);
- int ret = d->nativeSelect(msecs, checkRead, checkWrite, readyToRead, readyToWrite);
+ int ret = d->nativeSelect(deadline, checkRead, checkWrite, readyToRead, readyToWrite);
// On Windows, the socket is in connected state if a call to
// select(writable) is successful. In this case we should not
// issue a second call to WSAConnect()
@@ -1291,7 +1255,7 @@ bool QReadNotifier::event(QEvent *e)
class QWriteNotifier : public QSocketNotifier
{
public:
- QWriteNotifier(int fd, QNativeSocketEngine *parent)
+ QWriteNotifier(qintptr fd, QNativeSocketEngine *parent)
: QSocketNotifier(fd, QSocketNotifier::Write, parent) { engine = parent; }
protected:
@@ -1315,7 +1279,7 @@ bool QWriteNotifier::event(QEvent *e)
class QExceptionNotifier : public QSocketNotifier
{
public:
- QExceptionNotifier(int fd, QNativeSocketEngine *parent)
+ QExceptionNotifier(qintptr fd, QNativeSocketEngine *parent)
: QSocketNotifier(fd, QSocketNotifier::Exception, parent) { engine = parent; }
protected:
diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h
index e5f0701d14..4c185b7a4a 100644
--- a/src/network/socket/qnativesocketengine_p.h
+++ b/src/network/socket/qnativesocketengine_p.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QNATIVESOCKETENGINE_P_H
#define QNATIVESOCKETENGINE_P_H
@@ -56,8 +20,9 @@
#include "QtNetwork/qhostaddress.h"
#include "QtNetwork/qnetworkinterface.h"
#include "private/qabstractsocketengine_p.h"
+#include "qplatformdefs.h"
+
#ifndef Q_OS_WIN
-# include "qplatformdefs.h"
# include <netinet/in.h>
#else
# include <winsock2.h>
@@ -70,51 +35,63 @@ QT_BEGIN_NAMESPACE
#ifdef Q_OS_WIN
# define QT_SOCKLEN_T int
# define QT_SOCKOPTLEN_T int
-
-// 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 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 // !WSAID_WSARECVMSG
-# 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 // !WSAID_WSASENDMSG
-#endif // Q_OS_WIN
-
-union qt_sockaddr {
- sockaddr a;
- sockaddr_in a4;
- sockaddr_in6 a6;
-};
+#endif
namespace {
namespace SetSALen {
template <typename T> void set(T *sa, typename std::enable_if<(&T::sa_len, true), QT_SOCKLEN_T>::type len)
{ sa->sa_len = len; }
+ template <typename T> void set(T *sa, typename std::enable_if<(&T::sin_len, true), QT_SOCKLEN_T>::type len)
+ { sa->sin_len = len; }
template <typename T> void set(T *sin6, typename std::enable_if<(&T::sin6_len, true), QT_SOCKLEN_T>::type len)
{ sin6->sin6_len = len; }
template <typename T> void set(T *, ...) {}
}
+
+inline QT_SOCKLEN_T setSockaddr(sockaddr_in *sin, const QHostAddress &addr, quint16 port = 0)
+{
+ *sin = {};
+ SetSALen::set(sin, sizeof(*sin));
+ sin->sin_family = AF_INET;
+ sin->sin_port = htons(port);
+ sin->sin_addr.s_addr = htonl(addr.toIPv4Address());
+ return sizeof(*sin);
+}
+
+inline QT_SOCKLEN_T setSockaddr(sockaddr_in6 *sin6, const QHostAddress &addr, quint16 port = 0)
+{
+ *sin6 = {};
+ SetSALen::set(sin6, sizeof(*sin6));
+ sin6->sin6_family = AF_INET6;
+ sin6->sin6_port = htons(port);
+ memcpy(sin6->sin6_addr.s6_addr, addr.toIPv6Address().c, sizeof(sin6->sin6_addr));
+#if QT_CONFIG(networkinterface)
+ sin6->sin6_scope_id = QNetworkInterface::interfaceIndexFromName(addr.scopeId());
+#else
+ // it had better be a number then, if it is not empty
+ sin6->sin6_scope_id = addr.scopeId().toUInt();
+#endif
+ return sizeof(*sin6);
+}
+
+inline QT_SOCKLEN_T setSockaddr(sockaddr *sa, const QHostAddress &addr, quint16 port = 0)
+{
+ switch (addr.protocol()) {
+ case QHostAddress::IPv4Protocol:
+ return setSockaddr(reinterpret_cast<sockaddr_in *>(sa), addr, port);
+
+ case QHostAddress::IPv6Protocol:
+ case QHostAddress::AnyIPProtocol:
+ return setSockaddr(reinterpret_cast<sockaddr_in6 *>(sa), addr, port);
+
+ case QHostAddress::UnknownNetworkLayerProtocol:
+ break;
+ }
+ *sa = {};
+ sa->sa_family = AF_UNSPEC;
+ return 0;
}
+} // unnamed namespace
class QNativeSocketEnginePrivate;
#ifndef QT_NO_NETWORKINTERFACE
@@ -138,8 +115,8 @@ public:
bool connectToHost(const QHostAddress &address, quint16 port) override;
bool connectToHostByName(const QString &name, quint16 port) override;
bool bind(const QHostAddress &address, quint16 port) override;
- bool listen() override;
- int accept() override;
+ bool listen(int backlog) override;
+ qintptr accept() override;
void close() override;
qint64 bytesAvailable() const override;
@@ -177,11 +154,14 @@ public:
int option(SocketOption option) const override;
bool setOption(SocketOption option, int value) override;
- bool waitForRead(int msecs = 30000, bool *timedOut = nullptr) override;
- bool waitForWrite(int msecs = 30000, bool *timedOut = nullptr) override;
+ bool waitForRead(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
+ bool waitForWrite(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
bool waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs = 30000, bool *timedOut = nullptr) override;
+ QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
bool isReadNotificationEnabled() const override;
void setReadNotificationEnabled(bool enable) override;
@@ -199,132 +179,6 @@ private:
Q_DISABLE_COPY_MOVE(QNativeSocketEngine)
};
-class QSocketNotifier;
-
-class QNativeSocketEnginePrivate : public QAbstractSocketEnginePrivate
-{
- Q_DECLARE_PUBLIC(QNativeSocketEngine)
-public:
- QNativeSocketEnginePrivate();
- ~QNativeSocketEnginePrivate();
-
- qintptr socketDescriptor;
-
- QSocketNotifier *readNotifier, *writeNotifier, *exceptNotifier;
-
-#if defined(Q_OS_WIN)
- LPFN_WSASENDMSG sendmsg;
- LPFN_WSARECVMSG recvmsg;
-# endif
- enum ErrorString {
- NonBlockingInitFailedErrorString,
- BroadcastingInitFailedErrorString,
- NoIpV6ErrorString,
- RemoteHostClosedErrorString,
- TimeOutErrorString,
- ResourceErrorString,
- OperationUnsupportedErrorString,
- ProtocolUnsupportedErrorString,
- InvalidSocketErrorString,
- HostUnreachableErrorString,
- NetworkUnreachableErrorString,
- AccessErrorString,
- ConnectionTimeOutErrorString,
- ConnectionRefusedErrorString,
- AddressInuseErrorString,
- AddressNotAvailableErrorString,
- AddressProtectedErrorString,
- DatagramTooLargeErrorString,
- SendDatagramErrorString,
- ReceiveDatagramErrorString,
- WriteErrorString,
- ReadErrorString,
- PortInuseErrorString,
- NotSocketErrorString,
- InvalidProxyTypeString,
- TemporaryErrorString,
- NetworkDroppedConnectionErrorString,
- ConnectionResetErrorString,
-
- UnknownSocketErrorString = -1
- };
-
- void setError(QAbstractSocket::SocketError error, ErrorString errorString) const;
- QHostAddress adjustAddressProtocol(const QHostAddress &address) const;
-
- // native functions
- int option(QNativeSocketEngine::SocketOption option) const;
- bool setOption(QNativeSocketEngine::SocketOption option, int value);
-
- bool createNewSocket(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol &protocol);
-
- bool nativeConnect(const QHostAddress &address, quint16 port);
- bool nativeBind(const QHostAddress &address, quint16 port);
- bool nativeListen(int backlog);
- int nativeAccept();
-#ifndef QT_NO_NETWORKINTERFACE
- bool nativeJoinMulticastGroup(const QHostAddress &groupAddress,
- const QNetworkInterface &iface);
- bool nativeLeaveMulticastGroup(const QHostAddress &groupAddress,
- const QNetworkInterface &iface);
- QNetworkInterface nativeMulticastInterface() const;
- bool nativeSetMulticastInterface(const QNetworkInterface &iface);
-#endif
- qint64 nativeBytesAvailable() const;
-
- bool nativeHasPendingDatagrams() const;
- qint64 nativePendingDatagramSize() const;
- 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;
-
- void nativeClose();
-
- bool checkProxy(const QHostAddress &address);
- bool fetchConnectionParameters();
-
-#if QT_CONFIG(networkinterface)
- static uint scopeIdFromString(const QString &scopeid)
- { return QNetworkInterface::interfaceIndexFromName(scopeid); }
-#endif
-
- /*! \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;
-#if QT_CONFIG(networkinterface)
- aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());
-#endif
- aa->a6.sin6_port = htons(port);
- Q_IPV6ADDR tmp = address.toIPv6Address();
- memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));
- *sockAddrSize = sizeof(sockaddr_in6);
- SetSALen::set(&aa->a, 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);
- SetSALen::set(&aa->a, sizeof(sockaddr_in));
- }
- }
-
-};
-
QT_END_NAMESPACE
#endif // QNATIVESOCKETENGINE_P_H
diff --git a/src/network/socket/qnativesocketengine_p_p.h b/src/network/socket/qnativesocketengine_p_p.h
new file mode 100644
index 0000000000..189a4327fd
--- /dev/null
+++ b/src/network/socket/qnativesocketengine_p_p.h
@@ -0,0 +1,189 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QNATIVESOCKETENGINE_P_P_H
+#define QNATIVESOCKETENGINE_P_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "private/qabstractsocketengine_p.h"
+#include "private/qnativesocketengine_p.h"
+
+#ifndef Q_OS_WIN
+# include <netinet/in.h>
+#else
+# include <winsock2.h>
+# include <ws2tcpip.h>
+# include <mswsock.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+#ifdef Q_OS_WIN
+
+// 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 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 // !WSAID_WSARECVMSG
+# 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 // !WSAID_WSASENDMSG
+#endif // Q_OS_WIN
+
+union qt_sockaddr {
+ sockaddr a;
+ sockaddr_in a4;
+ sockaddr_in6 a6;
+};
+
+class QSocketNotifier;
+
+class QNativeSocketEnginePrivate : public QAbstractSocketEnginePrivate
+{
+ Q_DECLARE_PUBLIC(QNativeSocketEngine)
+public:
+ QNativeSocketEnginePrivate();
+ ~QNativeSocketEnginePrivate();
+
+ qintptr socketDescriptor;
+
+ QSocketNotifier *readNotifier, *writeNotifier, *exceptNotifier;
+
+#if defined(Q_OS_WIN)
+ LPFN_WSASENDMSG sendmsg;
+ LPFN_WSARECVMSG recvmsg;
+# endif
+ enum ErrorString {
+ NonBlockingInitFailedErrorString,
+ BroadcastingInitFailedErrorString,
+ NoIpV6ErrorString,
+ RemoteHostClosedErrorString,
+ TimeOutErrorString,
+ ResourceErrorString,
+ OperationUnsupportedErrorString,
+ ProtocolUnsupportedErrorString,
+ InvalidSocketErrorString,
+ HostUnreachableErrorString,
+ NetworkUnreachableErrorString,
+ AccessErrorString,
+ ConnectionTimeOutErrorString,
+ ConnectionRefusedErrorString,
+ AddressInuseErrorString,
+ AddressNotAvailableErrorString,
+ AddressProtectedErrorString,
+ DatagramTooLargeErrorString,
+ SendDatagramErrorString,
+ ReceiveDatagramErrorString,
+ WriteErrorString,
+ ReadErrorString,
+ PortInuseErrorString,
+ NotSocketErrorString,
+ InvalidProxyTypeString,
+ TemporaryErrorString,
+ NetworkDroppedConnectionErrorString,
+ ConnectionResetErrorString,
+
+ UnknownSocketErrorString = -1
+ };
+
+ void setError(QAbstractSocket::SocketError error, ErrorString errorString) const;
+ QHostAddress adjustAddressProtocol(const QHostAddress &address) const;
+
+ // native functions
+ int option(QNativeSocketEngine::SocketOption option) const;
+ bool setOption(QNativeSocketEngine::SocketOption option, int value);
+
+ bool createNewSocket(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol &protocol);
+
+ bool nativeConnect(const QHostAddress &address, quint16 port);
+ bool nativeBind(const QHostAddress &address, quint16 port);
+ bool nativeListen(int backlog);
+ qintptr nativeAccept();
+#ifndef QT_NO_NETWORKINTERFACE
+ bool nativeJoinMulticastGroup(const QHostAddress &groupAddress,
+ const QNetworkInterface &iface);
+ bool nativeLeaveMulticastGroup(const QHostAddress &groupAddress,
+ const QNetworkInterface &iface);
+ QNetworkInterface nativeMulticastInterface() const;
+ bool nativeSetMulticastInterface(const QNetworkInterface &iface);
+#endif
+ qint64 nativeBytesAvailable() const;
+
+ bool nativeHasPendingDatagrams() const;
+ qint64 nativePendingDatagramSize() const;
+ 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(QDeadlineTimer deadline, bool selectForRead) const;
+ int nativeSelect(QDeadlineTimer deadline, bool checkRead, bool checkWrite,
+ bool *selectForRead, bool *selectForWrite) const;
+
+ void nativeClose();
+
+ bool checkProxy(const QHostAddress &address);
+ bool fetchConnectionParameters();
+
+ /*! \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)
+ {
+ switch (socketProtocol) {
+ case QHostAddress::IPv6Protocol:
+ case QHostAddress::AnyIPProtocol:
+ // force to IPv6
+ setSockaddr(&aa->a6, address, port);
+ *sockAddrSize = sizeof(sockaddr_in6);
+ return;
+
+ case QHostAddress::IPv4Protocol:
+ // force to IPv4
+ setSockaddr(&aa->a4, address, port);
+ *sockAddrSize = sizeof(sockaddr_in);
+ return;
+
+ case QHostAddress::UnknownNetworkLayerProtocol:
+ // don't force
+ break;
+ }
+ *sockAddrSize = setSockaddr(&aa->a, address, port);
+ }
+
+};
+
+QT_END_NAMESPACE
+
+#endif // QNATIVESOCKETENGINE_P_P_H
diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp
index a39b345d30..b6df412253 100644
--- a/src/network/socket/qnativesocketengine_unix.cpp
+++ b/src/network/socket/qnativesocketengine_unix.cpp
@@ -1,70 +1,28 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QNATIVESOCKETENGINE_DEBUG
-#include "qnativesocketengine_p.h"
+#include "qnativesocketengine_p_p.h"
#include "private/qnet_unix_p.h"
+#include "qdeadlinetimer.h"
#include "qiodevice.h"
#include "qhostaddress.h"
-#include "qelapsedtimer.h"
#include "qvarlengtharray.h"
#include "qnetworkinterface.h"
+#include "qendian.h"
+#ifdef Q_OS_WASM
+#include <private/qeventdispatcher_wasm_p.h>
+#endif
#include <time.h>
#include <errno.h>
#include <fcntl.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-#ifdef QT_LINUXBASE
-#include <arpa/inet.h>
-#endif
-#ifdef Q_OS_BSD4
-#include <net/if_dl.h>
-#endif
#ifdef Q_OS_INTEGRITY
#include <sys/uio.h>
#endif
#if defined QNATIVESOCKETENGINE_DEBUG
-#include <qstring.h>
-#include <ctype.h>
+#include <private/qdebug_p.h>
#endif
#include <netinet/tcp.h>
@@ -73,41 +31,12 @@
#include <sys/socket.h>
#include <netinet/sctp.h>
#endif
+#ifdef Q_OS_BSD4
+# include <net/if_dl.h>
+#endif
QT_BEGIN_NAMESPACE
-#if defined QNATIVESOCKETENGINE_DEBUG
-
-/*
- Returns a human readable representation of the first \a len
- characters in \a data.
-*/
-static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
-{
- if (!data) return "(null)";
- QByteArray out;
- for (int i = 0; i < len; ++i) {
- char c = data[i];
- if (isprint(c)) {
- out += c;
- } else switch (c) {
- case '\n': out += "\\n"; break;
- case '\r': out += "\\r"; break;
- case '\t': out += "\\t"; break;
- default:
- QString tmp;
- tmp.sprintf("\\%o", c);
- out += tmp.toLatin1();
- }
- }
-
- if (len < maxSize)
- out += "...";
-
- return out;
-}
-#endif
-
/*
Extracts the port and address from a sockaddr, and stores them in
\a port and \a addr if they are non-null.
@@ -312,10 +241,8 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
#endif
socketDescriptor = socket;
- if (socket != -1) {
- this->socketProtocol = socketProtocol;
- this->socketType = socketType;
- }
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
return true;
}
@@ -364,12 +291,12 @@ int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) co
}
int n, level;
- int v = -1;
+ int v = 0;
QT_SOCKOPTLEN_T len = sizeof(v);
convertToLevelAndOption(opt, socketProtocol, level, n);
if (n != -1 && ::getsockopt(socketDescriptor, level, n, (char *) &v, &len) != -1)
- return v;
+ return len == 1 ? qFromUnaligned<quint8>(&v) : v;
return -1;
}
@@ -509,6 +436,7 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
case EFAULT:
case ENOTSOCK:
socketState = QAbstractSocket::UnconnectedState;
+ break;
default:
break;
}
@@ -626,7 +554,7 @@ bool QNativeSocketEnginePrivate::nativeListen(int backlog)
return true;
}
-int QNativeSocketEnginePrivate::nativeAccept()
+qintptr QNativeSocketEnginePrivate::nativeAccept()
{
int acceptedDescriptor = qt_safe_accept(socketDescriptor, nullptr, nullptr);
if (acceptedDescriptor == -1) {
@@ -672,7 +600,7 @@ int QNativeSocketEnginePrivate::nativeAccept()
}
}
- return acceptedDescriptor;
+ return qintptr(acceptedDescriptor);
}
#ifndef QT_NO_NETWORKINTERFACE
@@ -785,17 +713,21 @@ QNetworkInterface QNativeSocketEnginePrivate::nativeMulticastInterface() const
return QNetworkInterface::interfaceFromIndex(v);
}
+#if defined(Q_OS_SOLARIS)
+ struct in_addr v = { 0, 0, 0, 0};
+#else
struct in_addr v = { 0 };
+#endif
QT_SOCKOPTLEN_T sizeofv = sizeof(v);
if (::getsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, &v, &sizeofv) == -1)
return QNetworkInterface();
if (v.s_addr != 0 && sizeofv >= QT_SOCKOPTLEN_T(sizeof(v))) {
QHostAddress ipv4(ntohl(v.s_addr));
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
- for (int i = 0; i < ifaces.count(); ++i) {
+ for (int i = 0; i < ifaces.size(); ++i) {
const QNetworkInterface &iface = ifaces.at(i);
QList<QNetworkAddressEntry> entries = iface.addressEntries();
- for (int j = 0; j < entries.count(); ++j) {
+ for (int j = 0; j < entries.size(); ++j) {
const QNetworkAddressEntry &entry = entries.at(j);
if (entry.ip() == ipv4)
return iface;
@@ -815,7 +747,7 @@ bool QNativeSocketEnginePrivate::nativeSetMulticastInterface(const QNetworkInter
struct in_addr v;
if (iface.isValid()) {
QList<QNetworkAddressEntry> entries = iface.addressEntries();
- for (int i = 0; i < entries.count(); ++i) {
+ for (int i = 0; i < entries.size(); ++i) {
const QNetworkAddressEntry &entry = entries.at(i);
const QHostAddress &ip = entry.ip();
if (ip.protocol() == QAbstractSocket::IPv4Protocol) {
@@ -862,7 +794,7 @@ bool QNativeSocketEnginePrivate::nativeHasPendingDatagrams() const
// Peek 1 bytes into the next message.
ssize_t readBytes;
char c;
- EINTR_LOOP(readBytes, ::recv(socketDescriptor, &c, 1, MSG_PEEK));
+ QT_EINTR_LOOP(readBytes, ::recv(socketDescriptor, &c, 1, MSG_PEEK));
// If there's no error, or if our buffer was too small, there must be a
// pending datagram.
@@ -881,7 +813,7 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
#ifdef Q_OS_LINUX
// Linux can return the actual datagram size if we use MSG_TRUNC
char c;
- EINTR_LOOP(recvResult, ::recv(socketDescriptor, &c, 1, MSG_PEEK | MSG_TRUNC));
+ QT_EINTR_LOOP(recvResult, ::recv(socketDescriptor, &c, 1, MSG_PEEK | MSG_TRUNC));
#elif defined(SO_NREAD)
// macOS can return the actual datagram size if we use SO_NREAD
int value;
@@ -1061,7 +993,7 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxS
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
- data, qt_prettyDebug(data, qMin(recvResult, ssize_t(16)), recvResult).data(), maxSize,
+ data, QtDebugUtils::toPrintable(data, recvResult, 16).constData(), maxSize,
(recvResult != -1 && options != QAbstractSocketEngine::WantNone)
? header->senderAddress.toString().toLatin1().constData() : "(unknown)",
(recvResult != -1 && options != QAbstractSocketEngine::WantNone)
@@ -1190,7 +1122,7 @@ 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,
+ QtDebugUtils::toPrintable(data, len, 16).constData(), len,
header.destinationAddress.toString().toLatin1().constData(),
header.destinationPort, (qint64) sentBytes);
#endif
@@ -1344,6 +1276,9 @@ qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
setError(QAbstractSocket::RemoteHostClosedError, RemoteHostClosedErrorString);
q->close();
break;
+#if EWOULDBLOCK != EAGAIN
+ case EWOULDBLOCK:
+#endif
case EAGAIN:
writtenBytes = 0;
break;
@@ -1356,9 +1291,8 @@ qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
- qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %llu) == %i",
- data, qt_prettyDebug(data, qMin((int) len, 16),
- (int) len).data(), len, (int) writtenBytes);
+ qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %llu) == %i", data,
+ QtDebugUtils::toPrintable(data, len, 16).constData(), len, (int) writtenBytes);
#endif
return qint64(writtenBytes);
@@ -1407,22 +1341,24 @@ qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxSize)
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
- qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %llu) == %zd",
- data, qt_prettyDebug(data, qMin(r, ssize_t(16)), r).data(),
- maxSize, r);
+ qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %llu) == %zd", data,
+ QtDebugUtils::toPrintable(data, r, 16).constData(), maxSize, r);
#endif
return qint64(r);
}
-int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
+int QNativeSocketEnginePrivate::nativeSelect(QDeadlineTimer deadline, bool selectForRead) const
{
bool dummy;
- return nativeSelect(timeout, selectForRead, !selectForRead, &dummy, &dummy);
+ return nativeSelect(deadline, selectForRead, !selectForRead, &dummy, &dummy);
}
-int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool checkRead, bool checkWrite,
- bool *selectForRead, bool *selectForWrite) const
+#ifndef Q_OS_WASM
+
+int QNativeSocketEnginePrivate::nativeSelect(QDeadlineTimer deadline, bool checkRead,
+ bool checkWrite, bool *selectForRead,
+ bool *selectForWrite) const
{
pollfd pfd = qt_make_pollfd(socketDescriptor, 0);
@@ -1432,7 +1368,7 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool checkRead, bool c
if (checkWrite)
pfd.events |= POLLOUT;
- const int ret = qt_poll_msecs(&pfd, 1, timeout);
+ const int ret = qt_safe_poll(&pfd, 1, deadline);
if (ret <= 0)
return ret;
@@ -1451,4 +1387,27 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool checkRead, bool c
return ret;
}
+#else
+
+int QNativeSocketEnginePrivate::nativeSelect(QDeadlineTimer deadline, bool checkRead,
+ bool checkWrite, bool *selectForRead,
+ bool *selectForWrite) const
+{
+ *selectForRead = checkRead;
+ *selectForWrite = checkWrite;
+ bool socketDisconnect = false;
+ QEventDispatcherWasm::socketSelect(deadline.remainingTime(), socketDescriptor, checkRead,
+ checkWrite, selectForRead, selectForWrite,
+ &socketDisconnect);
+
+ // The disconnect/close handling code in QAbstractsScket::canReadNotification()
+ // does not detect remote disconnect properly; do that here as a workardound.
+ if (socketDisconnect)
+ receiver->closeNotification();
+
+ return 1;
+}
+
+#endif // Q_OS_WASM
+
QT_END_NAMESPACE
diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp
index 35422a1e80..6525f46e30 100644
--- a/src/network/socket/qnativesocketengine_win.cpp
+++ b/src/network/socket/qnativesocketengine_win.cpp
@@ -1,50 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Prevent windows system header files from defining min/max as macros.
-#define NOMINMAX 1
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include <winsock2.h>
#include <ws2tcpip.h>
-#include "qnativesocketengine_p.h"
+#include "qnativesocketengine_p_p.h"
#include <qabstracteventdispatcher.h>
#include <qsocketnotifier.h>
@@ -52,13 +13,14 @@
#include <qdatetime.h>
#include <qnetworkinterface.h>
#include <qoperatingsystemversion.h>
+#include <qvarlengtharray.h>
#include <algorithm>
+#include <chrono>
//#define QNATIVESOCKETENGINE_DEBUG
#if defined(QNATIVESOCKETENGINE_DEBUG)
-# include <qstring.h>
-# include <qbytearray.h>
+#include <private/qdebug_p.h>
#endif
QT_BEGIN_NAMESPACE
@@ -127,36 +89,6 @@ void verboseWSErrorDebug(int r)
qErrnoWarning(r, "more details");
}
-/*
- Returns a human readable representation of the first \a len
- characters in \a data.
-*/
-static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
-{
- if (!data) return "(null)";
- QByteArray out;
- for (int i = 0; i < len; ++i) {
- char c = data[i];
- if (isprint(int(uchar(c)))) {
- out += c;
- } else switch (c) {
- case '\n': out += "\\n"; break;
- case '\r': out += "\\r"; break;
- case '\t': out += "\\t"; break;
- default:
- QString tmp;
- tmp.sprintf("\\%o", c);
- out += tmp.toLatin1().constData();
- }
- }
-
- if (len < maxLength)
- out += "...";
-
- return out;
-}
-
-
#define WS_ERROR_DEBUG(x) verboseWSErrorDebug(x)
#else
@@ -325,15 +257,6 @@ static inline QAbstractSocket::SocketType qt_socket_getType(qintptr socketDescri
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
-
- //### no ip6 support on winsocket 1.1 but we will try not to use this !!!!!!!!!!!!1
- /*
- if (winsockVersion < 0x20 && socketProtocol == QAbstractSocket::IPv6Protocol) {
- //### no ip6 support
- return -1;
- }
- */
-
//### SCTP not implemented
if (socketType == QAbstractSocket::SctpSocket) {
setError(QAbstractSocket::UnsupportedSocketOperationError,
@@ -346,34 +269,15 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
|| (socketProtocol == QAbstractSocket::AnyIPProtocol)) ? AF_INET6 : AF_INET;
int type = (socketType == QAbstractSocket::UdpSocket) ? SOCK_DGRAM : SOCK_STREAM;
- // MSDN KB179942 states that on winnt 4 WSA_FLAG_OVERLAPPED is needed if socket is to be non blocking
- // and recomends alwasy doing it for cross windows version comapablity.
+ // MSDN KB179942 states that on winnt 4 WSA_FLAG_OVERLAPPED is needed if socket is to be non
+ // blocking and recommends always doing it for cross-windows-version compatibility.
- // WSA_FLAG_NO_HANDLE_INHERIT is atomic (like linux O_CLOEXEC), but requires windows 7 SP 1 or later
- // SetHandleInformation is supported since W2K but isn't atomic
+ // WSA_FLAG_NO_HANDLE_INHERIT is atomic (like linux O_CLOEXEC)
#ifndef WSA_FLAG_NO_HANDLE_INHERIT
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
#endif
SOCKET socket = ::WSASocket(protocol, type, 0, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
- // previous call fails if the windows 7 service pack 1 or hot fix isn't installed.
-
- // Try the old API if the new one failed on Windows 7
- if (socket == INVALID_SOCKET && QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8) {
- socket = ::WSASocket(protocol, type, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
-#ifdef HANDLE_FLAG_INHERIT
- if (socket != INVALID_SOCKET) {
- // make non inheritable the old way
- BOOL handleFlags = SetHandleInformation(reinterpret_cast<HANDLE>(socket), HANDLE_FLAG_INHERIT, 0);
-#ifdef QNATIVESOCKETENGINE_DEBUG
- qDebug() << "QNativeSocketEnginePrivate::createNewSocket - set inheritable" << handleFlags;
-#else
- Q_UNUSED(handleFlags);
-#endif
- }
-#endif
- }
-
if (socket == INVALID_SOCKET) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
@@ -426,10 +330,8 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
sendmsg = 0;
socketDescriptor = socket;
- if (socket != INVALID_SOCKET) {
- this->socketProtocol = socketProtocol;
- this->socketType = socketType;
- }
+ this->socketProtocol = socketProtocol;
+ this->socketType = socketType;
// Make the socket nonblocking.
if (!setOption(QAbstractSocketEngine::NonBlockingSocketOption, 1)) {
@@ -510,7 +412,6 @@ bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt
return false;
}
return true;
- break;
}
case QNativeSocketEngine::TypeOfServiceOption:
case QNativeSocketEngine::MaxStreamsSocketOption:
@@ -870,10 +771,10 @@ bool QNativeSocketEnginePrivate::nativeListen(int backlog)
return true;
}
-int QNativeSocketEnginePrivate::nativeAccept()
+qintptr QNativeSocketEnginePrivate::nativeAccept()
{
- int acceptedDescriptor = WSAAccept(socketDescriptor, 0,0,0,0);
- if (acceptedDescriptor == -1) {
+ SOCKET acceptedDescriptor = WSAAccept(socketDescriptor, 0,0,0,0);
+ if (acceptedDescriptor == INVALID_SOCKET) {
int err = WSAGetLastError();
switch (err) {
case WSAEACCES:
@@ -907,19 +808,19 @@ int QNativeSocketEnginePrivate::nativeAccept()
setError(QAbstractSocket::UnknownSocketError, UnknownSocketErrorString);
break;
}
- } else if (acceptedDescriptor != -1 && QAbstractEventDispatcher::instance()) {
+ } else if (acceptedDescriptor != INVALID_SOCKET && QAbstractEventDispatcher::instance()) {
// Because of WSAAsyncSelect() WSAAccept returns a non blocking socket
// with the same attributes as the listening socket including the current
// WSAAsyncSelect(). To be able to change the socket to blocking mode the
- // WSAAsyncSelect() call must be cancled.
+ // WSAAsyncSelect() call must be canceled.
QSocketNotifier n(acceptedDescriptor, QSocketNotifier::Read);
n.setEnabled(true);
n.setEnabled(false);
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
- qDebug("QNativeSocketEnginePrivate::nativeAccept() == %i", acceptedDescriptor);
+ qDebug("QNativeSocketEnginePrivate::nativeAccept() == %lld", qint64(acceptedDescriptor));
#endif
- return acceptedDescriptor;
+ return qintptr(acceptedDescriptor);
}
static bool multicastMembershipHelper(QNativeSocketEnginePrivate *d,
@@ -1282,7 +1183,7 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
#if defined (QNATIVESOCKETENGINE_DEBUG)
bool printSender = (ret != -1 && (options & QNativeSocketEngine::WantDatagramSender) != 0);
qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
- data, qt_prettyDebug(data, qMin<qint64>(ret, 16), ret).data(), maxLength,
+ data, QtDebugUtils::toPrintable(data, ret, 16).constData(), maxLength,
printSender ? header->senderAddress.toString().toLatin1().constData() : "(unknown)",
printSender ? header->senderPort : 0, ret);
#endif
@@ -1415,8 +1316,8 @@ qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 l
}
#if defined (QNATIVESOCKETENGINE_DEBUG)
- qDebug("QNativeSocketEnginePrivate::nativeSendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli", data,
- qt_prettyDebug(data, qMin<qint64>(len, 16), len).data(), len,
+ qDebug("QNativeSocketEnginePrivate::nativeSendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli",
+ data, QtDebugUtils::toPrintable(data, len, 16).constData(), len,
header.destinationAddress.toString().toLatin1().constData(),
header.destinationPort, ret);
#endif
@@ -1475,7 +1376,7 @@ qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %lli) == %lli",
- data, qt_prettyDebug(data, qMin(int(ret), 16), int(ret)).data(), len, ret);
+ data, QtDebugUtils::toPrintable(data, ret, 16).constData(), len, ret);
#endif
return ret;
@@ -1517,8 +1418,8 @@ qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxLength)
#if defined (QNATIVESOCKETENGINE_DEBUG)
if (ret != -2) {
- qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %lli) == %lli",
- data, qt_prettyDebug(data, qMin(int(bytesRead), 16), int(bytesRead)).data(), maxLength, ret);
+ qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %lli) == %lli", data,
+ QtDebugUtils::toPrintable(data, bytesRead, 16).constData(), maxLength, ret);
} else {
qDebug("QNativeSocketEnginePrivate::nativeRead(%p, %lli) == -2 (WOULD BLOCK)",
data, maxLength);
@@ -1528,7 +1429,18 @@ qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxLength)
return ret;
}
-int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
+inline timeval durationToTimeval(std::chrono::nanoseconds dur) noexcept
+{
+ using namespace std::chrono;
+ const auto secs = duration_cast<seconds>(dur);
+ const auto frac = duration_cast<microseconds>(dur - secs);
+ struct timeval tval;
+ tval.tv_sec = secs.count();
+ tval.tv_usec = frac.count();
+ return tval;
+}
+
+int QNativeSocketEnginePrivate::nativeSelect(QDeadlineTimer deadline, bool selectForRead) const
{
bool readEnabled = selectForRead && readNotifier && readNotifier->isEnabled();
if (readEnabled)
@@ -1542,12 +1454,10 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) co
fds.fd_count = 1;
fds.fd_array[0] = (SOCKET)socketDescriptor;
- struct timeval tv;
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = (timeout % 1000) * 1000;
+ struct timeval tv = durationToTimeval(deadline.remainingTimeAsDuration());
if (selectForRead) {
- ret = select(0, &fds, 0, 0, timeout < 0 ? 0 : &tv);
+ ret = select(0, &fds, 0, 0, &tv);
} else {
// select for write
@@ -1556,7 +1466,7 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) co
FD_ZERO(&fdexception);
FD_SET((SOCKET)socketDescriptor, &fdexception);
- ret = select(0, 0, &fds, &fdexception, timeout < 0 ? 0 : &tv);
+ ret = select(0, 0, &fds, &fdexception, &tv);
// ... but if it is actually set, pretend it did not happen
if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
@@ -1569,7 +1479,7 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) co
return ret;
}
-int QNativeSocketEnginePrivate::nativeSelect(int timeout,
+int QNativeSocketEnginePrivate::nativeSelect(QDeadlineTimer deadline,
bool checkRead, bool checkWrite,
bool *selectForRead, bool *selectForWrite) const
{
@@ -1598,11 +1508,9 @@ int QNativeSocketEnginePrivate::nativeSelect(int timeout,
FD_SET((SOCKET)socketDescriptor, &fdexception);
}
- struct timeval tv;
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = (timeout % 1000) * 1000;
+ struct timeval tv = durationToTimeval(deadline.remainingTimeAsDuration());
- ret = select(socketDescriptor + 1, &fdread, &fdwrite, &fdexception, timeout < 0 ? 0 : &tv);
+ ret = select(socketDescriptor + 1, &fdread, &fdwrite, &fdexception, &tv);
//... but if it is actually set, pretend it did not happen
if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
diff --git a/src/network/socket/qnet_unix_p.h b/src/network/socket/qnet_unix_p.h
index e038352352..a172a14a10 100644
--- a/src/network/socket/qnet_unix_p.h
+++ b/src/network/socket/qnet_unix_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QNET_UNIX_P_H
#define QNET_UNIX_P_H
@@ -144,7 +108,7 @@ static inline int qt_safe_connect(int sockfd, const struct sockaddr *addr, QT_SO
{
int ret;
// Solaris e.g. expects a non-const 2nd parameter
- EINTR_LOOP(ret, QT_SOCKET_CONNECT(sockfd, const_cast<struct sockaddr *>(addr), addrlen));
+ QT_EINTR_LOOP(ret, QT_SOCKET_CONNECT(sockfd, const_cast<struct sockaddr *>(addr), addrlen));
return ret;
}
#undef QT_SOCKET_CONNECT
@@ -160,15 +124,10 @@ static inline int qt_safe_connect(int sockfd, const struct sockaddr *addr, QT_SO
# undef listen
#endif
-// VxWorks' headers specify 'int' instead of '...' for the 3rd ioctl() parameter.
template <typename T>
static inline int qt_safe_ioctl(int sockfd, unsigned long request, T arg)
{
-#ifdef Q_OS_VXWORKS
- return ::ioctl(sockfd, request, (int) arg);
-#else
return ::ioctl(sockfd, request, arg);
-#endif
}
static inline int qt_safe_sendmsg(int sockfd, const struct msghdr *msg, int flags)
@@ -180,7 +139,7 @@ static inline int qt_safe_sendmsg(int sockfd, const struct msghdr *msg, int flag
#endif
int ret;
- EINTR_LOOP(ret, ::sendmsg(sockfd, msg, flags));
+ QT_EINTR_LOOP(ret, ::sendmsg(sockfd, msg, flags));
return ret;
}
@@ -188,7 +147,7 @@ static inline int qt_safe_recvmsg(int sockfd, struct msghdr *msg, int flags)
{
int ret;
- EINTR_LOOP(ret, ::recvmsg(sockfd, msg, flags));
+ QT_EINTR_LOOP(ret, ::recvmsg(sockfd, msg, flags));
return ret;
}
diff --git a/src/network/socket/qsctpserver.cpp b/src/network/socket/qsctpserver.cpp
index 2aa694b3fd..cd060d93e8 100644
--- a/src/network/socket/qsctpserver.cpp
+++ b/src/network/socket/qsctpserver.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QSCTPSERVER_DEBUG
@@ -82,7 +46,7 @@
between endpoints. Call nextPendingDatagramConnection() to accept
the pending datagram-mode connection as a connected QSctpSocket.
- \note This feature is not supported on the Windows platform.
+ \note This class is not supported on the Windows platform.
\sa QTcpServer, QSctpSocket, QAbstractSocket
*/
diff --git a/src/network/socket/qsctpserver.h b/src/network/socket/qsctpserver.h
index b678ba053d..f82ae71f16 100644
--- a/src/network/socket/qsctpserver.h
+++ b/src/network/socket/qsctpserver.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QSCTPSERVER_H
#define QSCTPSERVER_H
@@ -45,7 +9,7 @@
QT_BEGIN_NAMESPACE
-#if !defined(QT_NO_SCTP) || defined(Q_CLANG_QDOC)
+#if !defined(QT_NO_SCTP) || defined(Q_QDOC)
class QSctpServerPrivate;
class QSctpSocket;
diff --git a/src/network/socket/qsctpserver_p.h b/src/network/socket/qsctpserver_p.h
index 8816cc150e..a4200547ea 100644
--- a/src/network/socket/qsctpserver_p.h
+++ b/src/network/socket/qsctpserver_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QSCTPSERVER_P_H
#define QSCTPSERVER_P_H
diff --git a/src/network/socket/qsctpsocket.cpp b/src/network/socket/qsctpsocket.cpp
index fe76f64c42..868c9e3785 100644
--- a/src/network/socket/qsctpsocket.cpp
+++ b/src/network/socket/qsctpsocket.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QSCTPSOCKET_DEBUG
@@ -110,7 +74,7 @@
etc. is allowed in datagram mode with the same limitations as in
continuous byte stream mode.
- \note This feature is not supported on the Windows platform.
+ \note This class is not supported on the Windows platform.
\sa QSctpServer, QTcpSocket, QAbstractSocket
*/
@@ -119,7 +83,6 @@
#include "qsctpsocket_p.h"
#include "qabstractsocketengine_p.h"
-#include "private/qbytearray_p.h"
#ifdef QSCTPSOCKET_DEBUG
#include <qdebug.h>
@@ -156,7 +119,7 @@ bool QSctpSocketPrivate::canReadNotification()
const int savedCurrentChannel = currentReadChannel;
bool currentChannelRead = false;
do {
- int datagramSize = incomingDatagram.size();
+ qsizetype datagramSize = incomingDatagram.size();
QIpPacketHeader header;
do {
@@ -169,7 +132,7 @@ bool QSctpSocketPrivate::canReadNotification()
bytesToRead = 4096;
}
- Q_ASSERT((datagramSize + int(bytesToRead)) < MaxByteArraySize);
+ Q_ASSERT((datagramSize + qsizetype(bytesToRead)) < QByteArray::max_size());
incomingDatagram.resize(datagramSize + int(bytesToRead));
#if defined (QSCTPSOCKET_DEBUG)
@@ -545,3 +508,5 @@ bool QSctpSocket::writeDatagram(const QNetworkDatagram &datagram)
}
QT_END_NAMESPACE
+
+#include "moc_qsctpsocket.cpp"
diff --git a/src/network/socket/qsctpsocket.h b/src/network/socket/qsctpsocket.h
index 5288da6129..8f0578ac26 100644
--- a/src/network/socket/qsctpsocket.h
+++ b/src/network/socket/qsctpsocket.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QSCTPSOCKET_H
#define QSCTPSOCKET_H
@@ -45,7 +9,7 @@
QT_BEGIN_NAMESPACE
-#if !defined(QT_NO_SCTP) || defined(Q_CLANG_QDOC)
+#if !defined(QT_NO_SCTP) || defined(Q_QDOC)
class QSctpSocketPrivate;
diff --git a/src/network/socket/qsctpsocket_p.h b/src/network/socket/qsctpsocket_p.h
index c17b9c1c9a..bcc407eb67 100644
--- a/src/network/socket/qsctpsocket_p.h
+++ b/src/network/socket/qsctpsocket_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QSCTPSOCKET_P_H
#define QSCTPSOCKET_P_H
diff --git a/src/network/socket/qsocks5socketengine.cpp b/src/network/socket/qsocks5socketengine.cpp
index d681bec2d5..0564ad7a33 100644
--- a/src/network/socket/qsocks5socketengine.cpp
+++ b/src/network/socket/qsocks5socketengine.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qsocks5socketengine_p.h"
@@ -45,6 +9,7 @@
#include "qdebug.h"
#include "qhash.h"
#include "qqueue.h"
+#include "qdeadlinetimer.h"
#include "qelapsedtimer.h"
#include "qmutex.h"
#include "qthread.h"
@@ -56,14 +21,21 @@
#include <qendian.h>
#include <qnetworkinterface.h>
+#include <QtCore/qpointer.h>
+
+#include <memory>
+
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+using namespace std::chrono_literals;
+
static const int MaxWriteBufferSize = 128*1024;
//#define QSOCKS5SOCKETLAYER_DEBUG
#define MAX_DATA_DUMP 256
-#define SOCKS5_BLOCKING_BIND_TIMEOUT 5000
+static constexpr auto Socks5BlockingBindTimeout = 5s;
#define Q_INIT_CHECK(returnValue) do { \
if (!d->data) { \
@@ -100,35 +72,35 @@ static const int MaxWriteBufferSize = 128*1024;
static QString s5StateToString(QSocks5SocketEnginePrivate::Socks5State s)
{
switch (s) {
- case QSocks5SocketEnginePrivate::Uninitialized: return QLatin1String("Uninitialized");
- case QSocks5SocketEnginePrivate::ConnectError: return QLatin1String("ConnectError");
- case QSocks5SocketEnginePrivate::AuthenticationMethodsSent: return QLatin1String("AuthenticationMethodsSent");
- case QSocks5SocketEnginePrivate::Authenticating: return QLatin1String("Authenticating");
- case QSocks5SocketEnginePrivate::AuthenticatingError: return QLatin1String("AuthenticatingError");
- case QSocks5SocketEnginePrivate::RequestMethodSent: return QLatin1String("RequestMethodSent");
- case QSocks5SocketEnginePrivate::RequestError: return QLatin1String("RequestError");
- case QSocks5SocketEnginePrivate::Connected: return QLatin1String("Connected");
- case QSocks5SocketEnginePrivate::UdpAssociateSuccess: return QLatin1String("UdpAssociateSuccess");
- case QSocks5SocketEnginePrivate::BindSuccess: return QLatin1String("BindSuccess");
- case QSocks5SocketEnginePrivate::ControlSocketError: return QLatin1String("ControlSocketError");
- case QSocks5SocketEnginePrivate::SocksError: return QLatin1String("SocksError");
- case QSocks5SocketEnginePrivate::HostNameLookupError: return QLatin1String("HostNameLookupError");
+ case QSocks5SocketEnginePrivate::Uninitialized: return "Uninitialized"_L1;
+ case QSocks5SocketEnginePrivate::ConnectError: return "ConnectError"_L1;
+ case QSocks5SocketEnginePrivate::AuthenticationMethodsSent: return "AuthenticationMethodsSent"_L1;
+ case QSocks5SocketEnginePrivate::Authenticating: return "Authenticating"_L1;
+ case QSocks5SocketEnginePrivate::AuthenticatingError: return "AuthenticatingError"_L1;
+ case QSocks5SocketEnginePrivate::RequestMethodSent: return "RequestMethodSent"_L1;
+ case QSocks5SocketEnginePrivate::RequestError: return "RequestError"_L1;
+ case QSocks5SocketEnginePrivate::Connected: return "Connected"_L1;
+ case QSocks5SocketEnginePrivate::UdpAssociateSuccess: return "UdpAssociateSuccess"_L1;
+ case QSocks5SocketEnginePrivate::BindSuccess: return "BindSuccess"_L1;
+ case QSocks5SocketEnginePrivate::ControlSocketError: return "ControlSocketError"_L1;
+ case QSocks5SocketEnginePrivate::SocksError: return "SocksError"_L1;
+ case QSocks5SocketEnginePrivate::HostNameLookupError: return "HostNameLookupError"_L1;
default: break;
}
- return QLatin1String("unknown state");
+ return "unknown state"_L1;
}
static QString dump(const QByteArray &buf)
{
QString data;
for (int i = 0; i < qMin<int>(MAX_DATA_DUMP, buf.size()); ++i) {
- if (i) data += QLatin1Char(' ');
+ if (i) data += u' ';
uint val = (unsigned char)buf.at(i);
- // data += QString("0x%1").arg(val, 3, 16, QLatin1Char('0'));
+ // data += QString("0x%1").arg(val, 3, 16, u'0');
data += QString::number(val);
}
if (buf.size() > MAX_DATA_DUMP)
- data += QLatin1String(" ...");
+ data += " ..."_L1;
return QString::fromLatin1("size: %1 data: { %2 }").arg(buf.size()).arg(data);
}
@@ -144,7 +116,7 @@ static inline QString dump(const QByteArray &) { return QString(); }
/*
inserts the host address in buf at pos and updates pos.
- if the func fails the data in buf and the vallue of pos is undefined
+ if the func fails the data in buf and the value of pos is undefined
*/
static bool qt_socks5_set_host_address_and_port(const QHostAddress &address, quint16 port, QByteArray *pBuf)
{
@@ -186,11 +158,11 @@ static bool qt_socks5_set_host_name_and_port(const QString &hostname, quint16 po
QByteArray encodedHostName = QUrl::toAce(hostname);
QByteArray &buf = *pBuf;
- if (encodedHostName.length() > 255)
+ if (encodedHostName.size() > 255)
return false;
buf.append(S5_DOMAINNAME);
- buf.append(uchar(encodedHostName.length()));
+ buf.append(uchar(encodedHostName.size()));
buf.append(encodedHostName);
// add port
@@ -206,7 +178,7 @@ static bool qt_socks5_set_host_name_and_port(const QString &hostname, quint16 po
/*
- retrives the host address in buf at pos and updates pos.
+ retrieves the host address in buf at pos and updates pos.
return 1 if OK, 0 if need more data, -1 if error
if the func fails the value of the address and the pos is undefined
*/
@@ -325,7 +297,7 @@ protected:
QRecursiveMutex mutex;
int sweepTimerId = -1;
//socket descriptor, data, timestamp
- QHash<int, QSocks5BindData *> store;
+ QHash<qintptr, QSocks5BindData *> store;
};
Q_GLOBAL_STATIC(QSocks5BindStore, socks5BindStore)
@@ -349,9 +321,10 @@ void QSocks5BindStore::add(qintptr socketDescriptor, QSocks5BindData *bindData)
}
bindData->timeStamp.start();
store.insert(socketDescriptor, bindData);
+
// start sweep timer if not started
if (sweepTimerId == -1)
- sweepTimerId = startTimer(60000);
+ sweepTimerId = startTimer(1min);
}
bool QSocks5BindStore::contains(qintptr socketDescriptor)
@@ -492,7 +465,7 @@ bool QSocks5PasswordAuthenticator::continueAuthenticate(QTcpSocket *socket, bool
QString QSocks5PasswordAuthenticator::errorString()
{
- return QLatin1String("Socks5 user name or password incorrect");
+ return "Socks5 user name or password incorrect"_L1;
}
@@ -747,7 +720,7 @@ void QSocks5SocketEnginePrivate::parseAuthenticationMethodReply()
return;
} else if (buf.at(1) != data->authenticator->methodId()
|| !data->authenticator->beginAuthenticate(data->controlSocket, &authComplete)) {
- setErrorState(AuthenticatingError, QLatin1String("Socks5 host did not support authentication method."));
+ setErrorState(AuthenticatingError, "Socks5 host did not support authentication method."_L1);
socketError = QAbstractSocket::SocketAccessError; // change the socket error
emitConnectionNotification();
return;
@@ -1100,7 +1073,7 @@ bool QSocks5SocketEngine::connectInternal()
} else if (socketType() == QAbstractSocket::UdpSocket) {
d->initialize(QSocks5SocketEnginePrivate::UdpAssociateMode);
// all udp needs to be bound
- if (!bind(QHostAddress(QLatin1String("0.0.0.0")), 0))
+ if (!bind(QHostAddress("0.0.0.0"_L1), 0))
return false;
setState(QAbstractSocket::ConnectedState);
@@ -1190,7 +1163,7 @@ void QSocks5SocketEnginePrivate::_q_controlSocketReadNotification()
}
if (buf.size()) {
QSOCKS5_DEBUG << dump(buf);
- connectData->readBuffer.append(buf);
+ connectData->readBuffer.append(std::move(buf));
emitReadNotification();
}
break;
@@ -1290,7 +1263,7 @@ void QSocks5SocketEnginePrivate::_q_udpSocketReadNotification()
int pos = 0;
const char *buf = inBuf.constData();
if (inBuf.size() < 4) {
- QSOCKS5_D_DEBUG << "bugus udp data, discarding";
+ QSOCKS5_D_DEBUG << "bogus udp data, discarding";
return;
}
QSocks5RevivedDatagram datagram;
@@ -1317,7 +1290,7 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
{
Q_D(QSocks5SocketEngine);
- // when bind wee will block until the bind is finished as the info from the proxy server is needed
+ // when bind we will block until the bind is finished as the info from the proxy server is needed
QHostAddress address;
if (addr.protocol() == QAbstractSocket::AnyIPProtocol)
@@ -1357,11 +1330,8 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
return false;
}
- int msecs = SOCKS5_BLOCKING_BIND_TIMEOUT;
- QElapsedTimer stopWatch;
- stopWatch.start();
d->data->controlSocket->connectToHost(d->proxyInfo.hostName(), d->proxyInfo.port());
- if (!d->waitForConnected(msecs, nullptr) ||
+ if (!d->waitForConnected(QDeadlineTimer{Socks5BlockingBindTimeout}, nullptr) ||
d->data->controlSocket->state() == QAbstractSocket::UnconnectedState) {
// waitForConnected sets the error state and closes the socket
QSOCKS5_Q_DEBUG << "waitForConnected to proxy server" << d->data->controlSocket->errorString();
@@ -1383,7 +1353,7 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
// binding timed out
setError(QAbstractSocket::SocketTimeoutError,
- QLatin1String(QT_TRANSLATE_NOOP("QSocks5SocketEngine", "Network operation timed out")));
+ QLatin1StringView(QT_TRANSLATE_NOOP("QSocks5SocketEngine", "Network operation timed out")));
///### delete d->udpSocket;
///### d->udpSocket = 0;
@@ -1391,9 +1361,10 @@ bool QSocks5SocketEngine::bind(const QHostAddress &addr, quint16 port)
}
-bool QSocks5SocketEngine::listen()
+bool QSocks5SocketEngine::listen(int backlog)
{
Q_D(QSocks5SocketEngine);
+ Q_UNUSED(backlog);
QSOCKS5_Q_DEBUG << "listen()";
@@ -1410,7 +1381,7 @@ bool QSocks5SocketEngine::listen()
return false;
}
-int QSocks5SocketEngine::accept()
+qintptr QSocks5SocketEngine::accept()
{
Q_D(QSocks5SocketEngine);
// check we are listing ---
@@ -1436,10 +1407,10 @@ int QSocks5SocketEngine::accept()
d->socketState = QAbstractSocket::UnconnectedState;
break;
case QSocks5SocketEnginePrivate::ControlSocketError:
- setError(QAbstractSocket::ProxyProtocolError, QLatin1String("Control socket error"));
+ setError(QAbstractSocket::ProxyProtocolError, "Control socket error"_L1);
break;
default:
- setError(QAbstractSocket::ProxyProtocolError, QLatin1String("SOCKS5 proxy error"));
+ setError(QAbstractSocket::ProxyProtocolError, "SOCKS5 proxy error"_L1);
break;
}
return sd;
@@ -1451,11 +1422,9 @@ void QSocks5SocketEngine::close()
Q_D(QSocks5SocketEngine);
if (d->data && d->data->controlSocket) {
if (d->data->controlSocket->state() == QAbstractSocket::ConnectedState) {
- int msecs = 100;
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QDeadlineTimer deadline(100ms);
while (!d->data->controlSocket->bytesToWrite()) {
- if (!d->data->controlSocket->waitForBytesWritten(qt_subtract_from_timeout(msecs, stopWatch.elapsed())))
+ if (!d->data->controlSocket->waitForBytesWritten(deadline.remainingTime()))
break;
}
}
@@ -1476,7 +1445,7 @@ qint64 QSocks5SocketEngine::bytesAvailable() const
#ifndef QT_NO_UDPSOCKET
else if (d->mode == QSocks5SocketEnginePrivate::UdpAssociateMode
&& !d->udpData->pendingDatagrams.isEmpty())
- return d->udpData->pendingDatagrams.first().data.size();
+ return d->udpData->pendingDatagrams.constFirst().data.size();
#endif
return 0;
}
@@ -1491,7 +1460,7 @@ qint64 QSocks5SocketEngine::read(char *data, qint64 maxlen)
//imitate remote closed
close();
setError(QAbstractSocket::RemoteHostClosedError,
- QLatin1String("Remote host closed connection###"));
+ "Remote host closed connection###"_L1);
setState(QAbstractSocket::UnconnectedState);
return -1;
} else {
@@ -1525,8 +1494,12 @@ qint64 QSocks5SocketEngine::write(const char *data, qint64 len)
if (!d->data->authenticator->seal(buf, &sealedBuf)) {
// ### Handle this error.
}
+ // We pass pointer and size because 'sealedBuf' is (most definitely) raw data:
+ // QIODevice might have to cache the byte array if the socket cannot write the data.
+ // If the _whole_ array needs to be cached then it would simply store a copy of the
+ // array whose data will go out of scope and be deallocated before it can be used.
+ qint64 written = d->data->controlSocket->write(sealedBuf.constData(), sealedBuf.size());
- qint64 written = d->data->controlSocket->write(sealedBuf);
if (written <= 0) {
QSOCKS5_Q_DEBUG << "native write returned" << written;
return written;
@@ -1550,7 +1523,7 @@ bool QSocks5SocketEngine::joinMulticastGroup(const QHostAddress &,
const QNetworkInterface &)
{
setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Operation on socket is not supported"));
+ "Operation on socket is not supported"_L1);
return false;
}
@@ -1558,7 +1531,7 @@ bool QSocks5SocketEngine::leaveMulticastGroup(const QHostAddress &,
const QNetworkInterface &)
{
setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Operation on socket is not supported"));
+ "Operation on socket is not supported"_L1);
return false;
}
@@ -1571,7 +1544,7 @@ QNetworkInterface QSocks5SocketEngine::multicastInterface() const
bool QSocks5SocketEngine::setMulticastInterface(const QNetworkInterface &)
{
setError(QAbstractSocket::UnsupportedSocketOperationError,
- QLatin1String("Operation on socket is not supported"));
+ "Operation on socket is not supported"_L1);
return false;
}
#endif // QT_NO_NETWORKINTERFACE
@@ -1627,7 +1600,7 @@ qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QI
if (!d->data) {
d->initialize(QSocks5SocketEnginePrivate::UdpAssociateMode);
// all udp needs to be bound
- if (!bind(QHostAddress(QLatin1String("0.0.0.0")), 0)) {
+ if (!bind(QHostAddress("0.0.0.0"_L1), 0)) {
//### set error
return -1;
}
@@ -1637,6 +1610,10 @@ qint64 QSocks5SocketEngine::writeDatagram(const char *data, qint64 len, const QI
outBuf.reserve(270 + len);
outBuf.append(3, '\0');
if (!qt_socks5_set_host_address_and_port(header.destinationAddress, header.destinationPort, &outBuf)) {
+ QSOCKS5_DEBUG << "error setting address" << header.destinationAddress << " : "
+ << header.destinationPort;
+ //### set error code ....
+ return -1;
}
outBuf += QByteArray(data, len);
QSOCKS5_DEBUG << "sending" << dump(outBuf);
@@ -1700,7 +1677,7 @@ bool QSocks5SocketEngine::setOption(SocketOption option, int value)
return false;
}
-bool QSocks5SocketEnginePrivate::waitForConnected(int msecs, bool *timedOut)
+bool QSocks5SocketEnginePrivate::waitForConnected(QDeadlineTimer deadline, bool *timedOut)
{
if (data->controlSocket->state() == QAbstractSocket::UnconnectedState)
return false;
@@ -1710,11 +1687,8 @@ bool QSocks5SocketEnginePrivate::waitForConnected(int msecs, bool *timedOut)
mode == BindMode ? BindSuccess :
UdpAssociateSuccess;
- QElapsedTimer stopWatch;
- stopWatch.start();
-
while (socks5State != wantedState) {
- if (!data->controlSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ if (!data->controlSocket->waitForReadyRead(deadline.remainingTime())) {
if (data->controlSocket->state() == QAbstractSocket::UnconnectedState)
return true;
@@ -1728,18 +1702,15 @@ bool QSocks5SocketEnginePrivate::waitForConnected(int msecs, bool *timedOut)
return true;
}
-bool QSocks5SocketEngine::waitForRead(int msecs, bool *timedOut)
+bool QSocks5SocketEngine::waitForRead(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(QSocks5SocketEngine);
- QSOCKS5_DEBUG << "waitForRead" << msecs;
+ QSOCKS5_DEBUG << "waitForRead" << deadline.remainingTimeAsDuration();
d->readNotificationActivated = false;
- QElapsedTimer stopWatch;
- stopWatch.start();
-
// are we connected yet?
- if (!d->waitForConnected(msecs, timedOut))
+ if (!d->waitForConnected(deadline, timedOut))
return false;
if (d->data->controlSocket->state() == QAbstractSocket::UnconnectedState)
return true;
@@ -1753,7 +1724,7 @@ bool QSocks5SocketEngine::waitForRead(int msecs, bool *timedOut)
if (d->mode == QSocks5SocketEnginePrivate::ConnectMode ||
d->mode == QSocks5SocketEnginePrivate::BindMode) {
while (!d->readNotificationActivated) {
- if (!d->data->controlSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ if (!d->data->controlSocket->waitForReadyRead(deadline.remainingTime())) {
if (d->data->controlSocket->state() == QAbstractSocket::UnconnectedState)
return true;
@@ -1766,7 +1737,7 @@ bool QSocks5SocketEngine::waitForRead(int msecs, bool *timedOut)
#ifndef QT_NO_UDPSOCKET
} else {
while (!d->readNotificationActivated) {
- if (!d->udpData->udpSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
+ if (!d->udpData->udpSocket->waitForReadyRead(deadline.remainingTime())) {
setError(d->udpData->udpSocket->error(), d->udpData->udpSocket->errorString());
if (timedOut && d->udpData->udpSocket->error() == QAbstractSocket::SocketTimeoutError)
*timedOut = true;
@@ -1785,16 +1756,13 @@ bool QSocks5SocketEngine::waitForRead(int msecs, bool *timedOut)
}
-bool QSocks5SocketEngine::waitForWrite(int msecs, bool *timedOut)
+bool QSocks5SocketEngine::waitForWrite(QDeadlineTimer deadline, bool *timedOut)
{
Q_D(QSocks5SocketEngine);
- QSOCKS5_DEBUG << "waitForWrite" << msecs;
-
- QElapsedTimer stopWatch;
- stopWatch.start();
+ QSOCKS5_DEBUG << "waitForWrite" << deadline.remainingTimeAsDuration();
// are we connected yet?
- if (!d->waitForConnected(msecs, timedOut))
+ if (!d->waitForConnected(deadline, timedOut))
return false;
if (d->data->controlSocket->state() == QAbstractSocket::UnconnectedState)
return true;
@@ -1803,27 +1771,32 @@ bool QSocks5SocketEngine::waitForWrite(int msecs, bool *timedOut)
// flush any bytes we may still have buffered in the time that we have left
if (d->data->controlSocket->bytesToWrite())
- d->data->controlSocket->waitForBytesWritten(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
- while ((msecs == -1 || stopWatch.elapsed() < msecs)
- && d->data->controlSocket->state() == QAbstractSocket::ConnectedState
- && d->data->controlSocket->bytesToWrite() >= MaxWriteBufferSize)
- d->data->controlSocket->waitForBytesWritten(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
+ d->data->controlSocket->waitForBytesWritten(deadline.remainingTime());
+
+ auto shouldWriteBytes = [&]() {
+ return d->data->controlSocket->state() == QAbstractSocket::ConnectedState
+ && d->data->controlSocket->bytesToWrite() >= MaxWriteBufferSize;
+ };
+
+ qint64 remainingTime = deadline.remainingTime();
+ for (; remainingTime > 0 && shouldWriteBytes(); remainingTime = deadline.remainingTime())
+ d->data->controlSocket->waitForBytesWritten(remainingTime);
return d->data->controlSocket->bytesToWrite() < MaxWriteBufferSize;
}
bool QSocks5SocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs, bool *timedOut)
+ QDeadlineTimer deadline, bool *timedOut)
{
Q_UNUSED(checkRead);
if (!checkWrite) {
- bool canRead = waitForRead(msecs, timedOut);
+ bool canRead = waitForRead(deadline, timedOut);
if (readyToRead)
*readyToRead = canRead;
return canRead;
}
- bool canWrite = waitForWrite(msecs, timedOut);
+ bool canWrite = waitForWrite(deadline, timedOut);
if (readyToWrite)
*readyToWrite = canWrite;
return canWrite;
@@ -1903,9 +1876,9 @@ QSocks5SocketEngineHandler::createSocketEngine(QAbstractSocket::SocketType socke
QSOCKS5_DEBUG << "not proxying";
return nullptr;
}
- QScopedPointer<QSocks5SocketEngine> engine(new QSocks5SocketEngine(parent));
+ auto engine = std::make_unique<QSocks5SocketEngine>(parent);
engine->setProxy(proxy);
- return engine.take();
+ return engine.release();
}
QAbstractSocketEngine *QSocks5SocketEngineHandler::createSocketEngine(qintptr socketDescriptor, QObject *parent)
diff --git a/src/network/socket/qsocks5socketengine_p.h b/src/network/socket/qsocks5socketengine_p.h
index 77b461b944..3a169812df 100644
--- a/src/network/socket/qsocks5socketengine_p.h
+++ b/src/network/socket/qsocks5socketengine_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QSOCKS5SOCKETENGINE_P_H
#define QSOCKS5SOCKETENGINE_P_H
@@ -52,8 +16,10 @@
//
#include <QtNetwork/private/qtnetworkglobal_p.h>
+
+#include <QtNetwork/qnetworkproxy.h>
+
#include "qabstractsocketengine_p.h"
-#include "qnetworkproxy.h"
QT_REQUIRE_CONFIG(socks5);
@@ -81,8 +47,8 @@ public:
bool connectToHost(const QHostAddress &address, quint16 port) override;
bool connectToHostByName(const QString &name, quint16 port) override;
bool bind(const QHostAddress &address, quint16 port) override;
- bool listen() override;
- int accept() override;
+ bool listen(int backlog) override;
+ qintptr accept() override;
void close() override;
qint64 bytesAvailable() const override;
@@ -112,11 +78,14 @@ public:
int option(SocketOption option) const override;
bool setOption(SocketOption option, int value) override;
- bool waitForRead(int msecs = 30000, bool *timedOut = nullptr) override;
- bool waitForWrite(int msecs = 30000, bool *timedOut = nullptr) override;
+ bool waitForRead(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
+ bool waitForWrite(QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
bool waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
bool checkRead, bool checkWrite,
- int msecs = 30000, bool *timedOut = nullptr) override;
+ QDeadlineTimer deadline = QDeadlineTimer{DefaultTimeout},
+ bool *timedOut = nullptr) override;
bool isReadNotificationEnabled() const override;
void setReadNotificationEnabled(bool enable) override;
@@ -155,9 +124,9 @@ public:
virtual bool beginAuthenticate(QTcpSocket *socket, bool *completed);
virtual bool continueAuthenticate(QTcpSocket *socket, bool *completed);
- virtual bool seal(const QByteArray &buf, QByteArray *sealedBuf);
- virtual bool unSeal(const QByteArray &sealedBuf, QByteArray *buf);
- virtual bool unSeal(QTcpSocket *sealedSocket, QByteArray *buf);
+ bool seal(const QByteArray &buf, QByteArray *sealedBuf);
+ bool unSeal(const QByteArray &sealedBuf, QByteArray *buf);
+ bool unSeal(QTcpSocket *sealedSocket, QByteArray *buf);
virtual QString errorString() { return QString(); }
};
@@ -242,7 +211,7 @@ public:
void parseRequestMethodReply();
void parseNewConnection();
- bool waitForConnected(int msecs, bool *timedOut);
+ bool waitForConnected(QDeadlineTimer deadline, bool *timedOut);
void _q_controlSocketConnected();
void _q_controlSocketReadNotification();
diff --git a/src/network/socket/qtcpserver.cpp b/src/network/socket/qtcpserver.cpp
index a404350d98..a0c0f00aaa 100644
--- a/src/network/socket/qtcpserver.cpp
+++ b/src/network/socket/qtcpserver.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QTCPSERVER_DEBUG
@@ -54,7 +18,9 @@
Call listen() to have the server listen for incoming connections.
The newConnection() signal is then emitted each time a client
- connects to the server.
+ connects to the server. When the client connection has been added
+ to the pending connection queue using the addPendingConnection()
+ function, the pendingConnectionAvailable() signal is emitted.
Call nextPendingConnection() to accept the pending connection as
a connected QTcpSocket. The function returns a pointer to a
@@ -77,17 +43,27 @@
use waitForNewConnection(), which blocks until either a
connection is available or a timeout expires.
- \sa QTcpSocket, {Fortune Server Example}, {Threaded Fortune Server Example},
- {Loopback Example}, {Torrent Example}
+ \sa QTcpSocket, {Fortune Server}, {Threaded Fortune Server},
+ {Torrent Example}
*/
/*! \fn void QTcpServer::newConnection()
- This signal is emitted every time a new connection is available.
+ This signal is emitted every time a new connection is available, regardless
+ of whether it has been added to the pending connections queue or not.
\sa hasPendingConnections(), nextPendingConnection()
*/
+/*! \fn void QTcpServer::pendingConnectionAvailable()
+
+ This signal is emitted every time a new connection has been added to the
+ pending connections queue.
+
+ \sa hasPendingConnections(), nextPendingConnection()
+ \since 6.4
+*/
+
/*! \fn void QTcpServer::acceptError(QAbstractSocket::SocketError socketError)
\since 5.0
@@ -157,7 +133,7 @@ QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint
}
// return the first that we can use
- for (const QNetworkProxy &p : qAsConst(proxies)) {
+ for (const QNetworkProxy &p : std::as_const(proxies)) {
if (socketType == QAbstractSocket::TcpSocket &&
(p.capabilities() & QNetworkProxy::ListeningCapability) != 0)
return p;
@@ -196,7 +172,7 @@ void QTcpServerPrivate::readNotification()
{
Q_Q(QTcpServer);
for (;;) {
- if (pendingConnections.count() >= maxConnections) {
+ if (totalPendingConnections() >= maxConnections) {
#if defined (QTCPSERVER_DEBUG)
qDebug("QTcpServerPrivate::_q_processIncomingConnection() too many connections");
#endif
@@ -205,7 +181,7 @@ void QTcpServerPrivate::readNotification()
return;
}
- int descriptor = socketEngine->accept();
+ qintptr descriptor = socketEngine->accept();
if (descriptor == -1) {
if (socketEngine->error() != QAbstractSocket::TemporaryError) {
q->pauseAccepting();
@@ -218,16 +194,32 @@ void QTcpServerPrivate::readNotification()
#if defined (QTCPSERVER_DEBUG)
qDebug("QTcpServerPrivate::_q_processIncomingConnection() accepted socket %i", descriptor);
#endif
+ QPointer<QTcpServer> that = q;
q->incomingConnection(descriptor);
- QPointer<QTcpServer> that = q;
- emit q->newConnection();
+ if (that)
+ emit q->newConnection();
+
if (!that || !q->isListening())
return;
}
}
/*!
+ \internal
+ Return the amount of sockets currently in queue for the server.
+ This is to make maxPendingConnections work properly with servers that don't
+ necessarily have 'ready-to-go' sockets as soon as they connect,
+ e.g. QSslServer.
+ By default we just return pendingConnections.size(), which is equivalent to
+ what it did before.
+*/
+int QTcpServerPrivate::totalPendingConnections() const
+{
+ return int(pendingConnections.size());
+}
+
+/*!
Constructs a QTcpServer object.
\a parent is passed to the QObject constructor.
@@ -331,7 +323,7 @@ bool QTcpServer::listen(const QHostAddress &address, quint16 port)
return false;
}
- if (!d->socketEngine->listen()) {
+ if (!d->socketEngine->listen(d->listenBacklog)) {
d->serverSocketError = d->socketEngine->error();
d->serverSocketErrorString = d->socketEngine->errorString();
return false;
@@ -506,7 +498,7 @@ bool QTcpServer::waitForNewConnection(int msec, bool *timedOut)
if (d->state != QAbstractSocket::ListeningState)
return false;
- if (!d->socketEngine->waitForRead(msec, timedOut)) {
+ if (!d->socketEngine->waitForRead(QDeadlineTimer(msec), timedOut)) {
d->serverSocketError = d->socketEngine->error();
d->serverSocketErrorString = d->socketEngine->errorString();
return false;
@@ -608,14 +600,17 @@ void QTcpServer::incomingConnection(qintptr socketDescriptor)
\note Don't forget to call this member from reimplemented
incomingConnection() if you do not want to break the
- Pending Connections mechanism.
+ Pending Connections mechanism. This function emits the
+ pendingConnectionAvailable() signal after the socket has been
+ added.
- \sa incomingConnection()
+ \sa incomingConnection(), pendingConnectionAvailable()
\since 4.7
*/
void QTcpServer::addPendingConnection(QTcpSocket* socket)
{
d_func()->pendingConnections.append(socket);
+ emit pendingConnectionAvailable(QPrivateSignal());
}
/*!
@@ -650,6 +645,34 @@ int QTcpServer::maxPendingConnections() const
}
/*!
+ Sets the backlog queue size of to be accepted connections to \a
+ size. The operating system might reduce or ignore this value.
+ By default, the queue size is 50.
+
+ \note This property must be set prior to calling listen().
+
+ \since 6.3
+
+ \sa listenBacklogSize()
+*/
+void QTcpServer::setListenBacklogSize(int size)
+{
+ d_func()->listenBacklog = size;
+}
+
+/*!
+ Returns the backlog queue size of to be accepted connections.
+
+ \since 6.3
+
+ \sa setListenBacklogSize()
+*/
+int QTcpServer::listenBacklogSize() const
+{
+ return d_func()->listenBacklog;
+}
+
+/*!
Returns an error code for the last error that occurred.
\sa errorString()
diff --git a/src/network/socket/qtcpserver.h b/src/network/socket/qtcpserver.h
index 37df12919f..6177a3b0aa 100644
--- a/src/network/socket/qtcpserver.h
+++ b/src/network/socket/qtcpserver.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTCPSERVER_H
#define QTCPSERVER_H
@@ -69,6 +33,9 @@ public:
void setMaxPendingConnections(int numConnections);
int maxPendingConnections() const;
+ void setListenBacklogSize(int size);
+ int listenBacklogSize() const;
+
quint16 serverPort() const;
QHostAddress serverAddress() const;
@@ -99,6 +66,7 @@ protected:
Q_SIGNALS:
void newConnection();
+ void pendingConnectionAvailable(QPrivateSignal);
void acceptError(QAbstractSocket::SocketError socketError);
private:
diff --git a/src/network/socket/qtcpserver_p.h b/src/network/socket/qtcpserver_p.h
index 6ee8c5f0b1..853a4aaf96 100644
--- a/src/network/socket/qtcpserver_p.h
+++ b/src/network/socket/qtcpserver_p.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTCPSERVER_P_H
#define QTCPSERVER_P_H
@@ -83,6 +47,7 @@ public:
QAbstractSocket::SocketError serverSocketError;
QString serverSocketErrorString;
+ int listenBacklog = 50;
int maxConnections;
#ifndef QT_NO_NETWORKPROXY
@@ -91,6 +56,7 @@ public:
#endif
virtual void configureCreatedSocket();
+ virtual int totalPendingConnections() const;
// from QAbstractSocketEngineReceiver
void readNotification() override;
diff --git a/src/network/socket/qtcpsocket.cpp b/src/network/socket/qtcpsocket.cpp
index 85d425055b..979382f26c 100644
--- a/src/network/socket/qtcpsocket.cpp
+++ b/src/network/socket/qtcpsocket.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QTCPSOCKET_DEBUG
@@ -59,9 +23,9 @@
\note TCP sockets cannot be opened in QIODevice::Unbuffered mode.
\sa QTcpServer, QUdpSocket, QNetworkAccessManager,
- {Fortune Server Example}, {Fortune Client Example},
- {Threaded Fortune Server Example}, {Blocking Fortune Client Example},
- {Loopback Example}, {Torrent Example}
+ {Fortune Server}, {Fortune Client},
+ {Threaded Fortune Server}, {Blocking Fortune Client},
+ {Torrent Example}
*/
#include "qtcpsocket.h"
@@ -119,3 +83,5 @@ QTcpSocket::QTcpSocket(QAbstractSocket::SocketType socketType,
}
QT_END_NAMESPACE
+
+#include "moc_qtcpsocket.cpp"
diff --git a/src/network/socket/qtcpsocket.h b/src/network/socket/qtcpsocket.h
index e52eddfdbd..a1c610b69b 100644
--- a/src/network/socket/qtcpsocket.h
+++ b/src/network/socket/qtcpsocket.h
@@ -1,47 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTCPSOCKET_H
#define QTCPSOCKET_H
#include <QtNetwork/qtnetworkglobal.h>
#include <QtNetwork/qabstractsocket.h>
+#include <QtNetwork/qhostaddress.h>
#include <QtCore/qvariant.h>
QT_BEGIN_NAMESPACE
@@ -56,6 +21,13 @@ public:
explicit QTcpSocket(QObject *parent = nullptr);
virtual ~QTcpSocket();
+#if QT_VERSION < QT_VERSION_CHECK(7,0,0) && !defined(Q_QDOC)
+ // ### Qt7: move into QAbstractSocket
+ using QAbstractSocket::bind;
+ bool bind(QHostAddress::SpecialAddress addr, quint16 port = 0, BindMode mode = DefaultForPlatform)
+ { return bind(QHostAddress(addr), port, mode); }
+#endif
+
protected:
QTcpSocket(QTcpSocketPrivate &dd, QObject *parent = nullptr);
QTcpSocket(QAbstractSocket::SocketType socketType, QTcpSocketPrivate &dd,
diff --git a/src/network/socket/qtcpsocket_p.h b/src/network/socket/qtcpsocket_p.h
index ba1a0aa920..5823342f22 100644
--- a/src/network/socket/qtcpsocket_p.h
+++ b/src/network/socket/qtcpsocket_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QTCPSOCKET_P_H
#define QTCPSOCKET_P_H
diff --git a/src/network/socket/qudpsocket.cpp b/src/network/socket/qudpsocket.cpp
index 9694dfa507..bfeea307b2 100644
--- a/src/network/socket/qudpsocket.cpp
+++ b/src/network/socket/qudpsocket.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
//#define QUDPSOCKET_DEBUG
@@ -418,7 +382,7 @@ qint64 QUdpSocket::writeDatagram(const QNetworkDatagram &datagram)
if (state() == UnconnectedState)
bind();
- qint64 sent = d->socketEngine->writeDatagram(datagram.d->data,
+ qint64 sent = d->socketEngine->writeDatagram(datagram.d->data.constData(),
datagram.d->data.size(),
datagram.d->header);
d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
@@ -466,6 +430,7 @@ QNetworkDatagram QUdpSocket::receiveDatagram(qint64 maxSize)
qint64 readBytes = d->socketEngine->readDatagram(result.d->data.data(), maxSize, &result.d->header,
QAbstractSocketEngine::WantAll);
d->hasPendingData = false;
+ d->hasPendingDatagram = false;
d->socketEngine->setReadNotificationEnabled(true);
if (readBytes < 0) {
d->setErrorAndEmit(d->socketEngine->error(), d->socketEngine->errorString());
@@ -515,6 +480,7 @@ qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *addres
}
d->hasPendingData = false;
+ d->hasPendingDatagram = false;
d->socketEngine->setReadNotificationEnabled(true);
if (readBytes < 0) {
if (readBytes == -2) {
@@ -531,3 +497,5 @@ qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *addres
#endif // QT_NO_UDPSOCKET
QT_END_NAMESPACE
+
+#include "moc_qudpsocket.cpp"
diff --git a/src/network/socket/qudpsocket.h b/src/network/socket/qudpsocket.h
index e2ddba1362..3fd1d3710a 100644
--- a/src/network/socket/qudpsocket.h
+++ b/src/network/socket/qudpsocket.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** 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 https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://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 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QUDPSOCKET_H
#define QUDPSOCKET_H
@@ -60,6 +24,13 @@ public:
explicit QUdpSocket(QObject *parent = nullptr);
virtual ~QUdpSocket();
+#if QT_VERSION < QT_VERSION_CHECK(7,0,0) && !defined(Q_QDOC)
+ // ### Qt7: move into QAbstractSocket
+ using QAbstractSocket::bind;
+ bool bind(QHostAddress::SpecialAddress addr, quint16 port = 0, BindMode mode = DefaultForPlatform)
+ { return bind(QHostAddress(addr), port, mode); }
+#endif
+
#ifndef QT_NO_NETWORKINTERFACE
bool joinMulticastGroup(const QHostAddress &groupAddress);
bool joinMulticastGroup(const QHostAddress &groupAddress,
diff --git a/src/network/socket/socket.pri b/src/network/socket/socket.pri
deleted file mode 100644
index 67325ac70f..0000000000
--- a/src/network/socket/socket.pri
+++ /dev/null
@@ -1,84 +0,0 @@
-# Qt network socket
-
-HEADERS += socket/qabstractsocketengine_p.h \
- socket/qabstractsocket.h \
- socket/qabstractsocket_p.h \
- socket/qtcpsocket.h \
- socket/qudpsocket.h \
- socket/qtcpserver.h \
- socket/qtcpsocket_p.h \
- socket/qtcpserver_p.h
-
-SOURCES += socket/qabstractsocketengine.cpp \
- socket/qabstractsocket.cpp \
- socket/qtcpsocket.cpp \
- socket/qudpsocket.cpp \
- socket/qtcpserver.cpp
-
-# SOCK5 support.
-
-qtConfig(socks5) {
- HEADERS += \
- socket/qsocks5socketengine_p.h
- SOURCES += \
- socket/qsocks5socketengine.cpp
-}
-
-qtConfig(http) {
- HEADERS += \
- socket/qhttpsocketengine_p.h
- SOURCES += \
- socket/qhttpsocketengine.cpp
-}
-
-# SCTP support.
-
-qtConfig(sctp) {
- HEADERS += socket/qsctpserver.h \
- socket/qsctpserver_p.h \
- socket/qsctpsocket.h \
- socket/qsctpsocket_p.h
-
- SOURCES += socket/qsctpserver.cpp \
- socket/qsctpsocket.cpp
-}
-
-SOURCES += socket/qnativesocketengine.cpp
-HEADERS += socket/qnativesocketengine_p.h
-
-unix {
- SOURCES += socket/qnativesocketengine_unix.cpp
- HEADERS += socket/qnet_unix_p.h
-}
-
-# Suppress deprecation warnings with moc because MS headers have
-# invalid C/C++ code otherwise.
-msvc: QMAKE_MOC_OPTIONS += -D_WINSOCK_DEPRECATED_NO_WARNINGS
-
-win32: SOURCES += socket/qnativesocketengine_win.cpp
-win32: QMAKE_USE_PRIVATE += advapi32
-
-qtConfig(localserver) {
- HEADERS += socket/qlocalserver.h \
- socket/qlocalserver_p.h \
- socket/qlocalsocket.h \
- socket/qlocalsocket_p.h
- SOURCES += socket/qlocalsocket.cpp \
- socket/qlocalserver.cpp
-
- integrity {
- SOURCES += socket/qlocalsocket_tcp.cpp \
- socket/qlocalserver_tcp.cpp
- DEFINES += QT_LOCALSOCKET_TCP
- } else: unix {
- SOURCES += socket/qlocalsocket_unix.cpp \
- socket/qlocalserver_unix.cpp
- } else: win32 {
- SOURCES += socket/qlocalsocket_win.cpp \
- socket/qlocalserver_win.cpp
- }
-}
-
-qtConfig(system-proxies) {
- DEFINES += QT_USE_SYSTEM_PROXIES
-}