PageRenderTime 32ms CodeModel.GetById 21ms RepoModel.GetById 0ms 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
Possible License(s): LGPL-3.0, CC-BY-SA-4.0, MIT, AGPL-3.0, BSD-3-Clause, LGPL-2.1, CC0-1.0, GPL-2.0, LGPL-2.0, GPL-3.0

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

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