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