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