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