source: trunk/src/network/socket/qabstractsocket.cpp

Last change on this file was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

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