/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

  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. QAbstractSocket::~QAbstractSocket()
  1175. {
  1176. Q_D(QAbstractSocket);
  1177. #if defined(QABSTRACTSOCKET_DEBUG)
  1178. qDebug("QAbstractSocket::~QAbstractSocket()");
  1179. #endif
  1180. if (d->state != UnconnectedState)
  1181. abort();
  1182. }
  1183. /*!
  1184. \since 5.0
  1185. Continues data transfer on the socket. This method should only be used
  1186. after the socket has been set to pause upon notifications and a
  1187. notification has been received.
  1188. The only notification currently supported is QSslSocket::sslErrors().
  1189. Calling this method if the socket is not paused results in undefined
  1190. behavior.
  1191. \sa pauseMode(), setPauseMode()
  1192. */
  1193. void QAbstractSocket::resume()
  1194. {
  1195. QAbstractSocketPrivate::resumeSocketNotifiers(this);
  1196. }
  1197. /*!
  1198. \since 5.0
  1199. Returns the pause mode of this socket.
  1200. \sa setPauseMode(), resume()
  1201. */
  1202. QAbstractSocket::PauseModes QAbstractSocket::pauseMode() const
  1203. {
  1204. return d_func()->pauseMode;
  1205. }
  1206. /*!
  1207. \since 5.0
  1208. Controls whether to pause upon receiving a notification. The \pauseMode parameter
  1209. specifies the conditions in which the socket should be paused. The only notification
  1210. currently supported is QSslSocket::sslErrors(). If set to PauseOnSslErrors,
  1211. data transfer on the socket will be paused and needs to be enabled explicitly
  1212. again by calling resume().
  1213. By default this option is set to PauseNever.
  1214. This option must be called before connecting to the server, otherwise it will
  1215. result in undefined behavior.
  1216. \sa pauseMode(), resume()
  1217. */
  1218. void QAbstractSocket::setPauseMode(PauseModes pauseMode)
  1219. {
  1220. d_func()->pauseMode = pauseMode;
  1221. }
  1222. /*!
  1223. \since 5.0
  1224. Binds to \a address on port \a port, using the BindMode \a mode.
  1225. Binds this socket to the address \a address and the port \a port.
  1226. For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted
  1227. whenever a UDP datagram arrives on the specified address and port.
  1228. Thus, This function is useful to write UDP servers.
  1229. For TCP sockets, this function may be used to specify which interface to use
  1230. for an outgoing connection, which is useful in case of multiple network
  1231. interfaces.
  1232. By default, the socket is bound using the DefaultForPlatform BindMode.
  1233. If a port is not specified, a random port is chosen.
  1234. On success, the functions returns true and the socket enters
  1235. BoundState; otherwise it returns false.
  1236. */
  1237. bool QAbstractSocket::bind(const QHostAddress &address, quint16 port, BindMode mode)
  1238. {
  1239. Q_D(QAbstractSocket);
  1240. // now check if the socket engine is initialized and to the right type
  1241. if (!d->socketEngine || !d->socketEngine->isValid()) {
  1242. QHostAddress nullAddress;
  1243. d->resolveProxy(nullAddress.toString(), port);
  1244. QAbstractSocket::NetworkLayerProtocol protocol = address.protocol();
  1245. if (protocol == QAbstractSocket::UnknownNetworkLayerProtocol)
  1246. protocol = nullAddress.protocol();
  1247. if (!d->initSocketLayer(protocol))
  1248. return false;
  1249. }
  1250. if (mode != DefaultForPlatform) {
  1251. #ifdef Q_OS_UNIX
  1252. if ((mode & ShareAddress) || (mode & ReuseAddressHint))
  1253. d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
  1254. else
  1255. d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
  1256. #endif
  1257. #ifdef Q_OS_WIN
  1258. if (mode & ReuseAddressHint)
  1259. d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
  1260. else
  1261. d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
  1262. if (mode & DontShareAddress)
  1263. d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 1);
  1264. else
  1265. d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 0);
  1266. #endif
  1267. }
  1268. bool result = d->socketEngine->bind(address, port);
  1269. d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
  1270. if (!result) {
  1271. d->socketError = d->socketEngine->error();
  1272. setErrorString(d->socketEngine->errorString());
  1273. emit error(d->socketError);
  1274. return false;
  1275. }
  1276. d->state = BoundState;
  1277. d->localAddress = d->socketEngine->localAddress();
  1278. d->localPort = d->socketEngine->localPort();
  1279. emit stateChanged(d->state);
  1280. d->socketEngine->setReadNotificationEnabled(true);
  1281. return true;
  1282. }
  1283. /*!
  1284. \since 5.0
  1285. \overload
  1286. Binds to QHostAddress:Any on port \a port, using the BindMode \a mode.
  1287. By default, the socket is bound using the DefaultForPlatform BindMode.
  1288. If a port is not specified, a random port is chosen.
  1289. */
  1290. bool QAbstractSocket::bind(quint16 port, BindMode mode)
  1291. {
  1292. return bind(QHostAddress::Any, port, mode);
  1293. }
  1294. /*!
  1295. Returns true if the socket is valid and ready for use; otherwise
  1296. returns false.
  1297. \b{Note:} The socket's state must be ConnectedState before reading and
  1298. writing can occur.
  1299. \sa state()
  1300. */
  1301. bool QAbstractSocket::isValid() const
  1302. {
  1303. return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
  1304. }
  1305. /*!
  1306. Attempts to make a connection to \a hostName on the given \a port.
  1307. The \a protocol parameter can be used to specify which network
  1308. protocol to use (eg. IPv4 or IPv6).
  1309. The socket is opened in the given \a openMode and first enters
  1310. HostLookupState, then performs a host name lookup of \a hostName.
  1311. If the lookup succeeds, hostFound() is emitted and QAbstractSocket
  1312. enters ConnectingState. It then attempts to connect to the address
  1313. or addresses returned by the lookup. Finally, if a connection is
  1314. established, QAbstractSocket enters ConnectedState and
  1315. emits connected().
  1316. At any point, the socket can emit error() to signal that an error
  1317. occurred.
  1318. \a hostName may be an IP address in string form (e.g.,
  1319. "43.195.83.32"), or it may be a host name (e.g.,
  1320. "example.com"). QAbstractSocket will do a lookup only if
  1321. required. \a port is in native byte order.
  1322. \sa state(), peerName(), peerAddress(), peerPort(), waitForConnected()
  1323. */
  1324. void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
  1325. OpenMode openMode,
  1326. NetworkLayerProtocol protocol)
  1327. {
  1328. Q_D(QAbstractSocket);
  1329. #if defined(QABSTRACTSOCKET_DEBUG)
  1330. qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
  1331. (int) openMode);
  1332. #endif
  1333. if (d->state == ConnectedState || d->state == ConnectingState
  1334. || d->state == ClosingState || d->state == HostLookupState) {
  1335. qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
  1336. d->socketError = QAbstractSocket::OperationError;
  1337. setErrorString(QAbstractSocket::tr("Trying to connect while connection is in progress"));
  1338. emit error(d->socketError);
  1339. return;
  1340. }
  1341. d->preferredNetworkLayerProtocol = protocol;
  1342. d->hostName = hostName;
  1343. d->port = port;
  1344. d->state = UnconnectedState;
  1345. d->buffer.clear();
  1346. d->writeBuffer.clear();
  1347. d->abortCalled = false;
  1348. d->closeCalled = false;
  1349. d->pendingClose = false;
  1350. d->localPort = 0;
  1351. d->peerPort = 0;
  1352. d->localAddress.clear();
  1353. d->peerAddress.clear();
  1354. d->peerName = hostName;
  1355. if (d->hostLookupId != -1) {
  1356. QHostInfo::abortHostLookup(d->hostLookupId);
  1357. d->hostLookupId = -1;
  1358. }
  1359. #ifndef QT_NO_NETWORKPROXY
  1360. // Get the proxy information
  1361. d->resolveProxy(hostName, port);
  1362. if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
  1363. // failed to setup the proxy
  1364. d->socketError = QAbstractSocket::UnsupportedSocketOperationError;
  1365. setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
  1366. emit error(d->socketError);
  1367. return;
  1368. }
  1369. #endif
  1370. if (openMode & QIODevice::Unbuffered)
  1371. d->isBuffered = false; // Unbuffered QTcpSocket
  1372. else if (!d_func()->isBuffered)
  1373. openMode |= QAbstractSocket::Unbuffered; // QUdpSocket
  1374. QIODevice::open(openMode);
  1375. d->state = HostLookupState;
  1376. emit stateChanged(d->state);
  1377. QHostAddress temp;
  1378. if (temp.setAddress(hostName)) {
  1379. QHostInfo info;
  1380. info.setAddresses(QList<QHostAddress>() << temp);
  1381. d->_q_startConnecting(info);
  1382. #ifndef QT_NO_NETWORKPROXY
  1383. } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
  1384. // the proxy supports connection by name, so use it
  1385. d->startConnectingByName(hostName);
  1386. return;
  1387. #endif
  1388. } else {
  1389. if (d->threadData->eventDispatcher) {
  1390. // this internal API for QHostInfo either immediately gives us the desired
  1391. // QHostInfo from cache or later calls the _q_startConnecting slot.
  1392. bool immediateResultValid = false;
  1393. QHostInfo hostInfo = qt_qhostinfo_lookup(hostName,
  1394. this,
  1395. SLOT(_q_startConnecting(QHostInfo)),
  1396. &immediateResultValid,
  1397. &d->hostLookupId);
  1398. if (immediateResultValid) {
  1399. d->hostLookupId = -1;
  1400. d->_q_startConnecting(hostInfo);
  1401. }
  1402. }
  1403. }
  1404. #if defined(QABSTRACTSOCKET_DEBUG)
  1405. qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
  1406. (d->state == ConnectedState) ? "true" : "false",
  1407. (d->state == ConnectingState || d->state == HostLookupState)
  1408. ? " (connection in progress)" : "");
  1409. #endif
  1410. }
  1411. /*! \overload
  1412. Attempts to make a connection to \a address on port \a port.
  1413. */
  1414. void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port,
  1415. OpenMode openMode)
  1416. {
  1417. #if defined(QABSTRACTSOCKET_DEBUG)
  1418. qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
  1419. address.toString().toLatin1().constData(), port, (int) openMode);
  1420. #endif
  1421. connectToHost(address.toString(), port, openMode);
  1422. }
  1423. /*!
  1424. Returns the number of bytes that are waiting to be written. The
  1425. bytes are written when control goes back to the event loop or
  1426. when flush() is called.
  1427. \sa bytesAvailable(), flush()
  1428. */
  1429. qint64 QAbstractSocket::bytesToWrite() const
  1430. {
  1431. Q_D(const QAbstractSocket);
  1432. #if defined(QABSTRACTSOCKET_DEBUG)
  1433. qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
  1434. #endif
  1435. return (qint64)d->writeBuffer.size();
  1436. }
  1437. /*!
  1438. Returns the number of incoming bytes that are waiting to be read.
  1439. \sa bytesToWrite(), read()
  1440. */
  1441. qint64 QAbstractSocket::bytesAvailable() const
  1442. {
  1443. Q_D(const QAbstractSocket);
  1444. qint64 available = QIODevice::bytesAvailable();
  1445. if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
  1446. available += d->socketEngine->bytesAvailable();
  1447. #if defined(QABSTRACTSOCKET_DEBUG)
  1448. qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
  1449. #endif
  1450. return available;
  1451. }
  1452. /*!
  1453. Returns the host port number (in native byte order) of the local
  1454. socket if available; otherwise returns 0.
  1455. \sa localAddress(), peerPort(), setLocalPort()
  1456. */
  1457. quint16 QAbstractSocket::localPort() const
  1458. {
  1459. Q_D(const QAbstractSocket);
  1460. return d->localPort;
  1461. }
  1462. /*!
  1463. Returns the host address of the local socket if available;
  1464. otherwise returns QHostAddress::Null.
  1465. This is normally the main IP address of the host, but can be
  1466. QHostAddress::LocalHost (127.0.0.1) for connections to the
  1467. local host.
  1468. \sa localPort(), peerAddress(), setLocalAddress()
  1469. */
  1470. QHostAddress QAbstractSocket::localAddress() const
  1471. {
  1472. Q_D(const QAbstractSocket);
  1473. return d->localAddress;
  1474. }
  1475. /*!
  1476. Returns the port of the connected peer if the socket is in
  1477. ConnectedState; otherwise returns 0.
  1478. \sa peerAddress(), localPort(), setPeerPort()
  1479. */
  1480. quint16 QAbstractSocket::peerPort() const
  1481. {
  1482. Q_D(const QAbstractSocket);
  1483. return d->peerPort;
  1484. }
  1485. /*!
  1486. Returns the address of the connected peer if the socket is in
  1487. ConnectedState; otherwise returns QHostAddress::Null.
  1488. \sa peerName(), peerPort(), localAddress(), setPeerAddress()
  1489. */
  1490. QHostAddress QAbstractSocket::peerAddress() const
  1491. {
  1492. Q_D(const QAbstractSocket);
  1493. return d->peerAddress;
  1494. }
  1495. /*!
  1496. Returns the name of the peer as specified by connectToHost(), or
  1497. an empty QString if connectToHost() has not been called.
  1498. \sa peerAddress(), peerPort(), setPeerName()
  1499. */
  1500. QString QAbstractSocket::peerName() const
  1501. {
  1502. Q_D(const QAbstractSocket);
  1503. return d->peerName.isEmpty() ? d->hostName : d->peerName;
  1504. }
  1505. /*!
  1506. Returns true if a line of data can be read from the socket;
  1507. otherwise returns false.
  1508. \sa readLine()
  1509. */
  1510. bool QAbstractSocket::canReadLine() const
  1511. {
  1512. bool hasLine = d_func()->buffer.canReadLine();
  1513. #if defined (QABSTRACTSOCKET_DEBUG)
  1514. qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
  1515. d_func()->buffer.size(), d_func()->buffer.size());
  1516. #endif
  1517. return hasLine || QIODevice::canReadLine();
  1518. }
  1519. /*!
  1520. Returns the native socket descriptor of the QAbstractSocket object
  1521. if this is available; otherwise returns -1.
  1522. If the socket is using QNetworkProxy, the returned descriptor
  1523. may not be usable with native socket functions.
  1524. The socket descriptor is not available when QAbstractSocket is in
  1525. UnconnectedState.
  1526. \sa setSocketDescriptor()
  1527. */
  1528. qintptr QAbstractSocket::socketDescriptor() const
  1529. {
  1530. Q_D(const QAbstractSocket);
  1531. return d->cachedSocketDescriptor;
  1532. }
  1533. /*!
  1534. Initializes QAbstractSocket with the native socket descriptor \a
  1535. socketDescriptor. Returns true if \a socketDescriptor is accepted
  1536. as a valid socket descriptor; otherwise returns false.
  1537. The socket is opened in the mode specified by \a openMode, and
  1538. enters the socket state specified by \a socketState.
  1539. \b{Note:} It is not possible to initialize two abstract sockets
  1540. with the same native socket descriptor.
  1541. \sa socketDescriptor()
  1542. */
  1543. bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState socketState,
  1544. OpenMode openMode)
  1545. {
  1546. Q_D(QAbstractSocket);
  1547. d->resetSocketLayer();
  1548. d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
  1549. if (!d->socketEngine) {
  1550. d->socketError = UnsupportedSocketOperationError;
  1551. setErrorString(tr("Operation on socket is not supported"));
  1552. return false;
  1553. }
  1554. #ifndef QT_NO_BEARERMANAGEMENT
  1555. //copy network session down to the socket engine (if it has been set)
  1556. d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
  1557. #endif
  1558. bool result = d->socketEngine->initialize(socketDescriptor, socketState);
  1559. if (!result) {
  1560. d->socketError = d->socketEngine->error();
  1561. setErrorString(d->socketEngine->errorString());
  1562. return false;
  1563. }
  1564. if (d->threadData->eventDispatcher)
  1565. d->socketEngine->setReceiver(d);
  1566. QIODevice::open(openMode);
  1567. if (d->state != socketState) {
  1568. d->state = socketState;
  1569. emit stateChanged(d->state);
  1570. }
  1571. d->pendingClose = false;
  1572. d->socketEngine->setReadNotificationEnabled(true);
  1573. d->localPort = d->socketEngine->localPort();
  1574. d->peerPort = d->socketEngine->peerPort();
  1575. d->localAddress = d->socketEngine->localAddress();
  1576. d->peerAddress = d->socketEngine->peerAddress();
  1577. d->cachedSocketDescriptor = socketDescriptor;
  1578. return true;
  1579. }
  1580. /*!
  1581. \since 4.6
  1582. Sets the given \a option to the value described by \a value.
  1583. \sa socketOption()
  1584. */
  1585. void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
  1586. {
  1587. if (!d_func()->socketEngine)
  1588. return;
  1589. switch (option) {
  1590. case LowDelayOption:
  1591. d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
  1592. break;
  1593. case KeepAliveOption:
  1594. d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
  1595. break;
  1596. case MulticastTtlOption:
  1597. d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastTtlOption, value.toInt());
  1598. break;
  1599. case MulticastLoopbackOption:
  1600. d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastLoopbackOption, value.toInt());
  1601. break;
  1602. case TypeOfServiceOption:
  1603. d_func()->socketEngine->setOption(QAbstractSocketEngine::TypeOfServiceOption, value.toInt());
  1604. break;
  1605. }
  1606. }
  1607. /*!
  1608. \since 4.6
  1609. Returns the value of the \a option option.
  1610. \sa setSocketOption()
  1611. */
  1612. QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)
  1613. {
  1614. if (!d_func()->socketEngine)
  1615. return QVariant();
  1616. int ret = -1;
  1617. switch (option) {
  1618. case LowDelayOption:
  1619. ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
  1620. break;
  1621. case KeepAliveOption:
  1622. ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
  1623. break;
  1624. case MulticastTtlOption:
  1625. ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastTtlOption);
  1626. break;
  1627. case MulticastLoopbackOption:
  1628. ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastLoopbackOption);
  1629. break;
  1630. case TypeOfServiceOption:
  1631. ret = d_func()->socketEngine->option(QAbstractSocketEngine::TypeOfServiceOption);
  1632. break;
  1633. }
  1634. if (ret == -1)
  1635. return QVariant();
  1636. else
  1637. return QVariant(ret);
  1638. }
  1639. /*
  1640. Returns the difference between msecs and elapsed. If msecs is -1,
  1641. however, -1 is returned.
  1642. */
  1643. static int qt_timeout_value(int msecs, int elapsed)
  1644. {
  1645. if (msecs == -1)
  1646. return -1;
  1647. int timeout = msecs - elapsed;
  1648. return timeout < 0 ? 0 : timeout;
  1649. }
  1650. /*!
  1651. Waits until the socket is connected, up to \a msecs
  1652. milliseconds. If the connection has been established, this
  1653. function returns true; otherwise it returns false. In the case
  1654. where it returns false, you can call error() to determine
  1655. the cause of the error.
  1656. The following example waits up to one second for a connection
  1657. to be established:
  1658. \snippet code/src_network_socket_qabstractsocket.cpp 0
  1659. If msecs is -1, this function will not time out.
  1660. \note This function may wait slightly longer than \a msecs,
  1661. depending on the time it takes to complete the host lookup.
  1662. \note Multiple calls to this functions do not accumulate the time.
  1663. If the function times out, the connecting process will be aborted.
  1664. \sa connectToHost(), connected()
  1665. */
  1666. bool QAbstractSocket::waitForConnected(int msecs)
  1667. {
  1668. Q_D(QAbstractSocket);
  1669. #if defined (QABSTRACTSOCKET_DEBUG)
  1670. qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
  1671. #endif
  1672. if (state() == ConnectedState) {
  1673. #if defined (QABSTRACTSOCKET_DEBUG)
  1674. qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
  1675. #endif
  1676. return true;
  1677. }
  1678. bool wasPendingClose = d->pendingClose;
  1679. d->pendingClose = false;
  1680. QElapsedTimer stopWatch;
  1681. stopWatch.start();
  1682. if (d->state == HostLookupState) {
  1683. #if defined (QABSTRACTSOCKET_DEBUG)
  1684. qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
  1685. #endif
  1686. QHostInfo::abortHostLookup(d->hostLookupId);
  1687. d->hostLookupId = -1;
  1688. #ifndef QT_NO_BEARERMANAGEMENT
  1689. QSharedPointer<QNetworkSession> networkSession;
  1690. QVariant v(property("_q_networksession"));
  1691. if (v.isValid()) {
  1692. networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v);
  1693. d->_q_startConnecting(QHostInfoPrivate::fromName(d->hostName, networkSession));
  1694. } else
  1695. #endif
  1696. {
  1697. QHostAddress temp;
  1698. if (temp.setAddress(d->hostName)) {
  1699. QHostInfo info;
  1700. info.setAddresses(QList<QHostAddress>() << temp);
  1701. d->_q_startConnecting(info);
  1702. } else {
  1703. d->_q_startConnecting(QHostInfo::fromName(d->hostName));
  1704. }
  1705. }
  1706. }
  1707. if (state() == UnconnectedState)
  1708. return false; // connect not im progress anymore!
  1709. bool timedOut = true;
  1710. #if defined (QABSTRACTSOCKET_DEBUG)
  1711. int attempt = 1;
  1712. #endif
  1713. while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
  1714. int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
  1715. if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
  1716. timeout = QT_CONNECT_TIMEOUT;
  1717. #if defined (QABSTRACTSOCKET_DEBUG)
  1718. qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
  1719. msecs, timeout / 1000.0, attempt++);
  1720. #endif
  1721. timedOut = false;
  1722. if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
  1723. d->_q_testConnection();
  1724. } else {
  1725. d->_q_connectToNextAddress();
  1726. }
  1727. }
  1728. if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
  1729. d->socketError = SocketTimeoutError;
  1730. d->state = UnconnectedState;
  1731. emit stateChanged(d->state);
  1732. d->resetSocketLayer();
  1733. setErrorString(tr("Socket operation timed out"));
  1734. }
  1735. #if defined (QABSTRACTSOCKET_DEBUG)
  1736. qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
  1737. state() == ConnectedState ? "true" : "false");
  1738. #endif
  1739. if (state() != ConnectedState)
  1740. return false;
  1741. if (wasPendingClose)
  1742. disconnectFromHost();
  1743. return true;
  1744. }
  1745. /*!
  1746. This function blocks until new data is available for reading and the
  1747. \l{QIODevice::}{readyRead()} signal has been emitted. The function
  1748. will timeout after \a msecs milliseconds; the default timeout is
  1749. 30000 milliseconds.
  1750. The function returns true if the readyRead() signal is emitted and
  1751. there is new data available for reading; otherwise it returns false
  1752. (if an error occurred or the operation timed out).
  1753. \sa waitForBytesWritten()
  1754. */
  1755. bool QAbstractSocket::waitForReadyRead(int msecs)
  1756. {
  1757. Q_D(QAbstractSocket);
  1758. #if defined (QABSTRACTSOCKET_DEBUG)
  1759. qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
  1760. #endif
  1761. // require calling connectToHost() before waitForReadyRead()
  1762. if (state() == UnconnectedState) {
  1763. /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
  1764. this, so you cannot avoid this warning. */
  1765. // qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
  1766. return false;
  1767. }
  1768. QElapsedTimer stopWatch;
  1769. stopWatch.start();
  1770. // handle a socket in connecting state
  1771. if (state() == HostLookupState || state() == ConnectingState) {
  1772. if (!waitForConnected(msecs))
  1773. return false;
  1774. }
  1775. Q_ASSERT(d->socketEngine);
  1776. do {
  1777. bool readyToRead = false;
  1778. bool readyToWrite = false;
  1779. if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
  1780. qt_timeout_value(msecs, stopWatch.elapsed()))) {
  1781. d->socketError = d->socketEngine->error();
  1782. setErrorString(d->socketEngine->errorString());
  1783. #if defined (QABSTRACTSOCKET_DEBUG)
  1784. qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
  1785. msecs, d->socketError, errorString().toLatin1().constData());
  1786. #endif
  1787. emit error(d->socketError);
  1788. if (d->socketError != SocketTimeoutError)
  1789. close();
  1790. return false;
  1791. }
  1792. if (readyToRead) {
  1793. if (d->canReadNotification())
  1794. return true;
  1795. }
  1796. if (readyToWrite)
  1797. d->canWriteNotification();
  1798. if (state() != ConnectedState)
  1799. return false;
  1800. } while (msecs == -1 || qt_timeout_value(msecs, stopWatch.elapsed()) > 0);
  1801. return false;
  1802. }
  1803. /*! \reimp
  1804. */
  1805. bool QAbstractSocket::waitForBytesWritten(int msecs)
  1806. {
  1807. Q_D(QAbstractSocket);
  1808. #if defined (QABSTRACTSOCKET_DEBUG)
  1809. qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
  1810. #endif
  1811. // require calling connectToHost() before waitForBytesWritten()
  1812. if (state() == UnconnectedState) {
  1813. qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
  1814. return false;
  1815. }
  1816. if (d->writeBuffer.isEmpty())
  1817. return false;
  1818. QElapsedTimer stopWatch;
  1819. stopWatch.start();
  1820. // handle a socket in connecting state
  1821. if (state() == HostLookupState || state() == ConnectingState) {
  1822. if (!waitForConnected(msecs))
  1823. return false;
  1824. }
  1825. forever {
  1826. bool readyToRead = false;
  1827. bool readyToWrite = false;
  1828. if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
  1829. qt_timeout_value(msecs, stopWatch.elapsed()))) {
  1830. d->socketError = d->socketEngine->error();
  1831. setErrorString(d->socketEngine->errorString());
  1832. #if defined (QABSTRACTSOCKET_DEBUG)
  1833. qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
  1834. msecs, d->socketError, errorString().toLatin1().constData());
  1835. #endif
  1836. emit error(d->socketError);
  1837. if (d->socketError != SocketTimeoutError)
  1838. close();
  1839. return false;
  1840. }
  1841. if (readyToRead) {
  1842. #if defined (QABSTRACTSOCKET_DEBUG)
  1843. qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
  1844. #endif
  1845. if(!d->canReadNotification())
  1846. return false;
  1847. }
  1848. if (readyToWrite) {
  1849. if (d->canWriteNotification()) {
  1850. #if defined (QABSTRACTSOCKET_DEBUG)
  1851. qDebug("QAbstractSocket::waitForBytesWritten returns true");
  1852. #endif
  1853. return true;
  1854. }
  1855. }
  1856. if (state() != ConnectedState)
  1857. return false;
  1858. }
  1859. return false;
  1860. }
  1861. /*!
  1862. Waits until the socket has disconnected, up to \a msecs
  1863. milliseconds. If the connection has been disconnected, this
  1864. function returns true; otherwise it returns false. In the case
  1865. where it returns false, you can call error() to determine
  1866. the cause of the error.
  1867. The following example waits up to one second for a connection
  1868. to be closed:
  1869. \snippet code/src_network_socket_qabstractsocket.cpp 1
  1870. If msecs is -1, this function will not time out.
  1871. \sa disconnectFromHost(), close()
  1872. */
  1873. bool QAbstractSocket::waitForDisconnected(int msecs)
  1874. {
  1875. Q_D(QAbstractSocket);
  1876. // require calling connectToHost() before waitForDisconnected()
  1877. if (state() == UnconnectedState) {
  1878. qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
  1879. return false;
  1880. }
  1881. QElapsedTimer stopWatch;
  1882. stopWatch.start();
  1883. // handle a socket in connecting state
  1884. if (state() == HostLookupState || state() == ConnectingState) {
  1885. if (!waitForConnected(msecs))
  1886. return false;
  1887. if (state() == UnconnectedState)
  1888. return true;
  1889. }
  1890. forever {
  1891. bool readyToRead = false;
  1892. bool readyToWrite = false;
  1893. if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
  1894. !d->writeBuffer.isEmpty(),
  1895. qt_timeout_value(msecs, stopWatch.elapsed()))) {
  1896. d->socketError = d->socketEngine->error();
  1897. setErrorString(d->socketEngine->errorString());
  1898. #if defined (QABSTRACTSOCKET_DEBUG)
  1899. qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
  1900. msecs, d->socketError, errorString().toLatin1().constData());
  1901. #endif
  1902. emit error(d->socketError);
  1903. if (d->socketError != SocketTimeoutError)
  1904. close();
  1905. return false;
  1906. }
  1907. if (readyToRead)
  1908. d->canReadNotification();
  1909. if (readyToWrite)
  1910. d->canWriteNotification();
  1911. if (state() == UnconnectedState)
  1912. return true;
  1913. }
  1914. return false;
  1915. }
  1916. /*!
  1917. Aborts the current connection and resets the socket. Unlike disconnectFromHost(),
  1918. this function immediately closes the socket, discarding any pending data in the
  1919. write buffer.
  1920. \sa disconnectFromHost(), close()
  1921. */
  1922. void QAbstractSocket::abort()
  1923. {
  1924. Q_D(QAbstractSocket);
  1925. #if defined (QABSTRACTSOCKET_DEBUG)
  1926. qDebug("QAbstractSocket::abort()");
  1927. #endif
  1928. if (d->state == UnconnectedState)
  1929. return;
  1930. #ifndef QT_NO_SSL
  1931. if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
  1932. socket->abort();
  1933. return;
  1934. }
  1935. #endif
  1936. if (d->connectTimer) {
  1937. d->connectTimer->stop();
  1938. delete d->connectTimer;
  1939. d->connectTimer = 0;
  1940. }
  1941. d->writeBuffer.clear();
  1942. d->abortCalled = true;
  1943. close();
  1944. }
  1945. /*! \reimp
  1946. */
  1947. bool QAbstractSocket::isSequential() const
  1948. {
  1949. return true;
  1950. }
  1951. /*! \reimp
  1952. Returns true if no more data is currently
  1953. available for reading; otherwise returns false.
  1954. This function is most commonly used when reading data from the
  1955. socket in a loop. For example:
  1956. \snippet code/src_network_socket_qabstractsocket.cpp 2
  1957. \sa bytesAvailable(), readyRead()
  1958. */
  1959. bool QAbstractSocket::atEnd() const
  1960. {
  1961. return QIODevice::atEnd() && (!isOpen() || d_func()->buffer.isEmpty());
  1962. }
  1963. /*!
  1964. This function writes as much as possible from the internal write buffer to
  1965. the underlying network socket, without blocking. If any data was written,
  1966. this function returns true; otherwise false is returned.
  1967. Call this function if you need QAbstractSocket to start sending buffered
  1968. data immediately. The number of bytes successfully written depends on the
  1969. operating system. In most cases, you do not need to call this function,
  1970. because QAbstractSocket will start sending data automatically once control
  1971. goes back to the event loop. In the absence of an event loop, call
  1972. waitForBytesWritten() instead.
  1973. \sa write(), waitForBytesWritten()
  1974. */
  1975. // Note! docs copied to QSslSocket::flush()
  1976. bool QAbstractSocket::flush()
  1977. {
  1978. Q_D(QAbstractSocket);
  1979. #ifndef QT_NO_SSL
  1980. // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
  1981. // it.
  1982. if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
  1983. return socket->flush();
  1984. #endif
  1985. Q_CHECK_SOCKETENGINE(false);
  1986. return d->flush();
  1987. }
  1988. /*! \reimp
  1989. */
  1990. qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
  1991. {
  1992. Q_D(QAbstractSocket);
  1993. // Check if the read notifier can be enabled again.
  1994. if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
  1995. d->socketEngine->setReadNotificationEnabled(true);
  1996. if (!maxSize)
  1997. return 0;
  1998. // This is for a buffered QTcpSocket
  1999. if (d->isBuffered && d->buffer.isEmpty())
  2000. // if we're still connected, return 0 indicating there may be more data in the future
  2001. // if we're not connected, return -1 indicating EOF
  2002. return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
  2003. if (!d->socketEngine)
  2004. return -1; // no socket engine is probably EOF
  2005. if (!d->socketEngine->isValid())
  2006. return -1; // This is for unbuffered TCP when we already had been disconnected
  2007. if (d->state != QAbstractSocket::ConnectedState)
  2008. return -1; // This is for unbuffered TCP if we're not connected yet
  2009. qint64 readBytes = d->socketEngine->read(data, maxSize);
  2010. if (readBytes == -2) {
  2011. // -2 from the engine means no bytes available (EAGAIN) so read more later
  2012. return 0;
  2013. } else if (readBytes < 0) {
  2014. d->socketError = d->socketEngine->error();
  2015. setErrorString(d->socketEngine->errorString());
  2016. d->resetSocketLayer();
  2017. d->state = QAbstractSocket::UnconnectedState;
  2018. } else if (!d->socketEngine->isReadNotificationEnabled()) {
  2019. // Only do this when there was no error
  2020. d->socketEngine->setReadNotificationEnabled(true);
  2021. }
  2022. #if defined (QABSTRACTSOCKET_DEBUG)
  2023. qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
  2024. data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
  2025. readBytes);
  2026. #endif
  2027. return readBytes;
  2028. }
  2029. /*! \reimp
  2030. */
  2031. qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)
  2032. {
  2033. return QIODevice::readLineData(data, maxlen);
  2034. }
  2035. /*! \reimp
  2036. */
  2037. qint64 QAbstractSocket::writeData(const char *data, qint64 size)
  2038. {
  2039. Q_D(QAbstractSocket);
  2040. if (d->state == QAbstractSocket::UnconnectedState) {
  2041. d->socketError = QAbstractSocket::UnknownSocketError;
  2042. setErrorString(tr("Socket is not connected"));
  2043. return -1;
  2044. }
  2045. if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {
  2046. // This code is for the new Unbuffered QTcpSocket use case
  2047. qint64 written = d->socketEngine->write(data, size);
  2048. if (written < 0) {
  2049. d->socketError = d->socketEngine->error();
  2050. setErrorString(d->socketEngine->errorString());
  2051. return written;
  2052. } else if (written < size) {
  2053. // Buffer what was not written yet
  2054. char *ptr = d->writeBuffer.reserve(size - written);
  2055. memcpy(ptr, data + written, size - written);
  2056. if (d->socketEngine)
  2057. d->socketEngine->setWriteNotificationEnabled(true);
  2058. }
  2059. return size; // size=actually written + what has been buffered
  2060. } else if (!d->isBuffered && d->socketType != TcpSocket) {
  2061. // This is for a QUdpSocket that was connect()ed
  2062. qint64 written = d->socketEngine->write(data, size);
  2063. if (written < 0) {
  2064. d->socketError = d->socketEngine->error();
  2065. setErrorString(d->socketEngine->errorString());
  2066. } else if (!d->writeBuffer.isEmpty()) {
  2067. d->socketEngine->setWriteNotificationEnabled(true);
  2068. }
  2069. #if defined (QABSTRACTSOCKET_DEBUG)
  2070. qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
  2071. qt_prettyDebug(data, qMin((int)size, 32), size).data(),
  2072. size, written);
  2073. #endif
  2074. if (written >= 0)
  2075. emit bytesWritten(written);
  2076. return written;
  2077. }
  2078. // This is the code path for normal buffered QTcpSocket or
  2079. // unbuffered QTcpSocket when there was already something in the
  2080. // write buffer and therefore we could not do a direct engine write.
  2081. // We just write to our write buffer and enable the write notifier
  2082. // The write notifier then flush()es the buffer.
  2083. char *ptr = d->writeBuffer.reserve(size);
  2084. if (size == 1)
  2085. *ptr = *data;
  2086. else
  2087. memcpy(ptr, data, size);
  2088. qint64 written = size;
  2089. if (d->socketEngine && !d->writeBuffer.isEmpty())
  2090. d->socketEngine->setWriteNotificationEnabled(true);
  2091. #if defined (QABSTRACTSOCKET_DEBUG)
  2092. qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
  2093. qt_prettyDebug(data, qMin((int)size, 32), size).data(),
  2094. size, written);
  2095. #endif
  2096. return written;
  2097. }
  2098. /*!
  2099. \since 4.1
  2100. Sets the port on the local side of a connection to \a port.
  2101. You can call this function in a subclass of QAbstractSocket to
  2102. change the return value of the localPort() function after a
  2103. connection has been established. This feature is commonly used by
  2104. proxy connections for virtual connection settings.
  2105. Note that this function does not bind the local port of the socket
  2106. prior to a connection (e.g., QAbstractSocket::bind()).
  2107. \sa localAddress(), setLocalAddress(), setPeerPort()
  2108. */
  2109. void QAbstractSocket::setLocalPort(quint16 port)
  2110. {
  2111. Q_D(QAbstractSocket);
  2112. d->localPort = port;
  2113. }
  2114. /*!
  2115. \since 4.1
  2116. Sets the address on the local side of a connection to
  2117. \a address.
  2118. You can call this function in a subclass of QAbstractSocket to
  2119. change the return value of the localAddress() function after a
  2120. connection has been established. This feature is commonly used by
  2121. proxy connections for virtual connection settings.
  2122. Note that this function does not bind the local address of the socket
  2123. prior to a connection (e.g., QAbstractSocket::bind()).
  2124. \sa localAddress(), setLocalPort(), setPeerAddress()
  2125. */
  2126. void QAbstractSocket::setLocalAddress(const QHostAddress &address)
  2127. {
  2128. Q_D(QAbstractSocket);
  2129. d->localAddress = address;
  2130. }
  2131. /*!
  2132. \since 4.1
  2133. Sets the port of the remote side of the connection to
  2134. \a port.
  2135. You can call this function in a subclass of QAbstractSocket to
  2136. change the return value of the peerPort() function after a
  2137. connection has been established. This feature is commonly used by
  2138. proxy connections for virtual connection settings.
  2139. \sa peerPort(), setPeerAddress(), setLocalPort()
  2140. */
  2141. void QAbstractSocket::setPeerPort(quint16 port)
  2142. {
  2143. Q_D(QAbstractSocket);
  2144. d->peerPort = port;
  2145. }
  2146. /*!
  2147. \since 4.1
  2148. Sets the address of the remote side of the connection
  2149. to \a address.
  2150. You can call this function in a subclass of QAbstractSocket to
  2151. change the return value of the peerAddress() function after a
  2152. connection has been established. This feature is commonly used by
  2153. proxy connections for virtual connection settings.
  2154. \sa peerAddress(), setPeerPort(), setLocalAddress()
  2155. */
  2156. void QAbstractSocket::setPeerAddress(const QHostAddress &address)
  2157. {
  2158. Q_D(QAbstractSocket);
  2159. d->peerAddress = address;
  2160. }
  2161. /*!
  2162. \since 4.1
  2163. Sets the host name of the remote peer to \a name.
  2164. You can call this function in a subclass of QAbstractSocket to
  2165. change the return value of the peerName() function after a
  2166. connection has been established. This feature is commonly used by
  2167. proxy connections for virtual connection settings.
  2168. \sa peerName()
  2169. */
  2170. void QAbstractSocket::setPeerName(const QString &name)
  2171. {
  2172. Q_D(QAbstractSocket);
  2173. d->peerName = name;
  2174. }
  2175. /*!
  2176. Closes the I/O device for the socket, disconnects the socket's connection with the
  2177. host, closes the socket, and resets the name, address, port number and underlying
  2178. socket descriptor.
  2179. See QIODevice::close() for a description of the actions that occur when an I/O
  2180. device is closed.
  2181. \sa abort()
  2182. */
  2183. void QAbstractSocket::close()
  2184. {
  2185. Q_D(QAbstractSocket);
  2186. #if defined(QABSTRACTSOCKET_DEBUG)
  2187. qDebug("QAbstractSocket::close()");
  2188. #endif
  2189. QIODevice::close();
  2190. if (d->state != UnconnectedState) {
  2191. d->closeCalled = true;
  2192. disconnectFromHost();
  2193. }
  2194. d->localPort = 0;
  2195. d->peerPort = 0;
  2196. d->localAddress.clear();
  2197. d->peerAddress.clear();
  2198. d->peerName.clear();
  2199. d->cachedSocketDescriptor = -1;
  2200. }
  2201. /*!
  2202. Attempts to close the socket. If there is pending data waiting to
  2203. be written, QAbstractSocket will enter ClosingState and wait
  2204. until all data has been written. Eventually, it will enter
  2205. UnconnectedState and emit the disconnected() signal.
  2206. \sa connectToHost()
  2207. */
  2208. void QAbstractSocket::disconnectFromHost()
  2209. {
  2210. Q_D(QAbstractSocket);
  2211. #if defined(QABSTRACTSOCKET_DEBUG)
  2212. qDebug("QAbstractSocket::disconnectFromHost()");
  2213. #endif
  2214. if (d->state == UnconnectedState) {
  2215. #if defined(QABSTRACTSOCKET_DEBUG)
  2216. qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
  2217. #endif
  2218. return;
  2219. }
  2220. if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
  2221. #if defined(QABSTRACTSOCKET_DEBUG)
  2222. qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
  2223. #endif
  2224. d->pendingClose = true;
  2225. return;
  2226. }
  2227. // Disable and delete read notification
  2228. if (d->socketEngine)
  2229. d->socketEngine->setReadNotificationEnabled(false);
  2230. if (d->abortCalled) {
  2231. #if defined(QABSTRACTSOCKET_DEBUG)
  2232. qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
  2233. #endif
  2234. if (d->state == HostLookupState) {
  2235. QHostInfo::abortHostLookup(d->hostLookupId);
  2236. d->hostLookupId = -1;
  2237. }
  2238. } else {
  2239. // Perhaps emit closing()
  2240. if (d->state != ClosingState) {
  2241. d->state = ClosingState;
  2242. #if defined(QABSTRACTSOCKET_DEBUG)
  2243. qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
  2244. #endif
  2245. emit stateChanged(d->state);
  2246. } else {
  2247. #if defined(QABSTRACTSOCKET_DEBUG)
  2248. qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
  2249. #endif
  2250. }
  2251. // Wait for pending data to be written.
  2252. if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
  2253. || d->socketEngine->bytesToWrite() > 0)) {
  2254. // hack: when we are waiting for the socket engine to write bytes (only
  2255. // possible when using Socks5 or HTTP socket engine), then close
  2256. // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
  2257. // sometimes just did not get the write notifier from the underlying
  2258. // CFSocket and no progress was made.
  2259. if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
  2260. if (!d->disconnectTimer) {
  2261. d->disconnectTimer = new QTimer(this);
  2262. connect(d->disconnectTimer, SIGNAL(timeout()), this,
  2263. SLOT(_q_forceDisconnect()), Qt::DirectConnection);
  2264. }
  2265. if (!d->disconnectTimer->isActive())
  2266. d->disconnectTimer->start(2000);
  2267. }
  2268. d->socketEngine->setWriteNotificationEnabled(true);
  2269. #if defined(QABSTRACTSOCKET_DEBUG)
  2270. qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
  2271. #endif
  2272. return;
  2273. } else {
  2274. #if defined(QABSTRACTSOCKET_DEBUG)
  2275. qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
  2276. #endif
  2277. }
  2278. }
  2279. SocketState previousState = d->state;
  2280. d->resetSocketLayer();
  2281. d->state = UnconnectedState;
  2282. emit stateChanged(d->state);
  2283. emit readChannelFinished(); // we got an EOF
  2284. // only emit disconnected if we were connected before
  2285. if (previousState == ConnectedState || previousState == ClosingState)
  2286. emit disconnected();
  2287. d->localPort = 0;
  2288. d->peerPort = 0;
  2289. d->localAddress.clear();
  2290. d->peerAddress.clear();
  2291. #if defined(QABSTRACTSOCKET_DEBUG)
  2292. qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
  2293. #endif
  2294. if (d->closeCalled) {
  2295. #if defined(QABSTRACTSOCKET_DEBUG)
  2296. qDebug("QAbstractSocket::disconnectFromHost() closed!");
  2297. #endif
  2298. d->buffer.clear();
  2299. d->writeBuffer.clear();
  2300. QIODevice::close();
  2301. }
  2302. }
  2303. /*!
  2304. Returns the size of the internal read buffer. This limits the
  2305. amount of data that the client can receive before you call read()
  2306. or readAll().
  2307. A read buffer size of 0 (the default) means that the buffer has
  2308. no size limit, ensuring that no data is lost.
  2309. \sa setReadBufferSize(), read()
  2310. */
  2311. qint64 QAbstractSocket::readBufferSize() const
  2312. {
  2313. return d_func()->readBufferMaxSize;
  2314. }
  2315. /*!
  2316. Sets the size of QAbstractSocket's internal read buffer to be \a
  2317. size bytes.
  2318. If the buffer size is limited to a certain size, QAbstractSocket
  2319. won't buffer more than this size of data. Exceptionally, a buffer
  2320. size of 0 means that the read buffer is unlimited and all
  2321. incoming data is buffered. This is the default.
  2322. This option is useful if you only read the data at certain points
  2323. in time (e.g., in a real-time streaming application) or if you
  2324. want to protect your socket against receiving too much data,
  2325. which may eventually cause your application to run out of memory.
  2326. Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket
  2327. does not use any buffering at all, but rather relies on the
  2328. implicit buffering provided by the operating system.
  2329. Because of this, calling this function on QUdpSocket has no
  2330. effect.
  2331. \sa readBufferSize(), read()
  2332. */
  2333. void QAbstractSocket::setReadBufferSize(qint64 size)
  2334. {
  2335. Q_D(QAbstractSocket);
  2336. if (d->readBufferMaxSize == size)
  2337. return;
  2338. d->readBufferMaxSize = size;
  2339. if (!d->readSocketNotifierCalled && d->socketEngine) {
  2340. // ensure that the read notification is enabled if we've now got
  2341. // room in the read buffer
  2342. // but only if we're not inside canReadNotification -- that will take care on its own
  2343. if ((size == 0 || d->buffer.size() < size) && d->state == QAbstractSocket::ConnectedState) // Do not change the notifier unless we are connected.
  2344. d->socketEngine->setReadNotificationEnabled(true);
  2345. }
  2346. }
  2347. /*!
  2348. Returns the state of the socket.
  2349. \sa error()
  2350. */
  2351. QAbstractSocket::SocketState QAbstractSocket::state() const
  2352. {
  2353. return d_func()->state;
  2354. }
  2355. /*!
  2356. Sets the state of the socket to \a state.
  2357. \sa state()
  2358. */
  2359. void QAbstractSocket::setSocketState(SocketState state)
  2360. {
  2361. d_func()->state = state;
  2362. }
  2363. /*!
  2364. Returns the socket type (TCP, UDP, or other).
  2365. \sa QTcpSocket, QUdpSocket
  2366. */
  2367. QAbstractSocket::SocketType QAbstractSocket::socketType() const
  2368. {
  2369. return d_func()->socketType;
  2370. }
  2371. /*!
  2372. Returns the type of error that last occurred.
  2373. \sa state(), errorString()
  2374. */
  2375. QAbstractSocket::SocketError QAbstractSocket::error() const
  2376. {
  2377. return d_func()->socketError;
  2378. }
  2379. /*!
  2380. Sets the type of error that last occurred to \a socketError.
  2381. \sa setSocketState(), setErrorString()
  2382. */
  2383. void QAbstractSocket::setSocketError(SocketError socketError)
  2384. {
  2385. d_func()->socketError = socketError;
  2386. }
  2387. #ifndef QT_NO_NETWORKPROXY
  2388. /*!
  2389. \since 4.1
  2390. Sets the explicit network proxy for this socket to \a networkProxy.
  2391. To disable the use of a proxy for this socket, use the
  2392. QNetworkProxy::NoProxy proxy type:
  2393. \snippet code/src_network_socket_qabstractsocket.cpp 3
  2394. The default value for the proxy is QNetworkProxy::DefaultProxy,
  2395. which means the socket will use the application settings: if a
  2396. proxy is set with QNetworkProxy::setApplicationProxy, it will use
  2397. that; otherwise, if a factory is set with
  2398. QNetworkProxyFactory::setApplicationProxyFactory, it will query
  2399. that factory with type QNetworkProxyQuery::TcpSocket.
  2400. \sa proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()
  2401. */
  2402. void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
  2403. {
  2404. Q_D(QAbstractSocket);
  2405. d->proxy = networkProxy;
  2406. }
  2407. /*!
  2408. \since 4.1
  2409. Returns the network proxy for this socket.
  2410. By default QNetworkProxy::DefaultProxy is used, which means this
  2411. socket will query the default proxy settings for the application.
  2412. \sa setProxy(), QNetworkProxy, QNetworkProxyFactory
  2413. */
  2414. QNetworkProxy QAbstractSocket::proxy() const
  2415. {
  2416. Q_D(const QAbstractSocket);
  2417. return d->proxy;
  2418. }
  2419. #endif // QT_NO_NETWORKPROXY
  2420. #ifndef QT_NO_DEBUG_STREAM
  2421. Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
  2422. {
  2423. switch (error) {
  2424. case QAbstractSocket::ConnectionRefusedError:
  2425. debug << "QAbstractSocket::ConnectionRefusedError";
  2426. break;
  2427. case QAbstractSocket::RemoteHostClosedError:
  2428. debug << "QAbstractSocket::RemoteHostClosedError";
  2429. break;
  2430. case QAbstractSocket::HostNotFoundError:
  2431. debug << "QAbstractSocket::HostNotFoundError";
  2432. break;
  2433. case QAbstractSocket::SocketAccessError:
  2434. debug << "QAbstractSocket::SocketAccessError";
  2435. break;
  2436. case QAbstractSocket::SocketResourceError:
  2437. debug << "QAbstractSocket::SocketResourceError";
  2438. break;
  2439. case QAbstractSocket::SocketTimeoutError:
  2440. debug << "QAbstractSocket::SocketTimeoutError";
  2441. break;
  2442. case QAbstractSocket::DatagramTooLargeError:
  2443. debug << "QAbstractSocket::DatagramTooLargeError";
  2444. break;
  2445. case QAbstractSocket::NetworkError:
  2446. debug << "QAbstractSocket::NetworkError";
  2447. break;
  2448. case QAbstractSocket::AddressInUseError:
  2449. debug << "QAbstractSocket::AddressInUseError";
  2450. break;
  2451. case QAbstractSocket::SocketAddressNotAvailableError:
  2452. debug << "QAbstractSocket::SocketAddressNotAvailableError";
  2453. break;
  2454. case QAbstractSocket::UnsupportedSocketOperationError:
  2455. debug << "QAbstractSocket::UnsupportedSocketOperationError";
  2456. break;
  2457. case QAbstractSocket::UnfinishedSocketOperationError:
  2458. debug << "QAbstractSocket::UnfinishedSocketOperationError";
  2459. break;
  2460. case QAbstractSocket::ProxyAuthenticationRequiredError:
  2461. debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
  2462. break;
  2463. case QAbstractSocket::UnknownSocketError:
  2464. debug << "QAbstractSocket::UnknownSocketError";
  2465. break;
  2466. case QAbstractSocket::ProxyConnectionRefusedError:
  2467. debug << "QAbstractSocket::ProxyConnectionRefusedError";
  2468. break;
  2469. case QAbstractSocket::ProxyConnectionClosedError:
  2470. debug << "QAbstractSocket::ProxyConnectionClosedError";
  2471. break;
  2472. case QAbstractSocket::ProxyConnectionTimeoutError:
  2473. debug << "QAbstractSocket::ProxyConnectionTimeoutError";
  2474. break;
  2475. case QAbstractSocket::ProxyNotFoundError:
  2476. debug << "QAbstractSocket::ProxyNotFoundError";
  2477. break;
  2478. case QAbstractSocket::ProxyProtocolError:
  2479. debug << "QAbstractSocket::ProxyProtocolError";
  2480. break;
  2481. default:
  2482. debug << "QAbstractSocket::SocketError(" << int(error) << ')';
  2483. break;
  2484. }
  2485. return debug;
  2486. }
  2487. Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state)
  2488. {
  2489. switch (state) {
  2490. case QAbstractSocket::UnconnectedState:
  2491. debug << "QAbstractSocket::UnconnectedState";
  2492. break;
  2493. case QAbstractSocket::HostLookupState:
  2494. debug << "QAbstractSocket::HostLookupState";
  2495. break;
  2496. case QAbstractSocket::ConnectingState:
  2497. debug << "QAbstractSocket::ConnectingState";
  2498. break;
  2499. case QAbstractSocket::ConnectedState:
  2500. debug << "QAbstractSocket::ConnectedState";
  2501. break;
  2502. case QAbstractSocket::BoundState:
  2503. debug << "QAbstractSocket::BoundState";
  2504. break;
  2505. case QAbstractSocket::ListeningState:
  2506. debug << "QAbstractSocket::ListeningState";
  2507. break;
  2508. case QAbstractSocket::ClosingState:
  2509. debug << "QAbstractSocket::ClosingState";
  2510. break;
  2511. default:
  2512. debug << "QAbstractSocket::SocketState(" << int(state) << ')';
  2513. break;
  2514. }
  2515. return debug;
  2516. }
  2517. #endif
  2518. QT_END_NAMESPACE
  2519. #include "moc_qabstractsocket.cpp"