PageRenderTime 65ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

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