PageRenderTime 67ms CodeModel.GetById 4ms app.highlight 50ms RepoModel.GetById 1ms app.codeStats 1ms

/src/qt/qtbase/src/network/socket/qabstractsocket.cpp

https://code.google.com/
C++ | 3003 lines | 1595 code | 275 blank | 1133 comment | 401 complexity | c21b748f31677e371bdb50995a6dafef MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/****************************************************************************
   2**
   3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
   4** Contact: http://www.qt-project.org/legal
   5**
   6** This file is part of the QtNetwork module of the Qt Toolkit.
   7**
   8** $QT_BEGIN_LICENSE:LGPL$
   9** Commercial License Usage
  10** Licensees holding valid commercial Qt licenses may use this file in
  11** accordance with the commercial license agreement provided with the
  12** Software or, alternatively, in accordance with the terms contained in
  13** a written agreement between you and Digia.  For licensing terms and
  14** conditions see http://qt.digia.com/licensing.  For further information
  15** use the contact form at http://qt.digia.com/contact-us.
  16**
  17** GNU Lesser General Public License Usage
  18** Alternatively, this file may be used under the terms of the GNU Lesser
  19** General Public License version 2.1 as published by the Free Software
  20** Foundation and appearing in the file LICENSE.LGPL included in the
  21** packaging of this file.  Please review the following information to
  22** ensure the GNU Lesser General Public License version 2.1 requirements
  23** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24**
  25** In addition, as a special exception, Digia gives you certain additional
  26** rights.  These rights are described in the Digia Qt LGPL Exception
  27** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28**
  29** GNU General Public License Usage
  30** Alternatively, this file may be used under the terms of the GNU
  31** General Public License version 3.0 as published by the Free Software
  32** Foundation and appearing in the file LICENSE.GPL included in the
  33** packaging of this file.  Please review the following information to
  34** ensure the GNU General Public License version 3.0 requirements will be
  35** met: http://www.gnu.org/copyleft/gpl.html.
  36**
  37**
  38** $QT_END_LICENSE$
  39**
  40****************************************************************************/
  41
  42//#define QABSTRACTSOCKET_DEBUG
  43
  44/*!
  45    \class QAbstractSocket
  46
  47    \brief The QAbstractSocket class provides the base functionality
  48    common to all socket types.
  49
  50    \reentrant
  51    \ingroup network
  52    \inmodule QtNetwork
  53
  54    QAbstractSocket is the base class for QTcpSocket and QUdpSocket
  55    and contains all common functionality of these two classes. If
  56    you need a socket, you have two options:
  57
  58    \list
  59    \li  Instantiate QTcpSocket or QUdpSocket.
  60    \li  Create a native socket descriptor, instantiate
  61        QAbstractSocket, and call setSocketDescriptor() to wrap the
  62        native socket.
  63    \endlist
  64
  65    TCP (Transmission Control Protocol) is a reliable,
  66    stream-oriented, connection-oriented transport protocol. UDP
  67    (User Datagram Protocol) is an unreliable, datagram-oriented,
  68    connectionless protocol. In practice, this means that TCP is
  69    better suited for continuous transmission of data, whereas the
  70    more lightweight UDP can be used when reliability isn't
  71    important.
  72
  73    QAbstractSocket's API unifies most of the differences between the
  74    two protocols. For example, although UDP is connectionless,
  75    connectToHost() establishes a virtual connection for UDP sockets,
  76    enabling you to use QAbstractSocket in more or less the same way
  77    regardless of the underlying protocol. Internally,
  78    QAbstractSocket remembers the address and port passed to
  79    connectToHost(), and functions like read() and write() use these
  80    values.
  81
  82    At any time, QAbstractSocket has a state (returned by
  83    state()). The initial state is UnconnectedState. After
  84    calling connectToHost(), the socket first enters
  85    HostLookupState. If the host is found, QAbstractSocket enters
  86    ConnectingState and emits the hostFound() signal. When the
  87    connection has been established, it enters ConnectedState and
  88    emits connected(). If an error occurs at any stage, error() is
  89    emitted. Whenever the state changes, stateChanged() is emitted.
  90    For convenience, isValid() returns \c true if the socket is ready for
  91    reading and writing, but note that the socket's state must be
  92    ConnectedState before reading and writing can occur.
  93
  94    Read or write data by calling read() or write(), or use the
  95    convenience functions readLine() and readAll(). QAbstractSocket
  96    also inherits getChar(), putChar(), and ungetChar() from
  97    QIODevice, which work on single bytes. The bytesWritten() signal
  98    is emitted when data has been written to the socket. Note that Qt does
  99    not limit the write buffer size. You can monitor its size by listening
 100    to this signal.
 101
 102    The readyRead() signal is emitted every time a new chunk of data
 103    has arrived. bytesAvailable() then returns the number of bytes
 104    that are available for reading. Typically, you would connect the
 105    readyRead() signal to a slot and read all available data there.
 106    If you don't read all the data at once, the remaining data will
 107    still be available later, and any new incoming data will be
 108    appended to QAbstractSocket's internal read buffer. To limit the
 109    size of the read buffer, call setReadBufferSize().
 110
 111    To close the socket, call disconnectFromHost(). QAbstractSocket enters
 112    QAbstractSocket::ClosingState. After all pending data has been written to
 113    the socket, QAbstractSocket actually closes the socket, enters
 114    QAbstractSocket::ClosedState, and emits disconnected(). If you want to
 115    abort a connection immediately, discarding all pending data, call abort()
 116    instead. If the remote host closes the connection, QAbstractSocket will
 117    emit error(QAbstractSocket::RemoteHostClosedError), during which the socket
 118    state will still be ConnectedState, and then the disconnected() signal
 119    will be emitted.
 120
 121    The port and address of the connected peer is fetched by calling
 122    peerPort() and peerAddress(). peerName() returns the host name of
 123    the peer, as passed to connectToHost(). localPort() and
 124    localAddress() return the port and address of the local socket.
 125
 126    QAbstractSocket provides a set of functions that suspend the
 127    calling thread until certain signals are emitted. These functions
 128    can be used to implement blocking sockets:
 129
 130    \list
 131    \li waitForConnected() blocks until a connection has been established.
 132
 133    \li waitForReadyRead() blocks until new data is available for
 134    reading.
 135
 136    \li waitForBytesWritten() blocks until one payload of data has been
 137    written to the socket.
 138
 139    \li waitForDisconnected() blocks until the connection has closed.
 140    \endlist
 141
 142    We show an example:
 143
 144    \snippet network/tcpwait.cpp 0
 145
 146    If \l{QIODevice::}{waitForReadyRead()} returns \c false, the
 147    connection has been closed or an error has occurred.
 148
 149    Programming with a blocking socket is radically different from
 150    programming with a non-blocking socket. A blocking socket doesn't
 151    require an event loop and typically leads to simpler code.
 152    However, in a GUI application, blocking sockets should only be
 153    used in non-GUI threads, to avoid freezing the user interface.
 154    See the \l fortuneclient and \l blockingfortuneclient
 155    examples for an overview of both approaches.
 156
 157    \note We discourage the use of the blocking functions together
 158    with signals. One of the two possibilities should be used.
 159
 160    QAbstractSocket can be used with QTextStream and QDataStream's
 161    stream operators (operator<<() and operator>>()). There is one
 162    issue to be aware of, though: You must make sure that enough data
 163    is available before attempting to read it using operator>>().
 164
 165    \sa QNetworkAccessManager, QTcpServer
 166*/
 167
 168/*!
 169    \fn void QAbstractSocket::hostFound()
 170
 171    This signal is emitted after connectToHost() has been called and
 172    the host lookup has succeeded.
 173
 174    \note Since Qt 4.6.3 QAbstractSocket may emit hostFound()
 175    directly from the connectToHost() call since a DNS result could have been
 176    cached.
 177
 178    \sa connected()
 179*/
 180
 181/*!
 182    \fn void QAbstractSocket::connected()
 183
 184    This signal is emitted after connectToHost() has been called and
 185    a connection has been successfully established.
 186
 187    \note On some operating systems the connected() signal may
 188    be directly emitted from the connectToHost() call for connections
 189    to the localhost.
 190
 191    \sa connectToHost(), disconnected()
 192*/
 193
 194/*!
 195    \fn void QAbstractSocket::disconnected()
 196
 197    This signal is emitted when the socket has been disconnected.
 198
 199    \warning If you need to delete the sender() of this signal in a slot connected
 200    to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
 201
 202    \sa connectToHost(), disconnectFromHost(), abort()
 203*/
 204
 205/*!
 206    \fn void QAbstractSocket::error(QAbstractSocket::SocketError socketError)
 207
 208    This signal is emitted after an error occurred. The \a socketError
 209    parameter describes the type of error that occurred.
 210
 211    When this signal is emitted, the socket may not be ready for a reconnect
 212    attempt. In that case, attempts to reconnect should be done from the event
 213    loop. For example, use a QTimer::singleShot() with 0 as the timeout.
 214
 215    QAbstractSocket::SocketError is not a registered metatype, so for queued
 216    connections, you will have to register it with Q_DECLARE_METATYPE() and
 217    qRegisterMetaType().
 218
 219    \sa error(), errorString(), {Creating Custom Qt Types}
 220*/
 221
 222/*!
 223    \fn void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)
 224
 225    This signal is emitted whenever QAbstractSocket's state changes.
 226    The \a socketState parameter is the new state.
 227
 228    QAbstractSocket::SocketState is not a registered metatype, so for queued
 229    connections, you will have to register it with Q_DECLARE_METATYPE() and
 230    qRegisterMetaType().
 231
 232    \sa state(), {Creating Custom Qt Types}
 233*/
 234
 235/*!
 236    \fn void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
 237    \since 4.3
 238
 239    This signal can be emitted when a \a proxy that requires
 240    authentication is used. The \a authenticator object can then be
 241    filled in with the required details to allow authentication and
 242    continue the connection.
 243
 244    \note It is not possible to use a QueuedConnection to connect to
 245    this signal, as the connection will fail if the authenticator has
 246    not been filled in with new information when the signal returns.
 247
 248    \sa QAuthenticator, QNetworkProxy
 249*/
 250
 251/*!
 252    \enum QAbstractSocket::NetworkLayerProtocol
 253
 254    This enum describes the network layer protocol values used in Qt.
 255
 256    \value IPv4Protocol IPv4
 257    \value IPv6Protocol IPv6
 258    \value AnyIPProtocol Either IPv4 or IPv6
 259    \value UnknownNetworkLayerProtocol Other than IPv4 and IPv6
 260
 261    \sa QHostAddress::protocol()
 262*/
 263
 264/*!
 265    \enum QAbstractSocket::SocketType
 266
 267    This enum describes the transport layer protocol.
 268
 269    \value TcpSocket TCP
 270    \value UdpSocket UDP
 271    \value UnknownSocketType Other than TCP and UDP
 272
 273    \sa QAbstractSocket::socketType()
 274*/
 275
 276/*!
 277    \enum QAbstractSocket::SocketError
 278
 279    This enum describes the socket errors that can occur.
 280
 281    \value ConnectionRefusedError The connection was refused by the
 282           peer (or timed out).
 283    \value RemoteHostClosedError The remote host closed the
 284           connection. Note that the client socket (i.e., this socket)
 285           will be closed after the remote close notification has
 286           been sent.
 287    \value HostNotFoundError The host address was not found.
 288    \value SocketAccessError The socket operation failed because the
 289           application lacked the required privileges.
 290    \value SocketResourceError The local system ran out of resources
 291           (e.g., too many sockets).
 292    \value SocketTimeoutError The socket operation timed out.
 293    \value DatagramTooLargeError The datagram was larger than the
 294           operating system's limit (which can be as low as 8192
 295           bytes).
 296    \value NetworkError An error occurred with the network (e.g., the
 297           network cable was accidentally plugged out).
 298    \value AddressInUseError The address specified to QAbstractSocket::bind() is
 299           already in use and was set to be exclusive.
 300    \value SocketAddressNotAvailableError The address specified to
 301           QAbstractSocket::bind() does not belong to the host.
 302    \value UnsupportedSocketOperationError The requested socket operation is
 303           not supported by the local operating system (e.g., lack of
 304           IPv6 support).
 305    \value ProxyAuthenticationRequiredError The socket is using a proxy, and
 306           the proxy requires authentication.
 307    \value SslHandshakeFailedError The SSL/TLS handshake failed, so
 308           the connection was closed (only used in QSslSocket)
 309    \value UnfinishedSocketOperationError Used by QAbstractSocketEngine only,
 310           The last operation attempted has not finished yet (still in progress in
 311            the background).
 312    \value ProxyConnectionRefusedError Could not contact the proxy server because
 313           the connection to that server was denied
 314    \value ProxyConnectionClosedError The connection to the proxy server was closed
 315           unexpectedly (before the connection to the final peer was established)
 316    \value ProxyConnectionTimeoutError The connection to the proxy server timed out
 317           or the proxy server stopped responding in the authentication phase.
 318    \value ProxyNotFoundError The proxy address set with setProxy() (or the application
 319           proxy) was not found.
 320    \value ProxyProtocolError The connection negotiation with the proxy server failed,
 321           because the response from the proxy server could not be understood.
 322    \value OperationError An operation was attempted while the socket was in a state that
 323           did not permit it.
 324    \value SslInternalError The SSL library being used reported an internal error. This is
 325           probably the result of a bad installation or misconfiguration of the library.
 326    \value SslInvalidUserDataError Invalid data (certificate, key, cypher, etc.) was
 327           provided and its use resulted in an error in the SSL library.
 328    \value TemporaryError A temporary error occurred (e.g., operation would block and socket
 329           is non-blocking).
 330
 331    \value UnknownSocketError An unidentified error occurred.
 332    \sa QAbstractSocket::error()
 333*/
 334
 335/*!
 336    \enum QAbstractSocket::SocketState
 337
 338    This enum describes the different states in which a socket can be.
 339
 340    \value UnconnectedState The socket is not connected.
 341    \value HostLookupState The socket is performing a host name lookup.
 342    \value ConnectingState The socket has started establishing a connection.
 343    \value ConnectedState A connection is established.
 344    \value BoundState The socket is bound to an address and port.
 345    \value ClosingState The socket is about to close (data may still
 346    be waiting to be written).
 347    \value ListeningState For internal use only.
 348
 349    \sa QAbstractSocket::state()
 350*/
 351
 352/*!
 353    \enum QAbstractSocket::SocketOption
 354    \since 4.6
 355
 356    This enum represents the options that can be set on a socket.  If
 357    desired, they can be set after having received the connected()
 358    signal from the socket or after having received a new socket from
 359    a QTcpServer.
 360
 361    \value LowDelayOption Try to optimize the socket for low
 362    latency. For a QTcpSocket this would set the TCP_NODELAY option
 363    and disable Nagle's algorithm. Set this to 1 to enable.
 364
 365    \value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE
 366    socket option
 367
 368    \value MulticastTtlOption Set this to an integer value to set
 369    IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
 370
 371    \value MulticastLoopbackOption Set this to 1 to enable the
 372    IP_MULTICAST_LOOP (multicast loopback) socket option.
 373
 374    \value TypeOfServiceOption This option is not supported on
 375    Windows. This maps to the IP_TOS socket option. For possible values,
 376    see table below.
 377
 378    \value SendBufferSizeSocketOption Sets the socket send buffer size
 379    in bytes at the OS level. This maps to the SO_SNDBUF socket option.
 380    This option does not affect the QIODevice or QAbstractSocket buffers.
 381    This enum value has been introduced in Qt 5.3.
 382
 383    \value ReceiveBufferSizeSocketOption Sets the socket receive
 384    buffer size in bytes at the OS level.
 385    This maps to the SO_RCVBUF socket option.
 386    This option does not affect the QIODevice or QAbstractSocket buffers
 387    (see \l{QAbstractSocket::}{setReadBufferSize()}).
 388    This enum value has been introduced in Qt 5.3.
 389
 390    Possible values for \e{TypeOfServiceOption} are:
 391
 392    \table
 393    \header \li Value \li Description
 394    \row \li 224 \li Network control
 395    \row \li 192 \li Internetwork control
 396    \row \li 160 \li CRITIC/ECP
 397    \row \li 128 \li Flash override
 398    \row \li 96 \li Flash
 399    \row \li 64 \li Immediate
 400    \row \li 32 \li Priority
 401    \row \li 0 \li Routine
 402    \endtable
 403
 404    \sa QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
 405*/
 406
 407/*! \enum QAbstractSocket::BindFlag
 408    \since 5.0
 409
 410    This enum describes the different flags you can pass to modify the
 411    behavior of QAbstractSocket::bind().
 412
 413    \value ShareAddress Allow other services to bind to the same address
 414    and port. This is useful when multiple processes share
 415    the load of a single service by listening to the same address and port
 416    (e.g., a web server with several pre-forked listeners can greatly
 417    improve response time). However, because any service is allowed to
 418    rebind, this option is subject to certain security considerations.
 419    Note that by combining this option with ReuseAddressHint, you will
 420    also allow your service to rebind an existing shared address. On
 421    Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows,
 422    this option is ignored.
 423
 424    \value DontShareAddress Bind the address and port exclusively, so that
 425    no other services are allowed to rebind. By passing this option to
 426    QAbstractSocket::bind(), you are guaranteed that on successs, your service
 427    is the only one that listens to the address and port. No services are
 428    allowed to rebind, even if they pass ReuseAddressHint. This option
 429    provides more security than ShareAddress, but on certain operating
 430    systems, it requires you to run the server with administrator privileges.
 431    On Unix and Mac OS X, not sharing is the default behavior for binding
 432    an address and port, so this option is ignored. On Windows, this
 433    option uses the SO_EXCLUSIVEADDRUSE socket option.
 434
 435    \value ReuseAddressHint Provides a hint to QAbstractSocket that it should try
 436    to rebind the service even if the address and port are already bound by
 437    another socket. On Windows, this is equivalent to the SO_REUSEADDR
 438    socket option. On Unix, this option is ignored.
 439
 440    \value DefaultForPlatform The default option for the current platform.
 441    On Unix and Mac OS X, this is equivalent to (DontShareAddress
 442    + ReuseAddressHint), and on Windows, its equivalent to ShareAddress.
 443*/
 444
 445/*! \enum QAbstractSocket::PauseMode
 446    \since 5.0
 447
 448    This enum describes the behavior of when the socket should hold
 449    back with continuing data transfer.
 450    The only notification currently supported is QSslSocket::sslErrors().
 451
 452    \value PauseNever Do not pause data transfer on the socket. This is the
 453    default and matches the behaviour of Qt 4.
 454    \value PauseOnSslErrors Pause data transfer on the socket upon receiving an
 455    SSL error notification. I.E. QSslSocket::sslErrors().
 456*/
 457
 458#include "qabstractsocket.h"
 459#include "qabstractsocket_p.h"
 460
 461#include "private/qhostinfo_p.h"
 462#include "private/qnetworksession_p.h"
 463
 464#include <qabstracteventdispatcher.h>
 465#include <qhostaddress.h>
 466#include <qhostinfo.h>
 467#include <qmetaobject.h>
 468#include <qpointer.h>
 469#include <qtimer.h>
 470#include <qelapsedtimer.h>
 471#include <qscopedvaluerollback.h>
 472
 473#ifndef QT_NO_SSL
 474#include <QtNetwork/qsslsocket.h>
 475#endif
 476
 477#include <private/qthread_p.h>
 478
 479#ifdef QABSTRACTSOCKET_DEBUG
 480#include <qdebug.h>
 481#endif
 482
 483#include <time.h>
 484
 485#define Q_CHECK_SOCKETENGINE(returnValue) do { \
 486    if (!d->socketEngine) { \
 487        return returnValue; \
 488    } } while (0)
 489
 490#ifndef QABSTRACTSOCKET_BUFFERSIZE
 491#define QABSTRACTSOCKET_BUFFERSIZE 32768
 492#endif
 493#define QT_CONNECT_TIMEOUT 30000
 494#define QT_TRANSFER_TIMEOUT 120000
 495
 496QT_BEGIN_NAMESPACE
 497
 498#if defined QABSTRACTSOCKET_DEBUG
 499QT_BEGIN_INCLUDE_NAMESPACE
 500#include <qstring.h>
 501#include <ctype.h>
 502QT_END_INCLUDE_NAMESPACE
 503
 504/*
 505    Returns a human readable representation of the first \a len
 506    characters in \a data.
 507*/
 508static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
 509{
 510    if (!data) return "(null)";
 511    QByteArray out;
 512    for (int i = 0; i < len; ++i) {
 513        char c = data[i];
 514        if (isprint(int(uchar(c)))) {
 515            out += c;
 516        } else switch (c) {
 517        case '\n': out += "\\n"; break;
 518        case '\r': out += "\\r"; break;
 519        case '\t': out += "\\t"; break;
 520        default:
 521            QString tmp;
 522            tmp.sprintf("\\%o", c);
 523            out += tmp.toLatin1();
 524        }
 525    }
 526
 527    if (len < maxLength)
 528        out += "...";
 529
 530    return out;
 531}
 532#endif
 533
 534static bool isProxyError(QAbstractSocket::SocketError error)
 535{
 536    switch (error) {
 537    case QAbstractSocket::ProxyAuthenticationRequiredError:
 538    case QAbstractSocket::ProxyConnectionRefusedError:
 539    case QAbstractSocket::ProxyConnectionClosedError:
 540    case QAbstractSocket::ProxyConnectionTimeoutError:
 541    case QAbstractSocket::ProxyNotFoundError:
 542    case QAbstractSocket::ProxyProtocolError:
 543        return true;
 544    default:
 545        return false;
 546    }
 547}
 548
 549/*! \internal
 550
 551    Constructs a QAbstractSocketPrivate. Initializes all members.
 552*/
 553QAbstractSocketPrivate::QAbstractSocketPrivate()
 554    : readSocketNotifierCalled(false),
 555      readSocketNotifierState(false),
 556      readSocketNotifierStateSet(false),
 557      emittedReadyRead(false),
 558      emittedBytesWritten(false),
 559      abortCalled(false),
 560      closeCalled(false),
 561      pendingClose(false),
 562      pauseMode(QAbstractSocket::PauseNever),
 563      port(0),
 564      localPort(0),
 565      peerPort(0),
 566      socketEngine(0),
 567      cachedSocketDescriptor(-1),
 568      readBufferMaxSize(0),
 569      writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
 570      isBuffered(false),
 571      blockingTimeout(30000),
 572      connectTimer(0),
 573      disconnectTimer(0),
 574      connectTimeElapsed(0),
 575      hostLookupId(-1),
 576      socketType(QAbstractSocket::UnknownSocketType),
 577      state(QAbstractSocket::UnconnectedState),
 578      socketError(QAbstractSocket::UnknownSocketError),
 579      preferredNetworkLayerProtocol(QAbstractSocket::UnknownNetworkLayerProtocol)
 580{
 581}
 582
 583/*! \internal
 584
 585    Destructs the QAbstractSocket. If the socket layer is open, it
 586    will be reset.
 587*/
 588QAbstractSocketPrivate::~QAbstractSocketPrivate()
 589{
 590}
 591
 592/*! \internal
 593
 594    Resets the socket layer and deletes any socket notifiers.
 595*/
 596void QAbstractSocketPrivate::resetSocketLayer()
 597{
 598#if defined (QABSTRACTSOCKET_DEBUG)
 599    qDebug("QAbstractSocketPrivate::resetSocketLayer()");
 600#endif
 601
 602    if (socketEngine) {
 603        socketEngine->close();
 604        socketEngine->disconnect();
 605        delete socketEngine;
 606        socketEngine = 0;
 607        cachedSocketDescriptor = -1;
 608    }
 609    if (connectTimer)
 610        connectTimer->stop();
 611    if (disconnectTimer)
 612        disconnectTimer->stop();
 613}
 614
 615/*! \internal
 616
 617    Initializes the socket layer to by of type \a type, using the
 618    network layer protocol \a protocol. Resets the socket layer first
 619    if it's already initialized. Sets up the socket notifiers.
 620*/
 621bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
 622{
 623#ifdef QT_NO_NETWORKPROXY
 624    // this is here to avoid a duplication of the call to createSocketEngine below
 625    static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
 626#endif
 627
 628    Q_Q(QAbstractSocket);
 629#if defined (QABSTRACTSOCKET_DEBUG)
 630    QString typeStr;
 631    if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
 632    else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
 633    else typeStr = QLatin1String("UnknownSocketType");
 634    QString protocolStr;
 635    if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
 636    else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
 637    else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
 638#endif
 639
 640    resetSocketLayer();
 641    socketEngine = QAbstractSocketEngine::createSocketEngine(q->socketType(), proxyInUse, q);
 642    if (!socketEngine) {
 643        socketError = QAbstractSocket::UnsupportedSocketOperationError;
 644        q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
 645        return false;
 646    }
 647#ifndef QT_NO_BEARERMANAGEMENT
 648    //copy network session down to the socket engine (if it has been set)
 649    socketEngine->setProperty("_q_networksession", q->property("_q_networksession"));
 650#endif
 651    if (!socketEngine->initialize(q->socketType(), protocol)) {
 652#if defined (QABSTRACTSOCKET_DEBUG)
 653        qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
 654               typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
 655               socketEngine->errorString().toLatin1().constData());
 656#endif
 657        socketError = socketEngine->error();
 658        q->setErrorString(socketEngine->errorString());
 659        return false;
 660    }
 661
 662    if (threadData->hasEventDispatcher())
 663        socketEngine->setReceiver(this);
 664
 665#if defined (QABSTRACTSOCKET_DEBUG)
 666    qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
 667           typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
 668#endif
 669    return true;
 670}
 671
 672/*! \internal
 673
 674    Slot connected to the read socket notifier. This slot is called
 675    when new data is available for reading, or when the socket has
 676    been closed. Handles recursive calls.
 677*/
 678bool QAbstractSocketPrivate::canReadNotification()
 679{
 680    Q_Q(QAbstractSocket);
 681#if defined (QABSTRACTSOCKET_DEBUG)
 682    qDebug("QAbstractSocketPrivate::canReadNotification()");
 683#endif
 684
 685    // Prevent recursive calls
 686    if (readSocketNotifierCalled) {
 687        if (!readSocketNotifierStateSet) {
 688            readSocketNotifierStateSet = true;
 689            readSocketNotifierState = socketEngine->isReadNotificationEnabled();
 690            socketEngine->setReadNotificationEnabled(false);
 691        }
 692    }
 693    QScopedValueRollback<bool> rsncrollback(readSocketNotifierCalled);
 694    readSocketNotifierCalled = true;
 695
 696    if (!isBuffered)
 697        socketEngine->setReadNotificationEnabled(false);
 698
 699    // If buffered, read data from the socket into the read buffer
 700    qint64 newBytes = 0;
 701    if (isBuffered) {
 702        // Return if there is no space in the buffer
 703        if (readBufferMaxSize && buffer.size() >= readBufferMaxSize) {
 704#if defined (QABSTRACTSOCKET_DEBUG)
 705            qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
 706#endif
 707            return false;
 708        }
 709
 710        // If reading from the socket fails after getting a read
 711        // notification, close the socket.
 712        newBytes = buffer.size();
 713        if (!readFromSocket()) {
 714#if defined (QABSTRACTSOCKET_DEBUG)
 715            qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
 716#endif
 717            q->disconnectFromHost();
 718            return false;
 719        }
 720        newBytes = buffer.size() - newBytes;
 721
 722        // If read buffer is full, disable the read socket notifier.
 723        if (readBufferMaxSize && buffer.size() == readBufferMaxSize) {
 724            socketEngine->setReadNotificationEnabled(false);
 725        }
 726    }
 727
 728    // only emit readyRead() when not recursing, and only if there is data available
 729    bool hasData = newBytes > 0
 730#ifndef QT_NO_UDPSOCKET
 731        || (!isBuffered && socketType != QAbstractSocket::TcpSocket && socketEngine && socketEngine->hasPendingDatagrams())
 732#endif
 733        || (!isBuffered && socketType == QAbstractSocket::TcpSocket && socketEngine)
 734        ;
 735
 736    if (!emittedReadyRead && hasData) {
 737        QScopedValueRollback<bool> r(emittedReadyRead);
 738        emittedReadyRead = true;
 739        emit q->readyRead();
 740    }
 741
 742    // If we were closed as a result of the readyRead() signal,
 743    // return.
 744    if (state == QAbstractSocket::UnconnectedState || state == QAbstractSocket::ClosingState) {
 745#if defined (QABSTRACTSOCKET_DEBUG)
 746        qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
 747#endif
 748        return true;
 749    }
 750
 751    if ((isBuffered || socketType != QAbstractSocket::TcpSocket) && socketEngine)
 752        socketEngine->setReadNotificationEnabled(readBufferMaxSize == 0 || readBufferMaxSize > q->bytesAvailable());
 753
 754    // reset the read socket notifier state if we reentered inside the
 755    // readyRead() connected slot.
 756    if (readSocketNotifierStateSet && socketEngine &&
 757        readSocketNotifierState != socketEngine->isReadNotificationEnabled()) {
 758        socketEngine->setReadNotificationEnabled(readSocketNotifierState);
 759        readSocketNotifierStateSet = false;
 760    }
 761    return true;
 762}
 763
 764/*! \internal
 765
 766    Slot connected to the close socket notifier. It's called when the
 767    socket is closed.
 768*/
 769void QAbstractSocketPrivate::canCloseNotification()
 770{
 771    Q_Q(QAbstractSocket);
 772
 773#if defined (QABSTRACTSOCKET_DEBUG)
 774    qDebug("QAbstractSocketPrivate::canCloseNotification()");
 775#endif
 776
 777    qint64 newBytes = 0;
 778    if (isBuffered) {
 779        // Try to read to the buffer, if the read fail we can close the socket.
 780        newBytes = buffer.size();
 781        if (!readFromSocket()) {
 782            q->disconnectFromHost();
 783            return;
 784        }
 785        newBytes = buffer.size() - newBytes;
 786        if (newBytes) {
 787            // If there was still some data to be read from the socket
 788            // then we could get another FD_READ. The disconnect will
 789            // then occur when we read from the socket again and fail
 790            // in canReadNotification or by the manually created
 791            // closeNotification below.
 792            emit q->readyRead();
 793
 794            QMetaObject::invokeMethod(socketEngine, "closeNotification", Qt::QueuedConnection);
 795        }
 796    } else if (socketType == QAbstractSocket::TcpSocket && socketEngine) {
 797        emit q->readyRead();
 798    }
 799}
 800
 801
 802/*! \internal
 803
 804    Slot connected to the write socket notifier. It's called during a
 805    delayed connect or when the socket is ready for writing.
 806*/
 807bool QAbstractSocketPrivate::canWriteNotification()
 808{
 809#if defined (Q_OS_WIN)
 810    if (socketEngine && socketEngine->isWriteNotificationEnabled())
 811        socketEngine->setWriteNotificationEnabled(false);
 812#endif
 813
 814#if defined (QABSTRACTSOCKET_DEBUG)
 815    qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
 816#endif
 817    int tmp = writeBuffer.size();
 818    flush();
 819
 820    if (socketEngine) {
 821#if defined (Q_OS_WIN)
 822        if (!writeBuffer.isEmpty())
 823            socketEngine->setWriteNotificationEnabled(true);
 824#else
 825        if (writeBuffer.isEmpty() && socketEngine->bytesToWrite() == 0)
 826            socketEngine->setWriteNotificationEnabled(false);
 827#endif
 828    }
 829
 830    return (writeBuffer.size() < tmp);
 831}
 832
 833/*! \internal
 834
 835    Slot connected to a notification of connection status
 836    change. Either we finished connecting or we failed to connect.
 837*/
 838void QAbstractSocketPrivate::connectionNotification()
 839{
 840    // If in connecting state, check if the connection has been
 841    // established, otherwise flush pending data.
 842    if (state == QAbstractSocket::ConnectingState) {
 843#if defined (QABSTRACTSOCKET_DEBUG)
 844        qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
 845#endif
 846        _q_testConnection();
 847    }
 848}
 849
 850/*! \internal
 851
 852    Writes pending data in the write buffers to the socket. The
 853    function writes as much as it can without blocking.
 854
 855    It is usually invoked by canWriteNotification after one or more
 856    calls to write().
 857
 858    Emits bytesWritten().
 859*/
 860bool QAbstractSocketPrivate::flush()
 861{
 862    Q_Q(QAbstractSocket);
 863    if (!socketEngine || !socketEngine->isValid() || (writeBuffer.isEmpty()
 864        && socketEngine->bytesToWrite() == 0)) {
 865#if defined (QABSTRACTSOCKET_DEBUG)
 866    qDebug("QAbstractSocketPrivate::flush() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
 867           (socketEngine && socketEngine->isValid()) ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
 868#endif
 869
 870        // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
 871        if (state == QAbstractSocket::ClosingState)
 872            q->disconnectFromHost();
 873
 874        return false;
 875    }
 876
 877    int nextSize = writeBuffer.nextDataBlockSize();
 878    const char *ptr = writeBuffer.readPointer();
 879
 880    // Attempt to write it all in one chunk.
 881    qint64 written = socketEngine->write(ptr, nextSize);
 882    if (written < 0) {
 883        socketError = socketEngine->error();
 884        q->setErrorString(socketEngine->errorString());
 885#if defined (QABSTRACTSOCKET_DEBUG)
 886        qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
 887#endif
 888        emit q->error(socketError);
 889        // an unexpected error so close the socket.
 890        q->abort();
 891        return false;
 892    }
 893
 894#if defined (QABSTRACTSOCKET_DEBUG)
 895    qDebug("QAbstractSocketPrivate::flush() %lld bytes written to the network",
 896           written);
 897#endif
 898
 899    // Remove what we wrote so far.
 900    writeBuffer.free(written);
 901    if (written > 0) {
 902        // Don't emit bytesWritten() recursively.
 903        if (!emittedBytesWritten) {
 904            QScopedValueRollback<bool> r(emittedBytesWritten);
 905            emittedBytesWritten = true;
 906            emit q->bytesWritten(written);
 907        }
 908    }
 909
 910    if (writeBuffer.isEmpty() && socketEngine && socketEngine->isWriteNotificationEnabled()
 911        && !socketEngine->bytesToWrite())
 912        socketEngine->setWriteNotificationEnabled(false);
 913    if (state == QAbstractSocket::ClosingState)
 914        q->disconnectFromHost();
 915
 916    return true;
 917}
 918
 919#ifndef QT_NO_NETWORKPROXY
 920/*! \internal
 921
 922    Resolve the proxy to its final value.
 923*/
 924void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
 925{
 926    QList<QNetworkProxy> proxies;
 927
 928    if (proxy.type() != QNetworkProxy::DefaultProxy) {
 929        // a non-default proxy was set with setProxy
 930        proxies << proxy;
 931    } else {
 932        // try the application settings instead
 933        QNetworkProxyQuery query(hostname, port, QString(),
 934                                 socketType == QAbstractSocket::TcpSocket ?
 935                                 QNetworkProxyQuery::TcpSocket :
 936                                 QNetworkProxyQuery::UdpSocket);
 937        proxies = QNetworkProxyFactory::proxyForQuery(query);
 938    }
 939
 940    // return the first that we can use
 941    foreach (const QNetworkProxy &p, proxies) {
 942        if (socketType == QAbstractSocket::UdpSocket &&
 943            (p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
 944            continue;
 945
 946        if (socketType == QAbstractSocket::TcpSocket &&
 947            (p.capabilities() & QNetworkProxy::TunnelingCapability) == 0)
 948            continue;
 949
 950        proxyInUse = p;
 951        return;
 952    }
 953
 954    // no proxy found
 955    // DefaultProxy here will raise an error
 956    proxyInUse = QNetworkProxy();
 957}
 958
 959/*!
 960    \internal
 961
 962    Starts the connection to \a host, like _q_startConnecting below,
 963    but without hostname resolution.
 964*/
 965void QAbstractSocketPrivate::startConnectingByName(const QString &host)
 966{
 967    Q_Q(QAbstractSocket);
 968    if (state == QAbstractSocket::ConnectingState || state == QAbstractSocket::ConnectedState)
 969        return;
 970
 971#if defined(QABSTRACTSOCKET_DEBUG)
 972    qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
 973#endif
 974
 975    // ### Let the socket engine drive this?
 976    state = QAbstractSocket::ConnectingState;
 977    emit q->stateChanged(state);
 978
 979    connectTimeElapsed = 0;
 980
 981    if (initSocketLayer(QAbstractSocket::UnknownNetworkLayerProtocol)) {
 982        if (socketEngine->connectToHostByName(host, port) ||
 983            socketEngine->state() == QAbstractSocket::ConnectingState) {
 984            cachedSocketDescriptor = socketEngine->socketDescriptor();
 985
 986            return;
 987        }
 988
 989        // failed to connect
 990        socketError = socketEngine->error();
 991        q->setErrorString(socketEngine->errorString());
 992    }
 993
 994    state = QAbstractSocket::UnconnectedState;
 995    emit q->error(socketError);
 996    emit q->stateChanged(state);
 997}
 998
 999#endif
1000
1001/*! \internal
1002
1003    Slot connected to QHostInfo::lookupHost() in connectToHost(). This
1004    function starts the process of connecting to any number of
1005    candidate IP addresses for the host, if it was found. Calls
1006    _q_connectToNextAddress().
1007*/
1008void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
1009{
1010    Q_Q(QAbstractSocket);
1011    addresses.clear();
1012    if (state != QAbstractSocket::HostLookupState)
1013        return;
1014
1015    if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
1016        qWarning("QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
1017    }
1018
1019    // Only add the addresses for the preferred network layer.
1020    // Or all if preferred network layer is not set.
1021    if (preferredNetworkLayerProtocol == QAbstractSocket::UnknownNetworkLayerProtocol || preferredNetworkLayerProtocol == QAbstractSocket::AnyIPProtocol) {
1022        addresses = hostInfo.addresses();
1023    } else {
1024        foreach (const QHostAddress &address, hostInfo.addresses())
1025            if (address.protocol() == preferredNetworkLayerProtocol)
1026                addresses += address;
1027    }
1028
1029
1030#if defined(QABSTRACTSOCKET_DEBUG)
1031    QString s = QLatin1String("{");
1032    for (int i = 0; i < addresses.count(); ++i) {
1033        if (i != 0) s += QLatin1String(", ");
1034        s += addresses.at(i).toString();
1035    }
1036    s += QLatin1Char('}');
1037    qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
1038#endif
1039
1040    // Try all addresses twice.
1041    addresses += addresses;
1042
1043    // If there are no addresses in the host list, report this to the
1044    // user.
1045    if (addresses.isEmpty()) {
1046#if defined(QABSTRACTSOCKET_DEBUG)
1047        qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
1048#endif
1049        state = QAbstractSocket::UnconnectedState;
1050        socketError = QAbstractSocket::HostNotFoundError;
1051        q->setErrorString(QAbstractSocket::tr("Host not found"));
1052        emit q->stateChanged(state);
1053        emit q->error(QAbstractSocket::HostNotFoundError);
1054        return;
1055    }
1056
1057    // Enter Connecting state (see also sn_write, which is called by
1058    // the write socket notifier after connect())
1059    state = QAbstractSocket::ConnectingState;
1060    emit q->stateChanged(state);
1061
1062    // Report the successful host lookup
1063    emit q->hostFound();
1064
1065    // Reset the total time spent connecting.
1066    connectTimeElapsed = 0;
1067
1068    // The addresses returned by the lookup will be tested one after
1069    // another by _q_connectToNextAddress().
1070    _q_connectToNextAddress();
1071}
1072
1073/*! \internal
1074
1075    Called by a queued or direct connection from _q_startConnecting() or
1076    _q_testConnection(), this function takes the first address of the
1077    pending addresses list and tries to connect to it. If the
1078    connection succeeds, QAbstractSocket will emit
1079    connected(). Otherwise, error(ConnectionRefusedError) or
1080    error(SocketTimeoutError) is emitted.
1081*/
1082void QAbstractSocketPrivate::_q_connectToNextAddress()
1083{
1084    Q_Q(QAbstractSocket);
1085    do {
1086        // Check for more pending addresses
1087        if (addresses.isEmpty()) {
1088#if defined(QABSTRACTSOCKET_DEBUG)
1089            qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
1090#endif
1091            state = QAbstractSocket::UnconnectedState;
1092            if (socketEngine) {
1093                if ((socketEngine->error() == QAbstractSocket::UnknownSocketError
1094#ifdef Q_OS_AIX
1095                     // On AIX, the second connect call will result in EINVAL and not
1096                     // ECONNECTIONREFUSED; although the meaning is the same.
1097                     || socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
1098#endif
1099                    ) && socketEngine->state() == QAbstractSocket::ConnectingState) {
1100                    socketError = QAbstractSocket::ConnectionRefusedError;
1101                    q->setErrorString(QAbstractSocket::tr("Connection refused"));
1102                } else {
1103                    socketError = socketEngine->error();
1104                    q->setErrorString(socketEngine->errorString());
1105                }
1106            } else {
1107//                socketError = QAbstractSocket::ConnectionRefusedError;
1108//                q->setErrorString(QAbstractSocket::tr("Connection refused"));
1109            }
1110            emit q->stateChanged(state);
1111            emit q->error(socketError);
1112            return;
1113        }
1114
1115        // Pick the first host address candidate
1116        host = addresses.takeFirst();
1117#if defined(QABSTRACTSOCKET_DEBUG)
1118        qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
1119               host.toString().toLatin1().constData(), port, addresses.count());
1120#endif
1121
1122        if (!initSocketLayer(host.protocol())) {
1123            // hope that the next address is better
1124#if defined(QABSTRACTSOCKET_DEBUG)
1125            qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
1126#endif
1127            continue;
1128        }
1129
1130        // Tries to connect to the address. If it succeeds immediately
1131        // (localhost address on BSD or any UDP connect), emit
1132        // connected() and return.
1133        if (socketEngine->connectToHost(host, port)) {
1134            //_q_testConnection();
1135            fetchConnectionParameters();
1136            return;
1137        }
1138
1139        // cache the socket descriptor even if we're not fully connected yet
1140        cachedSocketDescriptor = socketEngine->socketDescriptor();
1141
1142        // Check that we're in delayed connection state. If not, try
1143        // the next address
1144        if (socketEngine->state() != QAbstractSocket::ConnectingState) {
1145#if defined(QABSTRACTSOCKET_DEBUG)
1146            qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1147                   socketEngine->errorString().toLatin1().constData());
1148#endif
1149            continue;
1150        }
1151
1152        // Start the connect timer.
1153        if (threadData->hasEventDispatcher()) {
1154            if (!connectTimer) {
1155                connectTimer = new QTimer(q);
1156                QObject::connect(connectTimer, SIGNAL(timeout()),
1157                                 q, SLOT(_q_abortConnectionAttempt()),
1158                                 Qt::DirectConnection);
1159            }
1160            connectTimer->start(QT_CONNECT_TIMEOUT);
1161        }
1162
1163        // Wait for a write notification that will eventually call
1164        // _q_testConnection().
1165        socketEngine->setWriteNotificationEnabled(true);
1166        break;
1167    } while (state != QAbstractSocket::ConnectedState);
1168}
1169
1170/*! \internal
1171
1172    Tests if a connection has been established. If it has, connected()
1173    is emitted. Otherwise, _q_connectToNextAddress() is invoked.
1174*/
1175void QAbstractSocketPrivate::_q_testConnection()
1176{
1177    if (socketEngine) {
1178        if (threadData->hasEventDispatcher()) {
1179            if (connectTimer)
1180                connectTimer->stop();
1181        }
1182
1183        if (socketEngine->state() == QAbstractSocket::ConnectedState) {
1184            // Fetch the parameters if our connection is completed;
1185            // otherwise, fall out and try the next address.
1186            fetchConnectionParameters();
1187            if (pendingClose) {
1188                q_func()->disconnectFromHost();
1189                pendingClose = false;
1190            }
1191            return;
1192        }
1193
1194        // don't retry the other addresses if we had a proxy error
1195        if (isProxyError(socketEngine->error()))
1196            addresses.clear();
1197    }
1198
1199    if (threadData->hasEventDispatcher()) {
1200        if (connectTimer)
1201            connectTimer->stop();
1202    }
1203
1204#if defined(QABSTRACTSOCKET_DEBUG)
1205    qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1206           " checking for alternative addresses");
1207#endif
1208    _q_connectToNextAddress();
1209}
1210
1211/*! \internal
1212
1213    This function is called after a certain number of seconds has
1214    passed while waiting for a connection. It simply tests the
1215    connection, and continues to the next address if the connection
1216    failed.
1217*/
1218void QAbstractSocketPrivate::_q_abortConnectionAttempt()
1219{
1220    Q_Q(QAbstractSocket);
1221#if defined(QABSTRACTSOCKET_DEBUG)
1222    qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1223#endif
1224    if (socketEngine)
1225        socketEngine->setWriteNotificationEnabled(false);
1226
1227    connectTimer->stop();
1228
1229    if (addresses.isEmpty()) {
1230        state = QAbstractSocket::UnconnectedState;
1231        socketError = QAbstractSocket::SocketTimeoutError;
1232        q->setErrorString(QAbstractSocket::tr("Connection timed out"));
1233        emit q->stateChanged(state);
1234        emit q->error(socketError);
1235    } else {
1236        _q_connectToNextAddress();
1237    }
1238}
1239
1240void QAbstractSocketPrivate::_q_forceDisconnect()
1241{
1242    Q_Q(QAbstractSocket);
1243    if (socketEngine && socketEngine->isValid() && state == QAbstractSocket::ClosingState) {
1244        socketEngine->close();
1245        q->disconnectFromHost();
1246    }
1247}
1248
1249/*! \internal
1250
1251    Reads data from the socket layer into the read buffer. Returns
1252    true on success; otherwise false.
1253*/
1254bool QAbstractSocketPrivate::readFromSocket()
1255{
1256    Q_Q(QAbstractSocket);
1257    // Find how many bytes we can read from the socket layer.
1258    qint64 bytesToRead = socketEngine->bytesAvailable();
1259    if (bytesToRead == 0) {
1260        // Under heavy load, certain conditions can trigger read notifications
1261        // for socket notifiers on which there is no activity. If we continue
1262        // to read 0 bytes from the socket, we will trigger behavior similar
1263        // to that which signals a remote close. When we hit this condition,
1264        // we try to read 4k of data from the socket, which will give us either
1265        // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1266        // host has _not_ disappeared).
1267        bytesToRead = 4096;
1268    }
1269    if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size()))
1270        bytesToRead = readBufferMaxSize - buffer.size();
1271
1272#if defined(QABSTRACTSOCKET_DEBUG)
1273    qDebug("QAbstractSocketPrivate::readFromSocket() about to read %d bytes",
1274           int(bytesToRead));
1275#endif
1276
1277    // Read from the socket, store data in the read buffer.
1278    char *ptr = buffer.reserve(bytesToRead);
1279    qint64 readBytes = socketEngine->read(ptr, bytesToRead);
1280    if (readBytes == -2) {
1281        // No bytes currently available for reading.
1282        buffer.chop(bytesToRead);
1283        return true;
1284    }
1285    buffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
1286#if defined(QABSTRACTSOCKET_DEBUG)
1287    qDebug("QAbstractSocketPrivate::readFromSocket() got %d bytes, buffer size = %d",
1288           int(readBytes), buffer.size());
1289#endif
1290
1291    if (!socketEngine->isValid()) {
1292        socketError = socketEngine->error();
1293        q->setErrorString(socketEngine->errorString());
1294        emit q->error(socketError);
1295#if defined(QABSTRACTSOCKET_DEBUG)
1296        qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1297               q->errorString().toLatin1().constData());
1298#endif
1299        resetSocketLayer();
1300        return false;
1301    }
1302
1303    return true;
1304}
1305
1306/*! \internal
1307
1308    Sets up the internal state after the connection has succeeded.
1309*/
1310void QAbstractSocketPrivate::fetchConnectionParameters()
1311{
1312    Q_Q(QAbstractSocket);
1313
1314    peerName = hostName;
1315    if (socketEngine) {
1316        socketEngine->setReadNotificationEnabled(true);
1317        socketEngine->setWriteNotificationEnabled(true);
1318        localPort = socketEngine->localPort();
1319        peerPort = socketEngine->peerPort();
1320        localAddress = socketEngine->localAddress();
1321        peerAddress = socketEngine->peerAddress();
1322        cachedSocketDescriptor = socketEngine->socketDescriptor();
1323    }
1324
1325    state = QAbstractSocket::ConnectedState;
1326    emit q->stateChanged(state);
1327    emit q->connected();
1328
1329#if defined(QABSTRACTSOCKET_DEBUG)
1330    qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1331           host.toString().toLatin1().constData(), port);
1332#endif
1333}
1334
1335
1336void QAbstractSocketPrivate::pauseSocketNotifiers(QAbstractSocket *socket)
1337{
1338    QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1339    if (!socketEngine)
1340        return;
1341    socket->d_func()->prePauseReadSocketNotifierState = socketEngine->isReadNotificationEnabled();
1342    socket->d_func()->prePauseWriteSocketNotifierState = socketEngine->isWriteNotificationEnabled();
1343    socket->d_func()->prePauseExceptionSocketNotifierState = socketEngine->isExceptionNotificationEnabled();
1344    socketEngine->setReadNotificationEnabled(false);
1345    socketEngine->setWriteNotificationEnabled(false);
1346    socketEngine->setExceptionNotificationEnabled(false);
1347}
1348
1349void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
1350{
1351    QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1352    if (!socketEngine)
1353        return;
1354    socketEngine->setReadNotificationEnabled(socket->d_func()->prePauseReadSocketNotifierState);
1355    socketEngine->setWriteNotificationEnabled(socket->d_func()->prePauseWriteSocketNotifierState);
1356    socketEngine->setExceptionNotificationEnabled(socket->d_func()->prePauseExceptionSocketNotifierState);
1357}
1358
1359QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *socket)
1360{
1361    return socket->d_func()->socketEngine;
1362}
1363
1364
1365/*! \internal
1366
1367    Constructs a new abstract socket of type \a socketType. The \a
1368    parent …

Large files files are truncated, but you can click here to view the full file