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