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