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