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

https://review.tizen.org/git/ · C++ · 2976 lines · 1589 code · 272 blank · 1115 comment · 402 complexity · 46814652cd181abdbbae1d2d057d24a0 MD5 · raw file

Large files are truncated click here to view the full file

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