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