1/****************************************************************************
2**
3** Copyright (C) 2022 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41//#define QABSTRACTSOCKET_DEBUG
42
43/*!
44 \class QAbstractSocket
45
46 \brief The QAbstractSocket class provides the base functionality
47 common to all socket types.
48
49 \reentrant
50 \ingroup network
51 \inmodule QtNetwork
52
53 QAbstractSocket is the base class for QTcpSocket and QUdpSocket
54 and contains all common functionality of these two classes. If
55 you need a socket, you have two options:
56
57 \list
58 \li Instantiate QTcpSocket or QUdpSocket.
59 \li Create a native socket descriptor, instantiate
60 QAbstractSocket, and call setSocketDescriptor() to wrap the
61 native socket.
62 \endlist
63
64 TCP (Transmission Control Protocol) is a reliable,
65 stream-oriented, connection-oriented transport protocol. UDP
66 (User Datagram Protocol) is an unreliable, datagram-oriented,
67 connectionless protocol. In practice, this means that TCP is
68 better suited for continuous transmission of data, whereas the
69 more lightweight UDP can be used when reliability isn't
70 important.
71
72 QAbstractSocket's API unifies most of the differences between the
73 two protocols. For example, although UDP is connectionless,
74 connectToHost() establishes a virtual connection for UDP sockets,
75 enabling you to use QAbstractSocket in more or less the same way
76 regardless of the underlying protocol. Internally,
77 QAbstractSocket remembers the address and port passed to
78 connectToHost(), and functions like read() and write() use these
79 values.
80
81 At any time, QAbstractSocket has a state (returned by
82 state()). The initial state is UnconnectedState. After
83 calling connectToHost(), the socket first enters
84 HostLookupState. If the host is found, QAbstractSocket enters
85 ConnectingState and emits the hostFound() signal. When the
86 connection has been established, it enters ConnectedState and
87 emits connected(). If an error occurs at any stage, errorOccurred() is
88 emitted. Whenever the state changes, stateChanged() is emitted.
89 For convenience, isValid() returns \c true if the socket is ready for
90 reading and writing, but note that the socket's state must be
91 ConnectedState before reading and writing can occur.
92
93 Read or write data by calling read() or write(), or use the
94 convenience functions readLine() and readAll(). QAbstractSocket
95 also inherits getChar(), putChar(), and ungetChar() from
96 QIODevice, which work on single bytes. The bytesWritten() signal
97 is emitted when data has been written to the socket. Note that Qt does
98 not limit the write buffer size. You can monitor its size by listening
99 to this signal.
100
101 The readyRead() signal is emitted every time a new chunk of data
102 has arrived. bytesAvailable() then returns the number of bytes
103 that are available for reading. Typically, you would connect the
104 readyRead() signal to a slot and read all available data there.
105 If you don't read all the data at once, the remaining data will
106 still be available later, and any new incoming data will be
107 appended to QAbstractSocket's internal read buffer. To limit the
108 size of the read buffer, call setReadBufferSize().
109
110 To close the socket, call disconnectFromHost(). QAbstractSocket enters
111 QAbstractSocket::ClosingState. After all pending data has been written to
112 the socket, QAbstractSocket actually closes the socket, enters
113 QAbstractSocket::UnconnectedState, and emits disconnected(). If you want
114 to abort a connection immediately, discarding all pending data, call
115 abort() instead. If the remote host closes the connection,
116 QAbstractSocket will emit errorOccurred(QAbstractSocket::RemoteHostClosedError),
117 during which the socket state will still be ConnectedState, and then the
118 disconnected() signal will be emitted.
119
120 The port and address of the connected peer is fetched by calling
121 peerPort() and peerAddress(). peerName() returns the host name of
122 the peer, as passed to connectToHost(). localPort() and
123 localAddress() return the port and address of the local socket.
124
125 QAbstractSocket provides a set of functions that suspend the
126 calling thread until certain signals are emitted. These functions
127 can be used to implement blocking sockets:
128
129 \list
130 \li waitForConnected() blocks until a connection has been established.
131
132 \li waitForReadyRead() blocks until new data is available for
133 reading.
134
135 \li waitForBytesWritten() blocks until one payload of data has been
136 written to the socket.
137
138 \li waitForDisconnected() blocks until the connection has closed.
139 \endlist
140
141 We show an example:
142
143 \snippet network/tcpwait.cpp 0
144
145 If \l{QIODevice::}{waitForReadyRead()} returns \c false, the
146 connection has been closed or an error has occurred.
147
148 Programming with a blocking socket is radically different from
149 programming with a non-blocking socket. A blocking socket doesn't
150 require an event loop and typically leads to simpler code.
151 However, in a GUI application, blocking sockets should only be
152 used in non-GUI threads, to avoid freezing the user interface.
153 See the \l fortuneclient and \l blockingfortuneclient
154 examples for an overview of both approaches.
155
156 \note We discourage the use of the blocking functions together
157 with signals. One of the two possibilities should be used.
158
159 QAbstractSocket can be used with QTextStream and QDataStream's
160 stream operators (operator<<() and operator>>()). There is one
161 issue to be aware of, though: You must make sure that enough data
162 is available before attempting to read it using operator>>().
163
164 \sa QNetworkAccessManager, QTcpServer
165*/
166
167/*!
168 \fn void QAbstractSocket::hostFound()
169
170 This signal is emitted after connectToHost() has been called and
171 the host lookup has succeeded.
172
173 \note Since Qt 4.6.3 QAbstractSocket may emit hostFound()
174 directly from the connectToHost() call since a DNS result could have been
175 cached.
176
177 \sa connected()
178*/
179
180/*!
181 \fn void QAbstractSocket::connected()
182
183 This signal is emitted after connectToHost() has been called and
184 a connection has been successfully established.
185
186 \note On some operating systems the connected() signal may
187 be directly emitted from the connectToHost() call for connections
188 to the localhost.
189
190 \sa connectToHost(), disconnected()
191*/
192
193/*!
194 \fn void QAbstractSocket::disconnected()
195
196 This signal is emitted when the socket has been disconnected.
197
198 \warning If you need to delete the sender() of this signal in a slot connected
199 to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
200
201 \sa connectToHost(), disconnectFromHost(), abort()
202*/
203
204/*!
205 \fn void QAbstractSocket::error(QAbstractSocket::SocketError socketError)
206 \obsolete
207
208 Use errorOccurred() instead.
209*/
210
211/*!
212 \fn void QAbstractSocket::errorOccurred(QAbstractSocket::SocketError socketError)
213 \since 5.15
214
215 This signal is emitted after an error occurred. The \a socketError
216 parameter describes the type of error that occurred.
217
218 When this signal is emitted, the socket may not be ready for a reconnect
219 attempt. In that case, attempts to reconnect should be done from the event
220 loop. For example, use a QTimer::singleShot() with 0 as the timeout.
221
222 QAbstractSocket::SocketError is not a registered metatype, so for queued
223 connections, you will have to register it with Q_DECLARE_METATYPE() and
224 qRegisterMetaType().
225
226 \sa error(), errorString(), {Creating Custom Qt Types}
227*/
228
229/*!
230 \fn void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)
231
232 This signal is emitted whenever QAbstractSocket's state changes.
233 The \a socketState parameter is the new state.
234
235 QAbstractSocket::SocketState is not a registered metatype, so for queued
236 connections, you will have to register it with Q_DECLARE_METATYPE() and
237 qRegisterMetaType().
238
239 \sa state(), {Creating Custom Qt Types}
240*/
241
242/*!
243 \fn void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
244 \since 4.3
245
246 This signal can be emitted when a \a proxy that requires
247 authentication is used. The \a authenticator object can then be
248 filled in with the required details to allow authentication and
249 continue the connection.
250
251 \note It is not possible to use a QueuedConnection to connect to
252 this signal, as the connection will fail if the authenticator has
253 not been filled in with new information when the signal returns.
254
255 \sa QAuthenticator, QNetworkProxy
256*/
257
258/*!
259 \enum QAbstractSocket::NetworkLayerProtocol
260
261 This enum describes the network layer protocol values used in Qt.
262
263 \value IPv4Protocol IPv4
264 \value IPv6Protocol IPv6
265 \value AnyIPProtocol Either IPv4 or IPv6
266 \value UnknownNetworkLayerProtocol Other than IPv4 and IPv6
267
268 \sa QHostAddress::protocol()
269*/
270
271/*!
272 \enum QAbstractSocket::SocketType
273
274 This enum describes the transport layer protocol.
275
276 \value TcpSocket TCP
277 \value UdpSocket UDP
278 \value SctpSocket SCTP
279 \value UnknownSocketType Other than TCP, UDP and SCTP
280
281 \sa QAbstractSocket::socketType()
282*/
283
284/*!
285 \enum QAbstractSocket::SocketError
286
287 This enum describes the socket errors that can occur.
288
289 \value ConnectionRefusedError The connection was refused by the
290 peer (or timed out).
291 \value RemoteHostClosedError The remote host closed the
292 connection. Note that the client socket (i.e., this socket)
293 will be closed after the remote close notification has
294 been sent.
295 \value HostNotFoundError The host address was not found.
296 \value SocketAccessError The socket operation failed because the
297 application lacked the required privileges.
298 \value SocketResourceError The local system ran out of resources
299 (e.g., too many sockets).
300 \value SocketTimeoutError The socket operation timed out.
301 \value DatagramTooLargeError The datagram was larger than the
302 operating system's limit (which can be as low as 8192
303 bytes).
304 \value NetworkError An error occurred with the network (e.g., the
305 network cable was accidentally plugged out).
306 \value AddressInUseError The address specified to QAbstractSocket::bind() is
307 already in use and was set to be exclusive.
308 \value SocketAddressNotAvailableError The address specified to
309 QAbstractSocket::bind() does not belong to the host.
310 \value UnsupportedSocketOperationError The requested socket operation is
311 not supported by the local operating system (e.g., lack of
312 IPv6 support).
313 \value ProxyAuthenticationRequiredError The socket is using a proxy, and
314 the proxy requires authentication.
315 \value SslHandshakeFailedError The SSL/TLS handshake failed, so
316 the connection was closed (only used in QSslSocket)
317 \value UnfinishedSocketOperationError Used by QAbstractSocketEngine only,
318 The last operation attempted has not finished yet (still in progress in
319 the background).
320 \value ProxyConnectionRefusedError Could not contact the proxy server because
321 the connection to that server was denied
322 \value ProxyConnectionClosedError The connection to the proxy server was closed
323 unexpectedly (before the connection to the final peer was established)
324 \value ProxyConnectionTimeoutError The connection to the proxy server timed out
325 or the proxy server stopped responding in the authentication phase.
326 \value ProxyNotFoundError The proxy address set with setProxy() (or the application
327 proxy) was not found.
328 \value ProxyProtocolError The connection negotiation with the proxy server failed,
329 because the response from the proxy server could not be understood.
330 \value OperationError An operation was attempted while the socket was in a state that
331 did not permit it.
332 \value SslInternalError The SSL library being used reported an internal error. This is
333 probably the result of a bad installation or misconfiguration of the library.
334 \value SslInvalidUserDataError Invalid data (certificate, key, cypher, etc.) was
335 provided and its use resulted in an error in the SSL library.
336 \value TemporaryError A temporary error occurred (e.g., operation would block and socket
337 is non-blocking).
338
339 \value UnknownSocketError An unidentified error occurred.
340 \sa QAbstractSocket::error()
341 \sa QAbstractSocket::errorOccurred()
342*/
343
344/*!
345 \enum QAbstractSocket::SocketState
346
347 This enum describes the different states in which a socket can be.
348
349 \value UnconnectedState The socket is not connected.
350 \value HostLookupState The socket is performing a host name lookup.
351 \value ConnectingState The socket has started establishing a connection.
352 \value ConnectedState A connection is established.
353 \value BoundState The socket is bound to an address and port.
354 \value ClosingState The socket is about to close (data may still
355 be waiting to be written).
356 \value ListeningState For internal use only.
357
358 \sa QAbstractSocket::state()
359*/
360
361/*!
362 \enum QAbstractSocket::SocketOption
363 \since 4.6
364
365 This enum represents the options that can be set on a socket. If
366 desired, they can be set after having received the connected()
367 signal from the socket or after having received a new socket from
368 a QTcpServer.
369
370 \value LowDelayOption Try to optimize the socket for low
371 latency. For a QTcpSocket this would set the TCP_NODELAY option
372 and disable Nagle's algorithm. Set this to 1 to enable.
373
374 \value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE
375 socket option
376
377 \value MulticastTtlOption Set this to an integer value to set
378 IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
379
380 \value MulticastLoopbackOption Set this to 1 to enable the
381 IP_MULTICAST_LOOP (multicast loopback) socket option.
382
383 \value TypeOfServiceOption This option is not supported on
384 Windows. This maps to the IP_TOS socket option. For possible values,
385 see table below.
386
387 \value SendBufferSizeSocketOption Sets the socket send buffer size
388 in bytes at the OS level. This maps to the SO_SNDBUF socket option.
389 This option does not affect the QIODevice or QAbstractSocket buffers.
390 This enum value has been introduced in Qt 5.3.
391
392 \value ReceiveBufferSizeSocketOption Sets the socket receive
393 buffer size in bytes at the OS level.
394 This maps to the SO_RCVBUF socket option.
395 This option does not affect the QIODevice or QAbstractSocket buffers
396 (see \l{QAbstractSocket::}{setReadBufferSize()}).
397 This enum value has been introduced in Qt 5.3.
398
399 \value PathMtuSocketOption Retrieves the Path Maximum Transmission Unit
400 (PMTU) value currently known by the IP stack, if any. Some IP stacks also
401 allow setting the MTU for transmission.
402 This enum value was introduced in Qt 5.11.
403
404 Possible values for \e{TypeOfServiceOption} are:
405
406 \table
407 \header \li Value \li Description
408 \row \li 224 \li Network control
409 \row \li 192 \li Internetwork control
410 \row \li 160 \li CRITIC/ECP
411 \row \li 128 \li Flash override
412 \row \li 96 \li Flash
413 \row \li 64 \li Immediate
414 \row \li 32 \li Priority
415 \row \li 0 \li Routine
416 \endtable
417
418 \sa QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
419*/
420
421/*! \enum QAbstractSocket::BindFlag
422 \since 5.0
423
424 This enum describes the different flags you can pass to modify the
425 behavior of QAbstractSocket::bind().
426
427 \value ShareAddress Allow other services to bind to the same address
428 and port. This is useful when multiple processes share
429 the load of a single service by listening to the same address and port
430 (e.g., a web server with several pre-forked listeners can greatly
431 improve response time). However, because any service is allowed to
432 rebind, this option is subject to certain security considerations.
433 Note that by combining this option with ReuseAddressHint, you will
434 also allow your service to rebind an existing shared address. On
435 Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows,
436 this is the default behavior, so this option is ignored.
437
438 \value DontShareAddress Bind the address and port exclusively, so that
439 no other services are allowed to rebind. By passing this option to
440 QAbstractSocket::bind(), you are guaranteed that on success, your service
441 is the only one that listens to the address and port. No services are
442 allowed to rebind, even if they pass ReuseAddressHint. This option
443 provides more security than ShareAddress, but on certain operating
444 systems, it requires you to run the server with administrator privileges.
445 On Unix and \macos, not sharing is the default behavior for binding
446 an address and port, so this option is ignored. On Windows, this
447 option uses the SO_EXCLUSIVEADDRUSE socket option.
448
449 \value ReuseAddressHint Provides a hint to QAbstractSocket that it should try
450 to rebind the service even if the address and port are already bound by
451 another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR
452 socket option.
453
454 \value DefaultForPlatform The default option for the current platform.
455 On Unix and \macos, this is equivalent to (DontShareAddress
456 + ReuseAddressHint), and on Windows, it is equivalent to ShareAddress.
457*/
458
459/*! \enum QAbstractSocket::PauseMode
460 \since 5.0
461
462 This enum describes the behavior of when the socket should hold
463 back with continuing data transfer.
464 The only notification currently supported is QSslSocket::sslErrors().
465
466 \value PauseNever Do not pause data transfer on the socket. This is the
467 default and matches the behavior of Qt 4.
468 \value PauseOnSslErrors Pause data transfer on the socket upon receiving an
469 SSL error notification. I.E. QSslSocket::sslErrors().
470*/
471
472#include <QtNetwork/private/qtnetworkglobal_p.h>
473
474#include "qabstractsocket.h"
475#include "qabstractsocket_p.h"
476
477#include "private/qhostinfo_p.h"
478#if QT_CONFIG(bearermanagement) // ### Qt6: Remove section
479#include "private/qnetworksession_p.h"
480#endif
481#include "private/qnetworkconfiguration_p.h" // ### Qt6: Remove include
482
483#include <qabstracteventdispatcher.h>
484#include <qhostaddress.h>
485#include <qhostinfo.h>
486#include <qmetaobject.h>
487#include <qpointer.h>
488#include <qtimer.h>
489#include <qelapsedtimer.h>
490#include <qscopedvaluerollback.h>
491#include <qvarlengtharray.h>
492
493#ifndef QT_NO_SSL
494#include <QtNetwork/qsslsocket.h>
495#endif
496
497#include <private/qthread_p.h>
498
499#ifdef QABSTRACTSOCKET_DEBUG
500#include <qdebug.h>
501#endif
502
503#include <time.h>
504
505#define Q_CHECK_SOCKETENGINE(returnValue) do { \
506 if (!d->socketEngine) { \
507 return returnValue; \
508 } } while (0)
509
510#ifndef QABSTRACTSOCKET_BUFFERSIZE
511#define QABSTRACTSOCKET_BUFFERSIZE 32768
512#endif
513#define QT_TRANSFER_TIMEOUT 120000
514
515QT_BEGIN_NAMESPACE
516
517#if defined QABSTRACTSOCKET_DEBUG
518QT_BEGIN_INCLUDE_NAMESPACE
519#include <qstring.h>
520#include <ctype.h>
521QT_END_INCLUDE_NAMESPACE
522
523/*
524 Returns a human readable representation of the first \a len
525 characters in \a data.
526*/
527static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
528{
529 if (!data) return "(null)";
530 QByteArray out;
531 for (int i = 0; i < qMin(len, maxLength); ++i) {
532 char c = data[i];
533 if (isprint(int(uchar(c)))) {
534 out += c;
535 } else switch (c) {
536 case '\n': out += "\\n"; break;
537 case '\r': out += "\\r"; break;
538 case '\t': out += "\\t"; break;
539 default:
540 QString tmp;
541 tmp.sprintf("\\%o", c);
542 out += tmp.toLatin1();
543 }
544 }
545
546 if (len < maxLength)
547 out += "...";
548
549 return out;
550}
551#endif
552
553static bool isProxyError(QAbstractSocket::SocketError error)
554{
555 switch (error) {
556 case QAbstractSocket::ProxyAuthenticationRequiredError:
557 case QAbstractSocket::ProxyConnectionRefusedError:
558 case QAbstractSocket::ProxyConnectionClosedError:
559 case QAbstractSocket::ProxyConnectionTimeoutError:
560 case QAbstractSocket::ProxyNotFoundError:
561 case QAbstractSocket::ProxyProtocolError:
562 return true;
563 default:
564 return false;
565 }
566}
567
568/*! \internal
569
570 Constructs a QAbstractSocketPrivate. Initializes all members.
571*/
572QAbstractSocketPrivate::QAbstractSocketPrivate()
573 : emittedReadyRead(false),
574 emittedBytesWritten(false),
575 abortCalled(false),
576 pendingClose(false),
577 pauseMode(QAbstractSocket::PauseNever),
578 port(0),
579 localPort(0),
580 peerPort(0),
581 socketEngine(nullptr),
582 cachedSocketDescriptor(-1),
583 readBufferMaxSize(0),
584 isBuffered(false),
585 hasPendingData(false),
586 connectTimer(nullptr),
587 hostLookupId(-1),
588 socketType(QAbstractSocket::UnknownSocketType),
589 state(QAbstractSocket::UnconnectedState),
590 socketError(QAbstractSocket::UnknownSocketError),
591 preferredNetworkLayerProtocol(QAbstractSocket::UnknownNetworkLayerProtocol)
592{
593 writeBufferChunkSize = QABSTRACTSOCKET_BUFFERSIZE;
594}
595
596/*! \internal
597
598 Destructs the QAbstractSocket. If the socket layer is open, it
599 will be reset.
600*/
601QAbstractSocketPrivate::~QAbstractSocketPrivate()
602{
603}
604
605/*! \internal
606
607 Resets the socket layer and deletes any socket notifiers.
608*/
609void QAbstractSocketPrivate::resetSocketLayer()
610{
611#if defined (QABSTRACTSOCKET_DEBUG)
612 qDebug("QAbstractSocketPrivate::resetSocketLayer()");
613#endif
614
615 hasPendingData = false;
616 if (socketEngine) {
617 socketEngine->close();
618 socketEngine->disconnect();
619 delete socketEngine;
620 socketEngine = nullptr;
621 cachedSocketDescriptor = -1;
622 }
623 if (connectTimer)
624 connectTimer->stop();
625}
626
627/*! \internal
628
629 Initializes the socket layer to by of type \a type, using the
630 network layer protocol \a protocol. Resets the socket layer first
631 if it's already initialized. Sets up the socket notifiers.
632*/
633bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
634{
635#ifdef QT_NO_NETWORKPROXY
636 // this is here to avoid a duplication of the call to createSocketEngine below
637 static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
638#endif
639
640 Q_Q(QAbstractSocket);
641#if defined (QABSTRACTSOCKET_DEBUG)
642 QString typeStr;
643 if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
644 else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
645 else if (q->socketType() == QAbstractSocket::SctpSocket) typeStr = QLatin1String("SctpSocket");
646 else typeStr = QLatin1String("UnknownSocketType");
647 QString protocolStr;
648 if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
649 else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
650 else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
651#endif
652
653 resetSocketLayer();
654 socketEngine = QAbstractSocketEngine::createSocketEngine(socketType: q->socketType(), proxyInUse, parent: q);
655 if (!socketEngine) {
656 setError(errorCode: QAbstractSocket::UnsupportedSocketOperationError,
657 errorString: QAbstractSocket::tr(s: "Operation on socket is not supported"));
658 return false;
659 }
660#ifndef QT_NO_BEARERMANAGEMENT // ### Qt6: Remove section
661 //copy network session down to the socket engine (if it has been set)
662 socketEngine->setProperty(name: "_q_networksession", value: q->property(name: "_q_networksession"));
663#endif
664 if (!socketEngine->initialize(type: q->socketType(), protocol)) {
665#if defined (QABSTRACTSOCKET_DEBUG)
666 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
667 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
668 socketEngine->errorString().toLatin1().constData());
669#endif
670 setError(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
671 return false;
672 }
673
674 configureCreatedSocket();
675
676 if (threadData.loadRelaxed()->hasEventDispatcher())
677 socketEngine->setReceiver(this);
678
679#if defined (QABSTRACTSOCKET_DEBUG)
680 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
681 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
682#endif
683 return true;
684}
685
686/*! \internal
687*/
688void QAbstractSocketPrivate::configureCreatedSocket()
689{
690#ifndef QT_NO_SCTP
691 Q_Q(QAbstractSocket);
692 // Set single stream mode for unbuffered SCTP socket
693 if (socketEngine && q->socketType() == QAbstractSocket::SctpSocket)
694 socketEngine->setOption(QAbstractSocketEngine::MaxStreamsSocketOption, 1);
695#endif
696}
697
698/*! \internal
699
700 Slot connected to the read socket notifier. This slot is called
701 when new data is available for reading, or when the socket has
702 been closed. Handles recursive calls.
703*/
704bool QAbstractSocketPrivate::canReadNotification()
705{
706 Q_Q(QAbstractSocket);
707#if defined (QABSTRACTSOCKET_DEBUG)
708 qDebug("QAbstractSocketPrivate::canReadNotification()");
709#endif
710
711 // If buffered, read data from the socket into the read buffer
712 if (isBuffered) {
713 const qint64 oldBufferSize = buffer.size();
714
715 // Return if there is no space in the buffer
716 if (readBufferMaxSize && oldBufferSize >= readBufferMaxSize) {
717 socketEngine->setReadNotificationEnabled(false);
718#if defined (QABSTRACTSOCKET_DEBUG)
719 qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
720#endif
721 return false;
722 }
723
724 // If reading from the socket fails after getting a read
725 // notification, close the socket.
726 if (!readFromSocket()) {
727#if defined (QABSTRACTSOCKET_DEBUG)
728 qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
729#endif
730 q->disconnectFromHost();
731 return false;
732 }
733
734 // Return if there is no new data available.
735 if (buffer.size() == oldBufferSize) {
736 // If the socket is opened only for writing, return true
737 // to indicate that the data was discarded.
738 return !q->isReadable();
739 }
740 } else {
741 if (hasPendingData) {
742 socketEngine->setReadNotificationEnabled(false);
743 return true;
744 }
745 hasPendingData = true;
746 }
747
748 emitReadyRead();
749
750#if defined (QABSTRACTSOCKET_DEBUG)
751 // If we were closed as a result of the readyRead() signal.
752 if (state == QAbstractSocket::UnconnectedState || state == QAbstractSocket::ClosingState)
753 qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
754#endif
755
756 return true;
757}
758
759/*! \internal
760
761 Slot connected to the close socket notifier. It's called when the
762 socket is closed.
763*/
764void QAbstractSocketPrivate::canCloseNotification()
765{
766 Q_Q(QAbstractSocket);
767 // Note that this method is only called on Windows. Other platforms close in the canReadNotification()
768
769#if defined (QABSTRACTSOCKET_DEBUG)
770 qDebug("QAbstractSocketPrivate::canCloseNotification()");
771#endif
772
773 qint64 newBytes = 0;
774 if (isBuffered) {
775 // Try to read to the buffer, if the read fail we can close the socket.
776 newBytes = buffer.size();
777 qint64 oldReadBufferMaxSize = readBufferMaxSize;
778 readBufferMaxSize = 0; // temporarily disable max read buffer, we want to empty the OS buffer
779 bool hadReadFromSocket = readFromSocket();
780 readBufferMaxSize = oldReadBufferMaxSize;
781 if (!hadReadFromSocket) {
782 q->disconnectFromHost();
783 return;
784 }
785 newBytes = buffer.size() - newBytes;
786 if (newBytes) {
787 // If there was still some data to be read from the socket
788 // then we could get another FD_READ. The disconnect will
789 // then occur when we read from the socket again and fail
790 // in canReadNotification or by the manually created
791 // closeNotification below.
792 emitReadyRead();
793
794 QMetaObject::invokeMethod(obj: socketEngine, member: "closeNotification", type: Qt::QueuedConnection);
795 }
796 } else if ((socketType == QAbstractSocket::TcpSocket ||
797 socketType == QAbstractSocket::SctpSocket) && socketEngine) {
798 emitReadyRead();
799 }
800}
801
802
803/*! \internal
804
805 Slot connected to the write socket notifier. It's called during a
806 delayed connect or when the socket is ready for writing.
807*/
808bool QAbstractSocketPrivate::canWriteNotification()
809{
810#if defined (QABSTRACTSOCKET_DEBUG)
811 qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
812#endif
813
814 return writeToSocket();
815}
816
817/*! \internal
818
819 Slot connected to a notification of connection status
820 change. Either we finished connecting or we failed to connect.
821*/
822void QAbstractSocketPrivate::connectionNotification()
823{
824 // If in connecting state, check if the connection has been
825 // established, otherwise flush pending data.
826 if (state == QAbstractSocket::ConnectingState) {
827#if defined (QABSTRACTSOCKET_DEBUG)
828 qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
829#endif
830 _q_testConnection();
831 }
832}
833
834/*! \internal
835
836 Writes one pending data block in the write buffer to the socket.
837
838 It is usually invoked by canWriteNotification after one or more
839 calls to write().
840
841 Emits bytesWritten().
842*/
843bool QAbstractSocketPrivate::writeToSocket()
844{
845 Q_Q(QAbstractSocket);
846 if (!socketEngine || !socketEngine->isValid() || (writeBuffer.isEmpty()
847 && socketEngine->bytesToWrite() == 0)) {
848#if defined (QABSTRACTSOCKET_DEBUG)
849 qDebug("QAbstractSocketPrivate::writeToSocket() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
850 (socketEngine && socketEngine->isValid()) ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
851#endif
852
853 // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
854 if (state == QAbstractSocket::ClosingState) {
855 q->disconnectFromHost();
856 } else {
857 if (socketEngine)
858 socketEngine->setWriteNotificationEnabled(false);
859 }
860
861 return false;
862 }
863
864 qint64 nextSize = writeBuffer.nextDataBlockSize();
865 const char *ptr = writeBuffer.readPointer();
866
867 // Attempt to write it all in one chunk.
868 qint64 written = nextSize ? socketEngine->write(data: ptr, len: nextSize) : Q_INT64_C(0);
869 if (written < 0) {
870#if defined (QABSTRACTSOCKET_DEBUG)
871 qDebug() << "QAbstractSocketPrivate::writeToSocket() write error, aborting."
872 << socketEngine->errorString();
873#endif
874 setErrorAndEmit(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
875 // an unexpected error so close the socket.
876 q->abort();
877 return false;
878 }
879
880#if defined (QABSTRACTSOCKET_DEBUG)
881 qDebug("QAbstractSocketPrivate::writeToSocket() %lld bytes written to the network",
882 written);
883#endif
884
885 if (written > 0) {
886 // Remove what we wrote so far.
887 writeBuffer.free(bytes: written);
888
889 // Emit notifications.
890 emitBytesWritten(bytes: written);
891 }
892
893 if (writeBuffer.isEmpty() && socketEngine && !socketEngine->bytesToWrite())
894 socketEngine->setWriteNotificationEnabled(false);
895 if (state == QAbstractSocket::ClosingState)
896 q->disconnectFromHost();
897
898 return written > 0;
899}
900
901/*! \internal
902
903 Writes pending data in the write buffers to the socket. The function
904 writes as much as it can without blocking. If any data was written,
905 this function returns true; otherwise false is returned.
906*/
907bool QAbstractSocketPrivate::flush()
908{
909 bool dataWasWritten = false;
910
911 while (!allWriteBuffersEmpty() && writeToSocket())
912 dataWasWritten = true;
913
914 return dataWasWritten;
915}
916
917#ifndef QT_NO_NETWORKPROXY
918/*! \internal
919
920 Resolve the proxy to its final value.
921*/
922void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
923{
924 QList<QNetworkProxy> proxies;
925
926 if (proxy.type() != QNetworkProxy::DefaultProxy) {
927 // a non-default proxy was set with setProxy
928 proxies << proxy;
929 } else {
930 // try the application settings instead
931 QNetworkProxyQuery query(hostname, port, protocolTag,
932 socketType == QAbstractSocket::TcpSocket ?
933 QNetworkProxyQuery::TcpSocket :
934 socketType == QAbstractSocket::SctpSocket ?
935 QNetworkProxyQuery::SctpSocket :
936 QNetworkProxyQuery::UdpSocket);
937 proxies = QNetworkProxyFactory::proxyForQuery(query);
938 }
939
940 // return the first that we can use
941 for (const QNetworkProxy &p : qAsConst(t&: proxies)) {
942 if (socketType == QAbstractSocket::UdpSocket &&
943 (p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
944 continue;
945
946 if (socketType == QAbstractSocket::TcpSocket &&
947 (p.capabilities() & QNetworkProxy::TunnelingCapability) == 0)
948 continue;
949
950 if (socketType == QAbstractSocket::SctpSocket &&
951 (p.capabilities() & QNetworkProxy::SctpTunnelingCapability) == 0)
952 continue;
953
954 proxyInUse = p;
955 return;
956 }
957
958 // no proxy found
959 // DefaultProxy here will raise an error
960 proxyInUse = QNetworkProxy();
961}
962#endif // !QT_NO_NETWORKPROXY
963
964#if !defined(QT_NO_NETWORKPROXY) || defined(Q_OS_WINRT)
965/*!
966 \internal
967
968 Starts the connection to \a host, like _q_startConnecting below,
969 but without hostname resolution.
970*/
971void QAbstractSocketPrivate::startConnectingByName(const QString &host)
972{
973 Q_Q(QAbstractSocket);
974 if (state == QAbstractSocket::ConnectingState || state == QAbstractSocket::ConnectedState)
975 return;
976
977#if defined(QABSTRACTSOCKET_DEBUG)
978 qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
979#endif
980
981 // ### Let the socket engine drive this?
982 state = QAbstractSocket::ConnectingState;
983 emit q->stateChanged(state);
984
985 if (cachedSocketDescriptor != -1 || initSocketLayer(protocol: QAbstractSocket::UnknownNetworkLayerProtocol)) {
986 // Try to connect to the host. If it succeeds immediately
987 // (e.g. QSocks5SocketEngine in UDPASSOCIATE mode), emit
988 // connected() and return.
989 if (socketEngine->connectToHostByName(name: host, port)) {
990 fetchConnectionParameters();
991 return;
992 }
993
994 if (socketEngine->state() == QAbstractSocket::ConnectingState)
995 return;
996
997 // failed to connect
998 setError(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
999 }
1000
1001 state = QAbstractSocket::UnconnectedState;
1002 emit q->errorOccurred(socketError);
1003 emit q->stateChanged(state);
1004}
1005
1006#endif // !QT_NO_NETWORKPROXY || Q_OS_WINRT
1007
1008/*! \internal
1009
1010 Slot connected to QHostInfo::lookupHost() in connectToHost(). This
1011 function starts the process of connecting to any number of
1012 candidate IP addresses for the host, if it was found. Calls
1013 _q_connectToNextAddress().
1014*/
1015void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
1016{
1017 Q_Q(QAbstractSocket);
1018 addresses.clear();
1019 if (state != QAbstractSocket::HostLookupState)
1020 return;
1021
1022 if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
1023 qWarning(msg: "QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
1024 }
1025
1026 // Only add the addresses for the preferred network layer.
1027 // Or all if preferred network layer is not set.
1028 if (preferredNetworkLayerProtocol == QAbstractSocket::UnknownNetworkLayerProtocol || preferredNetworkLayerProtocol == QAbstractSocket::AnyIPProtocol) {
1029 addresses = hostInfo.addresses();
1030 } else {
1031 const auto candidates = hostInfo.addresses();
1032 for (const QHostAddress &address : candidates) {
1033 if (address.protocol() == preferredNetworkLayerProtocol)
1034 addresses += address;
1035 }
1036 }
1037
1038
1039#if defined(QABSTRACTSOCKET_DEBUG)
1040 QString s = QLatin1String("{");
1041 for (int i = 0; i < addresses.count(); ++i) {
1042 if (i != 0) s += QLatin1String(", ");
1043 s += addresses.at(i).toString();
1044 }
1045 s += QLatin1Char('}');
1046 qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
1047#endif
1048
1049 // Try all addresses twice.
1050 addresses += addresses;
1051
1052 // If there are no addresses in the host list, report this to the
1053 // user.
1054 if (addresses.isEmpty()) {
1055#if defined(QABSTRACTSOCKET_DEBUG)
1056 qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
1057#endif
1058 state = QAbstractSocket::UnconnectedState;
1059 setError(errorCode: QAbstractSocket::HostNotFoundError, errorString: QAbstractSocket::tr(s: "Host not found"));
1060 emit q->stateChanged(state);
1061 emit q->errorOccurred(QAbstractSocket::HostNotFoundError);
1062 return;
1063 }
1064
1065 // Enter Connecting state (see also sn_write, which is called by
1066 // the write socket notifier after connect())
1067 state = QAbstractSocket::ConnectingState;
1068 emit q->stateChanged(state);
1069
1070 // Report the successful host lookup
1071 emit q->hostFound();
1072
1073 // The addresses returned by the lookup will be tested one after
1074 // another by _q_connectToNextAddress().
1075 _q_connectToNextAddress();
1076}
1077
1078/*! \internal
1079
1080 Called by a queued or direct connection from _q_startConnecting() or
1081 _q_testConnection(), this function takes the first address of the
1082 pending addresses list and tries to connect to it. If the
1083 connection succeeds, QAbstractSocket will emit
1084 connected(). Otherwise, errorOccurred(ConnectionRefusedError) or
1085 errorOccurred(SocketTimeoutError) is emitted.
1086*/
1087void QAbstractSocketPrivate::_q_connectToNextAddress()
1088{
1089 Q_Q(QAbstractSocket);
1090 do {
1091 // Check for more pending addresses
1092 if (addresses.isEmpty()) {
1093#if defined(QABSTRACTSOCKET_DEBUG)
1094 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
1095#endif
1096 state = QAbstractSocket::UnconnectedState;
1097 if (socketEngine) {
1098 if ((socketEngine->error() == QAbstractSocket::UnknownSocketError
1099#ifdef Q_OS_AIX
1100 // On AIX, the second connect call will result in EINVAL and not
1101 // ECONNECTIONREFUSED; although the meaning is the same.
1102 || socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
1103#endif
1104 ) && socketEngine->state() == QAbstractSocket::ConnectingState) {
1105 setError(errorCode: QAbstractSocket::ConnectionRefusedError,
1106 errorString: QAbstractSocket::tr(s: "Connection refused"));
1107 } else {
1108 setError(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
1109 }
1110 } else {
1111// socketError = QAbstractSocket::ConnectionRefusedError;
1112// q->setErrorString(QAbstractSocket::tr("Connection refused"));
1113 }
1114 emit q->stateChanged(state);
1115 emit q->errorOccurred(socketError);
1116 return;
1117 }
1118
1119 // Pick the first host address candidate
1120 host = addresses.takeFirst();
1121#if defined(QABSTRACTSOCKET_DEBUG)
1122 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
1123 host.toString().toLatin1().constData(), port, addresses.count());
1124#endif
1125
1126 if (cachedSocketDescriptor == -1 && !initSocketLayer(protocol: host.protocol())) {
1127 // hope that the next address is better
1128#if defined(QABSTRACTSOCKET_DEBUG)
1129 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
1130#endif
1131 continue;
1132 }
1133
1134 // Tries to connect to the address. If it succeeds immediately
1135 // (localhost address on BSD or any UDP connect), emit
1136 // connected() and return.
1137 if (
1138 socketEngine->connectToHost(address: host, port)) {
1139 //_q_testConnection();
1140 fetchConnectionParameters();
1141 return;
1142 }
1143
1144 // Check that we're in delayed connection state. If not, try
1145 // the next address
1146 if (socketEngine->state() != QAbstractSocket::ConnectingState) {
1147#if defined(QABSTRACTSOCKET_DEBUG)
1148 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1149 socketEngine->errorString().toLatin1().constData());
1150#endif
1151 continue;
1152 }
1153
1154 // Start the connect timer.
1155 if (threadData.loadRelaxed()->hasEventDispatcher()) {
1156 if (!connectTimer) {
1157 connectTimer = new QTimer(q);
1158 QObject::connect(sender: connectTimer, SIGNAL(timeout()),
1159 receiver: q, SLOT(_q_abortConnectionAttempt()),
1160 Qt::DirectConnection);
1161 }
1162#ifdef QT_NO_BEARERMANAGEMENT
1163 int connectTimeout = 30000;
1164#else
1165 int connectTimeout = QNetworkConfigurationPrivate::DefaultTimeout;
1166 QSharedPointer<QNetworkSession> networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v: q->property(name: "_q_networksession"));
1167 if (networkSession) {
1168 QNetworkConfiguration networkConfiguration = networkSession->configuration();
1169 connectTimeout = networkConfiguration.connectTimeout();
1170 }
1171#endif
1172 connectTimer->start(msec: connectTimeout);
1173 }
1174
1175 // Wait for a write notification that will eventually call
1176 // _q_testConnection().
1177 socketEngine->setWriteNotificationEnabled(true);
1178 break;
1179 } while (state != QAbstractSocket::ConnectedState);
1180}
1181
1182/*! \internal
1183
1184 Tests if a connection has been established. If it has, connected()
1185 is emitted. Otherwise, _q_connectToNextAddress() is invoked.
1186*/
1187void QAbstractSocketPrivate::_q_testConnection()
1188{
1189 if (connectTimer)
1190 connectTimer->stop();
1191
1192 if (socketEngine) {
1193 if (socketEngine->state() == QAbstractSocket::ConnectedState) {
1194 // Fetch the parameters if our connection is completed;
1195 // otherwise, fall out and try the next address.
1196 fetchConnectionParameters();
1197 if (pendingClose) {
1198 q_func()->disconnectFromHost();
1199 pendingClose = false;
1200 }
1201 return;
1202 }
1203
1204 // don't retry the other addresses if we had a proxy error
1205 if (isProxyError(error: socketEngine->error()))
1206 addresses.clear();
1207 }
1208
1209#if defined(QABSTRACTSOCKET_DEBUG)
1210 qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1211 " checking for alternative addresses");
1212#endif
1213 _q_connectToNextAddress();
1214}
1215
1216/*! \internal
1217
1218 This function is called after a certain number of seconds has
1219 passed while waiting for a connection. It simply tests the
1220 connection, and continues to the next address if the connection
1221 failed.
1222*/
1223void QAbstractSocketPrivate::_q_abortConnectionAttempt()
1224{
1225 Q_Q(QAbstractSocket);
1226#if defined(QABSTRACTSOCKET_DEBUG)
1227 qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1228#endif
1229 if (socketEngine)
1230 socketEngine->setWriteNotificationEnabled(false);
1231
1232 connectTimer->stop();
1233
1234 if (addresses.isEmpty()) {
1235 state = QAbstractSocket::UnconnectedState;
1236 setError(errorCode: QAbstractSocket::SocketTimeoutError,
1237 errorString: QAbstractSocket::tr(s: "Connection timed out"));
1238 emit q->stateChanged(state);
1239 emit q->errorOccurred(socketError);
1240 } else {
1241 _q_connectToNextAddress();
1242 }
1243}
1244
1245/*! \internal
1246
1247 Reads data from the socket layer into the read buffer. Returns
1248 true on success; otherwise false.
1249*/
1250bool QAbstractSocketPrivate::readFromSocket()
1251{
1252 Q_Q(QAbstractSocket);
1253 // Find how many bytes we can read from the socket layer.
1254 qint64 bytesToRead = socketEngine->bytesAvailable();
1255 if (bytesToRead == 0) {
1256 // Under heavy load, certain conditions can trigger read notifications
1257 // for socket notifiers on which there is no activity. If we continue
1258 // to read 0 bytes from the socket, we will trigger behavior similar
1259 // to that which signals a remote close. When we hit this condition,
1260 // we try to read 4k of data from the socket, which will give us either
1261 // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1262 // host has _not_ disappeared).
1263 bytesToRead = 4096;
1264 }
1265
1266 if (q->isReadable()) {
1267 if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size()))
1268 bytesToRead = readBufferMaxSize - buffer.size();
1269
1270#if defined(QABSTRACTSOCKET_DEBUG)
1271 qDebug("QAbstractSocketPrivate::readFromSocket() about to read %lld bytes",
1272 bytesToRead);
1273#endif
1274
1275 // Read from the socket, store data in the read buffer.
1276 char *ptr = buffer.reserve(bytes: bytesToRead);
1277 qint64 readBytes = socketEngine->read(data: ptr, maxlen: bytesToRead);
1278 if (readBytes == -2) {
1279 // No bytes currently available for reading.
1280 buffer.chop(bytes: bytesToRead);
1281 return true;
1282 }
1283 buffer.chop(bytes: bytesToRead - (readBytes < 0 ? qint64(0) : readBytes));
1284#if defined(QABSTRACTSOCKET_DEBUG)
1285 qDebug("QAbstractSocketPrivate::readFromSocket() got %lld bytes, buffer size = %lld",
1286 readBytes, buffer.size());
1287#endif
1288 } else {
1289 // Discard unwanted data if opened in WriteOnly mode
1290 QVarLengthArray<char, 4096> discardBuffer(bytesToRead);
1291
1292#if defined(QABSTRACTSOCKET_DEBUG)
1293 qDebug("QAbstractSocketPrivate::readFromSocket() about to discard %lld bytes",
1294 bytesToRead);
1295#endif
1296 socketEngine->read(data: discardBuffer.data(), maxlen: bytesToRead);
1297 }
1298
1299 if (!socketEngine->isValid()) {
1300#if defined(QABSTRACTSOCKET_DEBUG)
1301 qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1302 socketEngine->errorString().toLatin1().constData());
1303#endif
1304 setErrorAndEmit(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
1305 resetSocketLayer();
1306 return false;
1307 }
1308
1309 return true;
1310}
1311
1312/*! \internal
1313
1314 Emits readyRead(), protecting against recursion.
1315*/
1316void QAbstractSocketPrivate::emitReadyRead(int channel)
1317{
1318 Q_Q(QAbstractSocket);
1319 // Only emit readyRead() when not recursing.
1320 if (!emittedReadyRead && channel == currentReadChannel) {
1321 QScopedValueRollback<bool> r(emittedReadyRead);
1322 emittedReadyRead = true;
1323 emit q->readyRead();
1324 }
1325 // channelReadyRead() can be emitted recursively - even for the same channel.
1326 emit q->channelReadyRead(channel);
1327}
1328
1329/*! \internal
1330
1331 Emits bytesWritten(), protecting against recursion.
1332*/
1333void QAbstractSocketPrivate::emitBytesWritten(qint64 bytes, int channel)
1334{
1335 Q_Q(QAbstractSocket);
1336 // Only emit bytesWritten() when not recursing.
1337 if (!emittedBytesWritten && channel == currentWriteChannel) {
1338 QScopedValueRollback<bool> r(emittedBytesWritten);
1339 emittedBytesWritten = true;
1340 emit q->bytesWritten(bytes);
1341 }
1342 // channelBytesWritten() can be emitted recursively - even for the same channel.
1343 emit q->channelBytesWritten(channel, bytes);
1344}
1345
1346/*! \internal
1347
1348 Sets up the internal state after the connection has succeeded.
1349*/
1350void QAbstractSocketPrivate::fetchConnectionParameters()
1351{
1352 Q_Q(QAbstractSocket);
1353
1354 peerName = hostName;
1355 if (socketEngine) {
1356 if (q->isReadable()) {
1357 const int inboundStreamCount = socketEngine->inboundStreamCount();
1358 setReadChannelCount(qMax(a: 1, b: inboundStreamCount));
1359 if (inboundStreamCount == 0)
1360 readChannelCount = 0;
1361 }
1362 if (q->isWritable()) {
1363 const int outboundStreamCount = socketEngine->outboundStreamCount();
1364 setWriteChannelCount(qMax(a: 1, b: outboundStreamCount));
1365 if (outboundStreamCount == 0)
1366 writeChannelCount = 0;
1367 }
1368 socketEngine->setReadNotificationEnabled(true);
1369 socketEngine->setWriteNotificationEnabled(true);
1370 localPort = socketEngine->localPort();
1371 peerPort = socketEngine->peerPort();
1372 localAddress = socketEngine->localAddress();
1373 peerAddress = socketEngine->peerAddress();
1374 cachedSocketDescriptor = socketEngine->socketDescriptor();
1375 }
1376
1377 state = QAbstractSocket::ConnectedState;
1378#if defined(QABSTRACTSOCKET_DEBUG)
1379 qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1380 host.toString().toLatin1().constData(), port);
1381#endif
1382 emit q->stateChanged(state);
1383 emit q->connected();
1384}
1385
1386/*! \internal
1387*/
1388qint64 QAbstractSocketPrivate::skip(qint64 maxSize)
1389{
1390 // if we're not connected, return -1 indicating EOF
1391 if (!socketEngine || !socketEngine->isValid() || state != QAbstractSocket::ConnectedState)
1392 return -1;
1393
1394 // Caller, QIODevice::skip(), has ensured buffer is empty. So, wait
1395 // for more data in buffered mode.
1396 if (isBuffered)
1397 return 0;
1398
1399 return QIODevicePrivate::skip(maxSize);
1400}
1401
1402void QAbstractSocketPrivate::pauseSocketNotifiers(QAbstractSocket *socket)
1403{
1404 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1405 if (!socketEngine)
1406 return;
1407 bool read = socketEngine->isReadNotificationEnabled();
1408 bool write = socketEngine->isWriteNotificationEnabled();
1409 bool except = socketEngine->isExceptionNotificationEnabled();
1410
1411#ifdef QABSTRACTSOCKET_DEBUG
1412 qDebug() << socketEngine->socketDescriptor()
1413 << "pause notifiers, storing 'true' states, currently read:" << read
1414 << "write:" << write << "except:" << except;
1415#endif
1416 // We do this if-check to avoid accidentally overwriting any previously stored state
1417 // It will reset to false once the socket is re-enabled.
1418 if (read) {
1419 socket->d_func()->prePauseReadSocketNotifierState = true;
1420 socketEngine->setReadNotificationEnabled(false);
1421 }
1422 if (write) {
1423 socket->d_func()->prePauseWriteSocketNotifierState = true;
1424 socketEngine->setWriteNotificationEnabled(false);
1425 }
1426 if (except) {
1427 socket->d_func()->prePauseExceptionSocketNotifierState = true;
1428 socketEngine->setExceptionNotificationEnabled(false);
1429 }
1430}
1431
1432void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
1433{
1434 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1435 if (!socketEngine)
1436 return;
1437 QAbstractSocketPrivate *priv = socket->d_func();
1438#ifdef QABSTRACTSOCKET_DEBUG
1439 qDebug() << socketEngine->socketDescriptor()
1440 << "Maybe resume notifiers, read:" << priv->prePauseReadSocketNotifierState
1441 << "write:" << priv->prePauseWriteSocketNotifierState
1442 << "exception:" << priv->prePauseExceptionSocketNotifierState;
1443#endif
1444 if (qExchange(t&: priv->prePauseReadSocketNotifierState, newValue: false))
1445 socketEngine->setReadNotificationEnabled(true);
1446 if (qExchange(t&: priv->prePauseWriteSocketNotifierState, newValue: false))
1447 socketEngine->setWriteNotificationEnabled(true);
1448 if (qExchange(t&: priv->prePauseExceptionSocketNotifierState, newValue: false))
1449 socketEngine->setExceptionNotificationEnabled(true);
1450}
1451
1452QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *socket)
1453{
1454 return socket->d_func()->socketEngine;
1455}
1456
1457/*!
1458 \internal
1459
1460 Sets the socket error state to \c errorCode and \a errorString.
1461*/
1462void QAbstractSocketPrivate::setError(QAbstractSocket::SocketError errorCode,
1463 const QString &errStr)
1464{
1465 socketError = errorCode;
1466 errorString = errStr;
1467}
1468
1469/*!
1470 \internal
1471
1472 Sets the socket error state to \c errorCode and \a errorString,
1473 and emits the QAbstractSocket::errorOccurred() signal.
1474*/
1475void QAbstractSocketPrivate::setErrorAndEmit(QAbstractSocket::SocketError errorCode,
1476 const QString &errorString)
1477{
1478 Q_Q(QAbstractSocket);
1479 setError(errorCode, errStr: errorString);
1480 emit q->errorOccurred(errorCode);
1481}
1482
1483/*! \internal
1484
1485 Constructs a new abstract socket of type \a socketType. The \a
1486 parent argument is passed to QObject's constructor.
1487*/
1488QAbstractSocket::QAbstractSocket(SocketType socketType,
1489 QAbstractSocketPrivate &dd, QObject *parent)
1490 : QIODevice(dd, parent)
1491{
1492 Q_D(QAbstractSocket);
1493#if defined(QABSTRACTSOCKET_DEBUG)
1494 qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1495 socketType == TcpSocket ? "Tcp" : socketType == UdpSocket ? "Udp"
1496 : socketType == SctpSocket ? "Sctp" : "Unknown", &dd, parent);
1497#endif
1498 d->socketType = socketType;
1499
1500 // Support the deprecated error() signal:
1501 connect(sender: this, signal: &QAbstractSocket::errorOccurred, receiver: this, slot: QOverload<QAbstractSocket::SocketError>::of(ptr: &QAbstractSocket::error));
1502}
1503
1504/*!
1505 Creates a new abstract socket of type \a socketType. The \a
1506 parent argument is passed to QObject's constructor.
1507
1508 \sa socketType(), QTcpSocket, QUdpSocket
1509*/
1510QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)
1511 : QAbstractSocket(socketType, *new QAbstractSocketPrivate, parent)
1512{
1513}
1514
1515/*!
1516 Destroys the socket.
1517*/
1518QAbstractSocket::~QAbstractSocket()
1519{
1520 Q_D(QAbstractSocket);
1521#if defined(QABSTRACTSOCKET_DEBUG)
1522 qDebug("QAbstractSocket::~QAbstractSocket()");
1523#endif
1524 if (d->state != UnconnectedState)
1525 abort();
1526}
1527
1528/*!
1529 \since 5.0
1530
1531 Continues data transfer on the socket. This method should only be used
1532 after the socket has been set to pause upon notifications and a
1533 notification has been received.
1534 The only notification currently supported is QSslSocket::sslErrors().
1535 Calling this method if the socket is not paused results in undefined
1536 behavior.
1537
1538 \sa pauseMode(), setPauseMode()
1539*/
1540void QAbstractSocket::resume()
1541{
1542 QAbstractSocketPrivate::resumeSocketNotifiers(socket: this);
1543}
1544
1545/*!
1546 \since 5.0
1547
1548 Returns the pause mode of this socket.
1549
1550 \sa setPauseMode(), resume()
1551*/
1552QAbstractSocket::PauseModes QAbstractSocket::pauseMode() const
1553{
1554 return d_func()->pauseMode;
1555}
1556
1557
1558/*!
1559 \since 5.0
1560
1561 Controls whether to pause upon receiving a notification. The \a pauseMode parameter
1562 specifies the conditions in which the socket should be paused. The only notification
1563 currently supported is QSslSocket::sslErrors(). If set to PauseOnSslErrors,
1564 data transfer on the socket will be paused and needs to be enabled explicitly
1565 again by calling resume().
1566 By default this option is set to PauseNever.
1567 This option must be called before connecting to the server, otherwise it will
1568 result in undefined behavior.
1569
1570 \sa pauseMode(), resume()
1571*/
1572void QAbstractSocket::setPauseMode(PauseModes pauseMode)
1573{
1574 d_func()->pauseMode = pauseMode;
1575}
1576
1577/*!
1578 \since 5.0
1579
1580 Binds to \a address on port \a port, using the BindMode \a mode.
1581
1582 For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted
1583 whenever a UDP datagram arrives on the specified address and port.
1584 Thus, this function is useful to write UDP servers.
1585
1586 For TCP sockets, this function may be used to specify which interface to use
1587 for an outgoing connection, which is useful in case of multiple network
1588 interfaces.
1589
1590 By default, the socket is bound using the DefaultForPlatform BindMode.
1591 If a port is not specified, a random port is chosen.
1592
1593 On success, the function returns \c true and the socket enters
1594 BoundState; otherwise it returns \c false.
1595
1596*/
1597bool QAbstractSocket::bind(const QHostAddress &address, quint16 port, BindMode mode)
1598{
1599 Q_D(QAbstractSocket);
1600 return d->bind(address, port, mode);
1601}
1602
1603bool QAbstractSocketPrivate::bind(const QHostAddress &address, quint16 port, QAbstractSocket::BindMode mode)
1604{
1605 Q_Q(QAbstractSocket);
1606
1607 // now check if the socket engine is initialized and to the right type
1608 if (!socketEngine || !socketEngine->isValid()) {
1609 QHostAddress nullAddress;
1610 resolveProxy(hostname: nullAddress.toString(), port);
1611
1612 QAbstractSocket::NetworkLayerProtocol protocol = address.protocol();
1613 if (protocol == QAbstractSocket::UnknownNetworkLayerProtocol)
1614 protocol = nullAddress.protocol();
1615
1616 if (!initSocketLayer(protocol))
1617 return false;
1618 }
1619
1620 if (mode != QAbstractSocket::DefaultForPlatform) {
1621#ifdef Q_OS_UNIX
1622 if ((mode & QAbstractSocket::ShareAddress) || (mode & QAbstractSocket::ReuseAddressHint))
1623 socketEngine->setOption(option: QAbstractSocketEngine::AddressReusable, value: 1);
1624 else
1625 socketEngine->setOption(option: QAbstractSocketEngine::AddressReusable, value: 0);
1626#endif
1627#ifdef Q_OS_WIN
1628 if (mode & QAbstractSocket::ReuseAddressHint)
1629 socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
1630 else
1631 socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
1632 if (mode & QAbstractSocket::DontShareAddress)
1633 socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 1);
1634 else
1635 socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 0);
1636#endif
1637 }
1638 bool result = socketEngine->bind(address, port);
1639 cachedSocketDescriptor = socketEngine->socketDescriptor();
1640
1641 if (!result) {
1642 setErrorAndEmit(errorCode: socketEngine->error(), errorString: socketEngine->errorString());
1643 return false;
1644 }
1645
1646 state = QAbstractSocket::BoundState;
1647 localAddress = socketEngine->localAddress();
1648 localPort = socketEngine->localPort();
1649
1650 emit q->stateChanged(state);
1651 // A slot attached to stateChanged() signal can break our invariant:
1652 // by closing the socket it will reset its socket engine - thus we
1653 // have additional check (isValid()) ...
1654 if (q->isValid() && socketType == QAbstractSocket::UdpSocket)
1655 socketEngine->setReadNotificationEnabled(true);
1656 return true;
1657}
1658
1659/*!
1660 \since 5.0
1661 \overload
1662
1663 Binds to QHostAddress:Any on port \a port, using the BindMode \a mode.
1664
1665 By default, the socket is bound using the DefaultForPlatform BindMode.
1666 If a port is not specified, a random port is chosen.
1667*/
1668bool QAbstractSocket::bind(quint16 port, BindMode mode)
1669{
1670 return bind(address: QHostAddress::Any, port, mode);
1671}
1672
1673/*!
1674 Returns \c true if the socket is valid and ready for use; otherwise
1675 returns \c false.
1676
1677 \note The socket's state must be ConnectedState before reading and
1678 writing can occur.
1679
1680 \sa state()
1681*/
1682bool QAbstractSocket::isValid() const
1683{
1684 return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1685}
1686
1687/*!
1688 Attempts to make a connection to \a hostName on the given \a port.
1689 The \a protocol parameter can be used to specify which network
1690 protocol to use (eg. IPv4 or IPv6).
1691
1692 The socket is opened in the given \a openMode and first enters
1693 HostLookupState, then performs a host name lookup of \a hostName.
1694 If the lookup succeeds, hostFound() is emitted and QAbstractSocket
1695 enters ConnectingState. It then attempts to connect to the address
1696 or addresses returned by the lookup. Finally, if a connection is
1697 established, QAbstractSocket enters ConnectedState and
1698 emits connected().
1699
1700 At any point, the socket can emit errorOccurred() to signal that an error
1701 occurred.
1702
1703 \a hostName may be an IP address in string form (e.g.,
1704 "43.195.83.32"), or it may be a host name (e.g.,
1705 "example.com"). QAbstractSocket will do a lookup only if
1706 required. \a port is in native byte order.
1707
1708 \sa state(), peerName(), peerAddress(), peerPort(), waitForConnected()
1709*/
1710void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
1711 OpenMode openMode,
1712 NetworkLayerProtocol protocol)
1713{
1714 Q_D(QAbstractSocket);
1715#if defined(QABSTRACTSOCKET_DEBUG)
1716 qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1717 (int) openMode);
1718#endif
1719
1720 if (d->state == ConnectedState || d->state == ConnectingState
1721 || d->state == ClosingState || d->state == HostLookupState) {
1722 qWarning(msg: "QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1723 d->setErrorAndEmit(errorCode: OperationError, errorString: tr(s: "Trying to connect while connection is in progress"));
1724 return;
1725 }
1726
1727 d->preferredNetworkLayerProtocol = protocol;
1728 d->hostName = hostName;
1729 d->port = port;
1730 d->setReadChannelCount(0);
1731 d->setWriteChannelCount(0);
1732 d->abortCalled = false;
1733 d->pendingClose = false;
1734 if (d->state != BoundState) {
1735 d->state = UnconnectedState;
1736 d->localPort = 0;
1737 d->localAddress.clear();
1738 }
1739 d->peerPort = 0;
1740 d->peerAddress.clear();
1741 d->peerName = hostName;
1742 if (d->hostLookupId != -1) {
1743 QHostInfo::abortHostLookup(lookupId: d->hostLookupId);
1744 d->hostLookupId = -1;
1745 }
1746
1747#ifndef QT_NO_NETWORKPROXY
1748 // Get the proxy information
1749 d->resolveProxy(hostname: hostName, port);
1750 if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1751 // failed to setup the proxy
1752 d->setErrorAndEmit(errorCode: UnsupportedSocketOperationError,
1753 errorString: tr(s: "Operation on socket is not supported"));
1754 return;
1755 }
1756#endif
1757
1758 // Sync up with error string, which open() shall clear.
1759 d->socketError = UnknownSocketError;
1760 if (openMode & QIODevice::Unbuffered)
1761 d->isBuffered = false;
1762 else if (!d_func()->isBuffered)
1763 openMode |= QAbstractSocket::Unbuffered;
1764
1765 QIODevice::open(mode: openMode);
1766 d->readChannelCount = d->writeChannelCount = 0;
1767
1768#ifndef Q_OS_WINRT
1769 d->state = HostLookupState;
1770 emit stateChanged(d->state);
1771
1772 QHostAddress temp;
1773 if (temp.setAddress(hostName)) {
1774 QHostInfo info;
1775 info.setAddresses(QList<QHostAddress>() << temp);
1776 d->_q_startConnecting(hostInfo: info);
1777#ifndef QT_NO_NETWORKPROXY
1778 } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1779 // the proxy supports connection by name, so use it
1780 d->startConnectingByName(host: hostName);
1781 return;
1782#endif
1783 } else {
1784 if (d->threadData.loadRelaxed()->hasEventDispatcher()) {
1785 // this internal API for QHostInfo either immediately gives us the desired
1786 // QHostInfo from cache or later calls the _q_startConnecting slot.
1787 bool immediateResultValid = false;
1788 QHostInfo hostInfo = qt_qhostinfo_lookup(name: hostName,
1789 receiver: this,
1790 SLOT(_q_startConnecting(QHostInfo)),
1791 valid: &immediateResultValid,
1792 id: &d->hostLookupId);
1793 if (immediateResultValid) {
1794 d->hostLookupId = -1;
1795 d->_q_startConnecting(hostInfo);
1796 }
1797 }
1798 }
1799
1800#if defined(QABSTRACTSOCKET_DEBUG)
1801 qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1802 (d->state == ConnectedState) ? "true" : "false",
1803 (d->state == ConnectingState || d->state == HostLookupState)
1804 ? " (connection in progress)" : "");
1805#endif
1806#else // !Q_OS_WINRT
1807 // On WinRT we should always connect by name. Lookup and proxy handling are done by the API.
1808 d->startConnectingByName(hostName);
1809#endif
1810}
1811
1812/*! \overload
1813
1814 Attempts to make a connection to \a address on port \a port.
1815*/
1816void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port,
1817 OpenMode openMode)
1818{
1819#if defined(QABSTRACTSOCKET_DEBUG)
1820 qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1821 address.toString().toLatin1().constData(), port, (int) openMode);
1822#endif
1823 connectToHost(hostName: address.toString(), port, openMode);
1824}
1825
1826/*!
1827 Returns the number of bytes that are waiting to be written. The
1828 bytes are written when control goes back to the event loop or
1829 when flush() is called.
1830
1831 \sa bytesAvailable(), flush()
1832*/
1833qint64 QAbstractSocket::bytesToWrite() const
1834{
1835 const qint64 pendingBytes = QIODevice::bytesToWrite();
1836#if defined(QABSTRACTSOCKET_DEBUG)
1837 qDebug("QAbstractSocket::bytesToWrite() == %lld", pendingBytes);
1838#endif
1839 return pendingBytes;
1840}
1841
1842/*!
1843 Returns the number of incoming bytes that are waiting to be read.
1844
1845 \sa bytesToWrite(), read()
1846*/
1847qint64 QAbstractSocket::bytesAvailable() const
1848{
1849 Q_D(const QAbstractSocket);
1850 qint64 available = QIODevice::bytesAvailable();
1851
1852 if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
1853 available += d->socketEngine->bytesAvailable();
1854
1855#if defined(QABSTRACTSOCKET_DEBUG)
1856 qDebug("QAbstractSocket::bytesAvailable() == %lld", available);
1857#endif
1858 return available;
1859}
1860
1861/*!
1862 Returns the host port number (in native byte order) of the local
1863 socket if available; otherwise returns 0.
1864
1865 \sa localAddress(), peerPort(), setLocalPort()
1866*/
1867quint16 QAbstractSocket::localPort() const
1868{
1869 Q_D(const QAbstractSocket);
1870 return d->localPort;
1871}
1872
1873/*!
1874 Returns the host address of the local socket if available;
1875 otherwise returns QHostAddress::Null.
1876
1877 This is normally the main IP address of the host, but can be
1878 QHostAddress::LocalHost (127.0.0.1) for connections to the
1879 local host.
1880
1881 \sa localPort(), peerAddress(), setLocalAddress()
1882*/
1883QHostAddress QAbstractSocket::localAddress() const
1884{
1885 Q_D(const QAbstractSocket);
1886 return d->localAddress;
1887}
1888
1889/*!
1890 Returns the port of the connected peer if the socket is in
1891 ConnectedState; otherwise returns 0.
1892
1893 \sa peerAddress(), localPort(), setPeerPort()
1894*/
1895quint16 QAbstractSocket::peerPort() const
1896{
1897 Q_D(const QAbstractSocket);
1898 return d->peerPort;
1899}
1900
1901/*!
1902 Returns the address of the connected peer if the socket is in
1903 ConnectedState; otherwise returns QHostAddress::Null.
1904
1905 \sa peerName(), peerPort(), localAddress(), setPeerAddress()
1906*/
1907QHostAddress QAbstractSocket::peerAddress() const
1908{
1909 Q_D(const QAbstractSocket);
1910 return d->peerAddress;
1911}
1912
1913/*!
1914 Returns the name of the peer as specified by connectToHost(), or
1915 an empty QString if connectToHost() has not been called.
1916
1917 \sa peerAddress(), peerPort(), setPeerName()
1918*/
1919QString QAbstractSocket::peerName() const
1920{
1921 Q_D(const QAbstractSocket);
1922 return d->peerName.isEmpty() ? d->hostName : d->peerName;
1923}
1924
1925/*!
1926 Returns \c true if a line of data can be read from the socket;
1927 otherwise returns \c false.
1928
1929 \sa readLine()
1930*/
1931bool QAbstractSocket::canReadLine() const
1932{
1933 bool hasLine = QIODevice::canReadLine();
1934#if defined (QABSTRACTSOCKET_DEBUG)
1935 qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %lld, size = %lld",
1936 hasLine ? "true" : "false", d_func()->buffer.size(), d_func()->buffer.size());
1937#endif
1938 return hasLine;
1939}
1940
1941/*!
1942 Returns the native socket descriptor of the QAbstractSocket object
1943 if this is available; otherwise returns -1.
1944
1945 If the socket is using QNetworkProxy, the returned descriptor
1946 may not be usable with native socket functions.
1947
1948 The socket descriptor is not available when QAbstractSocket is in
1949 UnconnectedState.
1950
1951 \sa setSocketDescriptor()
1952*/
1953qintptr QAbstractSocket::socketDescriptor() const
1954{
1955 Q_D(const QAbstractSocket);
1956 return d->cachedSocketDescriptor;
1957}
1958
1959/*!
1960 Initializes QAbstractSocket with the native socket descriptor \a
1961 socketDescriptor. Returns \c true if \a socketDescriptor is accepted
1962 as a valid socket descriptor; otherwise returns \c false.
1963 The socket is opened in the mode specified by \a openMode, and
1964 enters the socket state specified by \a socketState.
1965 Read and write buffers are cleared, discarding any pending data.
1966
1967 \b{Note:} It is not possible to initialize two abstract sockets
1968 with the same native socket descriptor.
1969
1970 \sa socketDescriptor()
1971*/
1972bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState socketState,
1973 OpenMode openMode)
1974{
1975 Q_D(QAbstractSocket);
1976
1977 d->resetSocketLayer();
1978 d->setReadChannelCount(0);
1979 d->setWriteChannelCount(0);
1980 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, parent: this);
1981 if (!d->socketEngine) {
1982 d->setError(errorCode: UnsupportedSocketOperationError, errStr: tr(s: "Operation on socket is not supported"));
1983 return false;
1984 }
1985#ifndef QT_NO_BEARERMANAGEMENT // ### Qt6: Remove section
1986 //copy network session down to the socket engine (if it has been set)
1987 d->socketEngine->setProperty(name: "_q_networksession", value: property(name: "_q_networksession"));
1988#endif
1989 bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1990 if (!result) {
1991 d->setError(errorCode: d->socketEngine->error(), errStr: d->socketEngine->errorString());
1992 return false;
1993 }
1994
1995 // Sync up with error string, which open() shall clear.
1996 d->socketError = UnknownSocketError;
1997 if (d->threadData.loadRelaxed()->hasEventDispatcher())
1998 d->socketEngine->setReceiver(d);
1999
2000 QIODevice::open(mode: openMode);
2001
2002 if (socketState == ConnectedState) {
2003 if (isReadable()) {
2004 const int inboundStreamCount = d->socketEngine->inboundStreamCount();
2005 d->setReadChannelCount(qMax(a: 1, b: inboundStreamCount));
2006 if (inboundStreamCount == 0)
2007 d->readChannelCount = 0;
2008 }
2009 if (isWritable()) {
2010 const int outboundStreamCount = d->socketEngine->outboundStreamCount();
2011 d->setWriteChannelCount(qMax(a: 1, b: outboundStreamCount));
2012 if (outboundStreamCount == 0)
2013 d->writeChannelCount = 0;
2014 }
2015 } else {
2016 d->readChannelCount = d->writeChannelCount = 0;
2017 }
2018
2019 if (d->state != socketState) {
2020 d->state = socketState;
2021 emit stateChanged(d->state);
2022 }
2023
2024 d->pendingClose = false;
2025 d->socketEngine->setReadNotificationEnabled(true);
2026 d->localPort = d->socketEngine->localPort();
2027 d->peerPort = d->socketEngine->peerPort();
2028 d->localAddress = d->socketEngine->localAddress();
2029 d->peerAddress = d->socketEngine->peerAddress();
2030 d->cachedSocketDescriptor = socketDescriptor;
2031
2032 return true;
2033}
2034
2035/*!
2036 \since 4.6
2037 Sets the given \a option to the value described by \a value.
2038
2039 \note On Windows Runtime, QAbstractSocket::KeepAliveOption must be set
2040 before the socket is connected.
2041
2042 \sa socketOption()
2043*/
2044void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
2045{
2046 if (!d_func()->socketEngine)
2047 return;
2048
2049 switch (option) {
2050 case LowDelayOption:
2051 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::LowDelayOption, value: value.toInt());
2052 break;
2053
2054 case KeepAliveOption:
2055 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::KeepAliveOption, value: value.toInt());
2056 break;
2057
2058 case MulticastTtlOption:
2059 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::MulticastTtlOption, value: value.toInt());
2060 break;
2061
2062 case MulticastLoopbackOption:
2063 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::MulticastLoopbackOption, value: value.toInt());
2064 break;
2065
2066 case TypeOfServiceOption:
2067 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::TypeOfServiceOption, value: value.toInt());
2068 break;
2069
2070 case SendBufferSizeSocketOption:
2071 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::SendBufferSocketOption, value: value.toInt());
2072 break;
2073
2074 case ReceiveBufferSizeSocketOption:
2075 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::ReceiveBufferSocketOption, value: value.toInt());
2076 break;
2077
2078 case PathMtuSocketOption:
2079 d_func()->socketEngine->setOption(option: QAbstractSocketEngine::PathMtuInformation, value: value.toInt());
2080 break;
2081 }
2082}
2083
2084/*!
2085 \since 4.6
2086 Returns the value of the \a option option.
2087
2088 \sa setSocketOption()
2089*/
2090QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)
2091{
2092 if (!d_func()->socketEngine)
2093 return QVariant();
2094
2095 int ret = -1;
2096 switch (option) {
2097 case LowDelayOption:
2098 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::LowDelayOption);
2099 break;
2100
2101 case KeepAliveOption:
2102 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::KeepAliveOption);
2103 break;
2104
2105 case MulticastTtlOption:
2106 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::MulticastTtlOption);
2107 break;
2108 case MulticastLoopbackOption:
2109 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::MulticastLoopbackOption);
2110 break;
2111
2112 case TypeOfServiceOption:
2113 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::TypeOfServiceOption);
2114 break;
2115
2116 case SendBufferSizeSocketOption:
2117 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::SendBufferSocketOption);
2118 break;
2119
2120 case ReceiveBufferSizeSocketOption:
2121 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::ReceiveBufferSocketOption);
2122 break;
2123
2124 case PathMtuSocketOption:
2125 ret = d_func()->socketEngine->option(option: QAbstractSocketEngine::PathMtuInformation);
2126 break;
2127 }
2128 if (ret == -1)
2129 return QVariant();
2130 else
2131 return QVariant(ret);
2132}
2133
2134/*!
2135 Waits until the socket is connected, up to \a msecs
2136 milliseconds. If the connection has been established, this
2137 function returns \c true; otherwise it returns \c false. In the case
2138 where it returns \c false, you can call error() to determine
2139 the cause of the error.
2140
2141 The following example waits up to one second for a connection
2142 to be established:
2143
2144 \snippet code/src_network_socket_qabstractsocket.cpp 0
2145
2146 If msecs is -1, this function will not time out.
2147
2148 \note This function may wait slightly longer than \a msecs,
2149 depending on the time it takes to complete the host lookup.
2150
2151 \note Multiple calls to this functions do not accumulate the time.
2152 If the function times out, the connecting process will be aborted.
2153
2154 \note This function may fail randomly on Windows. Consider using the event
2155 loop and the connected() signal if your software will run on Windows.
2156
2157 \sa connectToHost(), connected()
2158*/
2159bool QAbstractSocket::waitForConnected(int msecs)
2160{
2161 Q_D(QAbstractSocket);
2162#if defined (QABSTRACTSOCKET_DEBUG)
2163 qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
2164#endif
2165
2166 if (state() == ConnectedState) {
2167#if defined (QABSTRACTSOCKET_DEBUG)
2168 qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
2169#endif
2170 return true;
2171 }
2172
2173 bool wasPendingClose = d->pendingClose;
2174 d->pendingClose = false;
2175 QElapsedTimer stopWatch;
2176 stopWatch.start();
2177
2178#ifndef QT_NO_BEARERMANAGEMENT // ### Qt6: Remove section
2179 QSharedPointer<QNetworkSession> networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v: property(name: "_q_networksession"));
2180#endif
2181
2182 if (d->state == HostLookupState) {
2183#if defined (QABSTRACTSOCKET_DEBUG)
2184 qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
2185#endif
2186 QHostInfo::abortHostLookup(lookupId: d->hostLookupId);
2187 d->hostLookupId = -1;
2188 QHostAddress temp;
2189 if (temp.setAddress(d->hostName)) {
2190 QHostInfo info;
2191 info.setAddresses(QList<QHostAddress>() << temp);
2192 d->_q_startConnecting(hostInfo: info);
2193 } else {
2194 d->_q_startConnecting(hostInfo: QHostInfo::fromName(name: d->hostName));
2195 }
2196 }
2197 if (state() == UnconnectedState)
2198 return false; // connect not im progress anymore!
2199
2200#ifdef QT_NO_BEARERMANAGEMENT
2201 int connectTimeout = 30000;
2202#else
2203 int connectTimeout = QNetworkConfigurationPrivate::DefaultTimeout;
2204 if (networkSession) {
2205 QNetworkConfiguration networkConfiguration = networkSession->configuration();
2206 connectTimeout = networkConfiguration.connectTimeout();
2207 }
2208#endif
2209 bool timedOut = true;
2210#if defined (QABSTRACTSOCKET_DEBUG)
2211 int attempt = 1;
2212#endif
2213 while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
2214 int timeout = qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed());
2215 if (msecs != -1 && timeout > connectTimeout)
2216 timeout = connectTimeout;
2217#if defined (QABSTRACTSOCKET_DEBUG)
2218 qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
2219 msecs, timeout / 1000.0, attempt++);
2220#endif
2221 timedOut = false;
2222
2223 if (d->socketEngine && d->socketEngine->waitForWrite(msecs: timeout, timedOut: &timedOut) && !timedOut) {
2224 d->_q_testConnection();
2225 } else {
2226 d->_q_connectToNextAddress();
2227 }
2228 }
2229
2230 if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
2231 d->setError(errorCode: SocketTimeoutError, errStr: tr(s: "Socket operation timed out"));
2232 d->state = UnconnectedState;
2233 emit stateChanged(d->state);
2234 d->resetSocketLayer();
2235 }
2236
2237#if defined (QABSTRACTSOCKET_DEBUG)
2238 qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
2239 state() == ConnectedState ? "true" : "false");
2240#endif
2241 if (state() != ConnectedState)
2242 return false;
2243 if (wasPendingClose)
2244 disconnectFromHost();
2245 return true;
2246}
2247
2248/*!
2249 This function blocks until new data is available for reading and the
2250 \l{QIODevice::}{readyRead()} signal has been emitted. The function
2251 will timeout after \a msecs milliseconds; the default timeout is
2252 30000 milliseconds.
2253
2254 The function returns \c true if the readyRead() signal is emitted and
2255 there is new data available for reading; otherwise it returns \c false
2256 (if an error occurred or the operation timed out).
2257
2258 \note This function may fail randomly on Windows. Consider using the event
2259 loop and the readyRead() signal if your software will run on Windows.
2260
2261 \sa waitForBytesWritten()
2262*/
2263bool QAbstractSocket::waitForReadyRead(int msecs)
2264{
2265 Q_D(QAbstractSocket);
2266#if defined (QABSTRACTSOCKET_DEBUG)
2267 qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
2268#endif
2269
2270 // require calling connectToHost() before waitForReadyRead()
2271 if (state() == UnconnectedState) {
2272 /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
2273 this, so you cannot avoid this warning. */
2274// qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
2275 return false;
2276 }
2277
2278 QElapsedTimer stopWatch;
2279 stopWatch.start();
2280
2281 // handle a socket in connecting state
2282 if (state() == HostLookupState || state() == ConnectingState) {
2283 if (!waitForConnected(msecs))
2284 return false;
2285 }
2286
2287 do {
2288 if (state() != ConnectedState && state() != BoundState)
2289 return false;
2290
2291 bool readyToRead = false;
2292 bool readyToWrite = false;
2293 if (!d->socketEngine->waitForReadOrWrite(readyToRead: &readyToRead, readyToWrite: &readyToWrite, checkRead: true, checkWrite: !d->writeBuffer.isEmpty(),
2294 msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()))) {
2295#if defined (QABSTRACTSOCKET_DEBUG)
2296 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2297 msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
2298#endif
2299 d->setErrorAndEmit(errorCode: d->socketEngine->error(), errorString: d->socketEngine->errorString());
2300 if (d->socketError != SocketTimeoutError)
2301 close();
2302 return false;
2303 }
2304
2305 if (readyToRead) {
2306 if (d->canReadNotification())
2307 return true;
2308 }
2309
2310 if (readyToWrite)
2311 d->canWriteNotification();
2312 } while (msecs == -1 || qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()) > 0);
2313 return false;
2314}
2315
2316/*! \reimp
2317
2318 This function blocks until at least one byte has been written on the socket
2319 and the \l{QIODevice::}{bytesWritten()} signal has been emitted. The
2320 function will timeout after \a msecs milliseconds; the default timeout is
2321 30000 milliseconds.
2322
2323 The function returns \c true if the bytesWritten() signal is emitted;
2324 otherwise it returns \c false (if an error occurred or the operation timed
2325 out).
2326
2327 \note This function may fail randomly on Windows. Consider using the event
2328 loop and the bytesWritten() signal if your software will run on Windows.
2329
2330 \sa waitForReadyRead()
2331 */
2332bool QAbstractSocket::waitForBytesWritten(int msecs)
2333{
2334 Q_D(QAbstractSocket);
2335#if defined (QABSTRACTSOCKET_DEBUG)
2336 qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
2337#endif
2338
2339 // require calling connectToHost() before waitForBytesWritten()
2340 if (state() == UnconnectedState) {
2341 qWarning(msg: "QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
2342 return false;
2343 }
2344
2345 if (d->writeBuffer.isEmpty())
2346 return false;
2347
2348 QElapsedTimer stopWatch;
2349 stopWatch.start();
2350
2351 // handle a socket in connecting state
2352 if (state() == HostLookupState || state() == ConnectingState) {
2353 if (!waitForConnected(msecs))
2354 return false;
2355 }
2356
2357 forever {
2358 bool readyToRead = false;
2359 bool readyToWrite = false;
2360 if (!d->socketEngine->waitForReadOrWrite(readyToRead: &readyToRead, readyToWrite: &readyToWrite,
2361 checkRead: !d->readBufferMaxSize || d->buffer.size() < d->readBufferMaxSize,
2362 checkWrite: !d->writeBuffer.isEmpty(),
2363 msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()))) {
2364#if defined (QABSTRACTSOCKET_DEBUG)
2365 qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
2366 msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
2367#endif
2368 d->setErrorAndEmit(errorCode: d->socketEngine->error(), errorString: d->socketEngine->errorString());
2369 if (d->socketError != SocketTimeoutError)
2370 close();
2371 return false;
2372 }
2373
2374 if (readyToRead) {
2375#if defined (QABSTRACTSOCKET_DEBUG)
2376 qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
2377#endif
2378 d->canReadNotification();
2379 }
2380
2381
2382 if (readyToWrite) {
2383 if (d->canWriteNotification()) {
2384#if defined (QABSTRACTSOCKET_DEBUG)
2385 qDebug("QAbstractSocket::waitForBytesWritten returns true");
2386#endif
2387 return true;
2388 }
2389 }
2390
2391 if (state() != ConnectedState)
2392 return false;
2393 }
2394 return false;
2395}
2396
2397/*!
2398 Waits until the socket has disconnected, up to \a msecs milliseconds. If the
2399 connection was successfully disconnected, this function returns \c true;
2400 otherwise it returns \c false (if the operation timed out, if an error
2401 occurred, or if this QAbstractSocket is already disconnected). In the case
2402 where it returns \c false, you can call error() to determine the cause of
2403 the error.
2404
2405 The following example waits up to one second for a connection
2406 to be closed:
2407
2408 \snippet code/src_network_socket_qabstractsocket.cpp 1
2409
2410 If msecs is -1, this function will not time out.
2411
2412 \note This function may fail randomly on Windows. Consider using the event
2413 loop and the disconnected() signal if your software will run on Windows.
2414
2415 \sa disconnectFromHost(), close()
2416*/
2417bool QAbstractSocket::waitForDisconnected(int msecs)
2418{
2419 Q_D(QAbstractSocket);
2420
2421 // require calling connectToHost() before waitForDisconnected()
2422 if (state() == UnconnectedState) {
2423 qWarning(msg: "QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
2424 return false;
2425 }
2426
2427 QElapsedTimer stopWatch;
2428 stopWatch.start();
2429
2430 // handle a socket in connecting state
2431 if (state() == HostLookupState || state() == ConnectingState) {
2432 if (!waitForConnected(msecs))
2433 return false;
2434 if (state() == UnconnectedState)
2435 return true;
2436 }
2437
2438 forever {
2439 bool readyToRead = false;
2440 bool readyToWrite = false;
2441 if (!d->socketEngine->waitForReadOrWrite(readyToRead: &readyToRead, readyToWrite: &readyToWrite, checkRead: state() == ConnectedState,
2442 checkWrite: !d->writeBuffer.isEmpty(),
2443 msecs: qt_subtract_from_timeout(timeout: msecs, elapsed: stopWatch.elapsed()))) {
2444#if defined (QABSTRACTSOCKET_DEBUG)
2445 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2446 msecs, d->socketEngine->error(), d->socketEngine->errorString().toLatin1().constData());
2447#endif
2448 d->setErrorAndEmit(errorCode: d->socketEngine->error(), errorString: d->socketEngine->errorString());
2449 if (d->socketError != SocketTimeoutError)
2450 close();
2451 return false;
2452 }
2453
2454 if (readyToRead)
2455 d->canReadNotification();
2456 if (readyToWrite)
2457 d->canWriteNotification();
2458
2459 if (state() == UnconnectedState)
2460 return true;
2461 }
2462 return false;
2463}
2464
2465/*!
2466 Aborts the current connection and resets the socket. Unlike disconnectFromHost(),
2467 this function immediately closes the socket, discarding any pending data in the
2468 write buffer.
2469
2470 \sa disconnectFromHost(), close()
2471*/
2472void QAbstractSocket::abort()
2473{
2474 Q_D(QAbstractSocket);
2475#if defined (QABSTRACTSOCKET_DEBUG)
2476 qDebug("QAbstractSocket::abort()");
2477#endif
2478 d->setWriteChannelCount(0);
2479 if (d->state == UnconnectedState)
2480 return;
2481#ifndef QT_NO_SSL
2482 if (QSslSocket *socket = qobject_cast<QSslSocket *>(object: this)) {
2483 socket->abort();
2484 return;
2485 }
2486#endif
2487
2488 d->abortCalled = true;
2489 close();
2490}
2491
2492/*! \reimp
2493*/
2494bool QAbstractSocket::isSequential() const
2495{
2496 return true;
2497}
2498
2499/*! \reimp
2500
2501 Returns \c true if no more data is currently
2502 available for reading; otherwise returns \c false.
2503
2504 This function is most commonly used when reading data from the
2505 socket in a loop. For example:
2506
2507 \snippet code/src_network_socket_qabstractsocket.cpp 2
2508
2509 \sa bytesAvailable(), readyRead()
2510 */
2511bool QAbstractSocket::atEnd() const
2512{
2513 return QIODevice::atEnd();
2514}
2515
2516/*!
2517 This function writes as much as possible from the internal write buffer to
2518 the underlying network socket, without blocking. If any data was written,
2519 this function returns \c true; otherwise false is returned.
2520
2521 Call this function if you need QAbstractSocket to start sending buffered
2522 data immediately. The number of bytes successfully written depends on the
2523 operating system. In most cases, you do not need to call this function,
2524 because QAbstractSocket will start sending data automatically once control
2525 goes back to the event loop. In the absence of an event loop, call
2526 waitForBytesWritten() instead.
2527
2528 \sa write(), waitForBytesWritten()
2529*/
2530bool QAbstractSocket::flush()
2531{
2532 return d_func()->flush();
2533}
2534
2535/*! \reimp
2536*/
2537qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
2538{
2539 Q_D(QAbstractSocket);
2540
2541 // if we're not connected, return -1 indicating EOF
2542 if (!d->socketEngine || !d->socketEngine->isValid() || d->state != QAbstractSocket::ConnectedState)
2543 return maxSize ? qint64(-1) : qint64(0);
2544
2545 qint64 readBytes = (maxSize && !d->isBuffered) ? d->socketEngine->read(data, maxlen: maxSize)
2546 : qint64(0);
2547 if (readBytes == -2) {
2548 // -2 from the engine means no bytes available (EAGAIN) so read more later
2549 readBytes = 0;
2550 }
2551 if (readBytes < 0) {
2552 d->setError(errorCode: d->socketEngine->error(), errStr: d->socketEngine->errorString());
2553 d->resetSocketLayer();
2554 d->state = QAbstractSocket::UnconnectedState;
2555 } else {
2556 // Only do this when there was no error
2557 d->hasPendingData = false;
2558 d->socketEngine->setReadNotificationEnabled(true);
2559 }
2560
2561#if defined (QABSTRACTSOCKET_DEBUG)
2562 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
2563 data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2564 readBytes);
2565#endif
2566 return readBytes;
2567}
2568
2569/*! \reimp
2570*/
2571qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)
2572{
2573 return QIODevice::readLineData(data, maxlen);
2574}
2575
2576/*! \reimp
2577*/
2578qint64 QAbstractSocket::writeData(const char *data, qint64 size)
2579{
2580 Q_D(QAbstractSocket);
2581 if (d->state == QAbstractSocket::UnconnectedState
2582 || (!d->socketEngine && d->socketType != TcpSocket && !d->isBuffered)) {
2583 d->setError(errorCode: UnknownSocketError, errStr: tr(s: "Socket is not connected"));
2584 return -1;
2585 }
2586
2587 if (!d->isBuffered && d->socketType == TcpSocket
2588 && d->socketEngine && d->writeBuffer.isEmpty()) {
2589 // This code is for the new Unbuffered QTcpSocket use case
2590 qint64 written = size ? d->socketEngine->write(data, len: size) : Q_INT64_C(0);
2591 if (written < 0) {
2592 d->setError(errorCode: d->socketEngine->error(), errStr: d->socketEngine->errorString());
2593 } else if (written < size) {
2594 // Buffer what was not written yet
2595 d->writeBuffer.append(data: data + written, size: size - written);
2596 written = size;
2597 d->socketEngine->setWriteNotificationEnabled(true);
2598 }
2599
2600#if defined (QABSTRACTSOCKET_DEBUG)
2601 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2602 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2603 size, written);
2604#endif
2605 return written; // written = actually written + what has been buffered
2606 } else if (!d->isBuffered && d->socketType != TcpSocket) {
2607 // This is for a QUdpSocket that was connect()ed
2608 qint64 written = d->socketEngine->write(data, len: size);
2609 if (written < 0)
2610 d->setError(errorCode: d->socketEngine->error(), errStr: d->socketEngine->errorString());
2611
2612#if defined (QABSTRACTSOCKET_DEBUG)
2613 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2614 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2615 size, written);
2616#endif
2617 if (written >= 0)
2618 d->emitBytesWritten(bytes: written);
2619 return written;
2620 }
2621
2622 // This is the code path for normal buffered QTcpSocket or
2623 // unbuffered QTcpSocket when there was already something in the
2624 // write buffer and therefore we could not do a direct engine write.
2625 // We just write to our write buffer and enable the write notifier
2626 // The write notifier then flush()es the buffer.
2627
2628 d->writeBuffer.append(data, size);
2629 qint64 written = size;
2630
2631 if (d->socketEngine && !d->writeBuffer.isEmpty())
2632 d->socketEngine->setWriteNotificationEnabled(true);
2633
2634#if defined (QABSTRACTSOCKET_DEBUG)
2635 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2636 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2637 size, written);
2638#endif
2639 return written;
2640}
2641
2642/*!
2643 \since 4.1
2644
2645 Sets the port on the local side of a connection to \a port.
2646
2647 You can call this function in a subclass of QAbstractSocket to
2648 change the return value of the localPort() function after a
2649 connection has been established. This feature is commonly used by
2650 proxy connections for virtual connection settings.
2651
2652 Note that this function does not bind the local port of the socket
2653 prior to a connection (e.g., QAbstractSocket::bind()).
2654
2655 \sa localAddress(), setLocalAddress(), setPeerPort()
2656*/
2657void QAbstractSocket::setLocalPort(quint16 port)
2658{
2659 Q_D(QAbstractSocket);
2660 d->localPort = port;
2661}
2662
2663/*!
2664 \since 4.1
2665
2666 Sets the address on the local side of a connection to
2667 \a address.
2668
2669 You can call this function in a subclass of QAbstractSocket to
2670 change the return value of the localAddress() function after a
2671 connection has been established. This feature is commonly used by
2672 proxy connections for virtual connection settings.
2673
2674 Note that this function does not bind the local address of the socket
2675 prior to a connection (e.g., QAbstractSocket::bind()).
2676
2677 \sa localAddress(), setLocalPort(), setPeerAddress()
2678*/
2679void QAbstractSocket::setLocalAddress(const QHostAddress &address)
2680{
2681 Q_D(QAbstractSocket);
2682 d->localAddress = address;
2683}
2684
2685/*!
2686 \since 4.1
2687
2688 Sets the port of the remote side of the connection to
2689 \a port.
2690
2691 You can call this function in a subclass of QAbstractSocket to
2692 change the return value of the peerPort() function after a
2693 connection has been established. This feature is commonly used by
2694 proxy connections for virtual connection settings.
2695
2696 \sa peerPort(), setPeerAddress(), setLocalPort()
2697*/
2698void QAbstractSocket::setPeerPort(quint16 port)
2699{
2700 Q_D(QAbstractSocket);
2701 d->peerPort = port;
2702}
2703
2704/*!
2705 \since 4.1
2706
2707 Sets the address of the remote side of the connection
2708 to \a address.
2709
2710 You can call this function in a subclass of QAbstractSocket to
2711 change the return value of the peerAddress() function after a
2712 connection has been established. This feature is commonly used by
2713 proxy connections for virtual connection settings.
2714
2715 \sa peerAddress(), setPeerPort(), setLocalAddress()
2716*/
2717void QAbstractSocket::setPeerAddress(const QHostAddress &address)
2718{
2719 Q_D(QAbstractSocket);
2720 d->peerAddress = address;
2721}
2722
2723/*!
2724 \since 4.1
2725
2726 Sets the host name of the remote peer to \a name.
2727
2728 You can call this function in a subclass of QAbstractSocket to
2729 change the return value of the peerName() function after a
2730 connection has been established. This feature is commonly used by
2731 proxy connections for virtual connection settings.
2732
2733 \sa peerName()
2734*/
2735void QAbstractSocket::setPeerName(const QString &name)
2736{
2737 Q_D(QAbstractSocket);
2738 d->peerName = name;
2739}
2740
2741/*!
2742 Closes the I/O device for the socket and calls disconnectFromHost()
2743 to close the socket's connection.
2744
2745 See QIODevice::close() for a description of the actions that occur when an I/O
2746 device is closed.
2747
2748 \sa abort()
2749*/
2750void QAbstractSocket::close()
2751{
2752 Q_D(QAbstractSocket);
2753#if defined(QABSTRACTSOCKET_DEBUG)
2754 qDebug("QAbstractSocket::close()");
2755#endif
2756 QIODevice::close();
2757 if (d->state != UnconnectedState)
2758 disconnectFromHost();
2759}
2760
2761/*!
2762 Attempts to close the socket. If there is pending data waiting to
2763 be written, QAbstractSocket will enter ClosingState and wait
2764 until all data has been written. Eventually, it will enter
2765 UnconnectedState and emit the disconnected() signal.
2766
2767 \sa connectToHost()
2768*/
2769void QAbstractSocket::disconnectFromHost()
2770{
2771 Q_D(QAbstractSocket);
2772#if defined(QABSTRACTSOCKET_DEBUG)
2773 qDebug("QAbstractSocket::disconnectFromHost()");
2774#endif
2775
2776 if (d->state == UnconnectedState) {
2777#if defined(QABSTRACTSOCKET_DEBUG)
2778 qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2779#endif
2780 return;
2781 }
2782
2783 if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2784#if defined(QABSTRACTSOCKET_DEBUG)
2785 qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2786#endif
2787 d->pendingClose = true;
2788 return;
2789 }
2790
2791 // Disable and delete read notification
2792 if (d->socketEngine)
2793 d->socketEngine->setReadNotificationEnabled(false);
2794
2795 if (d->abortCalled) {
2796#if defined(QABSTRACTSOCKET_DEBUG)
2797 qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2798#endif
2799 if (d->state == HostLookupState) {
2800 QHostInfo::abortHostLookup(lookupId: d->hostLookupId);
2801 d->hostLookupId = -1;
2802 }
2803 } else {
2804 // Perhaps emit closing()
2805 if (d->state != ClosingState) {
2806 d->state = ClosingState;
2807#if defined(QABSTRACTSOCKET_DEBUG)
2808 qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2809#endif
2810 emit stateChanged(d->state);
2811 } else {
2812#if defined(QABSTRACTSOCKET_DEBUG)
2813 qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2814#endif
2815 }
2816
2817 // Wait for pending data to be written.
2818 if (d->socketEngine && d->socketEngine->isValid() && (!d->allWriteBuffersEmpty()
2819 || d->socketEngine->bytesToWrite() > 0)) {
2820 d->socketEngine->setWriteNotificationEnabled(true);
2821
2822#if defined(QABSTRACTSOCKET_DEBUG)
2823 qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2824#endif
2825 return;
2826 } else {
2827#if defined(QABSTRACTSOCKET_DEBUG)
2828 qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2829#endif
2830 }
2831 }
2832
2833 SocketState previousState = d->state;
2834 d->resetSocketLayer();
2835 d->state = UnconnectedState;
2836 emit stateChanged(d->state);
2837 emit readChannelFinished(); // we got an EOF
2838
2839 // only emit disconnected if we were connected before
2840 if (previousState == ConnectedState || previousState == ClosingState)
2841 emit disconnected();
2842
2843 d->localPort = 0;
2844 d->peerPort = 0;
2845 d->localAddress.clear();
2846 d->peerAddress.clear();
2847 d->peerName.clear();
2848 d->setWriteChannelCount(0);
2849
2850#if defined(QABSTRACTSOCKET_DEBUG)
2851 qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2852#endif
2853
2854}
2855
2856/*!
2857 Returns the size of the internal read buffer. This limits the
2858 amount of data that the client can receive before you call read()
2859 or readAll().
2860
2861 A read buffer size of 0 (the default) means that the buffer has
2862 no size limit, ensuring that no data is lost.
2863
2864 \sa setReadBufferSize(), read()
2865*/
2866qint64 QAbstractSocket::readBufferSize() const
2867{
2868 return d_func()->readBufferMaxSize;
2869}
2870
2871/*!
2872 Sets the size of QAbstractSocket's internal read buffer to be \a
2873 size bytes.
2874
2875 If the buffer size is limited to a certain size, QAbstractSocket
2876 won't buffer more than this size of data. Exceptionally, a buffer
2877 size of 0 means that the read buffer is unlimited and all
2878 incoming data is buffered. This is the default.
2879
2880 This option is useful if you only read the data at certain points
2881 in time (e.g., in a real-time streaming application) or if you
2882 want to protect your socket against receiving too much data,
2883 which may eventually cause your application to run out of memory.
2884
2885 Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket
2886 does not use any buffering at all, but rather relies on the
2887 implicit buffering provided by the operating system.
2888 Because of this, calling this function on QUdpSocket has no
2889 effect.
2890
2891 \sa readBufferSize(), read()
2892*/
2893void QAbstractSocket::setReadBufferSize(qint64 size)
2894{
2895 Q_D(QAbstractSocket);
2896
2897 if (d->readBufferMaxSize == size)
2898 return;
2899 d->readBufferMaxSize = size;
2900
2901 // Do not change the notifier unless we are connected.
2902 if (d->socketEngine && d->state == QAbstractSocket::ConnectedState) {
2903 // Ensure that the read notification is enabled if we've now got
2904 // room in the read buffer.
2905 d->socketEngine->setReadNotificationEnabled(size == 0 || d->buffer.size() < size);
2906 }
2907}
2908
2909/*!
2910 Returns the state of the socket.
2911
2912 \sa error()
2913*/
2914QAbstractSocket::SocketState QAbstractSocket::state() const
2915{
2916 return d_func()->state;
2917}
2918
2919/*!
2920 Sets the state of the socket to \a state.
2921
2922 \sa state()
2923*/
2924void QAbstractSocket::setSocketState(SocketState state)
2925{
2926 d_func()->state = state;
2927}
2928
2929/*!
2930 Returns the socket type (TCP, UDP, or other).
2931
2932 \sa QTcpSocket, QUdpSocket
2933*/
2934QAbstractSocket::SocketType QAbstractSocket::socketType() const
2935{
2936 return d_func()->socketType;
2937}
2938
2939/*!
2940 Returns the type of error that last occurred.
2941
2942 \sa state(), errorString()
2943*/
2944QAbstractSocket::SocketError QAbstractSocket::error() const
2945{
2946 return d_func()->socketError;
2947}
2948
2949/*!
2950 Sets the type of error that last occurred to \a socketError.
2951
2952 \sa setSocketState(), setErrorString()
2953*/
2954void QAbstractSocket::setSocketError(SocketError socketError)
2955{
2956 d_func()->socketError = socketError;
2957}
2958
2959#ifndef QT_NO_NETWORKPROXY
2960/*!
2961 \since 4.1
2962
2963 Sets the explicit network proxy for this socket to \a networkProxy.
2964
2965 To disable the use of a proxy for this socket, use the
2966 QNetworkProxy::NoProxy proxy type:
2967
2968 \snippet code/src_network_socket_qabstractsocket.cpp 3
2969
2970 The default value for the proxy is QNetworkProxy::DefaultProxy,
2971 which means the socket will use the application settings: if a
2972 proxy is set with QNetworkProxy::setApplicationProxy, it will use
2973 that; otherwise, if a factory is set with
2974 QNetworkProxyFactory::setApplicationProxyFactory, it will query
2975 that factory with type QNetworkProxyQuery::TcpSocket.
2976
2977 \sa proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()
2978*/
2979void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
2980{
2981 Q_D(QAbstractSocket);
2982 d->proxy = networkProxy;
2983}
2984
2985/*!
2986 \since 4.1
2987
2988 Returns the network proxy for this socket.
2989 By default QNetworkProxy::DefaultProxy is used, which means this
2990 socket will query the default proxy settings for the application.
2991
2992 \sa setProxy(), QNetworkProxy, QNetworkProxyFactory
2993*/
2994QNetworkProxy QAbstractSocket::proxy() const
2995{
2996 Q_D(const QAbstractSocket);
2997 return d->proxy;
2998}
2999
3000/*!
3001 \since 5.13
3002
3003 Returns the protocol tag for this socket.
3004 If the protocol tag is set then this is passed to QNetworkProxyQuery
3005 when this is created internally to indicate the protocol tag to be
3006 used.
3007
3008 \sa setProtocolTag(), QNetworkProxyQuery
3009*/
3010
3011QString QAbstractSocket::protocolTag() const
3012{
3013 Q_D(const QAbstractSocket);
3014 return d->protocolTag;
3015}
3016
3017/*!
3018 \since 5.13
3019
3020 Sets the protocol tag for this socket to \a tag.
3021
3022 \sa protocolTag()
3023*/
3024
3025void QAbstractSocket::setProtocolTag(const QString &tag)
3026{
3027 Q_D(QAbstractSocket);
3028 d->protocolTag = tag;
3029}
3030
3031#endif // QT_NO_NETWORKPROXY
3032
3033#ifndef QT_NO_DEBUG_STREAM
3034Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
3035{
3036 QDebugStateSaver saver(debug);
3037 debug.resetFormat().nospace();
3038 switch (error) {
3039 case QAbstractSocket::ConnectionRefusedError:
3040 debug << "QAbstractSocket::ConnectionRefusedError";
3041 break;
3042 case QAbstractSocket::RemoteHostClosedError:
3043 debug << "QAbstractSocket::RemoteHostClosedError";
3044 break;
3045 case QAbstractSocket::HostNotFoundError:
3046 debug << "QAbstractSocket::HostNotFoundError";
3047 break;
3048 case QAbstractSocket::SocketAccessError:
3049 debug << "QAbstractSocket::SocketAccessError";
3050 break;
3051 case QAbstractSocket::SocketResourceError:
3052 debug << "QAbstractSocket::SocketResourceError";
3053 break;
3054 case QAbstractSocket::SocketTimeoutError:
3055 debug << "QAbstractSocket::SocketTimeoutError";
3056 break;
3057 case QAbstractSocket::DatagramTooLargeError:
3058 debug << "QAbstractSocket::DatagramTooLargeError";
3059 break;
3060 case QAbstractSocket::NetworkError:
3061 debug << "QAbstractSocket::NetworkError";
3062 break;
3063 case QAbstractSocket::AddressInUseError:
3064 debug << "QAbstractSocket::AddressInUseError";
3065 break;
3066 case QAbstractSocket::SocketAddressNotAvailableError:
3067 debug << "QAbstractSocket::SocketAddressNotAvailableError";
3068 break;
3069 case QAbstractSocket::UnsupportedSocketOperationError:
3070 debug << "QAbstractSocket::UnsupportedSocketOperationError";
3071 break;
3072 case QAbstractSocket::UnfinishedSocketOperationError:
3073 debug << "QAbstractSocket::UnfinishedSocketOperationError";
3074 break;
3075 case QAbstractSocket::ProxyAuthenticationRequiredError:
3076 debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
3077 break;
3078 case QAbstractSocket::UnknownSocketError:
3079 debug << "QAbstractSocket::UnknownSocketError";
3080 break;
3081 case QAbstractSocket::ProxyConnectionRefusedError:
3082 debug << "QAbstractSocket::ProxyConnectionRefusedError";
3083 break;
3084 case QAbstractSocket::ProxyConnectionClosedError:
3085 debug << "QAbstractSocket::ProxyConnectionClosedError";
3086 break;
3087 case QAbstractSocket::ProxyConnectionTimeoutError:
3088 debug << "QAbstractSocket::ProxyConnectionTimeoutError";
3089 break;
3090 case QAbstractSocket::ProxyNotFoundError:
3091 debug << "QAbstractSocket::ProxyNotFoundError";
3092 break;
3093 case QAbstractSocket::ProxyProtocolError:
3094 debug << "QAbstractSocket::ProxyProtocolError";
3095 break;
3096 default:
3097 debug << "QAbstractSocket::SocketError(" << int(error) << ')';
3098 break;
3099 }
3100 return debug;
3101}
3102
3103Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state)
3104{
3105 QDebugStateSaver saver(debug);
3106 debug.resetFormat().nospace();
3107 switch (state) {
3108 case QAbstractSocket::UnconnectedState:
3109 debug << "QAbstractSocket::UnconnectedState";
3110 break;
3111 case QAbstractSocket::HostLookupState:
3112 debug << "QAbstractSocket::HostLookupState";
3113 break;
3114 case QAbstractSocket::ConnectingState:
3115 debug << "QAbstractSocket::ConnectingState";
3116 break;
3117 case QAbstractSocket::ConnectedState:
3118 debug << "QAbstractSocket::ConnectedState";
3119 break;
3120 case QAbstractSocket::BoundState:
3121 debug << "QAbstractSocket::BoundState";
3122 break;
3123 case QAbstractSocket::ListeningState:
3124 debug << "QAbstractSocket::ListeningState";
3125 break;
3126 case QAbstractSocket::ClosingState:
3127 debug << "QAbstractSocket::ClosingState";
3128 break;
3129 default:
3130 debug << "QAbstractSocket::SocketState(" << int(state) << ')';
3131 break;
3132 }
3133 return debug;
3134}
3135#endif
3136
3137QT_END_NAMESPACE
3138
3139#include "moc_qabstractsocket.cpp"
3140

source code of qtbase/src/network/socket/qabstractsocket.cpp