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